ls.go 1.37 KB
Newer Older
Matt Bell's avatar
Matt Bell committed
1 2 3 4 5 6 7 8 9 10 11 12 13
package commands

import (
	"fmt"

	cmds "github.com/jbenet/go-ipfs/commands"
)

type Link struct {
	Name, Hash string
	Size       uint64
}

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

type LsOutput struct {
	Objects []Object
}

23
var lsCmd = &cmds.Command{
24 25 26
	Arguments: []cmds.Argument{
		cmds.Argument{"object", cmds.ArgString, false, true},
	},
Matt Bell's avatar
Matt Bell committed
27 28 29
	Help: "TODO",
	Run: func(res cmds.Response, req cmds.Request) {
		node := req.Context().Node
30
		output := make([]Object, len(req.Arguments()))
Matt Bell's avatar
Matt Bell committed
31

32 33
		for i, arg := range req.Arguments() {
			path := arg.(string)
Matt Bell's avatar
Matt Bell committed
34 35 36 37 38 39
			dagnode, err := node.Resolver.ResolvePath(path)
			if err != nil {
				res.SetError(err, cmds.ErrNormal)
				return
			}

40 41 42 43 44 45
			output[i] = Object{
				Hash:  path,
				Links: make([]Link, len(dagnode.Links)),
			}
			for j, link := range dagnode.Links {
				output[i].Links[j] = Link{
Matt Bell's avatar
Matt Bell committed
46 47 48 49 50 51 52
					Name: link.Name,
					Hash: link.Hash.B58String(),
					Size: link.Size,
				}
			}
		}

53
		res.SetValue(&LsOutput{output})
Matt Bell's avatar
Matt Bell committed
54 55 56
	},
	Format: func(res cmds.Response) (string, error) {
		s := ""
57
		output := res.Value().(*LsOutput).Objects
Matt Bell's avatar
Matt Bell committed
58

59 60 61
		for _, object := range output {
			if len(output) > 1 {
				s += fmt.Sprintf("%s:\n", object.Hash)
Matt Bell's avatar
Matt Bell committed
62 63
			}

64
			for _, link := range object.Links {
Matt Bell's avatar
Matt Bell committed
65 66 67
				s += fmt.Sprintf("-> %s %s (%v bytes)\n", link.Name, link.Hash, link.Size)
			}

68
			if len(output) > 1 {
Matt Bell's avatar
Matt Bell committed
69 70 71 72 73 74
				s += "\n"
			}
		}

		return s, nil
	},
75
	Type: &LsOutput{},
Matt Bell's avatar
Matt Bell committed
76
}