forked from ipfs/kubo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ls.go
103 lines (88 loc) · 2.11 KB
/
ls.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package commands
import (
"fmt"
"io"
"strings"
cmds "github.com/jbenet/go-ipfs/commands"
merkledag "github.com/jbenet/go-ipfs/merkledag"
path "github.com/jbenet/go-ipfs/path"
)
type Link struct {
Name, Hash string
Size uint64
}
type Object struct {
Hash string
Links []Link
}
type LsOutput struct {
Objects []Object
}
var LsCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List links from an object.",
ShortDescription: `
Retrieves the object named by <ipfs-path> and displays the links
it contains, with the following format:
<link base58 hash> <link size in bytes> <link name>
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("ipfs-path", true, true, "The path to the IPFS object(s) to list links from").EnableStdin(),
},
Run: func(req cmds.Request, res cmds.Response) {
node, err := req.Context().GetNode()
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
paths := req.Arguments()
dagnodes := make([]*merkledag.Node, 0)
for _, fpath := range paths {
dagnode, err := node.Resolver.ResolvePath(path.Path(fpath))
if err != nil {
res.SetError(err, cmds.ErrNormal)
return
}
dagnodes = append(dagnodes, dagnode)
}
output := make([]Object, len(req.Arguments()))
for i, dagnode := range dagnodes {
output[i] = Object{
Hash: paths[i],
Links: make([]Link, len(dagnode.Links)),
}
for j, link := range dagnode.Links {
output[i].Links[j] = Link{
Name: link.Name,
Hash: link.Hash.B58String(),
Size: link.Size,
}
}
}
res.SetOutput(&LsOutput{output})
},
Marshalers: cmds.MarshalerMap{
cmds.Text: func(res cmds.Response) (io.Reader, error) {
s := ""
output := res.Output().(*LsOutput).Objects
for _, object := range output {
if len(output) > 1 {
s += fmt.Sprintf("%s:\n", object.Hash)
}
s += marshalLinks(object.Links)
if len(output) > 1 {
s += "\n"
}
}
return strings.NewReader(s), nil
},
},
Type: LsOutput{},
}
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
}