refs.go 1.26 KB
Newer Older
1 2 3 4 5 6 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 60 61 62 63 64 65
package commands

import (
	"io"

	mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash"
	"github.com/jbenet/go-ipfs/core"
	mdag "github.com/jbenet/go-ipfs/merkledag"
	u "github.com/jbenet/go-ipfs/util"
)

func Refs(n *core.IpfsNode, args []string, opts map[string]interface{}, out io.Writer) error {
	unique, ok := opts["u"].(bool)
	if !ok {
		unique = false
	}

	recursive, ok := opts["r"].(bool)
	if !ok {
		recursive = false
	}

	var refsSeen map[u.Key]bool
	if unique {
		refsSeen = make(map[u.Key]bool)
	}

	for _, fn := range args {
		nd, err := n.Resolver.ResolvePath(fn)
		if err != nil {
			return err
		}

		printRefs(n, nd, refsSeen, recursive)
	}
	return nil
}

func printRefs(n *core.IpfsNode, nd *mdag.Node, refSeen map[u.Key]bool, recursive bool) {
	for _, link := range nd.Links {
		printRef(link.Hash, refSeen)

		if recursive {
			nd, err := n.DAG.Get(u.Key(link.Hash))
			if err != nil {
				log.Errorf("error: cannot retrieve %s (%s)", link.Hash.B58String(), err)
				return
			}

			printRefs(n, nd, refSeen, recursive)
		}
	}
}

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

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