refs.go 6.72 KB
Newer Older
1 2 3
package commands

import (
4
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"errors"
6
	"io"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8

9
	key "github.com/ipfs/go-ipfs/blocks/key"
10 11 12 13
	cmds "github.com/ipfs/go-ipfs/commands"
	"github.com/ipfs/go-ipfs/core"
	dag "github.com/ipfs/go-ipfs/merkledag"
	path "github.com/ipfs/go-ipfs/path"
14
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
Jeromy's avatar
Jeromy committed
15
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
16 17
)

18 19
// KeyList is a general type for outputting lists of keys
type KeyList struct {
20
	Keys []key.Key
21 22 23
}

// KeyListTextMarshaler outputs a KeyList as plaintext, one key per line
24
func KeyListTextMarshaler(res cmds.Response) (io.Reader, error) {
25
	output := res.Output().(*KeyList)
26
	buf := new(bytes.Buffer)
27
	for _, key := range output.Keys {
28
		buf.WriteString(key.B58String() + "\n")
29
	}
30
	return buf, nil
31 32
}

33
var RefsCmd = &cmds.Command{
34
	Helptext: cmds.HelpText{
rht's avatar
rht committed
35
		Tagline: "Lists links (references) from an object.",
36
		ShortDescription: `
37 38
Lists the hashes of all the links an IPFS or IPNS object(s) contains,
with the following format:
39

40 41
  <link base58 hash>

42
NOTE: List all references recursively by using the flag '-r'.
43 44
`,
	},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45 46 47
	Subcommands: map[string]*cmds.Command{
		"local": RefsLocalCmd,
	},
48
	Arguments: []cmds.Argument{
49
		cmds.StringArg("ipfs-path", true, true, "Path to the object(s) to list refs from."),
50 51
	},
	Options: []cmds.Option{
Richard Littauer's avatar
Richard Littauer committed
52
		cmds.StringOption("format", "Emit edges with given format. Available tokens: <src> <dst> <linkname>.").Default("<dst>"),
53 54 55
		cmds.BoolOption("edges", "e", "Emit edge format: `<from> -> <to>`.").Default(false),
		cmds.BoolOption("unique", "u", "Omit duplicate refs from output.").Default(false),
		cmds.BoolOption("recursive", "r", "Recursively list links of child nodes.").Default(false),
56
	},
57
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
58 59
		ctx := req.Context()
		n, err := req.InvocContext().GetNode()
60
		if err != nil {
61 62
			res.SetError(err, cmds.ErrNormal)
			return
63
		}
64

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65
		unique, _, err := req.Option("unique").Bool()
66
		if err != nil {
67 68
			res.SetError(err, cmds.ErrNormal)
			return
69
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70 71 72

		recursive, _, err := req.Option("recursive").Bool()
		if err != nil {
73 74
			res.SetError(err, cmds.ErrNormal)
			return
75 76
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77
		edges, _, err := req.Option("edges").Bool()
78
		if err != nil {
79 80
			res.SetError(err, cmds.ErrNormal)
			return
81
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84
		format, _, err := req.Option("format").String()
		if err != nil {
85 86
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88
		}

89
		objs, err := objectsForPaths(ctx, n, req.Arguments())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
		if err != nil {
91 92
			res.SetError(err, cmds.ErrNormal)
			return
93
		}
94

Jeromy's avatar
Jeromy committed
95 96
		out := make(chan interface{})
		res.SetOutput((<-chan interface{})(out))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97 98

		go func() {
Jeromy's avatar
Jeromy committed
99
			defer close(out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100 101

			rw := RefWriter{
Jeromy's avatar
Jeromy committed
102
				out:       out,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
				DAG:       n.DAG,
104
				Ctx:       ctx,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105 106
				Unique:    unique,
				PrintEdge: edges,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107
				PrintFmt:  format,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108 109 110 111 112
				Recursive: recursive,
			}

			for _, o := range objs {
				if _, err := rw.WriteRefs(o); err != nil {
Jeromy's avatar
Jeromy committed
113
					out <- &RefWrapper{Err: err.Error()}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115 116 117
					return
				}
			}
		}()
Jeromy's avatar
Jeromy committed
118
	},
Jakub Sztandera's avatar
Jakub Sztandera committed
119 120
	Marshalers: refsMarshallerMap,
	Type:       RefWrapper{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121 122 123 124
}

var RefsLocalCmd = &cmds.Command{
	Helptext: cmds.HelpText{
rht's avatar
rht committed
125
		Tagline: "Lists all local references.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126 127 128 129 130
		ShortDescription: `
Displays the hashes of all local objects.
`,
	},

131
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
132 133
		ctx := req.Context()
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
		if err != nil {
135 136
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139
		}

		// todo: make async
140
		allKeys, err := n.Blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141
		if err != nil {
142 143
			res.SetError(err, cmds.ErrNormal)
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144 145
		}

Jakub Sztandera's avatar
Jakub Sztandera committed
146 147
		out := make(chan interface{})
		res.SetOutput((<-chan interface{})(out))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149

		go func() {
Jakub Sztandera's avatar
Jakub Sztandera committed
150
			defer close(out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151

152
			for k := range allKeys {
Jakub Sztandera's avatar
Jakub Sztandera committed
153
				out <- &RefWrapper{Ref: k.B58String()}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
			}
		}()
Jakub Sztandera's avatar
Jakub Sztandera committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
	},
	Marshalers: refsMarshallerMap,
	Type:       RefWrapper{},
}

var refsMarshallerMap = cmds.MarshalerMap{
	cmds.Text: func(res cmds.Response) (io.Reader, error) {
		outChan, ok := res.Output().(<-chan interface{})
		if !ok {
			return nil, u.ErrCast()
		}

		marshal := func(v interface{}) (io.Reader, error) {
			obj, ok := v.(*RefWrapper)
			if !ok {
				return nil, u.ErrCast()
			}

			if obj.Err != "" {
				return nil, errors.New(obj.Err)
			}

			return strings.NewReader(obj.Ref + "\n"), nil
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
180

Jakub Sztandera's avatar
Jakub Sztandera committed
181 182 183 184 185
		return &cmds.ChannelMarshaler{
			Channel:   outChan,
			Marshaler: marshal,
			Res:       res,
		}, nil
186 187 188
	},
}

189
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]*dag.Node, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191
	objects := make([]*dag.Node, len(paths))
	for i, p := range paths {
192
		o, err := core.Resolve(ctx, n, path.Path(p))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193 194 195 196 197 198 199 200
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

Jeromy's avatar
Jeromy committed
201 202 203
type RefWrapper struct {
	Ref string
	Err string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204 205 206
}

type RefWriter struct {
Jeromy's avatar
Jeromy committed
207
	out chan interface{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208 209
	DAG dag.DAGService
	Ctx context.Context
210

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211 212 213
	Unique    bool
	Recursive bool
	PrintEdge bool
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
214
	PrintFmt  string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
215

216
	seen map[key.Key]struct{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217 218 219 220
}

// WriteRefs writes refs of the given object to the underlying writer.
func (rw *RefWriter) WriteRefs(n *dag.Node) (int, error) {
221 222 223
	if rw.Recursive {
		return rw.writeRefsRecursive(n)
	}
rht's avatar
rht committed
224
	return rw.writeRefsSingle(n)
225 226 227
}

func (rw *RefWriter) writeRefsRecursive(n *dag.Node) (int, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228 229 230 231 232
	nkey, err := n.Key()
	if err != nil {
		return 0, err
	}

233
	var count int
234
	for i, ng := range dag.GetDAG(rw.Ctx, rw.DAG, n) {
235
		lk := key.Key(n.Links[i].Hash)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
236 237 238 239
		if rw.skip(lk) {
			continue
		}

240
		if err := rw.WriteEdge(nkey, lk, n.Links[i].Name); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242
			return count, err
		}
243

244
		nd, err := ng.Get(rw.Ctx)
245
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246
			return count, err
247 248
		}

249
		c, err := rw.writeRefsRecursive(nd)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250
		count += c
251
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252
			return count, err
253 254
		}
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255
	return count, nil
256 257
}

258 259 260 261 262 263 264 265 266 267 268 269
func (rw *RefWriter) writeRefsSingle(n *dag.Node) (int, error) {
	nkey, err := n.Key()
	if err != nil {
		return 0, err
	}

	if rw.skip(nkey) {
		return 0, nil
	}

	count := 0
	for _, l := range n.Links {
270
		lk := key.Key(l.Hash)
271 272 273 274 275 276 277 278 279 280 281 282 283

		if rw.skip(lk) {
			continue
		}

		if err := rw.WriteEdge(nkey, lk, l.Name); err != nil {
			return count, err
		}
		count++
	}
	return count, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284
// skip returns whether to skip a key
285
func (rw *RefWriter) skip(k key.Key) bool {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286 287 288
	if !rw.Unique {
		return false
	}
289

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
290
	if rw.seen == nil {
291
		rw.seen = make(map[key.Key]struct{})
292 293
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294 295 296 297 298
	_, found := rw.seen[k]
	if !found {
		rw.seen[k] = struct{}{}
	}
	return found
299 300
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301
// Write one edge
302
func (rw *RefWriter) WriteEdge(from, to key.Key, linkname string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
303 304 305 306 307
	if rw.Ctx != nil {
		select {
		case <-rw.Ctx.Done(): // just in case.
			return rw.Ctx.Err()
		default:
308 309 310
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
312 313 314
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
Michael Muré's avatar
Michael Muré committed
315 316
		s = strings.Replace(s, "<src>", from.B58String(), -1)
		s = strings.Replace(s, "<dst>", to.B58String(), -1)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
317 318
		s = strings.Replace(s, "<linkname>", linkname, -1)
	case rw.PrintEdge:
Michael Muré's avatar
Michael Muré committed
319
		s = from.B58String() + " -> " + to.B58String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
320
	default:
Michael Muré's avatar
Michael Muré committed
321
		s += to.B58String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322 323
	}

Jeromy's avatar
Jeromy committed
324
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
325
	return nil
326
}