refs.go 1.76 KB
Newer Older
Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
1 2 3 4 5
package main

import (
	"github.com/gonuts/flag"
	"github.com/jbenet/commander"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	mdag "github.com/jbenet/go-ipfs/merkledag"
Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
	u "github.com/jbenet/go-ipfs/util"
	mh "github.com/jbenet/go-multihash"
)

var cmdIpfsRefs = &commander.Command{
	UsageLine: "refs",
	Short:     "List link hashes from an object.",
	Long: `ipfs refs <ipfs-path> - List link hashes from an object..

    Retrieves the object named by <ipfs-path> and displays the link
    hashes it contains, with the following format:

    <link base58 hash>

    Note: list all refs recursively with -r.

`,
	Run:  refCmd,
	Flag: *flag.NewFlagSet("ipfs-refs", flag.ExitOnError),
}

func init() {
	cmdIpfsRefs.Flag.Bool("r", false, "recursive: list refs recursively")
	cmdIpfsRefs.Flag.Bool("u", false, "unique: list each ref only once")
}

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

	n, err := localNode()
	if err != nil {
		return err
	}

	recursive := c.Flag.Lookup("r").Value.Get().(bool)
	unique := c.Flag.Lookup("u").Value.Get().(bool)
	refsSeen := map[u.Key]bool{}

	printRef := func(h mh.Multihash) {
		if unique {
			_, found := refsSeen[u.Key(h)]
			if found {
				return
			}
			refsSeen[u.Key(h)] = true
		}

		u.POut("%s\n", h.B58String())
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60 61
	var printRefs func(nd *mdag.Node, recursive bool)
	printRefs = func(nd *mdag.Node, recursive bool) {
Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
62 63 64

		for _, link := range nd.Links {
			printRef(link.Hash)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65

Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
66
			if recursive {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69 70 71 72 73
				nd, err := n.DAG.Get(u.Key(link.Hash))
				if err != nil {
					u.PErr("error: cannot retrieve %s (%s)\n", link.Hash.B58String(), err)
					return
				}

				printRefs(nd, recursive)
Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
74 75 76 77 78
			}
		}
	}

	for _, fn := range inp {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79
		nd, err := n.Resolver.ResolvePath(fn)
Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
80 81 82 83
		if err != nil {
			return err
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
		printRefs(nd, recursive)
Juan Batiz-Benet's avatar
refs  
Juan Batiz-Benet committed
85 86 87
	}
	return nil
}