-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.go
1076 lines (917 loc) · 24.2 KB
/
files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package commands
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
gopath "path"
"strings"
cmds "github.com/ipfs/go-ipfs/commands"
core "github.com/ipfs/go-ipfs/core"
dag "github.com/ipfs/go-ipfs/merkledag"
mfs "github.com/ipfs/go-ipfs/mfs"
path "github.com/ipfs/go-ipfs/path"
ft "github.com/ipfs/go-ipfs/unixfs"
uio "github.com/ipfs/go-ipfs/unixfs/io"
cid "gx/ipfs/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ/go-cid"
node "gx/ipfs/QmPN7cwmpcc4DWXb4KTB9dNAJgjuPY69h3npsMfhRrQL9c/go-ipld-format"
logging "gx/ipfs/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52/go-log"
mh "gx/ipfs/QmU9a9NV9RdPNwZQDYd5uKsm6N6LJLSvLbywDDYFbaaC6P/go-multihash"
)
var log = logging.Logger("cmds/files")
var FilesCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Interact with unixfs files.",
ShortDescription: `
Files is an API for manipulating IPFS objects as if they were a unix
filesystem.
NOTE:
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.
`,
},
Options: []cmds.Option{
cmds.BoolOption("f", "flush", "Flush target and ancestors after write.").Default(true),
},
Subcommands: map[string]*cmds.Command{
"read": FilesReadCmd,
"write": FilesWriteCmd,
"mv": FilesMvCmd,
"cp": FilesCpCmd,
"ls": FilesLsCmd,
"mkdir": FilesMkdirCmd,
"stat": FilesStatCmd,
"rm": FilesRmCmd,
"flush": FilesFlushCmd,
"chcid": FilesChcidCmd,
},
}
var cidVersionOption = cmds.IntOption("cid-version", "cid-ver", "Cid version to use. (experimental)")
var hashOption = cmds.StringOption("hash", "Hash function to use. Will set Cid version to 1 if used. (experimental)")
var formatError = errors.New("Format was set by multiple options. Only one format option is allowed")
var FilesStatCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Display file status.",
},
Arguments: []cmds.Argument{
cmds.StringArg("path", true, false, "Path to node to stat."),
},
Options: []cmds.Option{
cmds.StringOption("format", "Print statistics in given format. Allowed tokens: "+
"<hash> <size> <cumulsize> <type> <childs>. Conflicts with other format options.").Default(
`<hash>
Size: <size>
CumulativeSize: <cumulsize>
ChildBlocks: <childs>
Type: <type>`),
cmds.BoolOption("hash", "Print only hash. Implies '--format=<hash>'. Conflicts with other format options.").Default(false),
cmds.BoolOption("size", "Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options.").Default(false),
},
Run: func(req cmds.Request, res cmds.Response) {
_, err := statGetFormatOptions(req)
if err != nil {
res.SetError(err, cmds.ErrClient)
}
node, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
path, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fsn, err := mfs.Lookup(node.FilesRoot, path)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
o, err := statNode(node.DAG, fsn)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
res.SetOutput(o)
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
out := res.Output().(*Object)
buf := new(bytes.Buffer)
s, _ := statGetFormatOptions(res.Request())
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)
fmt.Fprintln(buf, s)
return buf, nil
},
},
Type: Object{},
}
func moreThanOne(a, b, c bool) bool {
return a && b || b && c || a && c
}
func statGetFormatOptions(req cmds.Request) (string, error) {
hash, _, _ := req.Option("hash").Bool()
size, _, _ := req.Option("size").Bool()
format, found, _ := req.Option("format").String()
if moreThanOne(hash, size, found) {
return "", formatError
}
if hash {
return "<hash>", nil
} else if size {
return "<cumulsize>", nil
} else {
return format, nil
}
}
func statNode(ds dag.DAGService, fsn mfs.FSNode) (*Object, error) {
nd, err := fsn.GetNode()
if err != nil {
return nil, err
}
c := nd.Cid()
cumulsize, err := nd.Size()
if err != nil {
return nil, err
}
switch n := nd.(type) {
case *dag.ProtoNode:
d, err := ft.FromBytes(n.Data())
if err != nil {
return nil, err
}
var ndtype string
switch fsn.Type() {
case mfs.TDir:
ndtype = "directory"
case mfs.TFile:
ndtype = "file"
default:
return nil, fmt.Errorf("unrecognized node type: %s", fsn.Type())
}
return &Object{
Hash: c.String(),
Blocks: len(nd.Links()),
Size: d.GetFilesize(),
CumulativeSize: cumulsize,
Type: ndtype,
}, nil
case *dag.RawNode:
return &Object{
Hash: c.String(),
Blocks: 0,
Size: cumulsize,
CumulativeSize: cumulsize,
Type: "file",
}, nil
default:
return nil, fmt.Errorf("not unixfs node (proto or raw)")
}
}
var FilesCpCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Copy files into mfs.",
},
Arguments: []cmds.Argument{
cmds.StringArg("source", true, false, "Source object to copy."),
cmds.StringArg("dest", true, false, "Destination to copy object to."),
},
Run: func(req cmds.Request, res cmds.Response) {
node, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
flush, _, _ := req.Option("flush").Bool()
src, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
src = strings.TrimRight(src, "/")
dst, err := checkPath(req.Arguments()[1])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if dst[len(dst)-1] == '/' {
dst += gopath.Base(src)
}
nd, err := getNodeFromPath(req.Context(), node, src)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
err = mfs.PutNode(node.FilesRoot, dst, nd)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if flush {
err := mfs.FlushPath(node.FilesRoot, dst)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
}
},
}
func getNodeFromPath(ctx context.Context, node *core.IpfsNode, p string) (node.Node, error) {
switch {
case strings.HasPrefix(p, "/ipfs/"):
np, err := path.ParsePath(p)
if err != nil {
return nil, err
}
resolver := &path.Resolver{
DAG: node.DAG,
ResolveOnce: uio.ResolveUnixfsOnce,
}
return core.Resolve(ctx, node.Namesys, resolver, np)
default:
fsn, err := mfs.Lookup(node.FilesRoot, p)
if err != nil {
return nil, err
}
return fsn.GetNode()
}
}
type Object struct {
Hash string
Size uint64
CumulativeSize uint64
Blocks int
Type string
}
type FilesLsOutput struct {
Entries []mfs.NodeListing
}
var FilesLsCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List directories in the local mutable namespace.",
ShortDescription: `
List directories in the local mutable namespace.
Examples:
$ ipfs files ls /welcome/docs/
about
contact
help
quick-start
readme
security-notes
$ ipfs files ls /myfiles/a/b/c/d
foo
bar
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", false, false, "Path to show listing for. Defaults to '/'."),
},
Options: []cmds.Option{
cmds.BoolOption("l", "Use long listing format."),
},
Run: func(req cmds.Request, res cmds.Response) {
var arg string
if len(req.Arguments()) == 0 {
arg = "/"
} else {
arg = req.Arguments()[0]
}
path, err := checkPath(arg)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
nd, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fsn, err := mfs.Lookup(nd.FilesRoot, path)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
long, _, _ := req.Option("l").Bool()
switch fsn := fsn.(type) {
case *mfs.Directory:
if !long {
var output []mfs.NodeListing
names, err := fsn.ListNames(req.Context())
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
for _, name := range names {
output = append(output, mfs.NodeListing{
Name: name,
})
}
res.SetOutput(&FilesLsOutput{output})
} else {
listing, err := fsn.List(req.Context())
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
res.SetOutput(&FilesLsOutput{listing})
}
return
case *mfs.File:
_, name := gopath.Split(path)
out := &FilesLsOutput{[]mfs.NodeListing{mfs.NodeListing{Name: name, Type: 1}}}
res.SetOutput(out)
return
default:
res.SetError(errors.New("unrecognized type"), cmds.ErrNormal)
}
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
out := res.Output().(*FilesLsOutput)
buf := new(bytes.Buffer)
long, _, _ := res.Request().Option("l").Bool()
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
},
},
Type: FilesLsOutput{},
}
var FilesReadCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Read a file in a given mfs.",
ShortDescription: `
Read a specified number of bytes from a file at a given offset. By default,
will read the entire file similar to unix cat.
Examples:
$ ipfs files read /test/hello
hello
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", true, false, "Path to file to be read."),
},
Options: []cmds.Option{
cmds.IntOption("offset", "o", "Byte offset to begin reading from."),
cmds.IntOption("count", "n", "Maximum number of bytes to read."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
path, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fsn, err := mfs.Lookup(n.FilesRoot, path)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
fi, ok := fsn.(*mfs.File)
if !ok {
res.SetError(fmt.Errorf("%s was not a file.", path), cmds.ErrNormal)
return
}
rfd, err := fi.Open(mfs.OpenReadOnly, false)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
defer rfd.Close()
offset, _, err := req.Option("offset").Int()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if offset < 0 {
res.SetError(fmt.Errorf("Cannot specify negative offset."), cmds.ErrNormal)
return
}
filen, err := rfd.Size()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if int64(offset) > filen {
res.SetError(fmt.Errorf("Offset was past end of file (%d > %d).", offset, filen), cmds.ErrNormal)
return
}
_, err = rfd.Seek(int64(offset), io.SeekStart)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
var r io.Reader = &contextReaderWrapper{R: rfd, ctx: req.Context()}
count, found, err := req.Option("count").Int()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if found {
if count < 0 {
res.SetError(fmt.Errorf("Cannot specify negative 'count'."), cmds.ErrNormal)
return
}
r = io.LimitReader(r, int64(count))
}
res.SetOutput(r)
},
}
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)
}
var FilesMvCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Move files.",
ShortDescription: `
Move files around. Just like traditional unix mv.
Example:
$ ipfs files mv /myfs/a/b/c /myfs/foo/newc
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("source", true, false, "Source file to move."),
cmds.StringArg("dest", true, false, "Destination path for file to be moved to."),
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
src, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dst, err := checkPath(req.Arguments()[1])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
err = mfs.Mv(n.FilesRoot, src, dst)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
},
}
var FilesWriteCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Write to a mutable file in a given filesystem.",
ShortDescription: `
Write data to a file in a given filesystem. This command allows you to specify
a beginning offset to write to. The entire length of the input will be
written.
If the '--create' option is specified, the file will be created if it does not
exist. Nonexistant intermediate directories will not be created.
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.
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.
EXAMPLE:
echo "hello world" | ipfs files write --create /myfs/a/b/file
echo "hello world" | ipfs files write --truncate /myfs/a/b/file
WARNING:
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.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", true, false, "Path to write to."),
cmds.FileArg("data", true, false, "Data to write.").EnableStdin(),
},
Options: []cmds.Option{
cmds.IntOption("offset", "o", "Byte offset to begin writing at."),
cmds.BoolOption("create", "e", "Create the file if it does not exist."),
cmds.BoolOption("truncate", "t", "Truncate the file to size zero before writing."),
cmds.IntOption("count", "n", "Maximum number of bytes to read."),
cmds.BoolOption("raw-leaves", "Use raw blocks for newly created leaf nodes. (experimental)"),
cidVersionOption,
hashOption,
},
Run: func(req cmds.Request, res cmds.Response) {
path, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
create, _, _ := req.Option("create").Bool()
trunc, _, _ := req.Option("truncate").Bool()
flush, _, _ := req.Option("flush").Bool()
rawLeaves, rawLeavesDef, _ := req.Option("raw-leaves").Bool()
prefix, err := getPrefix(req)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
nd, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
offset, _, err := req.Option("offset").Int()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if offset < 0 {
res.SetError(fmt.Errorf("cannot have negative write offset"), cmds.ErrNormal)
return
}
fi, err := getFileHandle(nd.FilesRoot, path, create, prefix)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if rawLeavesDef {
fi.RawLeaves = rawLeaves
}
wfd, err := fi.Open(mfs.OpenWriteOnly, flush)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
defer func() {
err := wfd.Close()
if err != nil {
res.SetError(err, cmds.ErrNormal)
}
}()
if trunc {
if err := wfd.Truncate(0); err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
}
count, countfound, err := req.Option("count").Int()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if countfound && count < 0 {
res.SetError(fmt.Errorf("cannot have negative byte count"), cmds.ErrNormal)
return
}
_, err = wfd.Seek(int64(offset), io.SeekStart)
if err != nil {
log.Error("seekfail: ", err)
res.SetError(err, cmds.ErrNormal)
return
}
input, err := req.Files().NextFile()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
var r io.Reader = input
if countfound {
r = io.LimitReader(r, int64(count))
}
n, err := io.Copy(wfd, r)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
log.Debugf("wrote %d bytes to %s", n, path)
},
}
var FilesMkdirCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Make directories.",
ShortDescription: `
Create the directory if it does not already exist.
The directory will have the same CID version and hash function of the
parent directory unless the --cid-version and --hash options are used.
NOTE: All paths must be absolute.
Examples:
$ ipfs mfs mkdir /test/newdir
$ ipfs mfs mkdir -p /test/does/not/exist/yet
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", true, false, "Path to dir to make."),
},
Options: []cmds.Option{
cmds.BoolOption("parents", "p", "No error if existing, make parent directories as needed."),
cidVersionOption,
hashOption,
},
Run: func(req cmds.Request, res cmds.Response) {
n, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dashp, _, _ := req.Option("parents").Bool()
dirtomake, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
flush, _, _ := req.Option("flush").Bool()
prefix, err := getPrefix(req)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
root := n.FilesRoot
err = mfs.Mkdir(root, dirtomake, mfs.MkdirOpts{
Mkparents: dashp,
Flush: flush,
Prefix: prefix,
})
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
},
}
var FilesFlushCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Flush a given path's data to disk.",
ShortDescription: `
Flush a given path to disk. This is only useful when other commands
are run with the '--flush=false'.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", false, false, "Path to flush. Default: '/'."),
},
Run: func(req cmds.Request, res cmds.Response) {
nd, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
path := "/"
if len(req.Arguments()) > 0 {
path = req.Arguments()[0]
}
err = mfs.FlushPath(nd.FilesRoot, path)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
},
}
var FilesChcidCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Change the cid version or hash function of the root node of a given path.",
ShortDescription: `
Change the cid version or hash function of the root node of a given path.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", false, false, "Path to change. Default: '/'."),
},
Options: []cmds.Option{
cidVersionOption,
hashOption,
},
Run: func(req cmds.Request, res cmds.Response) {
nd, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
path := "/"
if len(req.Arguments()) > 0 {
path = req.Arguments()[0]
}
flush, _, _ := req.Option("flush").Bool()
prefix, err := getPrefix(req)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
err = updatePath(nd.FilesRoot, path, prefix, flush)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
},
}
func updatePath(rt *mfs.Root, pth string, prefix *cid.Prefix, flush bool) error {
if prefix == nil {
return nil
}
nd, err := mfs.Lookup(rt, pth)
if err != nil {
return err
}
switch n := nd.(type) {
case *mfs.Directory:
n.SetPrefix(prefix)
default:
return fmt.Errorf("can only update directories")
}
if flush {
nd.Flush()
}
return nil
}
var FilesRmCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Remove a file.",
ShortDescription: `
Remove files or directories.
$ ipfs files rm /foo
$ ipfs files ls /bar
cat
dog
fish
$ ipfs files rm -r /bar
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("path", true, true, "File to remove."),
},
Options: []cmds.Option{
cmds.BoolOption("recursive", "r", "Recursively remove directories."),
},
Run: func(req cmds.Request, res cmds.Response) {
nd, err := req.InvocContext().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
path, err := checkPath(req.Arguments()[0])
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
if path == "/" {
res.SetError(fmt.Errorf("cannot delete root"), cmds.ErrNormal)
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]
}
dir, name := gopath.Split(path)
parent, err := mfs.Lookup(nd.FilesRoot, dir)
if err != nil {
res.SetError(fmt.Errorf("parent lookup: %s", err), cmds.ErrNormal)
return
}
pdir, ok := parent.(*mfs.Directory)
if !ok {
res.SetError(fmt.Errorf("No such file or directory: %s", path), cmds.ErrNormal)
return
}
dashr, _, _ := req.Option("r").Bool()
var success bool
defer func() {
if success {
err := pdir.Flush()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
}
}()
// if '-r' specified, don't check file type (in bad scenarios, the block may not exist)
if dashr {
err := pdir.Unlink(name)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
success = true
return
}
childi, err := pdir.Child(name)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
switch childi.(type) {
case *mfs.Directory:
res.SetError(fmt.Errorf("%s is a directory, use -r to remove directories", path), cmds.ErrNormal)
return
default:
err := pdir.Unlink(name)
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
success = true
}
},
}
func getPrefix(req cmds.Request) (*cid.Prefix, error) {
cidVer, cidVerSet, _ := req.Option("cid-version").Int()
hashFunStr, hashFunSet, _ := req.Option("hash").String()
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))