refs.go 8.57 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"
Łukasz Magiera's avatar
Łukasz Magiera committed
12
	"github.com/ipfs/go-ipfs/namesys/resolve"
Jeromy's avatar
Jeromy committed
13

Jakub Sztandera's avatar
Jakub Sztandera committed
14 15 16 17 18 19
	cid "github.com/ipfs/go-cid"
	cidenc "github.com/ipfs/go-cidutil/cidenc"
	cmdkit "github.com/ipfs/go-ipfs-cmdkit"
	cmds "github.com/ipfs/go-ipfs-cmds"
	ipld "github.com/ipfs/go-ipld-format"
	path "github.com/ipfs/go-path"
20 21
)

Overbool's avatar
Overbool committed
22 23 24 25 26 27 28 29 30 31 32
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
	}),
}

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

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

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

54 55
  <link base58 hash>

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

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

84 85 86 87 88
		enc, err := cmdenv.GetCidEncoder(req)
		if err != nil {
			return err
		}

Overbool's avatar
Overbool committed
89 90 91 92 93
		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
94 95 96 97 98

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

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

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

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

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

Overbool's avatar
Overbool committed
121
		for _, o := range objs {
122
			if _, err := rw.WriteRefs(o, enc); err != nil {
Overbool's avatar
Overbool committed
123 124
				if err := res.Emit(&RefWrapper{Err: err.Error()}); err != nil {
					return err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125 126
				}
			}
Overbool's avatar
Overbool committed
127
		}
Overbool's avatar
Overbool committed
128

Overbool's avatar
Overbool committed
129
		return nil
Overbool's avatar
Overbool committed
130
	},
Overbool's avatar
Overbool committed
131 132
	Encoders: refsEncoderMap,
	Type:     RefWrapper{},
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134 135
}

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

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

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

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

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

169 170
func objectsForPaths(ctx context.Context, n *core.IpfsNode, paths []string) ([]ipld.Node, error) {
	objects := make([]ipld.Node, len(paths))
171 172 173 174 175 176
	for i, sp := range paths {
		p, err := path.ParsePath(sp)
		if err != nil {
			return nil, err
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
177
		o, err := resolve.Resolve(ctx, n.Namesys, n.Resolver, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178 179 180 181 182 183 184 185
		if err != nil {
			return nil, err
		}
		objects[i] = o
	}
	return objects, nil
}

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

type RefWriter struct {
Overbool's avatar
Overbool committed
192
	res cmds.ResponseEmitter
193
	DAG ipld.DAGService
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
	Ctx context.Context
195

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

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

// WriteRefs writes refs of the given object to the underlying writer.
204 205
func (rw *RefWriter) WriteRefs(n ipld.Node, enc cidenc.Encoder) (int, error) {
	return rw.writeRefsRecursive(n, 0, enc)
206 207
}

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

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

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

Hector Sanjuan's avatar
Hector Sanjuan committed
236 237
		// Write this node if not done before (or !Unique)
		if shouldWrite {
238
			if err := rw.WriteEdge(nc, lc, n.Links()[i].Name, enc); err != nil {
Hector Sanjuan's avatar
Hector Sanjuan committed
239 240 241
				return count, err
			}
			count++
242 243
		}

Hector Sanjuan's avatar
Hector Sanjuan committed
244 245 246 247 248 249
		// 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 {
250
			c, err := rw.writeRefsRecursive(nd, depth+1, enc)
Hector Sanjuan's avatar
Hector Sanjuan committed
251 252 253 254
			count += c
			if err != nil {
				return count, err
			}
255 256
		}
	}
Hector Sanjuan's avatar
Hector Sanjuan committed
257

258 259 260
	return count, nil
}

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
328
	var s string
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329 330 331
	switch {
	case rw.PrintFmt != "":
		s = rw.PrintFmt
332 333
		s = strings.Replace(s, "<src>", enc.Encode(from), -1)
		s = strings.Replace(s, "<dst>", enc.Encode(to), -1)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334 335
		s = strings.Replace(s, "<linkname>", linkname, -1)
	default:
336
		s += enc.Encode(to)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
337 338
	}

Overbool's avatar
Overbool committed
339
	return rw.res.Emit(&RefWrapper{Ref: s})
340
}