cat.go 2.06 KB
Newer Older
1 2 3
package commands

import (
rht's avatar
rht committed
4
	"fmt"
5 6
	"io"

7 8
	cmds "github.com/ipfs/go-ipfs/commands"
	core "github.com/ipfs/go-ipfs/core"
rht's avatar
rht committed
9
	coreunix "github.com/ipfs/go-ipfs/core/coreunix"
10

11 12
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/cheggaaa/pb"
	context "github.com/ipfs/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

rht's avatar
rht committed
17 18 19 20 21
type clearlineReader struct {
	io.Reader
	out io.Writer
}

22
var CatCmd = &cmds.Command{
23 24 25
	Helptext: cmds.HelpText{
		Tagline: "Show IPFS object data",
		ShortDescription: `
26
Retrieves the object named by <ipfs-or-ipns-path> and outputs the data
27
it contains.
28 29
`,
	},
30 31

	Arguments: []cmds.Argument{
32
		cmds.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to be outputted").EnableStdin(),
33
	},
34
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
35
		node, err := req.InvocContext().GetNode()
36
		if err != nil {
37 38
			res.SetError(err, cmds.ErrNormal)
			return
39 40
		}

Jeromy's avatar
Jeromy committed
41
		readers, length, err := cat(req.Context(), node, req.Arguments())
42
		if err != nil {
43 44
			res.SetError(err, cmds.ErrNormal)
			return
45
		}
Matt Bell's avatar
Matt Bell committed
46

47 48
		res.SetLength(length)

Matt Bell's avatar
Matt Bell committed
49
		reader := io.MultiReader(readers...)
50
		res.SetOutput(reader)
Matt Bell's avatar
Matt Bell committed
51
	},
52
	PostRun: func(req cmds.Request, res cmds.Response) {
53 54 55 56 57
		if res.Length() < progressBarMinSize {
			return
		}

		bar := pb.New(int(res.Length())).SetUnits(pb.U_BYTES)
58
		bar.Output = res.Stderr()
59 60 61
		bar.Start()

		reader := bar.NewProxyReader(res.Output().(io.Reader))
rht's avatar
rht committed
62
		res.SetOutput(&clearlineReader{reader, res.Stderr()})
63
	},
64
}
65

66
func cat(ctx context.Context, node *core.IpfsNode, paths []string) ([]io.Reader, uint64, error) {
67
	readers := make([]io.Reader, 0, len(paths))
68
	length := uint64(0)
Jeromy's avatar
Jeromy committed
69
	for _, fpath := range paths {
rht's avatar
rht committed
70
		read, err := coreunix.Cat(node, fpath)
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
}
rht's avatar
rht committed
79 80 81 82 83 84 85 86

func (r *clearlineReader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	if err == io.EOF {
		fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF
	}
	return
}