cat.go 1.86 KB
Newer Older
1 2 3 4 5
package commands

import (
	"io"

Matt Bell's avatar
Matt Bell committed
6
	cmds "github.com/jbenet/go-ipfs/commands"
7
	core "github.com/jbenet/go-ipfs/core"
8
	uio "github.com/jbenet/go-ipfs/unixfs/io"
9 10

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"
11 12
)

13 14
const progressBarMinSize = 1024 * 1024 * 8 // show progress bar for outputs > 8MiB

15
var CatCmd = &cmds.Command{
16 17 18 19
	Helptext: cmds.HelpText{
		Tagline: "Show IPFS object data",
		ShortDescription: `
Retrieves the object named by <ipfs-path> and outputs the data
20
it contains.
21 22
`,
	},
23 24

	Arguments: []cmds.Argument{
25
		cmds.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted").EnableStdin(),
26
	},
27
	Run: func(req cmds.Request, res cmds.Response) {
28 29
		node, err := req.Context().GetNode()
		if err != nil {
30 31
			res.SetError(err, cmds.ErrNormal)
			return
32 33
		}

Matt Bell's avatar
Matt Bell committed
34
		readers := make([]io.Reader, 0, len(req.Arguments()))
35

36
		readers, length, err := cat(node, req.Arguments())
37
		if err != nil {
38 39
			res.SetError(err, cmds.ErrNormal)
			return
40
		}
Matt Bell's avatar
Matt Bell committed
41

42 43
		res.SetLength(length)

Matt Bell's avatar
Matt Bell committed
44
		reader := io.MultiReader(readers...)
45
		res.SetOutput(reader)
Matt Bell's avatar
Matt Bell committed
46
	},
47 48 49 50 51 52
	PostRun: func(res cmds.Response) {
		if res.Length() < progressBarMinSize {
			return
		}

		bar := pb.New(int(res.Length())).SetUnits(pb.U_BYTES)
53
		bar.Output = res.Stderr()
54 55 56 57 58
		bar.Start()

		reader := bar.NewProxyReader(res.Output().(io.Reader))
		res.SetOutput(reader)
	},
59
}
60

61
func cat(node *core.IpfsNode, paths []string) ([]io.Reader, uint64, error) {
62
	readers := make([]io.Reader, 0, len(paths))
63
	length := uint64(0)
64 65 66
	for _, path := range paths {
		dagnode, err := node.Resolver.ResolvePath(path)
		if err != nil {
67 68 69 70 71 72
			return nil, 0, err
		}

		nodeLength, err := dagnode.Size()
		if err != nil {
			return nil, 0, err
73
		}
74 75
		length += nodeLength

76 77
		read, err := uio.NewDagReader(dagnode, node.DAG)
		if err != nil {
78
			return nil, 0, err
79 80 81
		}
		readers = append(readers, read)
	}
82
	return readers, length, nil
83
}