-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
module_loader.go
184 lines (174 loc) · 4.13 KB
/
module_loader.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package gojq
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// ModuleLoader is the interface for loading modules.
//
// Implement following optional methods. Use [NewModuleLoader] to load local modules.
//
// LoadInitModules() ([]*Query, error)
// LoadModule(string) (*Query, error)
// LoadModuleWithMeta(string, map[string]any) (*Query, error)
// LoadJSON(string) (any, error)
// LoadJSONWithMeta(string, map[string]any) (any, error)
type ModuleLoader any
// NewModuleLoader creates a new [ModuleLoader] loading local modules in the paths.
// Note that user can load modules outside the paths using "search" path of metadata.
// Empty paths are ignored, so specify "." for the current working directory.
func NewModuleLoader(paths []string) ModuleLoader {
ps := make([]string, 0, len(paths))
for _, path := range paths {
if path = resolvePath(path, ""); path != "" {
ps = append(ps, path)
}
}
return &moduleLoader{ps}
}
type moduleLoader struct {
paths []string
}
func (l *moduleLoader) LoadInitModules() ([]*Query, error) {
var qs []*Query
for _, path := range l.paths {
if filepath.Base(path) != ".jq" {
continue
}
fi, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
if fi.IsDir() {
continue
}
cnt, err := os.ReadFile(path)
if err != nil {
return nil, err
}
q, err := parseModule(string(cnt), filepath.Dir(path))
if err != nil {
return nil, &queryParseError{path, string(cnt), err}
}
qs = append(qs, q)
}
return qs, nil
}
func (l *moduleLoader) LoadModuleWithMeta(name string, meta map[string]any) (*Query, error) {
path, err := l.lookupModule(name, ".jq", meta)
if err != nil {
return nil, err
}
cnt, err := os.ReadFile(path)
if err != nil {
return nil, err
}
q, err := parseModule(string(cnt), filepath.Dir(path))
if err != nil {
return nil, &queryParseError{path, string(cnt), err}
}
return q, nil
}
func (l *moduleLoader) LoadJSONWithMeta(name string, meta map[string]any) (any, error) {
path, err := l.lookupModule(name, ".json", meta)
if err != nil {
return nil, err
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
vals := []any{}
dec := json.NewDecoder(f)
dec.UseNumber()
for {
var val any
if err := dec.Decode(&val); err != nil {
if err == io.EOF {
break
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
cnt, er := io.ReadAll(f)
if er != nil {
return nil, er
}
return nil, &jsonParseError{path, string(cnt), err}
}
vals = append(vals, val)
}
return vals, nil
}
func (l *moduleLoader) lookupModule(name, extension string, meta map[string]any) (string, error) {
paths := l.paths
if path, ok := meta["search"].(string); ok {
if path = resolvePath(path, ""); path != "" {
paths = append([]string{path}, paths...)
}
}
for _, base := range paths {
path := filepath.Join(base, name+extension)
if _, err := os.Stat(path); err == nil {
return path, err
}
path = filepath.Join(base, name, filepath.Base(name)+extension)
if _, err := os.Stat(path); err == nil {
return path, err
}
}
return "", fmt.Errorf("module not found: %q", name)
}
func parseModule(cnt, dir string) (*Query, error) {
q, err := Parse(cnt)
if err != nil {
return nil, err
}
for _, i := range q.Imports {
if i.Meta != nil {
for _, e := range i.Meta.KeyVals {
if e.Key == "search" || e.KeyString == "search" {
if path, ok := e.Val.toString(); ok {
if path = resolvePath(path, dir); path != "" {
e.Val.Str = path
} else {
e.Val.Null = true
}
}
}
}
}
}
return q, nil
}
func resolvePath(path, dir string) string {
switch {
case filepath.IsAbs(path):
return path
case strings.HasPrefix(path, "~/"):
dir, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(dir, path[2:])
case strings.HasPrefix(path, "$ORIGIN/"):
exe, err := os.Executable()
if err != nil {
return ""
}
exe, err = filepath.EvalSymlinks(exe)
if err != nil {
return ""
}
return filepath.Join(filepath.Dir(exe), path[8:])
default:
return filepath.Join(dir, path)
}
}