File: option_module_loader_test.go

package info (click to toggle)
golang-github-wader-gojq 0.0~git20231105.2b6d9e2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 960 kB
  • sloc: yacc: 642; makefile: 84
file content (60 lines) | stat: -rw-r--r-- 952 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package gojq_test

import (
	"fmt"
	"log"

	"github.com/wader/gojq"
)

type moduleLoader struct{}

func (*moduleLoader) LoadModule(name string) (*gojq.Query, error) {
	switch name {
	case "module1":
		return gojq.Parse(`
			module { name: "module1", test: 42 };
			import "module2" as foo;
			def g: foo::f;
		`)
	case "module2":
		return gojq.Parse(`
			def f: .foo;
		`)
	case "module3":
		return gojq.Parse("")
	}
	return nil, fmt.Errorf("module not found: %q", name)
}

func ExampleWithModuleLoader() {
	query, err := gojq.Parse(`
		import "module1" as m;
		m::g
	`)
	if err != nil {
		log.Fatalln(err)
	}
	code, err := gojq.Compile(
		query,
		gojq.WithModuleLoader(&moduleLoader{}),
	)
	if err != nil {
		log.Fatalln(err)
	}
	input := map[string]any{"foo": 42}
	iter := code.Run(input)
	for {
		v, ok := iter.Next()
		if !ok {
			break
		}
		if err, ok := v.(error); ok {
			log.Fatalln(err)
		}
		fmt.Printf("%#v\n", v)
	}

	// Output:
	// 42
}