ls.go 1.94 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"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
7
	"github.com/jbenet/go-ipfs/core/commands2/internal"
8
	merkledag "github.com/jbenet/go-ipfs/merkledag"
Matt Bell's avatar
Matt Bell committed
9 10 11 12 13 14 15
)

type Link struct {
	Name, Hash string
	Size       uint64
}

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

type LsOutput struct {
	Objects []Object
}

25
var lsCmd = &cmds.Command{
26 27
	Description: "List links from an object.",
	Help: `Retrieves the object named by <ipfs-path> and displays the links
28 29 30
it contains, with the following format:

  <link base58 hash> <link size in bytes> <link name>
31 32
`,

33
	Arguments: []cmds.Argument{
34
		cmds.StringArg("ipfs-path", false, true, "The path to the IPFS object(s) to list links from"),
35
	},
36
	Run: func(req cmds.Request) (interface{}, error) {
Matt Bell's avatar
Matt Bell committed
37 38
		node := req.Context().Node

39
		paths, err := internal.CastToStrings(req.Arguments())
Brian Tiger Chow's avatar
Brian Tiger Chow committed
40
		if err != nil {
41
			return nil, err
42 43 44 45
		}

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

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

68
		return &LsOutput{output}, nil
Matt Bell's avatar
Matt Bell committed
69
	},
70 71 72 73
	Marshallers: map[cmds.EncodingType]cmds.Marshaller{
		cmds.Text: func(res cmds.Response) ([]byte, error) {
			s := ""
			output := res.Output().(*LsOutput).Objects
Matt Bell's avatar
Matt Bell committed
74

75 76 77 78
			for _, object := range output {
				if len(output) > 1 {
					s += fmt.Sprintf("%s:\n", object.Hash)
				}
Matt Bell's avatar
Matt Bell committed
79

80
				for _, link := range object.Links {
81
					s += fmt.Sprintf("%s %v %s\n", link.Hash, link.Size, link.Name)
82
				}
Matt Bell's avatar
Matt Bell committed
83

84 85 86
				if len(output) > 1 {
					s += "\n"
				}
Matt Bell's avatar
Matt Bell committed
87 88
			}

89 90
			return []byte(s), nil
		},
Matt Bell's avatar
Matt Bell committed
91
	},
92
	Type: &LsOutput{},
Matt Bell's avatar
Matt Bell committed
93
}