add.go 12.6 KB
Newer Older
1 2 3
package commands

import (
4
	"errors"
5
	"fmt"
6
	"io"
Jan Winkelmann's avatar
Jan Winkelmann committed
7
	"os"
8
	"path"
9
	"strings"
10

Łukasz Magiera's avatar
Łukasz Magiera committed
11
	"github.com/ipfs/go-ipfs/core/commands/cmdenv"
12

Fazlul Shahriar's avatar
Fazlul Shahriar committed
13
	"github.com/cheggaaa/pb"
Jakub Sztandera's avatar
Jakub Sztandera committed
14
	cmds "github.com/ipfs/go-ipfs-cmds"
15
	files "github.com/ipfs/go-ipfs-files"
Jakub Sztandera's avatar
Jakub Sztandera committed
16
	coreiface "github.com/ipfs/interface-go-ipfs-core"
17
	"github.com/ipfs/interface-go-ipfs-core/options"
Jakub Sztandera's avatar
Jakub Sztandera committed
18
	mh "github.com/multiformats/go-multihash"
19 20
)

Łukasz Magiera's avatar
Łukasz Magiera committed
21
// ErrDepthLimitExceeded indicates that the max depth has been exceeded.
22 23
var ErrDepthLimitExceeded = fmt.Errorf("depth limit exceeded")

24 25 26 27 28 29 30
type AddEvent struct {
	Name  string
	Hash  string `json:",omitempty"`
	Bytes int64  `json:",omitempty"`
	Size  string `json:",omitempty"`
}

31
const (
32
	quietOptionName       = "quiet"
33
	quieterOptionName     = "quieter"
34 35 36 37 38 39 40 41 42 43
	silentOptionName      = "silent"
	progressOptionName    = "progress"
	trickleOptionName     = "trickle"
	wrapOptionName        = "wrap-with-directory"
	onlyHashOptionName    = "only-hash"
	chunkerOptionName     = "chunker"
	pinOptionName         = "pin"
	rawLeavesOptionName   = "raw-leaves"
	noCopyOptionName      = "nocopy"
	fstoreCacheOptionName = "fscache"
44
	cidVersionOptionName  = "cid-version"
45
	hashOptionName        = "hash"
46
	inlineOptionName      = "inline"
Kevin Atkinson's avatar
Kevin Atkinson committed
47
	inlineLimitOptionName = "inline-limit"
48
)
49

50 51
const adderOutChanSize = 8

52
var AddCmd = &cmds.Command{
Steven Allen's avatar
Steven Allen committed
53
	Helptext: cmds.HelpText{
54
		Tagline: "Add a file or directory to ipfs.",
55
		ShortDescription: `
56
Adds contents of <path> to ipfs. Use -r to add directories (recursively).
57 58 59 60 61 62
`,
		LongDescription: `
Adds contents of <path> to ipfs. Use -r to add directories.
Note that directories are added recursively, to form the ipfs
MerkleDAG.

63 64 65 66
If the daemon is not running, it will just add locally.
If the daemon is started later, it will be advertised after a few
seconds when the reprovider runs.

67 68 69 70 71 72 73 74 75 76 77 78 79 80
The wrap option, '-w', wraps the file (or files, if using the
recursive option) in a directory. This directory contains only
the files which have been added, and means that the file retains
its filename. For example:

  > ipfs add example.jpg
  added QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH example.jpg
  > ipfs add example.jpg -w
  added QmbFMke1KXqnYyBBWxB74N4c5SBnJMVAiMNRcGu6x1AwQH example.jpg
  added QmaG4FuMqEBnQNn3C8XJ5bpW8kLs7zq2ZXgHptJHbKDDVx

You can now refer to the added file in a gateway, like so:

  /ipfs/QmaG4FuMqEBnQNn3C8XJ5bpW8kLs7zq2ZXgHptJHbKDDVx/example.jpg
81

82 83
The chunker option, '-s', specifies the chunking strategy that dictates
how to break files into blocks. Blocks with same content can
84 85
be deduplicated. Different chunking strategies will produce different
hashes for the same file. The default is a fixed block size of
86
256 * 1024 bytes, 'size-262144'. Alternatively, you can use the
87 88 89
Buzhash or Rabin fingerprint chunker for content defined chunking by
specifying buzhash or rabin-[min]-[avg]-[max] (where min/avg/max refer
to the desired chunk sizes in bytes), e.g. 'rabin-262144-524288-1048576'.
90 91 92 93

The following examples use very small byte sizes to demonstrate the
properties of the different chunkers on a small file. You'll likely
want to use a 1024 times larger chunk sizes for most files.
94

95 96 97 98
  > ipfs add --chunker=size-2048 ipfs-logo.svg
  added QmafrLBfzRLV4XSH1XcaMMeaXEUhDJjmtDfsYU95TrWG87 ipfs-logo.svg
  > ipfs add --chunker=rabin-512-1024-2048 ipfs-logo.svg
  added Qmf1hDN65tR55Ubh2RN1FPxr69xq3giVBz1KApsresY8Gn ipfs-logo.svg
99 100 101

You can now check what blocks have been created by:

102 103 104 105 106 107
  > ipfs object links QmafrLBfzRLV4XSH1XcaMMeaXEUhDJjmtDfsYU95TrWG87
  QmY6yj1GsermExDXoosVE3aSPxdMNYr6aKuw3nA8LoWPRS 2059
  Qmf7ZQeSxq2fJVJbCmgTrLLVN9tDR9Wy5k75DxQKuz5Gyt 1195
  > ipfs object links Qmf1hDN65tR55Ubh2RN1FPxr69xq3giVBz1KApsresY8Gn
  QmY6yj1GsermExDXoosVE3aSPxdMNYr6aKuw3nA8LoWPRS 2059
  QmerURi9k4XzKCaaPbsK6BL5pMEjF7PGphjDvkkjDtsVf3 868
108
  QmQB28iwSriSUSMqG2nXDTLtdPHgWb4rebBrU7Q1j4vxPv 338
109 110 111 112 113

Finally, a note on hash determinism. While not guaranteed, adding the same
file/directory with the same flags will almost always result in the same output
hash. However, almost all of the flags provided by this command (other than pin,
only-hash, and progress/status related flags) will change the final hash.
114 115 116
`,
	},

Steven Allen's avatar
Steven Allen committed
117 118
	Arguments: []cmds.Argument{
		cmds.FileArg("path", true, true, "The path to a file to be added to ipfs.").EnableRecursive().EnableStdin(),
119
	},
Steven Allen's avatar
Steven Allen committed
120
	Options: []cmds.Option{
121
		cmds.OptionRecursivePath, // a builtin option that allows recursive paths (-r, --recursive)
122
		cmds.OptionDerefArgs,     // a builtin option that resolves passed in filesystem links (--dereference-args)
123 124
		cmds.OptionStdinName,     // a builtin option that optionally allows wrapping stdin into a named file
		cmds.OptionHidden,
125 126
		cmds.OptionIgnore,
		cmds.OptionIgnoreRules,
Steven Allen's avatar
Steven Allen committed
127 128 129 130 131 132 133
		cmds.BoolOption(quietOptionName, "q", "Write minimal output."),
		cmds.BoolOption(quieterOptionName, "Q", "Write only final hash."),
		cmds.BoolOption(silentOptionName, "Write no output."),
		cmds.BoolOption(progressOptionName, "p", "Stream progress data."),
		cmds.BoolOption(trickleOptionName, "t", "Use trickle-dag format for dag generation."),
		cmds.BoolOption(onlyHashOptionName, "n", "Only chunk and hash - do not write to disk."),
		cmds.BoolOption(wrapOptionName, "w", "Wrap files with a directory object."),
134
		cmds.StringOption(chunkerOptionName, "s", "Chunking algorithm, size-[bytes], rabin-[min]-[avg]-[max] or buzhash").WithDefault("size-262144"),
Steven Allen's avatar
Steven Allen committed
135 136 137 138 139 140 141 142
		cmds.BoolOption(pinOptionName, "Pin this object when adding.").WithDefault(true),
		cmds.BoolOption(rawLeavesOptionName, "Use raw blocks for leaf nodes. (experimental)"),
		cmds.BoolOption(noCopyOptionName, "Add the file using filestore. Implies raw-leaves. (experimental)"),
		cmds.BoolOption(fstoreCacheOptionName, "Check the filestore for pre-existing blocks. (experimental)"),
		cmds.IntOption(cidVersionOptionName, "CID version. Defaults to 0 unless an option that depends on CIDv1 is passed. (experimental)"),
		cmds.StringOption(hashOptionName, "Hash function to use. Implies CIDv1 if not sha2-256. (experimental)").WithDefault("sha2-256"),
		cmds.BoolOption(inlineOptionName, "Inline small blocks into CIDs. (experimental)"),
		cmds.IntOption(inlineLimitOptionName, "Maximum block size to inline. (experimental)").WithDefault(32),
143
	},
Jeromy's avatar
Jeromy committed
144
	PreRun: func(req *cmds.Request, env cmds.Environment) error {
145 146
		quiet, _ := req.Options[quietOptionName].(bool)
		quieter, _ := req.Options[quieterOptionName].(bool)
147 148
		quiet = quiet || quieter

149
		silent, _ := req.Options[silentOptionName].(bool)
150 151

		if quiet || silent {
152 153 154
			return nil
		}

155
		// ipfs cli progress bar defaults to true unless quiet or silent is used
156
		_, found := req.Options[progressOptionName].(bool)
157
		if !found {
158
			req.Options[progressOptionName] = true
159 160
		}

161
		return nil
162
	},
keks's avatar
keks committed
163
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
164
		api, err := cmdenv.GetApi(env, req)
165
		if err != nil {
keks's avatar
keks committed
166
			return err
167
		}
168

169 170 171 172 173 174 175 176 177 178
		progress, _ := req.Options[progressOptionName].(bool)
		trickle, _ := req.Options[trickleOptionName].(bool)
		wrap, _ := req.Options[wrapOptionName].(bool)
		hash, _ := req.Options[onlyHashOptionName].(bool)
		silent, _ := req.Options[silentOptionName].(bool)
		chunker, _ := req.Options[chunkerOptionName].(string)
		dopin, _ := req.Options[pinOptionName].(bool)
		rawblks, rbset := req.Options[rawLeavesOptionName].(bool)
		nocopy, _ := req.Options[noCopyOptionName].(bool)
		fscache, _ := req.Options[fstoreCacheOptionName].(bool)
179 180
		cidVer, cidVerSet := req.Options[cidVersionOptionName].(int)
		hashFunStr, _ := req.Options[hashOptionName].(string)
181
		inline, _ := req.Options[inlineOptionName].(bool)
Kevin Atkinson's avatar
Kevin Atkinson committed
182
		inlineLimit, _ := req.Options[inlineLimitOptionName].(int)
183

184 185
		hashFunCode, ok := mh.Names[strings.ToLower(hashFunStr)]
		if !ok {
keks's avatar
keks committed
186
			return fmt.Errorf("unrecognized hash function: %s", strings.ToLower(hashFunStr))
187 188
		}

189 190 191 192 193
		enc, err := cmdenv.GetCidEncoder(req)
		if err != nil {
			return err
		}

194 195 196 197 198
		toadd := req.Files
		if wrap {
			toadd = files.NewSliceDirectory([]files.DirEntry{
				files.FileEntry("", req.Files),
			})
199
		}
200

Łukasz Magiera's avatar
Łukasz Magiera committed
201 202
		opts := []options.UnixfsAddOption{
			options.Unixfs.Hash(hashFunCode),
203

Łukasz Magiera's avatar
Łukasz Magiera committed
204 205
			options.Unixfs.Inline(inline),
			options.Unixfs.InlineLimit(inlineLimit),
206

Łukasz Magiera's avatar
Łukasz Magiera committed
207
			options.Unixfs.Chunker(chunker),
208

Łukasz Magiera's avatar
Łukasz Magiera committed
209 210 211 212
			options.Unixfs.Pin(dopin),
			options.Unixfs.HashOnly(hash),
			options.Unixfs.FsCache(fscache),
			options.Unixfs.Nocopy(nocopy),
Jan Winkelmann's avatar
Jan Winkelmann committed
213

Łukasz Magiera's avatar
Łukasz Magiera committed
214 215 216 217 218 219
			options.Unixfs.Progress(progress),
			options.Unixfs.Silent(silent),
		}

		if cidVerSet {
			opts = append(opts, options.Unixfs.CidVersion(cidVer))
Jeromy's avatar
Jeromy committed
220
		}
221

Łukasz Magiera's avatar
Łukasz Magiera committed
222 223
		if rbset {
			opts = append(opts, options.Unixfs.RawLeaves(rawblks))
224
		}
225

Łukasz Magiera's avatar
Łukasz Magiera committed
226 227
		if trickle {
			opts = append(opts, options.Unixfs.Layout(options.TrickleLayout))
Jeromy's avatar
Jeromy committed
228 229
		}

230 231 232 233 234 235
		opts = append(opts, nil) // events option placeholder

		var added int
		addit := toadd.Entries()
		for addit.Next() {
			_, dir := addit.Node().(files.Directory)
236 237 238
			errCh := make(chan error, 1)
			events := make(chan interface{}, adderOutChanSize)
			opts[len(opts)-1] = options.Unixfs.Events(events)
239

240 241 242
			go func() {
				var err error
				defer close(events)
243 244
				_, err = api.Unixfs().Add(req.Context, addit.Node(), opts...)
				errCh <- err
245
			}()
246

247 248 249 250 251 252 253 254 255 256 257
			for event := range events {
				output, ok := event.(*coreiface.AddEvent)
				if !ok {
					return errors.New("unknown event type")
				}

				h := ""
				if output.Path != nil {
					h = enc.Encode(output.Path.Cid())
				}

258 259
				if !dir && addit.Name() != "" {
					output.Name = addit.Name()
260
				} else {
261
					output.Name = path.Join(addit.Name(), output.Name)
262 263 264 265 266 267 268 269 270 271
				}

				if err := res.Emit(&AddEvent{
					Name:  output.Name,
					Hash:  h,
					Bytes: output.Bytes,
					Size:  output.Size,
				}); err != nil {
					return err
				}
272 273
			}

274
			if err := <-errCh; err != nil {
275
				return err
276
			}
277
			added++
278
		}
279

280 281 282 283
		if addit.Err() != nil {
			return addit.Err()
		}

284 285 286 287
		if added == 0 {
			return fmt.Errorf("expected a file argument")
		}

288
		return nil
Jan Winkelmann's avatar
Jan Winkelmann committed
289
	},
290
	PostRun: cmds.PostRunMap{
keks's avatar
keks committed
291
		cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
Steven Allen's avatar
Steven Allen committed
292
			sizeChan := make(chan int64, 1)
keks's avatar
keks committed
293 294
			outChan := make(chan interface{})
			req := res.Request()
Steven Allen's avatar
Steven Allen committed
295

Łukasz Magiera's avatar
Łukasz Magiera committed
296 297 298 299
			// Could be slow.
			go func() {
				size, err := req.Files.Size()
				if err != nil {
300
					log.Warnf("error getting files size: %s", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
301 302 303 304 305 306
					// see comment above
					return
				}

				sizeChan <- size
			}()
Steven Allen's avatar
Steven Allen committed
307

Jan Winkelmann's avatar
Jan Winkelmann committed
308 309
			progressBar := func(wait chan struct{}) {
				defer close(wait)
310

311 312
				quiet, _ := req.Options[quietOptionName].(bool)
				quieter, _ := req.Options[quieterOptionName].(bool)
Jan Winkelmann's avatar
Jan Winkelmann committed
313
				quiet = quiet || quieter
Jeromy's avatar
Jeromy committed
314

315
				progress, _ := req.Options[progressOptionName].(bool)
316

Jan Winkelmann's avatar
Jan Winkelmann committed
317 318 319 320 321 322 323 324 325
				var bar *pb.ProgressBar
				if progress {
					bar = pb.New64(0).SetUnits(pb.U_BYTES)
					bar.ManualUpdate = true
					bar.ShowTimeLeft = false
					bar.ShowPercent = false
					bar.Output = os.Stderr
					bar.Start()
				}
326

Jan Winkelmann's avatar
Jan Winkelmann committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
				lastFile := ""
				lastHash := ""
				var totalProgress, prevFiles, lastBytes int64

			LOOP:
				for {
					select {
					case out, ok := <-outChan:
						if !ok {
							if quieter {
								fmt.Fprintln(os.Stdout, lastHash)
							}

							break LOOP
						}
342
						output := out.(*AddEvent)
Jan Winkelmann's avatar
Jan Winkelmann committed
343 344 345 346 347 348 349 350 351 352 353 354 355
						if len(output.Hash) > 0 {
							lastHash = output.Hash
							if quieter {
								continue
							}

							if progress {
								// clear progress bar line before we print "added x" output
								fmt.Fprintf(os.Stderr, "\033[2K\r")
							}
							if quiet {
								fmt.Fprintf(os.Stdout, "%s\n", output.Hash)
							} else {
356
								fmt.Fprintf(os.Stdout, "added %s %s\n", output.Hash, cmdenv.EscNonPrint(output.Name))
Jan Winkelmann's avatar
Jan Winkelmann committed
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
							}

						} else {
							if !progress {
								continue
							}

							if len(lastFile) == 0 {
								lastFile = output.Name
							}
							if output.Name != lastFile || output.Bytes < lastBytes {
								prevFiles += lastBytes
								lastFile = output.Name
							}
							lastBytes = output.Bytes
							delta := prevFiles + lastBytes - totalProgress
							totalProgress = bar.Add64(delta)
						}

						if progress {
							bar.Update()
						}
					case size := <-sizeChan:
						if progress {
							bar.Total = size
							bar.ShowPercent = true
							bar.ShowBar = true
							bar.ShowTimeLeft = true
						}
386
					case <-req.Context.Done():
keks's avatar
cleanup  
keks committed
387
						// don't set or print error here, that happens in the goroutine below
388
						return
389
					}
Jan Winkelmann's avatar
Jan Winkelmann committed
390
				}
391 392 393 394 395 396 397 398

				if progress && bar.Total == 0 && bar.Get() != 0 {
					bar.Total = bar.Get()
					bar.ShowPercent = true
					bar.ShowBar = true
					bar.ShowTimeLeft = true
					bar.Update()
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
399
			}
400

keks's avatar
keks committed
401 402 403 404
			if e := res.Error(); e != nil {
				close(outChan)
				return e
			}
405

keks's avatar
keks committed
406 407
			wait := make(chan struct{})
			go progressBar(wait)
Jan Winkelmann's avatar
Jan Winkelmann committed
408

keks's avatar
keks committed
409 410
			defer func() { <-wait }()
			defer close(outChan)
Jan Winkelmann's avatar
Jan Winkelmann committed
411

keks's avatar
keks committed
412 413 414 415 416
			for {
				v, err := res.Next()
				if err != nil {
					if err == io.EOF {
						return nil
Jan Winkelmann's avatar
Jan Winkelmann committed
417 418
					}

keks's avatar
keks committed
419
					return err
Jeromy's avatar
Jeromy committed
420
				}
Jan Winkelmann's avatar
Jan Winkelmann committed
421

keks's avatar
keks committed
422 423 424 425 426 427
				select {
				case outChan <- v:
				case <-req.Context.Done():
					return req.Context.Err()
				}
			}
Jan Winkelmann's avatar
Jan Winkelmann committed
428
		},
429
	},
430
	Type: AddEvent{},
431
}