ls.go 1.96 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2 3 4 5 6
package commands

import (
	"fmt"

	cmds "github.com/jbenet/go-ipfs/commands"
7
	merkledag "github.com/jbenet/go-ipfs/merkledag"
Matt Bell's avatar
Matt Bell committed
8 9 10 11 12 13 14
)

type Link struct {
	Name, Hash string
	Size       uint64
}

15 16 17 18 19 20 21 22 23
type Object struct {
	Hash  string
	Links []Link
}

type LsOutput struct {
	Objects []Object
}

24
var LsCmd = &cmds.Command{
25 26 27 28
	Helptext: cmds.HelpText{
		Tagline: "List links from an object.",
		ShortDescription: `
Retrieves the object named by <ipfs-path> and displays the links
29 30 31
it contains, with the following format:

  <link base58 hash> <link size in bytes> <link name>
32
`,
33
	},
34

35
	Arguments: []cmds.Argument{
Brian Tiger Chow's avatar
Brian Tiger Chow committed
36
		cmds.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to list links from"),
37
	},
38
	Run: func(req cmds.Request) (interface{}, error) {
39 40 41 42
		node, err := req.Context().GetNode()
		if err != nil {
			return nil, err
		}
Matt Bell's avatar
Matt Bell committed
43

44
		paths := req.Arguments()
45 46 47

		dagnodes := make([]*merkledag.Node, 0)
		for _, path := range paths {
Matt Bell's avatar
Matt Bell committed
48 49
			dagnode, err := node.Resolver.ResolvePath(path)
			if err != nil {
50
				return nil, err
Matt Bell's avatar
Matt Bell committed
51
			}
52 53
			dagnodes = append(dagnodes, dagnode)
		}
Matt Bell's avatar
Matt Bell committed
54

55 56
		output := make([]Object, len(req.Arguments()))
		for i, dagnode := range dagnodes {
57
			output[i] = Object{
58
				Hash:  paths[i],
59 60 61 62
				Links: make([]Link, len(dagnode.Links)),
			}
			for j, link := range dagnode.Links {
				output[i].Links[j] = Link{
Matt Bell's avatar
Matt Bell committed
63 64 65 66 67 68 69
					Name: link.Name,
					Hash: link.Hash.B58String(),
					Size: link.Size,
				}
			}
		}

70
		return &LsOutput{output}, nil
Matt Bell's avatar
Matt Bell committed
71
	},
72
	Marshalers: cmds.MarshalerMap{
73 74 75
		cmds.Text: func(res cmds.Response) ([]byte, error) {
			s := ""
			output := res.Output().(*LsOutput).Objects
Matt Bell's avatar
Matt Bell committed
76

77 78 79 80
			for _, object := range output {
				if len(output) > 1 {
					s += fmt.Sprintf("%s:\n", object.Hash)
				}
81
				s += marshalLinks(object.Links)
82 83 84
				if len(output) > 1 {
					s += "\n"
				}
Matt Bell's avatar
Matt Bell committed
85 86
			}

87 88
			return []byte(s), nil
		},
Matt Bell's avatar
Matt Bell committed
89
	},
90
	Type: &LsOutput{},
Matt Bell's avatar
Matt Bell committed
91
}
92 93 94 95 96 97 98

func marshalLinks(links []Link) (s string) {
	for _, link := range links {
		s += fmt.Sprintf("%s %v %s\n", link.Hash, link.Size, link.Name)
	}
	return s
}