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

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

10 11
	cmds "github.com/ipfs/go-ipfs/commands"
	"github.com/ipfs/go-ipfs/core"
Jan Winkelmann's avatar
Jan Winkelmann committed
12
	e "github.com/ipfs/go-ipfs/core/commands/e"
Jeromy's avatar
Jeromy committed
13

Steven Allen's avatar
Steven Allen committed
14 15 16
	cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
	path "gx/ipfs/QmRG3XuGwT7GYuAqgWDJBKTzdaHMwAnc1x7J2KHEXNHxzG/go-path"
	ipld "gx/ipfs/QmcKKBwfz6FyQdHR2jsXrrF6XeSBXYL86anmWNewpFpoF5/go-ipld-format"
17
	cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
18 19
)

20 21
// KeyList is a general type for outputting lists of keys
type KeyList struct {
22
	Keys []cid.Cid
23 24
}

Kejie Zhang's avatar
Kejie Zhang committed
25 26 27 28 29 30 31 32
const (
	refsFormatOptionName    = "format"
	refsEdgesOptionName     = "edges"
	refsUniqueOptionName    = "unique"
	refsRecursiveOptionName = "recursive"
	refsMaxDepthOptionName  = "max-depth"
)

33
// KeyListTextMarshaler outputs a KeyList as plaintext, one key per line
34
func KeyListTextMarshaler(res cmds.Response) (io.Reader, error) {
Jan Winkelmann's avatar
Jan Winkelmann committed
35 36 37 38 39 40 41 42 43 44
	out, err := unwrapOutput(res.Output())
	if err != nil {
		return nil, err
	}

	output, ok := out.(*KeyList)
	if !ok {
		return nil, e.TypeErr(output, out)
	}

45
	buf := new(bytes.Buffer)
46
	for _, key := range output.Keys {
47
		buf.WriteString(key.String() + "\n")
48
	}
49
	return buf, nil
50 51
}

52
var RefsCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
53
	Helptext: cmdkit.HelpText{
54
		Tagline: "List links (references) from an object.",
55
		ShortDescription: `
56 57
Lists the hashes of all the links an IPFS or IPNS object(s) contains,
with the following format:
58

59 60
  <link base58 hash>

61
NOTE: List all references recursively by using the flag '-r'.
62 63
`,
	},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66
	Subcommands: map[string]*cmds.Command{
		"local": RefsLocalCmd,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
67 68
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("ipfs-path", true, true, "Path to the object(s) to list refs from.").EnableStdin(),
69
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
70
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
71 72 73 74 75
		cmdkit.StringOption(refsFormatOptionName, "Emit edges with given format. Available tokens: <src> <dst> <linkname>.").WithDefault("<dst>"),
		cmdkit.BoolOption(refsEdgesOptionName, "e", "Emit edge format: `<from> -> <to>`."),
		cmdkit.BoolOption(refsUniqueOptionName, "u", "Omit duplicate refs from output."),
		cmdkit.BoolOption(refsRecursiveOptionName, "r", "Recursively list links of child nodes."),
		cmdkit.IntOption(refsMaxDepthOptionName, "Only for recursive refs, limits fetch and listing to the given depth").WithDefault(-1),
76
	},
77
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
78 79
		ctx := req.Context()
		n, err := req.InvocContext().GetNode()
80
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
81
			res.SetError(err, cmdkit.ErrNormal)
82
			return
83
		}
84

Kejie Zhang's avatar
Kejie Zhang committed
85
		unique, _, err := req.Option(refsUniqueOptionName).Bool()
86
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
87
			res.SetError(err, cmdkit.ErrNormal)
88
			return
89
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90

Kejie Zhang's avatar
Kejie Zhang committed
91
		recursive, _, err := req.Option(refsRecursiveOptionName).Bool()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
93
			res.SetError(err, cmdkit.ErrNormal)
94
			return
95 96
		}

Kejie Zhang's avatar
Kejie Zhang committed
97
		maxDepth, _, err := req.Option(refsMaxDepthOptionName).Int()
Hector Sanjuan's avatar
Hector Sanjuan committed
98 99 100 101 102 103 104 105 106
		if err != nil {
			res.SetError(err, cmdkit.ErrNormal)
			return
		}

		if !recursive {
			maxDepth = 1 // write only direct refs
		}

Kejie Zhang's avatar
Kejie Zhang committed
107
		format, _, err := req.Option(refsFormatOptionName).String()
108
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
109
			res.SetError(err, cmdkit.ErrNormal)
110
			return
111
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112

Kejie Zhang's avatar
Kejie Zhang committed
113
		edges, _, err := req.Option(refsEdgesOptionName).Bool()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
115
			res.SetError(err, cmdkit.ErrNormal)
116
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
		}
118 119
		if edges {
			if format != "<dst>" {
Łukasz Magiera's avatar
Łukasz Magiera committed
120
				res.SetError(errors.New("using format argument with edges is not allowed"),
Jan Winkelmann's avatar
Jan Winkelmann committed
121
					cmdkit.ErrClient)
122 123 124 125 126
				return
			}

			format = "<src> -> <dst>"
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127

128
		objs, err := objectsForPaths(ctx, n, req.Arguments())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
130
			res.SetError(err, cmdkit.ErrNormal)
131
			return
132
		}
133

Jeromy's avatar
Jeromy committed
134 135
		out := make(chan interface{})
		res.SetOutput((<-chan interface{})(out))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137

		go func() {
Jeromy's avatar
Jeromy committed
138
			defer close(out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140

			rw := RefWriter{
Hector Sanjuan's avatar
Hector Sanjuan committed
141 142 143 144 145 146
				out:      out,
				DAG:      n.DAG,
				Ctx:      ctx,
				Unique:   unique,
				PrintFmt: format,
				MaxDepth: maxDepth,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147 148 149 150
			}

			for _, o := range objs {
				if _, err := rw.WriteRefs(o); err != nil {
forstmeier's avatar
forstmeier committed
151 152 153 154
					select {
					case out <- &RefWrapper{Err: err.Error()}:
					case <-ctx.Done():
					}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155 156 157 158
					return
				}
			}
		}()
Jeromy's avatar
Jeromy committed
159
	},
Jakub Sztandera's avatar
Jakub Sztandera committed
160 161
	Marshalers: refsMarshallerMap,
	Type:       RefWrapper{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163 164
}

var RefsLocalCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
165
	Helptext: cmdkit.HelpText{
166
		Tagline: "List all local references.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167 168 169 170 171
		ShortDescription: `
Displays the hashes of all local objects.
`,
	},

172
	Run: func(req cmds.Request, res cmds.Response) {
Jeromy's avatar
Jeromy committed
173 174
		ctx := req.Context()
		n, err := req.InvocContext().GetNode()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
176
			res.SetError(err, cmdkit.ErrNormal)
177
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178 179 180
		}

		// todo: make async
181
		allKeys, err := n.Blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
		if err != nil {
Jan Winkelmann's avatar
Jan Winkelmann committed
183
			res.SetError(err, cmdkit.ErrNormal)
184
			return
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185 186
		}

Jakub Sztandera's avatar
Jakub Sztandera committed
187 188
		out := make(chan interface{})
		res.SetOutput((<-chan interface{})(out))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189 190

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

193
			for k := range allKeys {
forstmeier's avatar
forstmeier committed
194 195 196 197 198
				select {
				case out <- &RefWrapper{Ref: k.String()}:
				case <-req.Context().Done():
					return
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199 200
			}
		}()
Jakub Sztandera's avatar
Jakub Sztandera committed
201 202 203 204 205 206 207
	},
	Marshalers: refsMarshallerMap,
	Type:       RefWrapper{},
}

var refsMarshallerMap = cmds.MarshalerMap{
	cmds.Text: func(res cmds.Response) (io.Reader, error) {
Jan Winkelmann's avatar
Jan Winkelmann committed
208 209 210
		v, err := unwrapOutput(res.Output())
		if err != nil {
			return nil, err
Jakub Sztandera's avatar
Jakub Sztandera committed
211 212
		}

Jan Winkelmann's avatar
Jan Winkelmann committed
213 214 215 216
		obj, ok := v.(*RefWrapper)
		if !ok {
			return nil, e.TypeErr(obj, v)
		}
Jakub Sztandera's avatar
Jakub Sztandera committed
217

Jan Winkelmann's avatar
Jan Winkelmann committed
218 219
		if obj.Err != "" {
			return nil, errors.New(obj.Err)
Jakub Sztandera's avatar
Jakub Sztandera committed
220
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221

Jan Winkelmann's avatar
Jan Winkelmann committed
222
		return strings.NewReader(obj.Ref + "\n"), nil
223 224 225
	},
}

226 227
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]ipld.Node, error) {
	objects := make([]ipld.Node, len(paths))
228 229 230 231 232 233 234
	for i, sp := range paths {
		p, err := path.ParsePath(sp)
		if err != nil {
			return nil, err
		}

		o, err := core.Resolve(ctx, n.Namesys, n.Resolver, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235 236 237 238 239 240 241 242
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

Jeromy's avatar
Jeromy committed
243 244 245
type RefWrapper struct {
	Ref string
	Err string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246 247 248
}

type RefWriter struct {
Jeromy's avatar
Jeromy committed
249
	out chan interface{}
250
	DAG ipld.DAGService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251
	Ctx context.Context
252

Hector Sanjuan's avatar
Hector Sanjuan committed
253 254 255
	Unique   bool
	MaxDepth int
	PrintFmt string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
256

Hector Sanjuan's avatar
Hector Sanjuan committed
257
	seen map[string]int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258 259 260
}

// WriteRefs writes refs of the given object to the underlying writer.
261
func (rw *RefWriter) WriteRefs(n ipld.Node) (int, error) {
Hector Sanjuan's avatar
Hector Sanjuan committed
262 263
	return rw.writeRefsRecursive(n, 0)

264 265
}

Hector Sanjuan's avatar
Hector Sanjuan committed
266
func (rw *RefWriter) writeRefsRecursive(n ipld.Node, depth int) (int, error) {
Jeromy's avatar
Jeromy committed
267
	nc := n.Cid()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
268

269
	var count int
270
	for i, ng := range ipld.GetDAG(rw.Ctx, rw.DAG, n) {
271
		lc := n.Links()[i].Cid
Hector Sanjuan's avatar
Hector Sanjuan committed
272 273 274 275 276 277 278 279 280 281
		goDeeper, shouldWrite := rw.visit(lc, depth+1) // The children are at depth+1

		// Avoid "Get()" on the node and continue with next Link.
		// We can do this if:
		// - We printed it before (thus it was already seen and
		//   fetched with Get()
		// - AND we must not go deeper.
		// This is an optimization for pruned branches which have been
		// visited before.
		if !shouldWrite && !goDeeper {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282 283 284
			continue
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
285 286 287 288
		// We must Get() the node because:
		// - it is new (never written)
		// - OR we need to go deeper.
		// This ensures printed refs are always fetched.
289
		nd, err := ng.Get(rw.Ctx)
290
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
291
			return count, err
292 293
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
294 295 296 297 298 299
		// Write this node if not done before (or !Unique)
		if shouldWrite {
			if err := rw.WriteEdge(nc, lc, n.Links()[i].Name); err != nil {
				return count, err
			}
			count++
300 301
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
302 303 304 305 306 307 308 309 310 311 312
		// Keep going deeper. This happens:
		// - On unexplored branches
		// - On branches not explored deep enough
		// Note when !Unique, branches are always considered
		// unexplored and only depth limits apply.
		if goDeeper {
			c, err := rw.writeRefsRecursive(nd, depth+1)
			count += c
			if err != nil {
				return count, err
			}
313 314
		}
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
315

316 317 318
	return count, nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
319 320 321 322 323 324 325 326 327
// visit returns two values:
// - the first boolean is true if we should keep traversing the DAG
// - the second boolean is true if we should print the CID
//
// visit will do branch pruning depending on rw.MaxDepth, previously visited
// cids and whether rw.Unique is set. i.e. rw.Unique = false and
// rw.MaxDepth = -1 disables any pruning. But setting rw.Unique to true will
// prune already visited branches at the cost of keeping as set of visited
// CIDs in memory.
328
func (rw *RefWriter) visit(c cid.Cid, depth int) (bool, bool) {
Hector Sanjuan's avatar
Hector Sanjuan committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342
	atMaxDepth := rw.MaxDepth >= 0 && depth == rw.MaxDepth
	overMaxDepth := rw.MaxDepth >= 0 && depth > rw.MaxDepth

	// Shortcut when we are over max depth. In practice, this
	// only applies when calling refs with --maxDepth=0, as root's
	// children are already over max depth. Otherwise nothing should
	// hit this.
	if overMaxDepth {
		return false, false
	}

	// We can shortcut right away if we don't need unique output:
	//   - we keep traversing when not atMaxDepth
	//   - always print
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343
	if !rw.Unique {
Hector Sanjuan's avatar
Hector Sanjuan committed
344
		return !atMaxDepth, true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345
	}
346

Hector Sanjuan's avatar
Hector Sanjuan committed
347 348
	// Unique == true from this point.
	// Thus, we keep track of seen Cids, and their depth.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
349
	if rw.seen == nil {
Hector Sanjuan's avatar
Hector Sanjuan committed
350
		rw.seen = make(map[string]int)
351
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
352 353 354 355 356 357 358 359 360 361 362 363 364
	key := string(c.Bytes())
	oldDepth, ok := rw.seen[key]

	// Unique == true && depth < MaxDepth (or unlimited) from this point

	// Branch pruning cases:
	// - We saw the Cid before and either:
	//   - Depth is unlimited (MaxDepth = -1)
	//   - We saw it higher (smaller depth) in the DAG (means we must have
	//     explored deep enough before)
	// Because we saw the CID, we don't print it again.
	if ok && (rw.MaxDepth < 0 || oldDepth <= depth) {
		return false, false
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
365
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
366 367 368 369 370 371 372 373

	// Final case, we must keep exploring the DAG from this CID
	// (unless we hit the depth limit).
	// We note down its depth because it was either not seen
	// or is lower than last time.
	// We print if it was not seen.
	rw.seen[key] = depth
	return !atMaxDepth, !ok
374 375
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
376
// Write one edge
377
func (rw *RefWriter) WriteEdge(from, to cid.Cid, linkname string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
378 379 380 381 382
	if rw.Ctx != nil {
		select {
		case <-rw.Ctx.Done(): // just in case.
			return rw.Ctx.Err()
		default:
383 384 385
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
386
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
387 388 389
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
Jeromy's avatar
Jeromy committed
390 391
		s = strings.Replace(s, "<src>", from.String(), -1)
		s = strings.Replace(s, "<dst>", to.String(), -1)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
392 393
		s = strings.Replace(s, "<linkname>", linkname, -1)
	default:
Jeromy's avatar
Jeromy committed
394
		s += to.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
395 396
	}

Jeromy's avatar
Jeromy committed
397
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
398
	return nil
399
}