-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule2json.go
More file actions
378 lines (330 loc) · 10 KB
/
module2json.go
File metadata and controls
378 lines (330 loc) · 10 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// module2json.go
//
// Usage:
// module2json /path/to/MODULE.bazel
// module2json --stdin
//
// Notes:
// - This is an extractor that does NOT evaluate Starlark.
// - It extracts top-level module(...) and bazel_dep(...) calls with literal string/bool kwargs.
// - If it sees load() statements or unknown top-level macro calls, it marks output complete=false.
// - If it sees positional args for calls it handles, it marks output complete=false (kw-only extractor).
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"os"
"strings"
"go.starlark.net/syntax"
)
type Output struct {
Module struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
} `json:"module"`
BazelDeps []BazelDep `json:"bazel_deps"`
Overrides []map[string]any `json:"overrides,omitempty"`
Complete bool `json:"complete"`
Warnings []string `json:"warnings,omitempty"`
}
type BazelDep struct {
Name string `json:"name"`
Version string `json:"version,omitempty"`
RepoName *string `json:"repo_name,omitempty"`
DevDependency bool `json:"dev_dependency"`
}
// KwArg preserves whether a kwarg was present and, if present, whether it was a literal.
// Value is:
// - literal Go value (string/bool/int64/float64/nil) when literal
// - nil when non-literal (but still Present=true)
type KwArg struct {
Present bool
Value any
}
func main() {
// Usage:
// stdin:
// module2json --stdin
// module2json --stdin=false
//
// pretty:
// module2json --pretty MODULE.bazel
// module2json --pretty=false
stdin := flag.Bool("stdin", false, "read MODULE.bazel content from stdin")
pretty := flag.Bool("pretty", true, "pretty-print JSON output")
flag.Parse()
var (
filename string
src any // string or []byte
)
// Check whether we are reading from a file or a stdin
if *stdin {
filename = "MODULE.bazel"
moduleContent, err := io.ReadAll(os.Stdin)
if err != nil {
fatalf("failed to read stdin: %v", err)
}
src = moduleContent
} else {
if flag.NArg() != 1 {
fatalf("usage: %s [--stdin] /path/to/MODULE.bazel", os.Args[0])
}
filename = flag.Arg(0)
// src=nil means syntax.Parse will read from filename.
src = nil
}
// Parse Starlark syntax using go.starlark.net/syntax
var opts syntax.FileOptions
file, err := opts.Parse(filename, src, 0)
if err != nil {
fatalf("parse error: %v", err)
}
// Extract top-level statements
output := extract(file)
enc := json.NewEncoder(os.Stdout)
if *pretty {
enc.SetIndent("", " ")
}
if err := enc.Encode(output); err != nil {
fatalf("failed to encode JSON: %v", err)
}
}
func extract(f *syntax.File) Output {
out := Output{Complete: true}
// Known "safe" top-level calls that don't imply hidden bazel_dep unless evaluated.
// Unknown top-level identifiers being called may be macros that declare bazel_dep.
knownTopLevelCalls := map[string]bool{
"module": true,
"bazel_dep": true,
// Overrides (recorded to understand how complete dependencies metadata of a module is)
"local_path_override": true,
"single_version_override": true,
"multiple_version_override": true,
"archive_override": true,
"git_override": true,
"bazel_dep_override": true,
"module_override": true,
"use_extension": true,
"use_repo": true,
"use_repo_rule": true,
"register_toolchains": true,
"register_execution_platforms": true,
}
for _, stmt := range f.Stmts {
// load() is a dedicated statement node in the AST.
if _, ok := stmt.(*syntax.LoadStmt); ok {
out.Complete = false
out.Warnings = append(out.Warnings,
"Found load() statement; dependencies may be declared via macros in loaded .bzl files (not evaluated).")
continue
}
expressionStmt, ok := stmt.(*syntax.ExprStmt)
if !ok {
continue
}
call, ok := expressionStmt.X.(*syntax.CallExpr)
if !ok {
continue
}
fnName, fnKind := calleeName(call.Fn)
if fnKind != "ident" {
// Something like obj.method(...). Could still declare deps, but we won't try.
out.Complete = false
out.Warnings = append(out.Warnings,
"Found non-identifier top-level call (e.g. obj.method(...)); cannot determine whether it declares bazel_dep.")
continue
}
// If it's a top-level call to an unknown identifier, it might be a macro that calls bazel_dep.
if !knownTopLevelCalls[fnName] {
out.Complete = false
out.Warnings = append(out.Warnings,
fmt.Sprintf("Found top-level call to %q; may declare bazel_dep via macro expansion which is not evaluated.", fnName))
continue
}
switch fnName {
case "module":
kw, sawPositional := kwArgs(call)
if sawPositional {
out.Complete = false
out.Warnings = append(out.Warnings,
"module() uses positional arguments; extractor supports keyword arguments only.")
}
if arg, ok := kw["name"]; ok && arg.Present {
if v, ok := arg.Value.(string); ok {
out.Module.Name = v
} else {
out.Complete = false
out.Warnings = append(out.Warnings, "module(name=...) is not a string literal; cannot extract reliably.")
}
}
if arg, ok := kw["version"]; ok && arg.Present {
if v, ok := arg.Value.(string); ok {
out.Module.Version = v
} else {
out.Complete = false
out.Warnings = append(out.Warnings, "module(version=...) is not a string literal; cannot extract reliably.")
}
}
case "bazel_dep":
dep, ok := parseBazelDep(call, &out)
if ok {
out.BazelDeps = append(out.BazelDeps, dep)
}
// Trying to catch all overrides
case "local_path_override", "single_version_override", "multiple_version_override",
"archive_override", "git_override", "bazel_dep_override", "module_override":
rec := map[string]any{"kind": fnName}
kw, sawPositional := kwArgs(call)
if sawPositional {
out.Complete = false
out.Warnings = append(out.Warnings,
fmt.Sprintf("%s() uses positional arguments; extractor supports keyword arguments only.", fnName))
}
for k, arg := range kw {
if !arg.Present {
continue
}
// Only keep literal values; non-literals are recorded as nil and skipped
if arg.Value != nil {
rec[k] = arg.Value
} else {
// kw present but non-literal
out.Complete = false
out.Warnings = append(out.Warnings,
fmt.Sprintf("%s(%s=...) is not a literal; override info may be incomplete.", fnName, k))
}
}
out.Overrides = append(out.Overrides, rec)
}
}
// Deduplicate repeated warnings (may have crazy loads there!)
out.Warnings = dedupe(out.Warnings)
return out
}
func parseBazelDep(call *syntax.CallExpr, out *Output) (BazelDep, bool) {
kw, sawPositional := kwArgs(call)
if sawPositional {
out.Complete = false
out.Warnings = append(out.Warnings,
"bazel_dep() uses positional arguments; extractor supports keyword arguments only.")
return BazelDep{}, false
}
nameArg, ok := kw["name"]
if !ok || !nameArg.Present {
out.Complete = false
out.Warnings = append(out.Warnings, "bazel_dep(name=...) missing; skipping one bazel_dep.")
return BazelDep{}, false
}
name, ok := nameArg.Value.(string)
if !ok || strings.TrimSpace(name) == "" {
out.Complete = false
out.Warnings = append(out.Warnings, "bazel_dep(name=...) is not a string literal; skipping one bazel_dep.")
return BazelDep{}, false
}
dep := BazelDep{Name: name}
if arg, ok := kw["version"]; ok && arg.Present {
if v, ok := arg.Value.(string); ok {
dep.Version = v
} else {
out.Complete = false
out.Warnings = append(out.Warnings,
fmt.Sprintf("bazel_dep(%s) version is not a string literal; omitting version.", name))
}
}
if arg, ok := kw["repo_name"]; ok && arg.Present {
if rn, ok := arg.Value.(string); ok {
rn = strings.TrimSpace(rn)
if rn != "" {
dep.RepoName = &rn
}
} else {
out.Complete = false
out.Warnings = append(out.Warnings,
fmt.Sprintf("bazel_dep(%s) repo_name is not a string literal; omitting repo_name.", name))
}
}
if arg, ok := kw["dev_dependency"]; ok && arg.Present {
if dd, ok := arg.Value.(bool); ok {
dep.DevDependency = dd
} else {
out.Complete = false
out.Warnings = append(out.Warnings,
fmt.Sprintf("bazel_dep(%s) dev_dependency is not a bool literal; defaulting to false.", name))
}
}
// If there are other kwargs we don't understand, we ignore them.
return dep, true
}
// kwArgs returns keyword args with presence tracking and literal values only.
// - string/bool/nil/number literals are returned as Go values.
// - any non-literal expression becomes Value=nil with Present=true.
// Positional args are ignored but reported via the returned sawPositional flag.
func kwArgs(call *syntax.CallExpr) (args map[string]KwArg, sawPositional bool) {
out := map[string]KwArg{}
positional := false
for _, arg := range call.Args {
be, ok := arg.(*syntax.BinaryExpr)
if !ok || be.Op != syntax.EQ {
// positional argument
positional = true
continue
}
id, ok := be.X.(*syntax.Ident)
if !ok {
continue
}
out[id.Name] = KwArg{
Present: true,
Value: literalValue(be.Y),
}
}
return out, positional
}
func literalValue(e syntax.Expr) any {
switch v := e.(type) {
case *syntax.Literal:
// v.Value can be: string, int64, float64, nil (and sometimes bool depending on parser)
return v.Value
case *syntax.Ident:
// In Starlark, True/False/None are identifiers (predeclared constants),
// and the parser represents them as Idents.
switch v.Name {
case "True":
return true
case "False":
return false
case "None":
return nil
default:
return nil
}
default:
// We do not attempt to evaluate expressions in this mode.
return nil
}
}
func calleeName(fn syntax.Expr) (name string, kind string) {
switch v := fn.(type) {
case *syntax.Ident:
return v.Name, "ident"
default:
return "", "other"
}
}
func dedupe(in []string) []string {
seen := map[string]bool{}
out := make([]string, 0, len(in))
for _, s := range in {
if !seen[s] {
seen[s] = true
out = append(out, s)
}
}
return out
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
}