cat.go 1.93 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"
Jeromy's avatar
Jeromy committed
8
	path "github.com/jbenet/go-ipfs/path"
9
	uio "github.com/jbenet/go-ipfs/unixfs/io"
10 11

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"
12
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
13 14
)

15 16
const progressBarMinSize = 1024 * 1024 * 8 // show progress bar for outputs > 8MiB

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

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

36
		readers, length, err := cat(req.Context().Context, 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
	PostRun: func(req cmds.Request, res cmds.Response) {
48 49 50 51 52
		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(ctx context.Context, node *core.IpfsNode, paths []string) ([]io.Reader, uint64, error) {
62
	readers := make([]io.Reader, 0, len(paths))
63
	length := uint64(0)
Jeromy's avatar
Jeromy committed
64 65
	for _, fpath := range paths {
		dagnode, err := node.Resolver.ResolvePath(path.Path(fpath))
66
		if err != nil {
67 68 69
			return nil, 0, err
		}

70
		read, err := uio.NewDagReader(ctx, dagnode, node.DAG)
71
		if err != nil {
72
			return nil, 0, err
73 74
		}
		readers = append(readers, read)
75
		length += uint64(read.Size())
76
	}
77
	return readers, length, nil
78
}