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"
24
	cmds "gx/ipfs/QmRRovo1DE6i5cMjCbf19mQCSuszF6SKwdZNUMS7MtBnH1/go-ipfs-cmds"
Steven Allen's avatar
Steven Allen committed
25
	bservice "gx/ipfs/QmSU7Nx5eUHWkc9zCTiXDu3ZkdXAZdRgRGRaKM86VjGU4m/go-blockservice"
Steven Allen's avatar
Steven Allen committed
26
	offline "gx/ipfs/QmT6dHGp3UYd3vUMpy7rzX2CXQv7HLcj42Vtq8qwwjgASb/go-ipfs-exchange-offline"
Steven Allen's avatar
Steven Allen committed
27
	dag "gx/ipfs/QmVvNkTCx8V9Zei8xuTYTBdUXmbnDRS4iNuw1SztYyhQwQ/go-merkledag"
28
	ft "gx/ipfs/QmWE6Ftsk98cG2MTVgH4wJT8VP2nL9TuBkYTrz9GSqcsh5/go-unixfs"
Steven Allen's avatar
Steven Allen committed
29
	logging "gx/ipfs/QmZChCsSt8DctjceaL56Eibc29CVQq4dGKRXC5JRZ6Ppae/go-log"
30
	ipld "gx/ipfs/QmdDXJs4axxefSPgK6Y1QhpJWKuDPnGJiqgq4uncb4rFHL/go-ipld-format"
31 32
	cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
	mfs "gx/ipfs/Qmf5gumjmXpwmn7uDfAvkXbFQ5sHGGbJGccS8znSYmDQaz/go-mfs"
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)
Overbool's avatar
Overbool committed
482
			out := &filesLsOutput{[]mfs.NodeListing{{Name: name}}}
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
			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
			for _, o := range out.Entries {
				if long {
Overbool's avatar
Overbool committed
530 531 532
					if o.Type == int(mfs.TDir) {
						o.Name += "/"
					}
Jeromy's avatar
Jeromy committed
533 534 535 536 537 538 539 540
					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
541
	Type: filesLsOutput{},
Jeromy's avatar
Jeromy committed
542 543
}

Kejie Zhang's avatar
Kejie Zhang committed
544 545 546 547 548
const (
	filesOffsetOptionName = "offset"
	filesCountOptionName  = "count"
)

Michael Muré's avatar
Michael Muré committed
549
var filesReadCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
550
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
551
		Tagline: "Read a file in a given mfs.",
Jeromy's avatar
Jeromy committed
552
		ShortDescription: `
553 554
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
555 556 557 558 559

Examples:

    $ ipfs files read /test/hello
    hello
Jeromy's avatar
Jeromy committed
560
        `,
Jeromy's avatar
Jeromy committed
561 562
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
563 564
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("path", true, false, "Path to file to be read."),
Jeromy's avatar
Jeromy committed
565
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
566
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
567 568
		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
569
	},
Michael Muré's avatar
Michael Muré committed
570
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
571 572
		n, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
573
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
574 575 576
			return
		}

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

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

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

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

		defer rfd.Close()

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

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

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

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

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

		res.SetOutput(r)
	},
}

Jeromy's avatar
Jeromy committed
648 649 650 651 652 653 654 655 656 657 658 659 660
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
661
var filesMvCmd = &oldcmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
662
	Helptext: cmdkit.HelpText{
rht's avatar
rht committed
663
		Tagline: "Move files.",
Jeromy's avatar
Jeromy committed
664 665 666 667 668 669 670
		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
671
`,
Jeromy's avatar
Jeromy committed
672 673
	},

Jan Winkelmann's avatar
Jan Winkelmann committed
674 675 676
	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
677
	},
Michael Muré's avatar
Michael Muré committed
678
	Run: func(req oldcmds.Request, res oldcmds.Response) {
Jeromy's avatar
Jeromy committed
679 680
		n, err := req.InvocContext().GetNode()
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
681
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
682 683 684
			return
		}

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

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

		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
703 704 705
	},
}

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

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

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

725 726 727 728 729 730 731
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.

732 733 734 735
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.

736
EXAMPLE:
Jeromy's avatar
Jeromy committed
737

Jeromy's avatar
Jeromy committed
738 739
    echo "hello world" | ipfs files write --create /myfs/a/b/file
    echo "hello world" | ipfs files write --truncate /myfs/a/b/file
740

741
WARNING:
742

743 744 745
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
746
`,
Jeromy's avatar
Jeromy committed
747
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
748 749 750
	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
751
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
752
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
753 754 755 756 757 758
		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)"),
759 760
		cidVersionOption,
		hashOption,
Jeromy's avatar
Jeromy committed
761
	},
keks's avatar
keks committed
762
	Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) (retErr error) {
763
		path, err := checkPath(req.Arguments[0])
Jeromy's avatar
Jeromy committed
764
		if err != nil {
keks's avatar
keks committed
765
			return err
Jeromy's avatar
Jeromy committed
766 767
		}

Kejie Zhang's avatar
Kejie Zhang committed
768 769 770 771 772
		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)
773

774
		prefix, err := getPrefixNew(req)
775
		if err != nil {
keks's avatar
keks committed
776
			return err
777
		}
Jeromy's avatar
Jeromy committed
778

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

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

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

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

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

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

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

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

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

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

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

Jan Winkelmann's avatar
Jan Winkelmann committed
847
		_, err = io.Copy(wfd, r)
keks's avatar
keks committed
848
		return err
Jeromy's avatar
Jeromy committed
849 850 851
	},
}

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

858 859 860
The directory will have the same CID version and hash function of the
parent directory unless the --cid-version and --hash options are used.

861
NOTE: All paths must be absolute.
Jeromy's avatar
Jeromy committed
862 863 864

Examples:

865 866
    $ ipfs files mkdir /test/newdir
    $ ipfs files mkdir -p /test/does/not/exist/yet
Jeromy's avatar
Jeromy committed
867 868 869
`,
	},

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

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

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

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

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

Jan Winkelmann's avatar
Jan Winkelmann committed
911
		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
912 913 914
	},
}

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

		res.SetOutput(nil)
Jeromy's avatar
Jeromy committed
945 946 947
	},
}

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

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

Kejie Zhang's avatar
Kejie Zhang committed
974
		flush, _, _ := req.Option(filesFlushOptionName).Bool()
Kevin Atkinson's avatar
Kevin Atkinson committed
975 976 977

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

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

		res.SetOutput(nil)
Kevin Atkinson's avatar
Kevin Atkinson committed
989 990 991
	},
}

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

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

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

	if flush {
		nd.Flush()
	}

	return nil
}

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

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

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

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

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

		if path == "/" {
Jan Winkelmann's avatar
Jan Winkelmann committed
1054
			res.SetError(fmt.Errorf("cannot delete root"), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1055 1056 1057 1058 1059 1060 1061 1062
			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
1063 1064 1065
		dir, name := gopath.Split(path)
		parent, err := mfs.Lookup(nd.FilesRoot, dir)
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1066
			res.SetError(fmt.Errorf("parent lookup: %s", err), cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1067 1068 1069 1070 1071
			return
		}

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

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

1087 1088 1089 1090
		// 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
1091 1092
			err := pdir.Unlink(name)
			if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1093
				res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1094 1095 1096
				return
			}

Jeromy's avatar
Jeromy committed
1097
			success = true
Jeromy's avatar
Jeromy committed
1098 1099 1100
			return
		}

1101 1102 1103
		// 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
1104
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
1105
			res.SetError(err, cmdkit.ErrNormal)
Jeromy's avatar
Jeromy committed
1106 1107 1108
			return
		}

1109 1110 1111
		dashr, _, _ := req.Option("r").Bool()

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

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

		success = true
Jeromy's avatar
Jeromy committed
1126 1127 1128
	},
}

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

	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
}

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

	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
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
	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
}

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
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,
	})
}

1200
func getFileHandle(r *mfs.Root, path string, create bool, builder cid.Builder) (*mfs.File, error) {
Jeromy's avatar
Jeromy committed
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
	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 {
1219
			flog.Error("lookupfail ", dirname)
Jeromy's avatar
Jeromy committed
1220 1221 1222 1223 1224 1225
			return nil, err
		}
		pdir, ok := pdiri.(*mfs.Directory)
		if !ok {
			return nil, fmt.Errorf("%s was not a directory", dirname)
		}
1226 1227
		if builder == nil {
			builder = pdir.GetCidBuilder()
1228
		}
Jeromy's avatar
Jeromy committed
1229

1230
		nd := dag.NodeWithData(ft.FilePBData(nil, 0))
1231
		nd.SetCidBuilder(builder)
Jeromy's avatar
Jeromy committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
		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
1242 1243
		fi, ok := fsn.(*mfs.File)
		if !ok {
Michael Muré's avatar
Michael Muré committed
1244
			return nil, errors.New("expected *mfs.File, didnt get it. This is likely a race condition")
Jeromy's avatar
Jeromy committed
1245 1246
		}
		return fi, nil
Jeromy's avatar
Jeromy committed
1247 1248 1249 1250 1251

	default:
		return nil, err
	}
}
Jeromy's avatar
Jeromy committed
1252 1253 1254

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

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

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