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

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

Overbool's avatar
Overbool committed
11 12 13
	oldcmds "github.com/ipfs/go-ipfs/commands"
	core "github.com/ipfs/go-ipfs/core"
	cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
Jan Winkelmann's avatar
Jan Winkelmann committed
14
	e "github.com/ipfs/go-ipfs/core/commands/e"
Jeromy's avatar
Jeromy committed
15

Steven Allen's avatar
Steven Allen committed
16 17 18
	cid "gx/ipfs/QmR8BauakNcBa3RbE4nbQu76PDiJgoQgz8AJdhJuiU4TAw/go-cid"
	path "gx/ipfs/QmRG3XuGwT7GYuAqgWDJBKTzdaHMwAnc1x7J2KHEXNHxzG/go-path"
	ipld "gx/ipfs/QmcKKBwfz6FyQdHR2jsXrrF6XeSBXYL86anmWNewpFpoF5/go-ipld-format"
Overbool's avatar
Overbool committed
19
	cmds "gx/ipfs/QmSXUokcP4TJpFfqozT69AVAYRtzXVMUjzQVkYX41R9Svs/go-ipfs-cmds"
20
	cmdkit "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit"
21 22
)

23 24
// KeyList is a general type for outputting lists of keys
type KeyList struct {
25
	Keys []cid.Cid
26 27
}

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

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

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

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

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

62 63
  <link base58 hash>

64
NOTE: List all references recursively by using the flag '-r'.
65 66
`,
	},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67 68 69
	Subcommands: map[string]*cmds.Command{
		"local": RefsLocalCmd,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
70 71
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("ipfs-path", true, true, "Path to the object(s) to list refs from.").EnableStdin(),
72
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
73
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
74 75 76 77 78
		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),
79
	},
Overbool's avatar
Overbool committed
80 81 82
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		ctx := req.Context
		n, err := cmdenv.GetNode(env)
83
		if err != nil {
Overbool's avatar
Overbool committed
84
			return err
85
		}
86

Overbool's avatar
Overbool committed
87 88 89 90 91
		unique, _ := req.Options[refsUniqueOptionName].(bool)
		recursive, _ := req.Options[refsRecursiveOptionName].(bool)
		maxDepth, _ := req.Options[refsMaxDepthOptionName].(int)
		edges, _ := req.Options[refsEdgesOptionName].(bool)
		format, _ := req.Options[refsFormatOptionName].(string)
Hector Sanjuan's avatar
Hector Sanjuan committed
92 93 94 95 96

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

97 98
		if edges {
			if format != "<dst>" {
Overbool's avatar
Overbool committed
99
				return errors.New("using format argument with edges is not allowed")
100 101 102 103
			}

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

Overbool's avatar
Overbool committed
105
		objs, err := objectsForPaths(ctx, n, req.Arguments)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
		if err != nil {
Overbool's avatar
Overbool committed
107
			return err
108
		}
109

Jeromy's avatar
Jeromy committed
110
		out := make(chan interface{})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112

		go func() {
Jeromy's avatar
Jeromy committed
113
			defer close(out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115

			rw := RefWriter{
Hector Sanjuan's avatar
Hector Sanjuan committed
116 117 118 119 120 121
				out:      out,
				DAG:      n.DAG,
				Ctx:      ctx,
				Unique:   unique,
				PrintFmt: format,
				MaxDepth: maxDepth,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122 123 124 125
			}

			for _, o := range objs {
				if _, err := rw.WriteRefs(o); err != nil {
forstmeier's avatar
forstmeier committed
126 127 128 129
					select {
					case out <- &RefWrapper{Err: err.Error()}:
					case <-ctx.Done():
					}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130 131 132 133
					return
				}
			}
		}()
Overbool's avatar
Overbool committed
134 135 136 137 138 139 140 141 142 143 144 145

		return res.Emit(out)
	},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *RefWrapper) error {
			if out.Err != "" {
				return fmt.Errorf(out.Err)
			}
			fmt.Fprintln(w, out.Ref)

			return nil
		}),
Jeromy's avatar
Jeromy committed
146
	},
Overbool's avatar
Overbool committed
147
	Type: RefWrapper{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149 150
}

var RefsLocalCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
151
	Helptext: cmdkit.HelpText{
152
		Tagline: "List all local references.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154 155 156 157
		ShortDescription: `
Displays the hashes of all local objects.
`,
	},

Overbool's avatar
Overbool committed
158 159 160
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
		ctx := req.Context
		n, err := cmdenv.GetNode(env)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161
		if err != nil {
Overbool's avatar
Overbool committed
162
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163 164 165
		}

		// todo: make async
166
		allKeys, err := n.Blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
		if err != nil {
Overbool's avatar
Overbool committed
168
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170
		}

Overbool's avatar
Overbool committed
171 172 173 174
		for k := range allKeys {
			err := res.Emit(&RefWrapper{Ref: k.String()})
			if err != nil {
				return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
			}
Overbool's avatar
Overbool committed
176
		}
Overbool's avatar
Overbool committed
177

Overbool's avatar
Overbool committed
178
		return nil
Overbool's avatar
Overbool committed
179 180 181 182 183 184 185 186 187 188
	},
	Encoders: cmds.EncoderMap{
		cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *RefWrapper) error {
			if out.Err != "" {
				return fmt.Errorf(out.Err)
			}
			fmt.Fprintln(w, out.Ref)

			return nil
		}),
Jakub Sztandera's avatar
Jakub Sztandera committed
189
	},
Overbool's avatar
Overbool committed
190
	Type: RefWrapper{},
Jakub Sztandera's avatar
Jakub Sztandera committed
191 192
}

Overbool's avatar
Overbool committed
193 194
var refsMarshallerMap = oldcmds.MarshalerMap{
	cmds.Text: func(res oldcmds.Response) (io.Reader, error) {
Jan Winkelmann's avatar
Jan Winkelmann committed
195 196 197
		v, err := unwrapOutput(res.Output())
		if err != nil {
			return nil, err
Jakub Sztandera's avatar
Jakub Sztandera committed
198 199
		}

Jan Winkelmann's avatar
Jan Winkelmann committed
200 201 202 203
		obj, ok := v.(*RefWrapper)
		if !ok {
			return nil, e.TypeErr(obj, v)
		}
Jakub Sztandera's avatar
Jakub Sztandera committed
204

Jan Winkelmann's avatar
Jan Winkelmann committed
205 206
		if obj.Err != "" {
			return nil, errors.New(obj.Err)
Jakub Sztandera's avatar
Jakub Sztandera committed
207
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208

Jan Winkelmann's avatar
Jan Winkelmann committed
209
		return strings.NewReader(obj.Ref + "\n"), nil
210 211 212
	},
}

213 214
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]ipld.Node, error) {
	objects := make([]ipld.Node, len(paths))
215 216 217 218 219 220 221
	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
222 223 224 225 226 227 228 229
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

Jeromy's avatar
Jeromy committed
230 231 232
type RefWrapper struct {
	Ref string
	Err string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233 234 235
}

type RefWriter struct {
Jeromy's avatar
Jeromy committed
236
	out chan interface{}
237
	DAG ipld.DAGService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
	Ctx context.Context
239

Hector Sanjuan's avatar
Hector Sanjuan committed
240 241 242
	Unique   bool
	MaxDepth int
	PrintFmt string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243

Hector Sanjuan's avatar
Hector Sanjuan committed
244
	seen map[string]int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245 246 247
}

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

251 252
}

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

256
	var count int
257
	for i, ng := range ipld.GetDAG(rw.Ctx, rw.DAG, n) {
258
		lc := n.Links()[i].Cid
Hector Sanjuan's avatar
Hector Sanjuan committed
259 260 261 262 263 264 265 266 267 268
		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
269 270 271
			continue
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
272 273 274 275
		// We must Get() the node because:
		// - it is new (never written)
		// - OR we need to go deeper.
		// This ensures printed refs are always fetched.
276
		nd, err := ng.Get(rw.Ctx)
277
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278
			return count, err
279 280
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
281 282 283 284 285 286
		// 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++
287 288
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
289 290 291 292 293 294 295 296 297 298 299
		// 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
			}
300 301
		}
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
302

303 304 305
	return count, nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
306 307 308 309 310 311 312 313 314
// 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.
315
func (rw *RefWriter) visit(c cid.Cid, depth int) (bool, bool) {
Hector Sanjuan's avatar
Hector Sanjuan committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329
	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
330
	if !rw.Unique {
Hector Sanjuan's avatar
Hector Sanjuan committed
331
		return !atMaxDepth, true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332
	}
333

Hector Sanjuan's avatar
Hector Sanjuan committed
334 335
	// Unique == true from this point.
	// Thus, we keep track of seen Cids, and their depth.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
336
	if rw.seen == nil {
Hector Sanjuan's avatar
Hector Sanjuan committed
337
		rw.seen = make(map[string]int)
338
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
339 340 341 342 343 344 345 346 347 348 349 350 351
	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
352
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
353 354 355 356 357 358 359 360

	// 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
361 362
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
363
// Write one edge
364
func (rw *RefWriter) WriteEdge(from, to cid.Cid, linkname string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
365 366 367 368 369
	if rw.Ctx != nil {
		select {
		case <-rw.Ctx.Done(): // just in case.
			return rw.Ctx.Err()
		default:
370 371 372
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
374 375 376
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
Jeromy's avatar
Jeromy committed
377 378
		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
379 380
		s = strings.Replace(s, "<linkname>", linkname, -1)
	default:
Jeromy's avatar
Jeromy committed
381
		s += to.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
382 383
	}

Jeromy's avatar
Jeromy committed
384
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
385
	return nil
386
}