cat.go 1.5 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package main

import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"fmt"
5 6
	"io"
	"os"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9
	"github.com/gonuts/flag"
	"github.com/jbenet/commander"
10 11
	bserv "github.com/jbenet/go-ipfs/blockservice"
	dag "github.com/jbenet/go-ipfs/merkledag"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
	u "github.com/jbenet/go-ipfs/util"
)

var cmdIpfsCat = &commander.Command{
	UsageLine: "cat",
	Short:     "Show ipfs object data.",
	Long: `ipfs cat <ipfs-path> - Show ipfs object data.

    Retrieves the object named by <ipfs-path> and displays the Data
    it contains.
`,
	Run:  catCmd,
	Flag: *flag.NewFlagSet("ipfs-cat", flag.ExitOnError),
}

func catCmd(c *commander.Command, inp []string) error {
	if len(inp) < 1 {
		u.POut(c.Long)
		return nil
	}

33
	n, err := localNode(false)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34 35 36 37
	if err != nil {
		return err
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38
	for _, fn := range inp {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
		nd, err := n.Resolver.ResolvePath(fn)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
40 41 42 43
		if err != nil {
			return err
		}

44
		err = ExpandDag(nd, n.Blocks)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45 46 47
		if err != nil {
			return err
		}
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
		read, err := dag.NewDagReader(nd)
		if err != nil {
			fmt.Println(err)
			continue
		}

		_, err = io.Copy(os.Stdout, read)
		if err != nil {
			fmt.Println(err)
			continue
		}
	}
	return nil
}

// Expand all subnodes in this dag so printing can occur without error
//TODO: this needs to be done MUCH better in a somewhat asynchronous way.
//also should be moved elsewhere.
func ExpandDag(nd *dag.Node, bs *bserv.BlockService) error {
	for _, lnk := range nd.Links {
		if lnk.Node == nil {
			blk, err := bs.GetBlock(u.Key(lnk.Hash))
71 72 73
			if err != nil {
				return err
			}
74
			lnk.Node = &dag.Node{Data: dag.WrapData(blk.Data)}
75
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77 78
	return nil
}