github.com/ipld/go-ipld-prime@v0.21.0/traversal/common.go (about) 1 package traversal 2 3 import ( 4 "context" 5 "fmt" 6 7 "github.com/ipld/go-ipld-prime/datamodel" 8 "github.com/ipld/go-ipld-prime/linking" 9 "github.com/ipld/go-ipld-prime/schema" 10 ) 11 12 // init sets all the values in TraveralConfig to reasonable defaults 13 // if they're currently the zero value. 14 // 15 // Note that you're absolutely going to need to replace the 16 // LinkLoader and LinkNodeBuilderChooser if you want automatic link traversal; 17 // the defaults return error and/or panic. 18 func (tc *Config) init() { 19 if tc.Ctx == nil { 20 tc.Ctx = context.Background() 21 } 22 if tc.LinkTargetNodePrototypeChooser == nil { 23 tc.LinkTargetNodePrototypeChooser = func(lnk datamodel.Link, lnkCtx linking.LinkContext) (datamodel.NodePrototype, error) { 24 if tlnkNd, ok := lnkCtx.LinkNode.(schema.TypedLinkNode); ok { 25 return tlnkNd.LinkTargetNodePrototype(), nil 26 } 27 return nil, fmt.Errorf("no LinkTargetNodePrototypeChooser configured") 28 } 29 } 30 } 31 32 func (prog *Progress) init() { 33 if prog.Cfg == nil { 34 prog.Cfg = &Config{} 35 } 36 prog.Cfg.init() 37 if prog.Cfg.LinkVisitOnlyOnce { 38 prog.SeenLinks = make(map[datamodel.Link]struct{}) 39 } 40 } 41 42 // asPathSegment figures out how to coerce a node into a PathSegment. 43 // If it's a typed node: we take its representation. (Could be a struct with some string representation.) 44 // If it's a string or an int, that's it. 45 // Any other case will panic. (If you're using this one keys returned by a MapIterator, though, you can ignore this possibility; 46 // any compliant map implementation should've already rejected that data long ago, and should not be able to yield it to you from an iterator.) 47 func asPathSegment(n datamodel.Node) datamodel.PathSegment { 48 if n2, ok := n.(schema.TypedNode); ok { 49 n = n2.Representation() 50 } 51 switch n.Kind() { 52 case datamodel.Kind_String: 53 s, _ := n.AsString() 54 return datamodel.PathSegmentOfString(s) 55 case datamodel.Kind_Int: 56 i, _ := n.AsInt() 57 return datamodel.PathSegmentOfInt(i) 58 default: 59 panic(fmt.Errorf("cannot get pathsegment from a %s", n.Kind())) 60 } 61 }