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

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"bytes"
5
	"errors"
6 7
	"fmt"
	"io"
8
	"os"
9
	"path"
10
	"strings"
11 12

	cmds "github.com/jbenet/go-ipfs/commands"
13
	files "github.com/jbenet/go-ipfs/commands/files"
14 15
	core "github.com/jbenet/go-ipfs/core"
	importer "github.com/jbenet/go-ipfs/importer"
16
	"github.com/jbenet/go-ipfs/importer/chunk"
17
	dag "github.com/jbenet/go-ipfs/merkledag"
18
	pinning "github.com/jbenet/go-ipfs/pin"
19
	ft "github.com/jbenet/go-ipfs/unixfs"
20
	u "github.com/jbenet/go-ipfs/util"
21 22

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"
23 24 25 26 27
)

// Error indicating the max depth has been exceded.
var ErrDepthLimitExceeded = fmt.Errorf("depth limit exceeded")

28 29 30 31 32
// how many bytes of progress to wait before sending a progress update message
const progressReaderIncrement = 1024 * 256

const progressOptionName = "progress"

33
type AddedObject struct {
34 35 36
	Name  string
	Hash  string `json:",omitempty"`
	Bytes int64  `json:",omitempty"`
37 38
}

39
var AddCmd = &cmds.Command{
40 41 42 43 44 45 46 47 48 49
	Helptext: cmds.HelpText{
		Tagline: "Add an object to ipfs.",
		ShortDescription: `
Adds contents of <path> to ipfs. Use -r to add directories.
Note that directories are added recursively, to form the ipfs
MerkleDAG. A smarter partial add with a staging area (like git)
remains to be implemented.
`,
	},

50
	Arguments: []cmds.Argument{
51
		cmds.FileArg("path", true, true, "The path to a file to be added to IPFS").EnableRecursive().EnableStdin(),
52
	},
53 54
	Options: []cmds.Option{
		cmds.OptionRecursivePath, // a builtin option that allows recursive paths (-r, --recursive)
55
		cmds.BoolOption("quiet", "q", "Write minimal output"),
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
		cmds.BoolOption(progressOptionName, "p", "Stream progress data"),
	},
	PreRun: func(req cmds.Request) error {
		req.SetOption(progressOptionName, true)

		sizeFile, ok := req.Files().(files.SizeFile)
		if !ok {
			// we don't need to error, the progress bar just won't know how big the files are
			return nil
		}

		size, err := sizeFile.Size()
		if err != nil {
			// see comment above
			return nil
		}
		log.Debugf("Total size of file being added: %v\n", size)
		req.Values()["size"] = size

		return nil
76
	},
77
	Run: func(req cmds.Request, res cmds.Response) {
78 79
		n, err := req.Context().GetNode()
		if err != nil {
80 81
			res.SetError(err, cmds.ErrNormal)
			return
82
		}
83

84 85
		progress, _, _ := req.Option(progressOptionName).Bool()

86
		outChan := make(chan interface{})
87
		res.SetOutput((<-chan interface{})(outChan))
88

89 90
		go func() {
			defer close(outChan)
91

92 93 94 95 96
			for {
				file, err := req.Files().NextFile()
				if (err != nil && err != io.EOF) || file == nil {
					return
				}
97

98
				_, err = addFile(n, file, outChan, progress)
99 100 101 102 103
				if err != nil {
					return
				}
			}
		}()
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
	PostRun: func(res cmds.Response) {
		outChan, ok := res.Output().(<-chan interface{})
		if !ok {
			res.SetError(u.ErrCast(), cmds.ErrNormal)
			return
		}

		wrapperChan := make(chan interface{})
		res.SetOutput((<-chan interface{})(wrapperChan))

		size := int64(0)
		s, found := res.Request().Values()["size"]
		if found {
			size = s.(int64)
		}
		showProgressBar := size >= progressBarMinSize

		var bar *pb.ProgressBar
		var terminalWidth int
		if showProgressBar {
			bar = pb.New64(size).SetUnits(pb.U_BYTES)
			bar.ManualUpdate = true
			bar.Start()

			// the progress bar lib doesn't give us a way to get the width of the output,
			// so as a hack we just use a callback to measure the output, then git rid of it
			terminalWidth = 0
			bar.Callback = func(line string) {
				terminalWidth = len(line)
				bar.Callback = nil
				bar.Output = os.Stderr
				log.Infof("terminal width: %v\n", terminalWidth)
			}
			bar.Update()
		}

		go func() {
			lastFile := ""
			var totalProgress, prevFiles, lastBytes int64

			for out := range outChan {
				output := out.(*AddedObject)
				if len(output.Hash) > 0 {
					if showProgressBar {
						// clear progress bar line before we print "added x" output
						fmt.Fprintf(os.Stderr, "\r%s\r", strings.Repeat(" ", terminalWidth))
					}
					wrapperChan <- output

				} else {
					log.Debugf("add progress: %v %v\n", output.Name, output.Bytes)

					if !showProgressBar {
						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)
171
				}
172

173
				if showProgressBar {
174 175 176 177 178 179 180
					bar.Update()
				}
			}

			close(wrapperChan)
		}()
	},
181
	Marshalers: cmds.MarshalerMap{
182
		cmds.Text: func(res cmds.Response) (io.Reader, error) {
183
			outChan, ok := res.Output().(<-chan interface{})
Brian Tiger Chow's avatar
Brian Tiger Chow committed
184
			if !ok {
185
				return nil, u.ErrCast()
186
			}
187

188 189 190 191
			quiet, _, err := res.Request().Option("quiet").Bool()
			if err != nil {
				return nil, err
			}
192

193 194 195 196 197 198 199 200 201
			marshal := func(v interface{}) (io.Reader, error) {
				obj, ok := v.(*AddedObject)
				if !ok {
					return nil, u.ErrCast()
				}

				var buf bytes.Buffer
				if quiet {
					buf.WriteString(fmt.Sprintf("%s\n", obj.Hash))
202
				} else {
203
					buf.WriteString(fmt.Sprintf("added %s %s\n", obj.Hash, obj.Name))
204
				}
205
				return &buf, nil
206
			}
207 208 209 210 211

			return &cmds.ChannelMarshaler{
				Channel:   outChan,
				Marshaler: marshal,
			}, nil
212
		},
213
	},
214
	Type: AddedObject{},
215 216
}

217
func add(n *core.IpfsNode, readers []io.Reader) ([]*dag.Node, error) {
218 219 220 221 222
	mp, ok := n.Pinning.(pinning.ManualPinner)
	if !ok {
		return nil, errors.New("invalid pinner type! expected manual pinner")
	}

223
	dagnodes := make([]*dag.Node, 0)
224

225
	for _, reader := range readers {
226
		node, err := importer.BuildDagFromReader(reader, n.DAG, mp, chunk.DefaultSplitter)
227 228 229 230 231
		if err != nil {
			return nil, err
		}
		dagnodes = append(dagnodes, node)
	}
232

233 234 235 236 237
	err := n.Pinning.Flush()
	if err != nil {
		return nil, err
	}

238
	return dagnodes, nil
239
}
240 241 242 243 244 245 246 247 248 249 250 251 252 253

func addNode(n *core.IpfsNode, node *dag.Node) error {
	err := n.DAG.AddRecursive(node) // add the file to the graph + local storage
	if err != nil {
		return err
	}

	err = n.Pinning.Pin(node, true) // ensure we keep it
	if err != nil {
		return err
	}

	return nil
}
254

255
func addFile(n *core.IpfsNode, file files.File, out chan interface{}, progress bool) (*dag.Node, error) {
256
	if file.IsDirectory() {
257 258 259 260 261 262 263 264
		return addDir(n, file, out, progress)
	}

	// if the progress flag was specified, wrap the file so that we can send
	// progress updates to the client (over the output channel)
	var reader io.Reader = file
	if progress {
		reader = &progressReader{file: file, out: out}
265 266
	}

267
	dns, err := add(n, []io.Reader{reader})
268 269 270 271 272
	if err != nil {
		return nil, err
	}

	log.Infof("adding file: %s", file.FileName())
273
	if err := outputDagnode(out, file.FileName(), dns[len(dns)-1]); err != nil {
274 275 276 277 278
		return nil, err
	}
	return dns[len(dns)-1], nil // last dag node is the file.
}

279
func addDir(n *core.IpfsNode, dir files.File, out chan interface{}, progress bool) (*dag.Node, error) {
280 281 282 283 284 285 286 287 288 289 290 291 292
	log.Infof("adding directory: %s", dir.FileName())

	tree := &dag.Node{Data: ft.FolderPBData()}

	for {
		file, err := dir.NextFile()
		if err != nil && err != io.EOF {
			return nil, err
		}
		if file == nil {
			break
		}

293
		node, err := addFile(n, file, out, progress)
294 295 296 297
		if err != nil {
			return nil, err
		}

298
		_, name := path.Split(file.FileName())
299 300 301 302 303 304 305

		err = tree.AddNodeLink(name, node)
		if err != nil {
			return nil, err
		}
	}

306
	err := outputDagnode(out, dir.FileName(), tree)
307 308 309 310 311 312 313 314
	if err != nil {
		return nil, err
	}

	err = addNode(n, tree)
	if err != nil {
		return nil, err
	}
315

316
	return tree, nil
317 318
}

319 320
// outputDagnode sends dagnode info over the output channel
func outputDagnode(out chan interface{}, name string, dn *dag.Node) error {
321 322 323 324 325
	o, err := getOutput(dn)
	if err != nil {
		return err
	}

326 327 328 329
	out <- &AddedObject{
		Hash: o.Hash,
		Name: name,
	}
330

331
	return nil
332
}
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

type progressReader struct {
	file         files.File
	out          chan interface{}
	bytes        int64
	lastProgress int64
}

func (i *progressReader) Read(p []byte) (int, error) {
	n, err := i.file.Read(p)

	i.bytes += int64(n)
	if i.bytes-i.lastProgress >= progressReaderIncrement || err == io.EOF {
		i.lastProgress = i.bytes
		i.out <- &AddedObject{
			Name:  i.file.FileName(),
			Bytes: i.bytes,
		}
	}

	return n, err
}