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

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

Overbool's avatar
Overbool committed
10 11
	core "github.com/ipfs/go-ipfs/core"
	cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
Jeromy's avatar
Jeromy committed
12

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

Overbool's avatar
Overbool committed
20 21 22 23 24 25 26 27 28 29 30
var refsEncoderMap = 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
	}),
}

31 32
// KeyList is a general type for outputting lists of keys
type KeyList struct {
33
	Keys []cid.Cid
34 35
}

Kejie Zhang's avatar
Kejie Zhang committed
36 37 38 39 40 41 42 43
const (
	refsFormatOptionName    = "format"
	refsEdgesOptionName     = "edges"
	refsUniqueOptionName    = "unique"
	refsRecursiveOptionName = "recursive"
	refsMaxDepthOptionName  = "max-depth"
)

Overbool's avatar
Overbool committed
44
// RefsCmd is the `ipfs refs` command
45
var RefsCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
46
	Helptext: cmdkit.HelpText{
47
		Tagline: "List links (references) from an object.",
48
		ShortDescription: `
49 50
Lists the hashes of all the links an IPFS or IPNS object(s) contains,
with the following format:
51

52 53
  <link base58 hash>

54
NOTE: List all references recursively by using the flag '-r'.
55 56
`,
	},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58 59
	Subcommands: map[string]*cmds.Command{
		"local": RefsLocalCmd,
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
60 61
	Arguments: []cmdkit.Argument{
		cmdkit.StringArg("ipfs-path", true, true, "Path to the object(s) to list refs from.").EnableStdin(),
62
	},
Jan Winkelmann's avatar
Jan Winkelmann committed
63
	Options: []cmdkit.Option{
Kejie Zhang's avatar
Kejie Zhang committed
64 65 66 67 68
		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),
69
	},
Overbool's avatar
Overbool committed
70
	Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
Overbool's avatar
Overbool committed
71 72 73 74 75
		err := req.ParseBodyArgs()
		if err != nil {
			return err
		}

Overbool's avatar
Overbool committed
76 77
		ctx := req.Context
		n, err := cmdenv.GetNode(env)
78
		if err != nil {
Overbool's avatar
Overbool committed
79
			return err
80
		}
81

Overbool's avatar
Overbool committed
82 83 84 85 86
		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
87 88 89 90 91

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

92 93
		if edges {
			if format != "<dst>" {
Overbool's avatar
Overbool committed
94
				return errors.New("using format argument with edges is not allowed")
95 96 97 98
			}

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

Overbool's avatar
Overbool committed
100
		objs, err := objectsForPaths(ctx, n, req.Arguments)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
		if err != nil {
Overbool's avatar
Overbool committed
102
			return err
103
		}
104

Jeromy's avatar
Jeromy committed
105
		out := make(chan interface{})
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106 107

		go func() {
Jeromy's avatar
Jeromy committed
108
			defer close(out)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110

			rw := RefWriter{
Hector Sanjuan's avatar
Hector Sanjuan committed
111 112 113 114 115 116
				out:      out,
				DAG:      n.DAG,
				Ctx:      ctx,
				Unique:   unique,
				PrintFmt: format,
				MaxDepth: maxDepth,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117 118 119 120
			}

			for _, o := range objs {
				if _, err := rw.WriteRefs(o); err != nil {
forstmeier's avatar
forstmeier committed
121 122 123 124
					select {
					case out <- &RefWrapper{Err: err.Error()}:
					case <-ctx.Done():
					}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125 126 127 128
					return
				}
			}
		}()
Overbool's avatar
Overbool committed
129 130 131

		return res.Emit(out)
	},
Overbool's avatar
Overbool committed
132 133
	Encoders: refsEncoderMap,
	Type:     RefWrapper{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135 136
}

var RefsLocalCmd = &cmds.Command{
Jan Winkelmann's avatar
Jan Winkelmann committed
137
	Helptext: cmdkit.HelpText{
138
		Tagline: "List all local references.",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140 141 142 143
		ShortDescription: `
Displays the hashes of all local objects.
`,
	},

Overbool's avatar
Overbool committed
144 145 146
	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
147
		if err != nil {
Overbool's avatar
Overbool committed
148
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149 150 151
		}

		// todo: make async
152
		allKeys, err := n.Blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153
		if err != nil {
Overbool's avatar
Overbool committed
154
			return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155 156
		}

Overbool's avatar
Overbool committed
157 158 159 160
		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
161
			}
Overbool's avatar
Overbool committed
162
		}
Overbool's avatar
Overbool committed
163

Overbool's avatar
Overbool committed
164
		return nil
Overbool's avatar
Overbool committed
165
	},
Overbool's avatar
Overbool committed
166 167
	Encoders: refsEncoderMap,
	Type:     RefWrapper{},
168 169
}

170 171
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]ipld.Node, error) {
	objects := make([]ipld.Node, len(paths))
172 173 174 175 176 177 178
	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
179 180 181 182 183 184 185 186
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

Jeromy's avatar
Jeromy committed
187 188 189
type RefWrapper struct {
	Ref string
	Err string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191 192
}

type RefWriter struct {
Jeromy's avatar
Jeromy committed
193
	out chan interface{}
194
	DAG ipld.DAGService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195
	Ctx context.Context
196

Hector Sanjuan's avatar
Hector Sanjuan committed
197 198 199
	Unique   bool
	MaxDepth int
	PrintFmt string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200

Hector Sanjuan's avatar
Hector Sanjuan committed
201
	seen map[string]int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203 204
}

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

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

212
	var count int
213
	for i, ng := range ipld.GetDAG(rw.Ctx, rw.DAG, n) {
214
		lc := n.Links()[i].Cid
Hector Sanjuan's avatar
Hector Sanjuan committed
215 216 217 218 219 220 221 222 223 224
		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
225 226 227
			continue
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
228 229 230 231
		// We must Get() the node because:
		// - it is new (never written)
		// - OR we need to go deeper.
		// This ensures printed refs are always fetched.
232
		nd, err := ng.Get(rw.Ctx)
233
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234
			return count, err
235 236
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
237 238 239 240 241 242
		// 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++
243 244
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
245 246 247 248 249 250 251 252 253 254 255
		// 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
			}
256 257
		}
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
258

259 260 261
	return count, nil
}

Hector Sanjuan's avatar
Hector Sanjuan committed
262 263 264 265 266 267 268 269 270
// 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.
271
func (rw *RefWriter) visit(c cid.Cid, depth int) (bool, bool) {
Hector Sanjuan's avatar
Hector Sanjuan committed
272 273 274 275 276 277 278 279 280 281 282 283 284 285
	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
286
	if !rw.Unique {
Hector Sanjuan's avatar
Hector Sanjuan committed
287
		return !atMaxDepth, true
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
	}
289

Hector Sanjuan's avatar
Hector Sanjuan committed
290 291
	// Unique == true from this point.
	// Thus, we keep track of seen Cids, and their depth.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292
	if rw.seen == nil {
Hector Sanjuan's avatar
Hector Sanjuan committed
293
		rw.seen = make(map[string]int)
294
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
295 296 297 298 299 300 301 302 303 304 305 306 307
	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
308
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
309 310 311 312 313 314 315 316

	// 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
317 318
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
319
// Write one edge
320
func (rw *RefWriter) WriteEdge(from, to cid.Cid, linkname string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
321 322 323 324 325
	if rw.Ctx != nil {
		select {
		case <-rw.Ctx.Done(): // just in case.
			return rw.Ctx.Err()
		default:
326 327 328
		}
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
330 331 332
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
Jeromy's avatar
Jeromy committed
333 334
		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
335 336
		s = strings.Replace(s, "<linkname>", linkname, -1)
	default:
Jeromy's avatar
Jeromy committed
337
		s += to.String()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
338 339
	}

Jeromy's avatar
Jeromy committed
340
	rw.out <- &RefWrapper{Ref: s}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341
	return nil
342
}