common.go 1.78 KB
Newer Older
1 2 3 4 5 6
package traversal

import (
	"context"
	"fmt"

tavit ohanian's avatar
tavit ohanian committed
7
	ld "gitlab.dms3.io/ld/go-ld-prime"
tavit ohanian's avatar
tavit ohanian committed
8
	"gitlab.dms3.io/ld/go-ld-prime/schema"
9 10 11 12
)

// init sets all the values in TraveralConfig to reasonable defaults
// if they're currently the zero value.
13 14 15 16
//
// Note that you're absolutely going to need to replace the
// LinkLoader and LinkNodeBuilderChooser if you want automatic link traversal;
// the defaults return error and/or panic.
17
func (tc *Config) init() {
18 19 20
	if tc.Ctx == nil {
		tc.Ctx = context.Background()
	}
21
	if tc.LinkTargetNodePrototypeChooser == nil {
tavit ohanian's avatar
tavit ohanian committed
22
		tc.LinkTargetNodePrototypeChooser = func(lnk ld.Link, lnkCtx ld.LinkContext) (ld.NodePrototype, error) {
23
			if tlnkNd, ok := lnkCtx.LinkNode.(schema.TypedLinkNode); ok {
24
				return tlnkNd.LinkTargetNodePrototype(), nil
25
			}
26
			return nil, fmt.Errorf("no LinkTargetNodePrototypeChooser configured")
27 28 29 30
		}
	}
}

Eric Myhre's avatar
Eric Myhre committed
31 32 33
func (prog *Progress) init() {
	if prog.Cfg == nil {
		prog.Cfg = &Config{}
34
	}
Eric Myhre's avatar
Eric Myhre committed
35
	prog.Cfg.init()
36
}
37 38 39 40 41 42

// asPathSegment figures out how to coerce a node into a PathSegment.
// If it's a typed node: we take its representation.  (Could be a struct with some string representation.)
// If it's a string or an int, that's it.
// Any other case will panic.  (If you're using this one keys returned by a MapIterator, though, you can ignore this possibility;
// 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.)
tavit ohanian's avatar
tavit ohanian committed
43
func asPathSegment(n ld.Node) ld.PathSegment {
44 45 46 47
	if n2, ok := n.(schema.TypedNode); ok {
		n = n2.Representation()
	}
	switch n.Kind() {
tavit ohanian's avatar
tavit ohanian committed
48
	case ld.Kind_String:
49
		s, _ := n.AsString()
tavit ohanian's avatar
tavit ohanian committed
50 51
		return ld.PathSegmentOfString(s)
	case ld.Kind_Int:
52
		i, _ := n.AsInt()
tavit ohanian's avatar
tavit ohanian committed
53
		return ld.PathSegmentOfInt(i)
54 55 56 57
	default:
		panic(fmt.Errorf("cannot get pathsegment from a %s", n.Kind()))
	}
}