files.go 30 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3 4
package commands

import (
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"context"
Jeromy's avatar
Jeromy committed
6 7 8 9 10
	"errors"
	"fmt"
	"io"
	"os"
	gopath "path"
Lucas Molas's avatar
Lucas Molas committed
11
	"sort"
Jeromy's avatar
Jeromy committed
12 13
	"strings"

Michael Muré's avatar
Michael Muré committed
14 15
	oldcmds "github.com/ipfs/go-ipfs/commands"
	lgc "github.com/ipfs/go-ipfs/commands/legacy"
Jeromy's avatar
Jeromy committed
16
	core "github.com/ipfs/go-ipfs/core"
17
	cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
Jan Winkelmann's avatar
Jan Winkelmann committed
18
	e "github.com/ipfs/go-ipfs/core/commands/e"
19
	"github.com/ipfs/go-ipfs/core/coreapi/interface"
20

Michael Muré's avatar
Michael Muré committed
21
	humanize "gx/ipfs/QmPSBJL4momYnE7DcUyk2DVhD6rH488ZmHBGLbxNdhU44K/go-humanize"
22
	cid "gx/ipfs/QmPSQnBKM9g7BaUcZCvswUJVscQ1ipjmwxN5PXCjkp9EQ7/go-cid"
23
	mh "gx/ipfs/QmPnFwZ2JXKnXgMw8CdBPxn7FWh6LLdjUjxV1fKHuJnkr8/go-multihash"
Steven Allen's avatar
Steven Allen committed
24
	ft "gx/ipfs/QmRX6WZhMinQrQhyuwaqNHYQtNPhtBwzxKFySzNMaJmW9v/go-unixfs"
25
	cmdkit "gx/ipfs/QmSP88ryZkHSRn1fnngAaV2Vcn63WUJzAavnRM9CVdU1Ky/go-ipfs-cmdkit"
Steven Allen's avatar
Steven Allen committed
26
	bservice "gx/ipfs/QmSU7Nx5eUHWkc9zCTiXDu3ZkdXAZdRgRGRaKM86VjGU4m/go-blockservice"
Steven Allen's avatar
Steven Allen committed
27
	offline "gx/ipfs/QmT6dHGp3UYd3vUMpy7rzX2CXQv7HLcj42Vtq8qwwjgASb/go-ipfs-exchange-offline"
Steven Allen's avatar
Steven Allen committed
28
	dag "gx/ipfs/QmVvNkTCx8V9Zei8xuTYTBdUXmbnDRS4iNuw1SztYyhQwQ/go-merkledag"
Steven Allen's avatar
Steven Allen committed
29 30
	cmds "gx/ipfs/QmXTmUCBtDUrzDYVzASogLiNph7EBuYqEgPL7QoHNMzUnz/go-ipfs-cmds"
	logging "gx/ipfs/QmZChCsSt8DctjceaL56Eibc29CVQq4dGKRXC5JRZ6Ppae/go-log"
Steven Allen's avatar
Steven Allen committed
31
	mfs "gx/ipfs/Qmbs19iFfAxmYfjrHib6G2eJCczoNZ3GQED6CDxmhc2dn2/go-mfs"
32
	ipld "gx/ipfs/QmdDXJs4axxefSPgK6Y1QhpJWKuDPnGJiqgq4uncb4rFHL/go-ipld-format"
Jeromy's avatar
Jeromy committed
33 34
)

35
var flog = logging.Logger("cmds/files")
Jeromy's avatar
Jeromy committed
36

Michael Muré's avatar
Michael Muré committed
37
// FilesCmd is the 'ipfs files' command
Jeromy's avatar
Jeromy committed
38
var FilesCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
39
	Helptext: cmdkit.HelpText{
40
		Tagline: "Interact with unixfs files.",
Jeromy's avatar
Jeromy committed
41
		ShortDescription: `
42 43
Files is an API for manipulating IPFS objects as if they were a unix
filesystem.
Jeromy's avatar
Jeromy committed
44

45
NOTE:
46 47 48 49 50 51 52
Most of the subcommands of 'ipfs files' accept the '--flush' flag. It defaults
to true. Use caution when setting this flag to false. It will improve
performance for large numbers of file operations, but it does so at the cost
of consistency guarantees. If the daemon is unexpectedly killed before running
'ipfs files flush' on the files in question, then data may be lost. This also
applies to running 'ipfs repo gc' concurrently with '--flush=false'
operations.
Jeromy's avatar
Jeromy committed
53 54
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
55
	Options: []cmdkit.Option{
Michael Muré's avatar
Michael Muré committed
56
		cmdkit.BoolOption("f", "flush", "Flush target and ancestors after write.").WithDefault(true),
Jeromy's avatar
Jeromy committed
57
	},
Jeromy's avatar
Jeromy committed
58
	Subcommands: map[string]*cmds.Command{
Michael Muré's avatar
Michael Muré committed
59
		"read":  lgc.NewCommand(filesReadCmd),
60
		"write": filesWriteCmd,
Michael Muré's avatar
Michael Muré committed
61 62 63 64
		"mv":    lgc.NewCommand(filesMvCmd),
		"cp":    lgc.NewCommand(filesCpCmd),
		"ls":    lgc.NewCommand(filesLsCmd),
		"mkdir": lgc.NewCommand(filesMkdirCmd),
65
		"stat":  filesStatCmd,
Michael Muré's avatar
Michael Muré committed
66 67 68
		"rm":    lgc.NewCommand(filesRmCmd),
		"flush": lgc.NewCommand(filesFlushCmd),
		"chcid": lgc.NewCommand(filesChcidCmd),
Jeromy's avatar
Jeromy committed
69 70 71
	},
}

Kejie Zhang's avatar
Kejie Zhang committed
72 73 74 75 76 77 78
const (
	filesCidVersionOptionName = "cid-version"
	filesHashOptionName       = "hash"
)

var cidVersionOption = cmdkit.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)")
var hashOption = cmdkit.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)")
79

Michael Muré's avatar
Michael Muré committed
80
var errFormat = errors.New("format was set by multiple options. Only one format option is allowed")
81

Michael Muré's avatar
Michael Muré committed
82
type statOutput struct {
83 84 85 86 87
	Hash           string
	Size           uint64
	CumulativeSize uint64
	Blocks         int
	Type           string
Michael Muré's avatar
Michael Muré committed
88
	WithLocality   bool   `json:",omitempty"`
89 90 91 92
	Local          bool   `json:",omitempty"`
	SizeLocal      uint64 `json:",omitempty"`
}

Kejie Zhang's avatar
Kejie Zhang committed
93 94
const (
	defaultStatFormat = `<hash>
keks's avatar
keks committed
95 96 97 98
Size: <size>
CumulativeSize: <cumulsize>
ChildBlocks: <childs>
Type: <type>`
Kejie Zhang's avatar
Kejie Zhang committed
99 100 101 102
	filesFormatOptionName    = "format"
	filesSizeOptionName      = "size"
	filesWithLocalOptionName = "with-local"
)
keks's avatar
keks committed
103

104
var filesStatCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
105
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
106
		Tagline: "Display file status.",
Jeromy's avatar
Jeromy committed
107 108
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
109 110
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to node to stat."),
Jeromy's avatar
Jeromy committed
111
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
112
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
113
		cmdkit.StringOption(filesFormatOptionName, "Print statistics in given format. Allowed tokens: "+
keks's avatar
keks committed
114
			"<hash> <size> <cumulsize> <type> <childs>. Conflicts with other format options.").WithDefault(defaultStatFormat),
Kejie Zhang's avatar
Kejie Zhang committed
115 116 117
		cmdkit.BoolOption(filesHashOptionName, "Print only hash. Implies '--format=<hash>'. Conflicts with other format options."),
		cmdkit.BoolOption(filesSizeOptionName, "Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options."),
		cmdkit.BoolOption(filesWithLocalOptionName, "Compute the amount of the dag that is local, and if possible the total size"),
118
	},
keks's avatar
keks committed
119
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
120 121 122

		_, err := statGetFormatOptions(req)
		if err != nil {
keks's avatar
keks committed
123
			return cmdkit.Errorf(cmdkit.ErrClient, err.Error())
124 125
		}

126
		node, err := cmdenv.GetNode(env)
Jeromy's avatar
Jeromy committed
127
		if err != nil {
keks's avatar
keks committed
128
			return err
Jeromy's avatar
Jeromy committed
129 130
		}

131 132 133 134 135
		api, err := cmdenv.GetApi(env)
		if err != nil {
			return err
		}

136
		path, err := checkPath(req.Arguments[0])
Jeromy's avatar
Jeromy committed
137
		if err != nil {
keks's avatar
keks committed
138
			return err
Jeromy's avatar
Jeromy committed
139 140
		}

Kejie Zhang's avatar
Kejie Zhang committed
141
		withLocal, _ := req.Options[filesWithLocalOptionName].(bool)
142 143 144 145 146 147 148 149 150 151 152 153

		var dagserv ipld.DAGService
		if withLocal {
			// an offline DAGService will not fetch from the network
			dagserv = dag.NewDAGService(bservice.New(
				node.Blockstore,
				offline.Exchange(node.Blockstore),
			))
		} else {
			dagserv = node.DAG
		}

154
		nd, err := getNodeFromPath(req.Context, node, api, path)
Jeromy's avatar
Jeromy committed
155
		if err != nil {
keks's avatar
keks committed
156
			return err
Jeromy's avatar
Jeromy committed
157 158
		}

159
		o, err := statNode(nd)
Jeromy's avatar
Jeromy committed
160
		if err != nil {
keks's avatar
keks committed
161
			return err
Jeromy's avatar
Jeromy committed
162 163
		}

164
		if !withLocal {
keks's avatar
keks committed
165
			return cmds.EmitOnce(res, o)
166 167 168 169 170 171 172 173
		}

		local, sizeLocal, err := walkBlock(req.Context, dagserv, nd)

		o.WithLocality = true
		o.Local = local
		o.SizeLocal = sizeLocal

keks's avatar
keks committed
174
		return cmds.EmitOnce(res, o)
Jeromy's avatar
Jeromy committed
175
	},
176 177
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeEncoder(func(req *cmds.Request, w io.Writer, v interface{}) error {
Michael Muré's avatar
Michael Muré committed
178
			out, ok := v.(*statOutput)
Jan Winkelmann's avatar
Jan Winkelmann committed
179
			if !ok {
180
				return e.TypeErr(out, v)
Jan Winkelmann's avatar
Jan Winkelmann committed
181
			}
182

183
			s, _ := statGetFormatOptions(req)
184 185 186 187 188 189
			s = strings.Replace(s, "<hash>", out.Hash, -1)
			s = strings.Replace(s, "<size>", fmt.Sprintf("%d", out.Size), -1)
			s = strings.Replace(s, "<cumulsize>", fmt.Sprintf("%d", out.CumulativeSize), -1)
			s = strings.Replace(s, "<childs>", fmt.Sprintf("%d", out.Blocks), -1)
			s = strings.Replace(s, "<type>", out.Type, -1)

190 191 192 193 194 195 196 197 198 199 200
			fmt.Fprintln(w, s)

			if out.WithLocality {
				fmt.Fprintf(w, "Local: %s of %s (%.2f%%)\n",
					humanize.Bytes(out.SizeLocal),
					humanize.Bytes(out.CumulativeSize),
					100.0*float64(out.SizeLocal)/float64(out.CumulativeSize),
				)
			}

			return nil
201
		}),
Jeromy's avatar
Jeromy committed
202
	},
Michael Muré's avatar
Michael Muré committed
203
	Type: statOutput{},
Jeromy's avatar
Jeromy committed
204 205
}

206 207 208 209
func moreThanOne(a, b, c bool) bool {
	return a && b || b && c || a && c
}

210
func statGetFormatOptions(req *cmds.Request) (string, error) {
211

Kejie Zhang's avatar
Kejie Zhang committed
212 213 214
	hash, _ := req.Options[filesHashOptionName].(bool)
	size, _ := req.Options[filesSizeOptionName].(bool)
	format, _ := req.Options[filesFormatOptionName].(string)
215

keks's avatar
keks committed
216
	if moreThanOne(hash, size, format != defaultStatFormat) {
Michael Muré's avatar
Michael Muré committed
217
		return "", errFormat
218 219 220
	}

	if hash {
221 222 223 224 225
		return "<hash>", nil
	} else if size {
		return "<cumulsize>", nil
	} else {
		return format, nil
226 227 228
	}
}

Michael Muré's avatar
Michael Muré committed
229
func statNode(nd ipld.Node) (*statOutput, error) {
Jeromy's avatar
Jeromy committed
230
	c := nd.Cid()
Jeromy's avatar
Jeromy committed
231 232 233 234 235 236

	cumulsize, err := nd.Size()
	if err != nil {
		return nil, err
	}

237 238
	switch n := nd.(type) {
	case *dag.ProtoNode:
Overbool's avatar
Overbool committed
239
		d, err := ft.FSNodeFromBytes(n.Data())
240 241 242 243 244
		if err != nil {
			return nil, err
		}

		var ndtype string
Overbool's avatar
Overbool committed
245
		switch d.Type() {
246
		case ft.TDirectory, ft.THAMTShard:
247
			ndtype = "directory"
248
		case ft.TFile, ft.TMetadata, ft.TRaw:
249 250
			ndtype = "file"
		default:
Overbool's avatar
Overbool committed
251
			return nil, fmt.Errorf("unrecognized node type: %s", d.Type())
252 253
		}

Michael Muré's avatar
Michael Muré committed
254
		return &statOutput{
255 256
			Hash:           c.String(),
			Blocks:         len(nd.Links()),
Overbool's avatar
Overbool committed
257
			Size:           d.FileSize(),
258 259 260 261
			CumulativeSize: cumulsize,
			Type:           ndtype,
		}, nil
	case *dag.RawNode:
Michael Muré's avatar
Michael Muré committed
262
		return &statOutput{
263 264 265 266 267 268
			Hash:           c.String(),
			Blocks:         0,
			Size:           cumulsize,
			CumulativeSize: cumulsize,
			Type:           "file",
		}, nil
Jeromy's avatar
Jeromy committed
269
	default:
270
		return nil, fmt.Errorf("not unixfs node (proto or raw)")
Jeromy's avatar
Jeromy committed
271
	}
Jeromy's avatar
Jeromy committed
272 273
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
func walkBlock(ctx context.Context, dagserv ipld.DAGService, nd ipld.Node) (bool, uint64, error) {
	// Start with the block data size
	sizeLocal := uint64(len(nd.RawData()))

	local := true

	for _, link := range nd.Links() {
		child, err := dagserv.Get(ctx, link.Cid)

		if err == ipld.ErrNotFound {
			local = false
			continue
		}

		if err != nil {
			return local, sizeLocal, err
		}

		childLocal, childLocalSize, err := walkBlock(ctx, dagserv, child)

		if err != nil {
			return local, sizeLocal, err
		}

		// Recursively add the child size
		local = local && childLocal
		sizeLocal += childLocalSize
	}

	return local, sizeLocal, nil
}

Michael Muré's avatar
Michael Muré committed
306
var filesCpCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
307
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
308
		Tagline: "Copy files into mfs.",
Jeromy's avatar
Jeromy committed
309
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
310 311 312
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("source", true, false, "Source object to copy."),
		cmdkit.StringArg("dest", true, false, "Destination to copy object to."),
Jeromy's avatar
Jeromy committed
313
	},
Michael Muré's avatar
Michael Muré committed
314
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
315 316
		node, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
317
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
318 319 320
			return
		}

321 322 323 324 325 326
		api, err := req.InvocContext().GetApi()
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

327
		flush, _, _ := req.Option("flush").Bool()
328

Jeromy's avatar
Jeromy committed
329 330
		src, err := checkPath(req.Arguments()[0])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
331
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
332 333
			return
		}
334 335
		src = strings.TrimRight(src, "/")

Jeromy's avatar
Jeromy committed
336 337
		dst, err := checkPath(req.Arguments()[1])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
338
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
339 340
			return
		}
Jeromy's avatar
Jeromy committed
341

342 343 344 345
		if dst[len(dst)-1] == '/' {
			dst += gopath.Base(src)
		}

346
		nd, err := getNodeFromPath(req.Context(), node, api, src)
Jeromy's avatar
Jeromy committed
347
		if err != nil {
348
			res.SetError(fmt.Errorf("cp: cannot get node from path %s: %s", src, err), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
349
			return
Jeromy's avatar
Jeromy committed
350 351 352 353
		}

		err = mfs.PutNode(node.FilesRoot, dst, nd)
		if err != nil {
354
			res.SetError(fmt.Errorf("cp: cannot put node in path %s: %s", dst, err), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
355 356
			return
		}
357 358 359 360

		if flush {
			err := mfs.FlushPath(node.FilesRoot, dst)
			if err != nil {
Lucas Molas's avatar
Lucas Molas committed
361
				res.SetError(fmt.Errorf("cp: cannot flush the created file %s: %s", dst, err), cmdkit.ErrNormal)
362 363 364
				return
			}
		}
Jan Winkelmann's avatar
Jan Winkelmann committed
365 366

		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
367 368 369
	},
}

370
func getNodeFromPath(ctx context.Context, node *core.IpfsNode, api iface.CoreAPI, p string) (ipld.Node, error) {
Jeromy's avatar
Jeromy committed
371 372
	switch {
	case strings.HasPrefix(p, "/ipfs/"):
373
		np, err := iface.ParsePath(p)
Jeromy's avatar
Jeromy committed
374 375 376 377
		if err != nil {
			return nil, err
		}

378
		return api.ResolveNode(ctx, np)
Jeromy's avatar
Jeromy committed
379 380 381 382 383 384 385 386 387 388
	default:
		fsn, err := mfs.Lookup(node.FilesRoot, p)
		if err != nil {
			return nil, err
		}

		return fsn.GetNode()
	}
}

Michael Muré's avatar
Michael Muré committed
389
type filesLsOutput struct {
Jeromy's avatar
Jeromy committed
390 391 392
	Entries []mfs.NodeListing
}

Kejie Zhang's avatar
Kejie Zhang committed
393 394 395 396 397
const (
	longOptionName     = "l"
	dontSortOptionName = "U"
)

Michael Muré's avatar
Michael Muré committed
398
var filesLsCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
399
	Helptext: cmdkit.HelpText{
400
		Tagline: "List directories in the local mutable namespace.",
Jeromy's avatar
Jeromy committed
401
		ShortDescription: `
402
List directories in the local mutable namespace.
Jeromy's avatar
Jeromy committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418

Examples:

    $ ipfs files ls /welcome/docs/
    about
    contact
    help
    quick-start
    readme
    security-notes

    $ ipfs files ls /myfiles/a/b/c/d
    foo
    bar
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
419 420
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", false, false, "Path to show listing for. Defaults to '/'."),
Jeromy's avatar
Jeromy committed
421
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
422
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
423 424
		cmdkit.BoolOption(longOptionName, "Use long listing format."),
		cmdkit.BoolOption(dontSortOptionName, "Do not sort; list entries in directory order."),
Jeromy's avatar
Jeromy committed
425
	},
Michael Muré's avatar
Michael Muré committed
426
	Run: func(req oldcmds.Request, res oldcmds.Response) {
427 428 429 430 431 432 433 434 435
		var arg string

		if len(req.Arguments()) == 0 {
			arg = "/"
		} else {
			arg = req.Arguments()[0]
		}

		path, err := checkPath(arg)
Jeromy's avatar
Jeromy committed
436
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
437
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
438 439 440
			return
		}

Jeromy's avatar
Jeromy committed
441 442
		nd, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
443
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
444 445 446 447 448
			return
		}

		fsn, err := mfs.Lookup(nd.FilesRoot, path)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
449
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
450 451 452
			return
		}

Kejie Zhang's avatar
Kejie Zhang committed
453
		long, _, _ := req.Option(longOptionName).Bool()
Jeromy's avatar
Jeromy committed
454

Jeromy's avatar
Jeromy committed
455 456
		switch fsn := fsn.(type) {
		case *mfs.Directory:
Jeromy's avatar
Jeromy committed
457 458
			if !long {
				var output []mfs.NodeListing
Jeromy's avatar
Jeromy committed
459
				names, err := fsn.ListNames(req.Context())
460
				if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
461
					res.SetError(err, cmdkit.ErrNormal)
462 463 464 465
					return
				}

				for _, name := range names {
Jeromy's avatar
Jeromy committed
466
					output = append(output, mfs.NodeListing{
Jeromy's avatar
Jeromy committed
467
						Name: name,
Jeromy's avatar
Jeromy committed
468 469
					})
				}
Michael Muré's avatar
Michael Muré committed
470
				res.SetOutput(&filesLsOutput{output})
Jeromy's avatar
Jeromy committed
471
			} else {
Jeromy's avatar
Jeromy committed
472
				listing, err := fsn.List(req.Context())
Jeromy's avatar
Jeromy committed
473
				if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
474
					res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
475 476
					return
				}
Michael Muré's avatar
Michael Muré committed
477
				res.SetOutput(&filesLsOutput{listing})
Jeromy's avatar
Jeromy committed
478 479 480
			}
			return
		case *mfs.File:
rht's avatar
rht committed
481
			_, name := gopath.Split(path)
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
			out := &filesLsOutput{[]mfs.NodeListing{mfs.NodeListing{Name: name}}}
			if long {
				out.Entries[0].Type = int(fsn.Type())

				size, err := fsn.Size()
				if err != nil {
					res.SetError(err, cmdkit.ErrNormal)
					return
				}
				out.Entries[0].Size = size

				nd, err := fsn.GetNode()
				if err != nil {
					res.SetError(err, cmdkit.ErrNormal)
					return
				}
				out.Entries[0].Hash = nd.Cid().String()
			}
Jeromy's avatar
Jeromy committed
500 501 502
			res.SetOutput(out)
			return
		default:
Jan Winkelmann's avatar
Jan Winkelmann committed
503
			res.SetError(errors.New("unrecognized type"), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
504 505
		}
	},
Michael Muré's avatar
Michael Muré committed
506 507
	Marshalers: oldcmds.MarshalerMap{
		oldcmds.Text: func(res oldcmds.Response) (io.Reader, error) {
Jan Winkelmann's avatar
Jan Winkelmann committed
508 509 510 511 512
			v, err := unwrapOutput(res.Output())
			if err != nil {
				return nil, err
			}

Michael Muré's avatar
Michael Muré committed
513
			out, ok := v.(*filesLsOutput)
Jan Winkelmann's avatar
Jan Winkelmann committed
514 515 516 517
			if !ok {
				return nil, e.TypeErr(out, v)
			}

Jeromy's avatar
Jeromy committed
518 519
			buf := new(bytes.Buffer)

Kejie Zhang's avatar
Kejie Zhang committed
520
			noSort, _, _ := res.Request().Option(dontSortOptionName).Bool()
Lucas Molas's avatar
Lucas Molas committed
521 522 523 524 525 526
			if !noSort {
				sort.Slice(out.Entries, func(i, j int) bool {
					return strings.Compare(out.Entries[i].Name, out.Entries[j].Name) < 0
				})
			}

Kejie Zhang's avatar
Kejie Zhang committed
527
			long, _, _ := res.Request().Option(longOptionName).Bool()
Jeromy's avatar
Jeromy committed
528 529 530 531 532 533 534 535 536 537
			for _, o := range out.Entries {
				if long {
					fmt.Fprintf(buf, "%s\t%s\t%d\n", o.Name, o.Hash, o.Size)
				} else {
					fmt.Fprintf(buf, "%s\n", o.Name)
				}
			}
			return buf, nil
		},
	},
Michael Muré's avatar
Michael Muré committed
538
	Type: filesLsOutput{},
Jeromy's avatar
Jeromy committed
539 540
}

Kejie Zhang's avatar
Kejie Zhang committed
541 542 543 544 545
const (
	filesOffsetOptionName = "offset"
	filesCountOptionName  = "count"
)

Michael Muré's avatar
Michael Muré committed
546
var filesReadCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
547
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
548
		Tagline: "Read a file in a given mfs.",
Jeromy's avatar
Jeromy committed
549
		ShortDescription: `
550 551
Read a specified number of bytes from a file at a given offset. By default,
will read the entire file similar to unix cat.
Jeromy's avatar
Jeromy committed
552 553 554 555 556

Examples:

    $ ipfs files read /test/hello
    hello
Jeromy's avatar
Jeromy committed
557
        `,
Jeromy's avatar
Jeromy committed
558 559
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
560 561
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to file to be read."),
Jeromy's avatar
Jeromy committed
562
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
563
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
564 565
		cmdkit.IntOption(filesOffsetOptionName, "o", "Byte offset to begin reading from."),
		cmdkit.IntOption(filesCountOptionName, "n", "Maximum number of bytes to read."),
Jeromy's avatar
Jeromy committed
566
	},
Michael Muré's avatar
Michael Muré committed
567
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
568 569
		n, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
570
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
571 572 573
			return
		}

Jeromy's avatar
Jeromy committed
574 575
		path, err := checkPath(req.Arguments()[0])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
576
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
577 578 579
			return
		}

Jeromy's avatar
Jeromy committed
580 581
		fsn, err := mfs.Lookup(n.FilesRoot, path)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
582
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
583 584 585 586 587
			return
		}

		fi, ok := fsn.(*mfs.File)
		if !ok {
Michael Muré's avatar
Michael Muré committed
588
			res.SetError(fmt.Errorf("%s was not a file", path), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
589 590 591
			return
		}

592 593
		rfd, err := fi.Open(mfs.OpenReadOnly, false)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
594
			res.SetError(err, cmdkit.ErrNormal)
595 596 597 598 599
			return
		}

		defer rfd.Close()

Kejie Zhang's avatar
Kejie Zhang committed
600
		offset, _, err := req.Option(offsetOptionName).Int()
Jeromy's avatar
Jeromy committed
601
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
602
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
603 604 605
			return
		}
		if offset < 0 {
Michael Muré's avatar
Michael Muré committed
606
			res.SetError(fmt.Errorf("cannot specify negative offset"), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
607 608 609
			return
		}

610
		filen, err := rfd.Size()
Jeromy's avatar
Jeromy committed
611
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
612
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
613 614 615 616
			return
		}

		if int64(offset) > filen {
Michael Muré's avatar
Michael Muré committed
617
			res.SetError(fmt.Errorf("offset was past end of file (%d > %d)", offset, filen), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
618 619
			return
		}
Jeromy's avatar
Jeromy committed
620

621
		_, err = rfd.Seek(int64(offset), io.SeekStart)
Jeromy's avatar
Jeromy committed
622
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
623
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
624 625
			return
		}
626 627

		var r io.Reader = &contextReaderWrapper{R: rfd, ctx: req.Context()}
Kejie Zhang's avatar
Kejie Zhang committed
628
		count, found, err := req.Option(filesCountOptionName).Int()
Jeromy's avatar
Jeromy committed
629
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
630
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
631 632 633 634
			return
		}
		if found {
			if count < 0 {
Michael Muré's avatar
Michael Muré committed
635
				res.SetError(fmt.Errorf("cannot specify negative 'count'"), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
636 637
				return
			}
638
			r = io.LimitReader(r, int64(count))
Jeromy's avatar
Jeromy committed
639 640 641 642 643 644
		}

		res.SetOutput(r)
	},
}

Jeromy's avatar
Jeromy committed
645 646 647 648 649 650 651 652 653 654 655 656 657
type contextReader interface {
	CtxReadFull(context.Context, []byte) (int, error)
}

type contextReaderWrapper struct {
	R   contextReader
	ctx context.Context
}

func (crw *contextReaderWrapper) Read(b []byte) (int, error) {
	return crw.R.CtxReadFull(crw.ctx, b)
}

Michael Muré's avatar
Michael Muré committed
658
var filesMvCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
659
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
660
		Tagline: "Move files.",
Jeromy's avatar
Jeromy committed
661 662 663 664 665 666 667
		ShortDescription: `
Move files around. Just like traditional unix mv.

Example:

    $ ipfs files mv /myfs/a/b/c /myfs/foo/newc

Jeromy's avatar
Jeromy committed
668
`,
Jeromy's avatar
Jeromy committed
669 670
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
671 672 673
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("source", true, false, "Source file to move."),
		cmdkit.StringArg("dest", true, false, "Destination path for file to be moved to."),
Jeromy's avatar
Jeromy committed
674
	},
Michael Muré's avatar
Michael Muré committed
675
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
676 677
		n, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
678
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
679 680 681
			return
		}

Jeromy's avatar
Jeromy committed
682 683
		src, err := checkPath(req.Arguments()[0])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
684
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
685 686 687 688
			return
		}
		dst, err := checkPath(req.Arguments()[1])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
689
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
690 691
			return
		}
Jeromy's avatar
Jeromy committed
692 693 694

		err = mfs.Mv(n.FilesRoot, src, dst)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
695
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
696 697
			return
		}
Jan Winkelmann's avatar
Jan Winkelmann committed
698 699

		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
700 701 702
	},
}

Kejie Zhang's avatar
Kejie Zhang committed
703 704 705 706 707 708 709 710
const (
	filesCreateOptionName    = "create"
	filesParentsOptionName   = "parents"
	filesTruncateOptionName  = "truncate"
	filesRawLeavesOptionName = "raw-leaves"
	filesFlushOptionName     = "flush"
)

711
var filesWriteCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
712
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
713
		Tagline: "Write to a mutable file in a given filesystem.",
Jeromy's avatar
Jeromy committed
714 715
		ShortDescription: `
Write data to a file in a given filesystem. This command allows you to specify
716 717
a beginning offset to write to. The entire length of the input will be
written.
Jeromy's avatar
Jeromy committed
718

Jeromy's avatar
Jeromy committed
719
If the '--create' option is specified, the file will be created if it does not
Jeromy's avatar
Jeromy committed
720 721
exist. Nonexistant intermediate directories will not be created.

722 723 724 725 726 727 728
Newly created files will have the same CID version and hash function of the
parent directory unless the --cid-version and --hash options are used.

Newly created leaves will be in the legacy format (Protobuf) if the
CID version is 0, or raw is the CID version is non-zero.  Use of the
--raw-leaves option will override this behavior.

729 730 731 732
If the '--flush' option is set to false, changes will not be propogated to the
merkledag root. This can make operations much faster when doing a large number
of writes to a deeper directory structure.

733
EXAMPLE:
Jeromy's avatar
Jeromy committed
734

Jeromy's avatar
Jeromy committed
735 736
    echo "hello world" | ipfs files write --create /myfs/a/b/file
    echo "hello world" | ipfs files write --truncate /myfs/a/b/file
737

738
WARNING:
739

740 741 742
Usage of the '--flush=false' option does not guarantee data durability until
the tree has been flushed. This can be accomplished by running 'ipfs files
stat' on the file or any of its ancestors.
Jeromy's avatar
Jeromy committed
743
`,
Jeromy's avatar
Jeromy committed
744
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
745 746 747
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to write to."),
		cmdkit.FileArg("data", true, false, "Data to write.").EnableStdin(),
Jeromy's avatar
Jeromy committed
748
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
749
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
750 751 752 753 754 755
		cmdkit.IntOption(filesOffsetOptionName, "o", "Byte offset to begin writing at."),
		cmdkit.BoolOption(filesCreateOptionName, "e", "Create the file if it does not exist."),
		cmdkit.BoolOption(filesParentsOptionName, "p", "Make parent directories as needed."),
		cmdkit.BoolOption(filesTruncateOptionName, "t", "Truncate the file to size zero before writing."),
		cmdkit.IntOption(filesCountOptionName, "n", "Maximum number of bytes to read."),
		cmdkit.BoolOption(filesRawLeavesOptionName, "Use raw blocks for newly created leaf nodes. (experimental)"),
756 757
		cidVersionOption,
		hashOption,
Jeromy's avatar
Jeromy committed
758
	},
keks's avatar
keks committed
759
	Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) (retErr error) {
760
		path, err := checkPath(req.Arguments[0])
Jeromy's avatar
Jeromy committed
761
		if err != nil {
keks's avatar
keks committed
762
			return err
Jeromy's avatar
Jeromy committed
763 764
		}

Kejie Zhang's avatar
Kejie Zhang committed
765 766 767 768 769
		create, _ := req.Options[filesCreateOptionName].(bool)
		mkParents, _ := req.Options[filesParentsOptionName].(bool)
		trunc, _ := req.Options[filesTruncateOptionName].(bool)
		flush, _ := req.Options[filesFlushOptionName].(bool)
		rawLeaves, rawLeavesDef := req.Options[filesRawLeavesOptionName].(bool)
770

771
		prefix, err := getPrefixNew(req)
772
		if err != nil {
keks's avatar
keks committed
773
			return err
774
		}
Jeromy's avatar
Jeromy committed
775

776
		nd, err := cmdenv.GetNode(env)
Jeromy's avatar
Jeromy committed
777
		if err != nil {
keks's avatar
keks committed
778
			return err
Jeromy's avatar
Jeromy committed
779 780
		}

Kejie Zhang's avatar
Kejie Zhang committed
781
		offset, _ := req.Options[filesOffsetOptionName].(int)
Jeromy's avatar
Jeromy committed
782
		if offset < 0 {
keks's avatar
keks committed
783
			return fmt.Errorf("cannot have negative write offset")
Jeromy's avatar
Jeromy committed
784 785
		}

786 787 788
		if mkParents {
			err := ensureContainingDirectoryExists(nd.FilesRoot, path, prefix)
			if err != nil {
keks's avatar
keks committed
789
				return err
790 791 792
			}
		}

793
		fi, err := getFileHandle(nd.FilesRoot, path, create, prefix)
Jeromy's avatar
Jeromy committed
794
		if err != nil {
keks's avatar
keks committed
795
			return err
Jeromy's avatar
Jeromy committed
796
		}
797 798 799
		if rawLeavesDef {
			fi.RawLeaves = rawLeaves
		}
800

801 802
		wfd, err := fi.Open(mfs.OpenWriteOnly, flush)
		if err != nil {
keks's avatar
keks committed
803
			return err
804
		}
Jeromy's avatar
Jeromy committed
805

806 807 808
		defer func() {
			err := wfd.Close()
			if err != nil {
keks's avatar
keks committed
809 810 811 812 813
				if retErr == nil {
					retErr = err
				} else {
					log.Error("files: error closing file mfs file descriptor", err)
				}
814 815
			}
		}()
816

Jeromy's avatar
Jeromy committed
817
		if trunc {
818
			if err := wfd.Truncate(0); err != nil {
keks's avatar
keks committed
819
				return err
Jeromy's avatar
Jeromy committed
820 821 822
			}
		}

Kejie Zhang's avatar
Kejie Zhang committed
823
		count, countfound := req.Options[filesCountOptionName].(int)
Jeromy's avatar
Jeromy committed
824
		if countfound && count < 0 {
keks's avatar
keks committed
825
			return fmt.Errorf("cannot have negative byte count")
Jeromy's avatar
Jeromy committed
826
		}
Jeromy's avatar
Jeromy committed
827

828
		_, err = wfd.Seek(int64(offset), io.SeekStart)
Jeromy's avatar
Jeromy committed
829
		if err != nil {
830
			flog.Error("seekfail: ", err)
keks's avatar
keks committed
831
			return err
Jeromy's avatar
Jeromy committed
832 833
		}

834
		input, err := req.Files.NextFile()
Jeromy's avatar
Jeromy committed
835
		if err != nil {
keks's avatar
keks committed
836
			return err
Jeromy's avatar
Jeromy committed
837 838
		}

zramsay's avatar
zramsay committed
839 840 841 842 843
		var r io.Reader = input
		if countfound {
			r = io.LimitReader(r, int64(count))
		}

Jan Winkelmann's avatar
Jan Winkelmann committed
844
		_, err = io.Copy(wfd, r)
keks's avatar
keks committed
845
		return err
Jeromy's avatar
Jeromy committed
846 847 848
	},
}

Michael Muré's avatar
Michael Muré committed
849
var filesMkdirCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
850
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
851
		Tagline: "Make directories.",
Jeromy's avatar
Jeromy committed
852 853 854
		ShortDescription: `
Create the directory if it does not already exist.

855 856 857
The directory will have the same CID version and hash function of the
parent directory unless the --cid-version and --hash options are used.

858
NOTE: All paths must be absolute.
Jeromy's avatar
Jeromy committed
859 860 861

Examples:

862 863
    $ ipfs files mkdir /test/newdir
    $ ipfs files mkdir -p /test/does/not/exist/yet
Jeromy's avatar
Jeromy committed
864 865 866
`,
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
867 868
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to dir to make."),
Jeromy's avatar
Jeromy committed
869
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
870
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
871
		cmdkit.BoolOption(filesParentsOptionName, "p", "No error if existing, make parent directories as needed."),
872 873
		cidVersionOption,
		hashOption,
Jeromy's avatar
Jeromy committed
874
	},
Michael Muré's avatar
Michael Muré committed
875
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
876 877
		n, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
878
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
879 880 881
			return
		}

Kejie Zhang's avatar
Kejie Zhang committed
882
		dashp, _, _ := req.Option(filesParentsOptionName).Bool()
Jeromy's avatar
Jeromy committed
883 884
		dirtomake, err := checkPath(req.Arguments()[0])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
885
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
886 887 888
			return
		}

Kejie Zhang's avatar
Kejie Zhang committed
889
		flush, _, _ := req.Option(filesFlushOptionName).Bool()
Jeromy's avatar
Jeromy committed
890

891 892
		prefix, err := getPrefix(req)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
893
			res.SetError(err, cmdkit.ErrNormal)
894 895 896 897
			return
		}
		root := n.FilesRoot

898
		err = mfs.Mkdir(root, dirtomake, mfs.MkdirOpts{
899 900 901
			Mkparents:  dashp,
			Flush:      flush,
			CidBuilder: prefix,
902
		})
903
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
904
			res.SetError(err, cmdkit.ErrNormal)
905
			return
Jeromy's avatar
Jeromy committed
906
		}
keks's avatar
keks committed
907

Jan Winkelmann's avatar
Jan Winkelmann committed
908
		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
909 910 911
	},
}

Michael Muré's avatar
Michael Muré committed
912
var filesFlushCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
913
	Helptext: cmdkit.HelpText{
914
		Tagline: "Flush a given path's data to disk.",
Jeromy's avatar
Jeromy committed
915
		ShortDescription: `
916
Flush a given path to disk. This is only useful when other commands
Jeromy's avatar
Jeromy committed
917 918 919
are run with the '--flush=false'.
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
920 921
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", false, false, "Path to flush. Default: '/'."),
Jeromy's avatar
Jeromy committed
922
	},
Michael Muré's avatar
Michael Muré committed
923
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
924 925
		nd, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
926
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
927 928 929 930 931 932 933 934 935 936
			return
		}

		path := "/"
		if len(req.Arguments()) > 0 {
			path = req.Arguments()[0]
		}

		err = mfs.FlushPath(nd.FilesRoot, path)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
937
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
938 939
			return
		}
Jan Winkelmann's avatar
Jan Winkelmann committed
940 941

		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
942 943 944
	},
}

Michael Muré's avatar
Michael Muré committed
945
var filesChcidCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
946
	Helptext: cmdkit.HelpText{
947
		Tagline: "Change the cid version or hash function of the root node of a given path.",
Kevin Atkinson's avatar
Kevin Atkinson committed
948
		ShortDescription: `
949
Change the cid version or hash function of the root node of a given path.
Kevin Atkinson's avatar
Kevin Atkinson committed
950 951
`,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
952 953
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", false, false, "Path to change. Default: '/'."),
Kevin Atkinson's avatar
Kevin Atkinson committed
954
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
955
	Options: []cmdkit.Option{
956 957 958
		cidVersionOption,
		hashOption,
	},
Michael Muré's avatar
Michael Muré committed
959
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Kevin Atkinson's avatar
Kevin Atkinson committed
960 961
		nd, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
962
			res.SetError(err, cmdkit.ErrNormal)
Kevin Atkinson's avatar
Kevin Atkinson committed
963 964 965 966 967 968 969 970
			return
		}

		path := "/"
		if len(req.Arguments()) > 0 {
			path = req.Arguments()[0]
		}

Kejie Zhang's avatar
Kejie Zhang committed
971
		flush, _, _ := req.Option(filesFlushOptionName).Bool()
Kevin Atkinson's avatar
Kevin Atkinson committed
972 973 974

		prefix, err := getPrefix(req)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
975
			res.SetError(err, cmdkit.ErrNormal)
Kevin Atkinson's avatar
Kevin Atkinson committed
976 977 978 979 980
			return
		}

		err = updatePath(nd.FilesRoot, path, prefix, flush)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
981
			res.SetError(err, cmdkit.ErrNormal)
Kevin Atkinson's avatar
Kevin Atkinson committed
982 983
			return
		}
keks's avatar
keks committed
984 985

		res.SetOutput(nil)
Kevin Atkinson's avatar
Kevin Atkinson committed
986 987 988
	},
}

989 990
func updatePath(rt *mfs.Root, pth string, builder cid.Builder, flush bool) error {
	if builder == nil {
Kevin Atkinson's avatar
Kevin Atkinson committed
991 992 993 994 995 996 997 998 999 1000
		return nil
	}

	nd, err := mfs.Lookup(rt, pth)
	if err != nil {
		return err
	}

	switch n := nd.(type) {
	case *mfs.Directory:
1001
		n.SetCidBuilder(builder)
Kevin Atkinson's avatar
Kevin Atkinson committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	default:
		return fmt.Errorf("can only update directories")
	}

	if flush {
		nd.Flush()
	}

	return nil
}

Michael Muré's avatar
Michael Muré committed
1013
var filesRmCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
1014
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
1015
		Tagline: "Remove a file.",
Jeromy's avatar
Jeromy committed
1016
		ShortDescription: `
1017
Remove files or directories.
Jeromy's avatar
Jeromy committed
1018 1019 1020 1021 1022 1023 1024 1025

    $ ipfs files rm /foo
    $ ipfs files ls /bar
    cat
    dog
    fish
    $ ipfs files rm -r /bar
`,
Jeromy's avatar
Jeromy committed
1026 1027
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
1028 1029
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, true, "File to remove."),
Jeromy's avatar
Jeromy committed
1030
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
1031 1032
	Options: []cmdkit.Option{
		cmdkit.BoolOption("recursive", "r", "Recursively remove directories."),
1033
		cmdkit.BoolOption("force", "Forcibly remove target at path; implies -r for directories"),
Jeromy's avatar
Jeromy committed
1034
	},
Michael Muré's avatar
Michael Muré committed
1035
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jan Winkelmann's avatar
Jan Winkelmann committed
1036 1037
		defer res.SetOutput(nil)

Jeromy's avatar
Jeromy committed
1038 1039
		nd, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1040
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1041 1042 1043
			return
		}

Jeromy's avatar
Jeromy committed
1044 1045
		path, err := checkPath(req.Arguments()[0])
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1046
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1047 1048 1049 1050
			return
		}

		if path == "/" {
Jan Winkelmann's avatar
Jan Winkelmann committed
1051
			res.SetError(fmt.Errorf("cannot delete root"), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1052 1053 1054 1055 1056 1057 1058 1059
			return
		}

		// 'rm a/b/c/' will fail unless we trim the slash at the end
		if path[len(path)-1] == '/' {
			path = path[:len(path)-1]
		}

Jeromy's avatar
Jeromy committed
1060 1061 1062
		dir, name := gopath.Split(path)
		parent, err := mfs.Lookup(nd.FilesRoot, dir)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1063
			res.SetError(fmt.Errorf("parent lookup: %s", err), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1064 1065 1066 1067 1068
			return
		}

		pdir, ok := parent.(*mfs.Directory)
		if !ok {
Michael Muré's avatar
Michael Muré committed
1069
			res.SetError(fmt.Errorf("no such file or directory: %s", path), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1070 1071 1072
			return
		}

Jeromy's avatar
Jeromy committed
1073 1074 1075 1076 1077
		var success bool
		defer func() {
			if success {
				err := pdir.Flush()
				if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1078
					res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1079 1080 1081 1082 1083
					return
				}
			}
		}()

1084 1085 1086 1087
		// if '--force' specified, it will remove anything else,
		// including file, directory, corrupted node, etc
		force, _, _ := req.Option("force").Bool()
		if force {
Jeromy's avatar
Jeromy committed
1088 1089
			err := pdir.Unlink(name)
			if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1090
				res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1091 1092 1093
				return
			}

Jeromy's avatar
Jeromy committed
1094
			success = true
Jeromy's avatar
Jeromy committed
1095 1096 1097
			return
		}

1098 1099 1100
		// get child node by name, when the node is corrupted and nonexistent,
		// it will return specific error.
		child, err := pdir.Child(name)
Jeromy's avatar
Jeromy committed
1101
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1102
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1103 1104 1105
			return
		}

1106 1107 1108
		dashr, _, _ := req.Option("r").Bool()

		switch child.(type) {
Jeromy's avatar
Jeromy committed
1109
		case *mfs.Directory:
1110 1111
			if !dashr {
				res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1112 1113
				return
			}
1114
		}
Jeromy's avatar
Jeromy committed
1115

1116 1117 1118 1119
		err = pdir.Unlink(name)
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
Jeromy's avatar
Jeromy committed
1120
		}
1121 1122

		success = true
Jeromy's avatar
Jeromy committed
1123 1124 1125
	},
}

1126
func getPrefixNew(req *cmds.Request) (cid.Builder, error) {
Kejie Zhang's avatar
Kejie Zhang committed
1127 1128
	cidVer, cidVerSet := req.Options[filesCidVersionOptionName].(int)
	hashFunStr, hashFunSet := req.Options[filesHashOptionName].(string)
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

	if !cidVerSet && !hashFunSet {
		return nil, nil
	}

	if hashFunSet && cidVer == 0 {
		cidVer = 1
	}

	prefix, err := dag.PrefixForCidVersion(cidVer)
	if err != nil {
		return nil, err
	}

	if hashFunSet {
		hashFunCode, ok := mh.Names[strings.ToLower(hashFunStr)]
		if !ok {
			return nil, fmt.Errorf("unrecognized hash function: %s", strings.ToLower(hashFunStr))
		}
		prefix.MhType = hashFunCode
		prefix.MhLength = -1
	}

	return &prefix, nil
}

1155
func getPrefix(req oldcmds.Request) (cid.Builder, error) {
Kejie Zhang's avatar
Kejie Zhang committed
1156 1157
	cidVer, cidVerSet, _ := req.Option(filesCidVersionOptionName).Int()
	hashFunStr, hashFunSet, _ := req.Option(filesHashOptionName).String()
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170

	if !cidVerSet && !hashFunSet {
		return nil, nil
	}

	if hashFunSet && cidVer == 0 {
		cidVer = 1
	}

	prefix, err := dag.PrefixForCidVersion(cidVer)
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
1171

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
	if hashFunSet {
		hashFunCode, ok := mh.Names[strings.ToLower(hashFunStr)]
		if !ok {
			return nil, fmt.Errorf("unrecognized hash function: %s", strings.ToLower(hashFunStr))
		}
		prefix.MhType = hashFunCode
		prefix.MhLength = -1
	}

	return &prefix, nil
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
func ensureContainingDirectoryExists(r *mfs.Root, path string, builder cid.Builder) error {
	dirtomake := gopath.Dir(path)

	if dirtomake == "/" {
		return nil
	}

	return mfs.Mkdir(r, dirtomake, mfs.MkdirOpts{
		Mkparents:  true,
		CidBuilder: builder,
	})
}

1197
func getFileHandle(r *mfs.Root, path string, create bool, builder cid.Builder) (*mfs.File, error) {
Jeromy's avatar
Jeromy committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
	target, err := mfs.Lookup(r, path)
	switch err {
	case nil:
		fi, ok := target.(*mfs.File)
		if !ok {
			return nil, fmt.Errorf("%s was not a file", path)
		}
		return fi, nil

	case os.ErrNotExist:
		if !create {
			return nil, err
		}

		// if create is specified and the file doesnt exist, we create the file
		dirname, fname := gopath.Split(path)
		pdiri, err := mfs.Lookup(r, dirname)
		if err != nil {
1216
			flog.Error("lookupfail ", dirname)
Jeromy's avatar
Jeromy committed
1217 1218 1219 1220 1221 1222
			return nil, err
		}
		pdir, ok := pdiri.(*mfs.Directory)
		if !ok {
			return nil, fmt.Errorf("%s was not a directory", dirname)
		}
1223 1224
		if builder == nil {
			builder = pdir.GetCidBuilder()
1225
		}
Jeromy's avatar
Jeromy committed
1226

1227
		nd := dag.NodeWithData(ft.FilePBData(nil, 0))
1228
		nd.SetCidBuilder(builder)
Jeromy's avatar
Jeromy committed
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
		err = pdir.AddChild(fname, nd)
		if err != nil {
			return nil, err
		}

		fsn, err := pdir.Child(fname)
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
1239 1240
		fi, ok := fsn.(*mfs.File)
		if !ok {
Michael Muré's avatar
Michael Muré committed
1241
			return nil, errors.New("expected *mfs.File, didnt get it. This is likely a race condition")
Jeromy's avatar
Jeromy committed
1242 1243
		}
		return fi, nil
Jeromy's avatar
Jeromy committed
1244 1245 1246 1247 1248

	default:
		return nil, err
	}
}
Jeromy's avatar
Jeromy committed
1249 1250 1251

func checkPath(p string) (string, error) {
	if len(p) == 0 {
Michael Muré's avatar
Michael Muré committed
1252
		return "", fmt.Errorf("paths must not be empty")
Jeromy's avatar
Jeromy committed
1253 1254 1255
	}

	if p[0] != '/' {
Michael Muré's avatar
Michael Muré committed
1256
		return "", fmt.Errorf("paths must start with a leading slash")
Jeromy's avatar
Jeromy committed
1257 1258 1259 1260 1261 1262 1263 1264
	}

	cleaned := gopath.Clean(p)
	if p[len(p)-1] == '/' && p != "/" {
		cleaned += "/"
	}
	return cleaned, nil
}