-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathfiles.go
1300 lines (1089 loc) · 31.5 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 (
"context"
"errors"
"fmt"
"io"
"os"
gopath "path"
"sort"
"strings"
humanize "github.com/dustin/go-humanize"
"github.com/ipfs/kubo/core"
"github.com/ipfs/kubo/core/commands/cmdenv"
bservice "github.com/ipfs/go-blockservice"
cid "github.com/ipfs/go-cid"
cidenc "github.com/ipfs/go-cidutil/cidenc"
cmds "github.com/ipfs/go-ipfs-cmds"
offline "github.com/ipfs/go-ipfs-exchange-offline"
ipld "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log"
dag "github.com/ipfs/go-merkledag"
mfs "github.com/ipfs/go-mfs"
ft "github.com/ipfs/go-unixfs"
iface "github.com/ipfs/interface-go-ipfs-core"
path "github.com/ipfs/interface-go-ipfs-core/path"
mh "github.com/multiformats/go-multihash"
)
var flog = logging.Logger("cmds/files")
// FilesCmd is the 'ipfs files' command
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.
The files facility interacts with MFS (Mutable File System). MFS acts as a
single, dynamic filesystem mount. MFS has a root CID that is transparently
updated when a change happens (and can be checked with "ipfs files stat /").
All files and folders within MFS are respected and will not be deleted
during garbage collections. However, a DAG may be referenced in MFS without
being fully available locally (MFS content is lazy loaded when accessed).
MFS is independent from the list of pinned items ("ipfs pin ls"). Calls to
"ipfs pin add" and "ipfs pin rm" will add and remove pins independently of
MFS. If MFS content that was additionally pinned is removed by calling
"ipfs files rm", it will still remain pinned.
Content added with "ipfs add" (which by default also becomes pinned), is not
added to MFS. Any content can be lazily referenced from MFS with the command
"ipfs files cp /ipfs/<cid> /some/path/" (see ipfs files cp --help).
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 run 'ipfs repo gc' concurrently with '--flush=false'
operations.
`,
},
Options: []cmds.Option{
cmds.BoolOption(filesFlushOptionName, "f", "Flush target and ancestors after write.").WithDefault(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,
},
}
const (
filesCidVersionOptionName = "cid-version"
filesHashOptionName = "hash"
)
var cidVersionOption = cmds.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)")
var hashOption = cmds.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)")
var errFormat = errors.New("format was set by multiple options. Only one format option is allowed")
type statOutput struct {
Hash string
Size uint64
CumulativeSize uint64
Blocks int
Type string
WithLocality bool `json:",omitempty"`
Local bool `json:",omitempty"`
SizeLocal uint64 `json:",omitempty"`
}
const (
defaultStatFormat = `<hash>
Size: <size>
CumulativeSize: <cumulsize>
ChildBlocks: <childs>
Type: <type>`
filesFormatOptionName = "format"
filesSizeOptionName = "size"
filesWithLocalOptionName = "with-local"
)
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(filesFormatOptionName, "Print statistics in given format. Allowed tokens: "+
"<hash> <size> <cumulsize> <type> <childs>. Conflicts with other format options.").WithDefault(defaultStatFormat),
cmds.BoolOption(filesHashOptionName, "Print only hash. Implies '--format=<hash>'. Conflicts with other format options."),
cmds.BoolOption(filesSizeOptionName, "Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options."),
cmds.BoolOption(filesWithLocalOptionName, "Compute the amount of the dag that is local, and if possible the total size"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
_, err := statGetFormatOptions(req)
if err != nil {
return cmds.Errorf(cmds.ErrClient, err.Error())
}
node, err := cmdenv.GetNode(env)
if err != nil {
return err
}
api, err := cmdenv.GetApi(env, req)
if err != nil {
return err
}
path, err := checkPath(req.Arguments[0])
if err != nil {
return err
}
withLocal, _ := req.Options[filesWithLocalOptionName].(bool)
enc, err := cmdenv.GetCidEncoder(req)
if err != nil {
return err
}
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
}
nd, err := getNodeFromPath(req.Context, node, api, path)
if err != nil {
return err
}
o, err := statNode(nd, enc)
if err != nil {
return err
}
if !withLocal {
return cmds.EmitOnce(res, o)
}
local, sizeLocal, err := walkBlock(req.Context, dagserv, nd)
if err != nil {
return err
}
o.WithLocality = true
o.Local = local
o.SizeLocal = sizeLocal
return cmds.EmitOnce(res, o)
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *statOutput) error {
s, _ := statGetFormatOptions(req)
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(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
}),
},
Type: statOutput{},
}
func moreThanOne(a, b, c bool) bool {
return a && b || b && c || a && c
}
func statGetFormatOptions(req *cmds.Request) (string, error) {
hash, _ := req.Options[filesHashOptionName].(bool)
size, _ := req.Options[filesSizeOptionName].(bool)
format, _ := req.Options[filesFormatOptionName].(string)
if moreThanOne(hash, size, format != defaultStatFormat) {
return "", errFormat
}
if hash {
return "<hash>", nil
} else if size {
return "<cumulsize>", nil
} else {
return format, nil
}
}
func statNode(nd ipld.Node, enc cidenc.Encoder) (*statOutput, error) {
c := nd.Cid()
cumulsize, err := nd.Size()
if err != nil {
return nil, err
}
switch n := nd.(type) {
case *dag.ProtoNode:
d, err := ft.FSNodeFromBytes(n.Data())
if err != nil {
return nil, err
}
var ndtype string
switch d.Type() {
case ft.TDirectory, ft.THAMTShard:
ndtype = "directory"
case ft.TFile, ft.TMetadata, ft.TRaw:
ndtype = "file"
default:
return nil, fmt.Errorf("unrecognized node type: %s", d.Type())
}
return &statOutput{
Hash: enc.Encode(c),
Blocks: len(nd.Links()),
Size: d.FileSize(),
CumulativeSize: cumulsize,
Type: ndtype,
}, nil
case *dag.RawNode:
return &statOutput{
Hash: enc.Encode(c),
Blocks: 0,
Size: cumulsize,
CumulativeSize: cumulsize,
Type: "file",
}, nil
default:
return nil, fmt.Errorf("not unixfs node (proto or raw)")
}
}
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 ipld.IsNotFound(err) {
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
}
var filesCpCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Add references to IPFS files and directories in MFS (or copy within MFS).",
ShortDescription: `
"ipfs files cp" can be used to add references to any IPFS file or directory
(usually in the form /ipfs/<CID>, but also any resolvable path) into MFS.
This performs a lazy copy: the full DAG will not be fetched, only the root
node being copied.
It can also be used to copy files within MFS, but in the case when an
IPFS-path matches an existing MFS path, the IPFS path wins.
In order to add content to MFS from disk, you can use "ipfs add" to obtain the
IPFS Content Identifier and then "ipfs files cp" to copy it into MFS:
$ ipfs add --quieter --pin=false <your file>
# ...
# ... outputs the root CID at the end
$ ipfs files cp /ipfs/<CID> /your/desired/mfs/path
If you wish to fully copy content from a different IPFS peer into MFS, do not
forget to force IPFS to fetch to full DAG after doing the "cp" operation. i.e:
$ ipfs files cp /ipfs/<CID> /your/desired/mfs/path
$ ipfs pin add <CID>
The lazy-copy feature can also be used to protect partial DAG contents from
garbage collection. i.e. adding the Wikipedia root to MFS would not download
all the Wikipedia, but will prevent any downloaded Wikipedia-DAG content from
being GC'ed.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("source", true, false, "Source IPFS or MFS path to copy."),
cmds.StringArg("dest", true, false, "Destination within MFS."),
},
Options: []cmds.Option{
cmds.BoolOption(filesParentsOptionName, "p", "Make parent directories as needed."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
mkParents, _ := req.Options[filesParentsOptionName].(bool)
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}
prefix, err := getPrefixNew(req)
if err != nil {
return err
}
api, err := cmdenv.GetApi(env, req)
if err != nil {
return err
}
flush, _ := req.Options[filesFlushOptionName].(bool)
src, err := checkPath(req.Arguments[0])
if err != nil {
return err
}
src = strings.TrimRight(src, "/")
dst, err := checkPath(req.Arguments[1])
if err != nil {
return err
}
if dst[len(dst)-1] == '/' {
dst += gopath.Base(src)
}
node, err := getNodeFromPath(req.Context, nd, api, src)
if err != nil {
return fmt.Errorf("cp: cannot get node from path %s: %s", src, err)
}
if mkParents {
err := ensureContainingDirectoryExists(nd.FilesRoot, dst, prefix)
if err != nil {
return err
}
}
err = mfs.PutNode(nd.FilesRoot, dst, node)
if err != nil {
return fmt.Errorf("cp: cannot put node in path %s: %s", dst, err)
}
if flush {
_, err := mfs.FlushPath(req.Context, nd.FilesRoot, dst)
if err != nil {
return fmt.Errorf("cp: cannot flush the created file %s: %s", dst, err)
}
}
return nil
},
}
func getNodeFromPath(ctx context.Context, node *core.IpfsNode, api iface.CoreAPI, p string) (ipld.Node, error) {
switch {
case strings.HasPrefix(p, "/ipfs/"):
return api.ResolveNode(ctx, path.New(p))
default:
fsn, err := mfs.Lookup(node.FilesRoot, p)
if err != nil {
return nil, err
}
return fsn.GetNode()
}
}
type filesLsOutput struct {
Entries []mfs.NodeListing
}
const (
longOptionName = "long"
dontSortOptionName = "U"
)
var filesLsCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List directories in the local mutable namespace.",
ShortDescription: `
List directories in the local mutable namespace (works on both IPFS and MFS paths).
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(longOptionName, "l", "Use long listing format."),
cmds.BoolOption(dontSortOptionName, "Do not sort; list entries in directory order."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
var arg string
if len(req.Arguments) == 0 {
arg = "/"
} else {
arg = req.Arguments[0]
}
path, err := checkPath(arg)
if err != nil {
return err
}
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}
fsn, err := mfs.Lookup(nd.FilesRoot, path)
if err != nil {
return err
}
long, _ := req.Options[longOptionName].(bool)
enc, err := cmdenv.GetCidEncoder(req)
if err != nil {
return err
}
switch fsn := fsn.(type) {
case *mfs.Directory:
if !long {
var output []mfs.NodeListing
names, err := fsn.ListNames(req.Context)
if err != nil {
return err
}
for _, name := range names {
output = append(output, mfs.NodeListing{
Name: name,
})
}
return cmds.EmitOnce(res, &filesLsOutput{output})
}
listing, err := fsn.List(req.Context)
if err != nil {
return err
}
return cmds.EmitOnce(res, &filesLsOutput{listing})
case *mfs.File:
_, name := gopath.Split(path)
out := &filesLsOutput{[]mfs.NodeListing{{Name: name}}}
if long {
out.Entries[0].Type = int(fsn.Type())
size, err := fsn.Size()
if err != nil {
return err
}
out.Entries[0].Size = size
nd, err := fsn.GetNode()
if err != nil {
return err
}
out.Entries[0].Hash = enc.Encode(nd.Cid())
}
return cmds.EmitOnce(res, out)
default:
return errors.New("unrecognized type")
}
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *filesLsOutput) error {
noSort, _ := req.Options[dontSortOptionName].(bool)
if !noSort {
sort.Slice(out.Entries, func(i, j int) bool {
return strings.Compare(out.Entries[i].Name, out.Entries[j].Name) < 0
})
}
long, _ := req.Options[longOptionName].(bool)
for _, o := range out.Entries {
if long {
if o.Type == int(mfs.TDir) {
o.Name += "/"
}
fmt.Fprintf(w, "%s\t%s\t%d\n", o.Name, o.Hash, o.Size)
} else {
fmt.Fprintf(w, "%s\n", o.Name)
}
}
return nil
}),
},
Type: filesLsOutput{},
}
const (
filesOffsetOptionName = "offset"
filesCountOptionName = "count"
)
var filesReadCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Read a file from MFS.",
ShortDescription: `
Read a specified number of bytes from a file at a given offset. By default,
it will read the entire file similar to the 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.Int64Option(filesOffsetOptionName, "o", "Byte offset to begin reading from."),
cmds.Int64Option(filesCountOptionName, "n", "Maximum number of bytes to read."),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}
path, err := checkPath(req.Arguments[0])
if err != nil {
return err
}
fsn, err := mfs.Lookup(nd.FilesRoot, path)
if err != nil {
return err
}
fi, ok := fsn.(*mfs.File)
if !ok {
return fmt.Errorf("%s was not a file", path)
}
rfd, err := fi.Open(mfs.Flags{Read: true})
if err != nil {
return err
}
defer rfd.Close()
offset, _ := req.Options[offsetOptionName].(int64)
if offset < 0 {
return fmt.Errorf("cannot specify negative offset")
}
filen, err := rfd.Size()
if err != nil {
return err
}
if int64(offset) > filen {
return fmt.Errorf("offset was past end of file (%d > %d)", offset, filen)
}
_, err = rfd.Seek(int64(offset), io.SeekStart)
if err != nil {
return err
}
var r io.Reader = &contextReaderWrapper{R: rfd, ctx: req.Context}
count, found := req.Options[filesCountOptionName].(int64)
if found {
if count < 0 {
return fmt.Errorf("cannot specify negative 'count'")
}
r = io.LimitReader(r, int64(count))
}
return res.Emit(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 the 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.ResponseEmitter, env cmds.Environment) error {
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}
flush, _ := req.Options[filesFlushOptionName].(bool)
src, err := checkPath(req.Arguments[0])
if err != nil {
return err
}
dst, err := checkPath(req.Arguments[1])
if err != nil {
return err
}
err = mfs.Mv(nd.FilesRoot, src, dst)
if err == nil && flush {
_, err = mfs.FlushPath(req.Context, nd.FilesRoot, "/")
}
return err
},
}
const (
filesCreateOptionName = "create"
filesParentsOptionName = "parents"
filesTruncateOptionName = "truncate"
filesRawLeavesOptionName = "raw-leaves"
filesFlushOptionName = "flush"
)
var filesWriteCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Append to (modify) a file in MFS.",
ShortDescription: `
A low-level MFS command that allows you to append data to a file. If you want
to add a file without modifying an existing one, use 'ipfs add --to-files'
instead.
`,
LongDescription: `
A low-level MFS command that allows you to append data at the end of a file, or
specify a beginning offset within a file 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. Nonexistent intermediate directories will not be created unless the
'--parents' option is specified.
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 if 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 propagated 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 --parents /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.
WARNING:
The CID produced by 'files write' will be different from 'ipfs add' because
'ipfs file write' creates a trickle-dag optimized for append-only operations
See '--trickle' in 'ipfs add --help' for more information.
If you want to add a file without modifying an existing one,
use 'ipfs add' with '--to-files':
> ipfs files mkdir -p /myfs/dir
> ipfs add example.jpg --to-files /myfs/dir/
> ipfs files ls /myfs/dir/
example.jpg
See '--to-files' in 'ipfs add --help' for more information.
`,
},
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.Int64Option(filesOffsetOptionName, "o", "Byte offset to begin writing at."),
cmds.BoolOption(filesCreateOptionName, "e", "Create the file if it does not exist."),
cmds.BoolOption(filesParentsOptionName, "p", "Make parent directories as needed."),
cmds.BoolOption(filesTruncateOptionName, "t", "Truncate the file to size zero before writing."),
cmds.Int64Option(filesCountOptionName, "n", "Maximum number of bytes to read."),
cmds.BoolOption(filesRawLeavesOptionName, "Use raw blocks for newly created leaf nodes. (experimental)"),
cidVersionOption,
hashOption,
},
Run: func(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment) (retErr error) {
path, err := checkPath(req.Arguments[0])
if err != nil {
return err
}
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)
prefix, err := getPrefixNew(req)
if err != nil {
return err
}
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}
offset, _ := req.Options[filesOffsetOptionName].(int64)
if offset < 0 {
return fmt.Errorf("cannot have negative write offset")
}
if mkParents {
err := ensureContainingDirectoryExists(nd.FilesRoot, path, prefix)
if err != nil {
return err
}
}
fi, err := getFileHandle(nd.FilesRoot, path, create, prefix)
if err != nil {
return err
}
if rawLeavesDef {
fi.RawLeaves = rawLeaves
}
wfd, err := fi.Open(mfs.Flags{Write: true, Sync: flush})
if err != nil {
return err
}
defer func() {
err := wfd.Close()
if err != nil {
if retErr == nil {
retErr = err
} else {
flog.Error("files: error closing file mfs file descriptor", err)
}
}
}()
if trunc {
if err := wfd.Truncate(0); err != nil {
return err
}
}
count, countfound := req.Options[filesCountOptionName].(int64)
if countfound && count < 0 {
return fmt.Errorf("cannot have negative byte count")
}
_, err = wfd.Seek(int64(offset), io.SeekStart)
if err != nil {
flog.Error("seekfail: ", err)
return err
}
var r io.Reader
r, err = cmdenv.GetFileArg(req.Files.Entries())
if err != nil {
return err
}
if countfound {
r = io.LimitReader(r, int64(count))
}
_, err = io.Copy(wfd, r)
return err
},
}
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 files mkdir /test/newdir
$ ipfs files 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(filesParentsOptionName, "p", "No error if existing, make parent directories as needed."),
cidVersionOption,
hashOption,
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
n, err := cmdenv.GetNode(env)
if err != nil {
return err
}
dashp, _ := req.Options[filesParentsOptionName].(bool)
dirtomake, err := checkPath(req.Arguments[0])
if err != nil {
return err
}
flush, _ := req.Options[filesFlushOptionName].(bool)
prefix, err := getPrefix(req)
if err != nil {
return err
}
root := n.FilesRoot
err = mfs.Mkdir(root, dirtomake, mfs.MkdirOpts{
Mkparents: dashp,
Flush: flush,
CidBuilder: prefix,
})
return err
},
}
type flushRes struct {
Cid string
}
var filesFlushCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Flush a given path's data to disk.",
ShortDescription: `
Flush a given path to the 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.ResponseEmitter, env cmds.Environment) error {
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}
enc, err := cmdenv.GetCidEncoder(req)
if err != nil {
return err
}
path := "/"
if len(req.Arguments) > 0 {
path = req.Arguments[0]
}
n, err := mfs.FlushPath(req.Context, nd.FilesRoot, path)
if err != nil {
return err
}
return cmds.EmitOnce(res, &flushRes{enc.Encode(n.Cid())})
},
Type: flushRes{},
}
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.ResponseEmitter, env cmds.Environment) error {
nd, err := cmdenv.GetNode(env)
if err != nil {
return err
}