refs.go 9.67 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
		}

Jakub Sztandera's avatar
Jakub Sztandera committed
171
		out := make(chan interface{})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172 173

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

176
			for k := range allKeys {
forstmeier's avatar
forstmeier committed
177 178
				select {
				case out <- &RefWrapper{Ref: k.String()}:
Overbool's avatar
Overbool committed
179
				case <-req.Context.Done():
forstmeier's avatar
forstmeier committed
180 181
					return
				}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182 183
			}
		}()
Overbool's avatar
Overbool committed
184 185 186 187 188 189 190 191 192 193 194 195

		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
		}),
Jakub Sztandera's avatar
Jakub Sztandera committed
196
	},
Overbool's avatar
Overbool committed
197
	Type: RefWrapper{},
Jakub Sztandera's avatar
Jakub Sztandera committed
198 199
}

Overbool's avatar
Overbool committed
200 201
var refsMarshallerMap = oldcmds.MarshalerMap{
	cmds.Text: func(res oldcmds.Response) (io.Reader, error) {
Jan Winkelmann's avatar
Jan Winkelmann committed
202 203 204
		v, err := unwrapOutput(res.Output())
		if err != nil {
			return nil, err
Jakub Sztandera's avatar
Jakub Sztandera committed
205 206
		}

Jan Winkelmann's avatar
Jan Winkelmann committed
207 208 209 210
		obj, ok := v.(*RefWrapper)
		if !ok {
			return nil, e.TypeErr(obj, v)
		}
Jakub Sztandera's avatar
Jakub Sztandera committed
211

Jan Winkelmann's avatar
Jan Winkelmann committed
212 213
		if obj.Err != "" {
			return nil, errors.New(obj.Err)
Jakub Sztandera's avatar
Jakub Sztandera committed
214
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
215

Jan Winkelmann's avatar
Jan Winkelmann committed
216
		return strings.NewReader(obj.Ref + "\n"), nil
217 218 219
	},
}

220 221
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]ipld.Node, error) {
	objects := make([]ipld.Node, len(paths))
222 223 224 225 226 227 228
	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
229 230 231 232 233 234 235 236
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

Jeromy's avatar
Jeromy committed
237 238 239
type RefWrapper struct {
	Ref string
	Err string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240 241 242
}

type RefWriter struct {
Jeromy's avatar
Jeromy committed
243
	out chan interface{}
244
	DAG ipld.DAGService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
	Ctx context.Context
246

Hector Sanjuan's avatar
Hector Sanjuan committed
247 248 249
	Unique   bool
	MaxDepth int
	PrintFmt string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
250

Hector Sanjuan's avatar
Hector Sanjuan committed
251
	seen map[string]int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253 254
}

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

258 259
}

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

263
	var count int
264
	for i, ng := range ipld.GetDAG(rw.Ctx, rw.DAG, n) {
265
		lc := n.Links()[i].Cid
Hector Sanjuan's avatar
Hector Sanjuan committed
266 267 268 269 270 271 272 273 274 275
		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
276 277 278
			continue
		}

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

Hector Sanjuan's avatar
Hector Sanjuan committed
288 289 290 291 292 293
		// 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++
294 295
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
296 297 298 299 300 301 302 303 304 305 306
		// 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
			}
307 308
		}
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
309

310 311 312
	return count, nil
}

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

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

	// 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
368 369
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
380
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
381 382 383
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
Jeromy's avatar
Jeromy committed
384 385
		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
386 387
		s = strings.Replace(s, "<linkname>", linkname, -1)
	default:
Jeromy's avatar
Jeromy committed
388
		s += to.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
389 390
	}

Jeromy's avatar
Jeromy committed
391
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
392
	return nil
393
}