Home

gen @e423ae92176cc817abac3a983cb7990c809d063e - refs - log -
-
https://git.jolheiser.com/gen.git
Generate Go flags and Nix module
gen / golang.go
- raw -
  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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"go/format"
	"maps"
	"slices"
	"strconv"
	"strings"
)

// goGen generates the Go source for a schema.
// The output is run through gofmt, so the code written here doesn't need to be indented.
type goGen struct {
	pkg     string
	schema  string
	root    *structType
	imports map[string]bool

	// regexVars are the package-level regexp declarations, in order
	regexVars []string
	// regexNames maps each regex pattern to its variable, so a pattern shared by fields is only compiled once
	regexNames map[string]string
	// regexNamesUsed are the regex variable names already declared
	regexNamesUsed map[string]bool

	// needsMustParse is set once a default uses a custom parse function
	needsMustParse bool
}

// flagFuncs are the flag.FlagSet methods for each kind, when it isn't a custom Go type
var flagFuncs = map[kind]string{
	kindBool:   "BoolVar",
	kindInt:    "IntVar",
	kindFloat:  "Float64Var",
	kindNumber: "Float64Var",
	kindString: "StringVar",
}

const mustParseFunc = `
// mustParse applies a hand-written parse hook to a schema default. gen has
// already checked the default against the schema, so a failure here means
// the hook and the schema disagree.
func mustParse[T any](parse func(string) (T, error), s string) T {
	v, err := parse(s)
	if err != nil {
		panic(fmt.Sprintf("schema default %q rejected by parse hook: %v", s, err))
	}
	return v
}
`

// genGo returns the generated Go source for root
func genGo(root *structType, pkg, schema string) ([]byte, error) {
	g := &goGen{
		pkg:    pkg,
		schema: schema,
		root:   root,
		imports: map[string]bool{
			"flag": true,
		},
		regexNames:     make(map[string]string),
		regexNamesUsed: make(map[string]bool),
	}

	// The body is generated first, since it decides which imports and regexes the header needs
	var body bytes.Buffer
	g.writeStructs(&body, root)
	g.writeDefaults(&body)
	g.writeRegisterFlags(&body)
	g.writeValidate(&body)
	if g.needsMustParse {
		g.imports["fmt"] = true
		body.WriteString(mustParseFunc)
	}

	var out bytes.Buffer
	g.writeHeader(&out)
	out.Write(body.Bytes())

	src, err := format.Source(out.Bytes())
	if err != nil {
		return nil, fmt.Errorf("formatting generated Go: %w\n%s", err, out.Bytes())
	}
	return src, nil
}

// writeHeader writes the package clause, imports, and regex variables
func (g *goGen) writeHeader(w *bytes.Buffer) {
	fmt.Fprintf(w, "// Code generated by gen from %s; DO NOT EDIT.\n\npackage %s\n\n", g.schema, g.pkg)

	w.WriteString("import (\n")
	for _, imp := range slices.Sorted(maps.Keys(g.imports)) {
		fmt.Fprintf(w, "%q\n", imp)
	}
	w.WriteString(")\n")

	if len(g.regexVars) > 0 {
		w.WriteString("\nvar (\n")
		for _, regexVar := range g.regexVars {
			w.WriteString(regexVar + "\n")
		}
		w.WriteString(")\n")
	}
}

// writeStructs writes the type declaration for st, followed by those of its nested structs
func (g *goGen) writeStructs(w *bytes.Buffer, st *structType) {
	fmt.Fprintf(w, "\ntype %s struct {\n", st.goName)
	for _, f := range st.fields {
		// Nested structs don't get a doc comment
		if f.doc != "" && f.nested == nil {
			for line := range strings.SplitSeq(f.doc, "\n") {
				fmt.Fprintf(w, "// %s\n", line)
			}
		}
		fmt.Fprintf(w, "%s %s\n", f.goName, g.fieldType(f))
	}
	w.WriteString("}\n")

	for _, f := range st.fields {
		if f.nested != nil {
			g.writeStructs(w, f.nested)
		}
	}
}

// fieldType returns the Go type of f
func (g *goGen) fieldType(f *field) string {
	if f.nested != nil {
		return f.nested.goName
	}
	if f.isList {
		return "[]" + g.scalarType(f.scalar)
	}
	return g.scalarType(f.scalar)
}

// scalarType returns the Go type of s, adding any imports a custom type needs
func (g *goGen) scalarType(s scalar) string {
	if s.customGo() {
		for _, imp := range s.goImports {
			g.imports[imp] = true
		}
		return s.goType
	}

	switch s.kind {
	case kindBool:
		return "bool"
	case kindInt:
		return "int"
	case kindFloat, kindNumber:
		return "float64"
	default:
		return "string"
	}
}

// writeDefaults writes defaultArgs, which returns the schema's defaults
func (g *goGen) writeDefaults(w *bytes.Buffer) {
	literal, _ := g.structLiteral(g.root)
	fmt.Fprintf(w, `
// defaultArgs returns the defaults from %s.
func defaultArgs() %s {
	return %s
}
`, g.schema, g.root.goName, literal)
}

// structLiteral returns a composite literal of st's defaults.
// Zero values are left out, and the bool reports whether anything was left in.
func (g *goGen) structLiteral(st *structType) (string, bool) {
	var literal strings.Builder
	hasValues := false

	literal.WriteString(st.goName + "{\n")
	for _, f := range st.fields {
		var value string
		var ok bool
		switch {
		case f.nested != nil:
			value, ok = g.structLiteral(f.nested)
		case f.hasDefault:
			value, ok = g.defaultLiteral(f)
		}
		if ok {
			fmt.Fprintf(&literal, "%s: %s,\n", f.goName, value)
			hasValues = true
		}
	}
	literal.WriteString("}")

	return literal.String(), hasValues
}

// defaultLiteral returns a Go literal of f's default, or false if it's the zero value
func (g *goGen) defaultLiteral(f *field) (string, bool) {
	if !f.isList {
		return g.scalarLiteral(f.scalar, f.defaultValue)
	}

	items, _ := f.defaultValue.([]any)
	if len(items) == 0 {
		return "", false
	}
	literals := make([]string, len(items))
	for idx, item := range items {
		literal, ok := g.scalarLiteral(f.scalar, item)
		if !ok {
			// Zero values can't be left out of a list
			literal = zeroLiteral(f.scalar)
		}
		literals[idx] = literal
	}
	return fmt.Sprintf("[]%s{%s}", g.scalarType(f.scalar), strings.Join(literals, ", ")), true
}

// scalarLiteral returns a Go literal of value, or false if it's the zero value
func (g *goGen) scalarLiteral(s scalar, value any) (string, bool) {
	if s.customGo() {
		g.needsMustParse = true
		return fmt.Sprintf("mustParse(%s, %q)", s.goParse, valueString(value)), true
	}

	switch value := value.(type) {
	case string:
		return strconv.Quote(value), value != ""
	case bool:
		return strconv.FormatBool(value), value
	case json.Number:
		f, _ := value.Float64()
		return value.String(), f != 0
	}
	return "", false
}

// zeroLiteral returns a Go literal of the zero value for s
func zeroLiteral(s scalar) string {
	switch s.kind {
	case kindBool:
		return "false"
	case kindString:
		return `""`
	default:
		return "0"
	}
}

// writeRegisterFlags writes registerFlags, which defines a flag for every field
func (g *goGen) writeRegisterFlags(w *bytes.Buffer) {
	fmt.Fprintf(w, `
// registerFlags defines a flag for every field of c, using c's current
// values as flag defaults.
func registerFlags(fs *flag.FlagSet, c *%s) {
`, g.root.goName)

	g.eachLeaf(g.root, "c", func(f *field, accessor string) {
		name := strconv.Quote(f.flagName())
		usage := strconv.Quote(usageText(f))
		switch {
		case f.isList:
			g.writeListFlag(w, f, accessor, name, usage)
		case f.scalar.customGo():
			g.writeCustomFlag(w, f, accessor, name, usage)
		default:
			fmt.Fprintf(w, "fs.%s(&%s, %s, %s, %s)\n", flagFuncs[f.scalar.kind], accessor, name, accessor, usage)
		}
	})

	w.WriteString("}\n")
}

// writeListFlag writes a repeatable flag, where the first use replaces the default
func (g *goGen) writeListFlag(w *bytes.Buffer, f *field, accessor, name, usage string) {
	fmt.Fprintf(w, `{
	set := false
	fs.Func(%s, %s, func(s string) error {
`, name, usage)
	g.writeParse(w, f.scalar)
	fmt.Fprintf(w, `	if !set {
			%[1]s, set = nil, true
		}
		%[1]s = append(%[1]s, v)
		return nil
	})
}
`, accessor)
}

// writeCustomFlag writes a flag for a custom Go type, using its parse function
func (g *goGen) writeCustomFlag(w *bytes.Buffer, f *field, accessor, name, usage string) {
	fmt.Fprintf(w, "fs.Func(%s, %s, func(s string) error {\n", name, usage)
	g.writeParse(w, f.scalar)
	fmt.Fprintf(w, `	%s = v
	return nil
})
`, accessor)
}

// writeParse writes code that parses the flag's string s into v, returning any error
func (g *goGen) writeParse(w *bytes.Buffer, s scalar) {
	var call string
	switch {
	case s.customGo():
		call = s.goParse + "(s)"
	case s.kind == kindString:
		w.WriteString("v := s\n")
		return
	case s.kind == kindBool:
		g.imports["strconv"] = true
		call = "strconv.ParseBool(s)"
	case s.kind == kindInt:
		g.imports["strconv"] = true
		call = "strconv.Atoi(s)"
	default:
		g.imports["strconv"] = true
		call = "strconv.ParseFloat(s, 64)"
	}

	fmt.Fprintf(w, `v, err := %s
if err != nil {
	return err
}
`, call)
}

// usageText returns the flag usage for f.
// This is the first paragraph of its doc, then notes such as enum values and defaults the flag package can't show itself.
func usageText(f *field) string {
	usage := strings.Join(strings.Fields(firstParagraph(f.doc)), " ")

	var notes []string
	if len(f.scalar.enum) > 0 {
		notes = append(notes, "one of: "+joinValues(f.scalar.enum))
	}
	if f.isList {
		notes = append(notes, "repeatable")
	}
	// The flag package only shows defaults of the basic flag types
	if f.hasDefault && (f.isList || f.scalar.customGo()) {
		if items, ok := f.defaultValue.([]any); ok {
			if len(items) > 0 {
				notes = append(notes, "default: "+joinValues(items))
			}
		} else {
			notes = append(notes, "default: "+valueString(f.defaultValue))
		}
	}

	if len(notes) == 0 {
		return usage
	}
	if usage != "" {
		usage += " "
	}
	return usage + "(" + strings.Join(notes, "; ") + ")"
}

// joinValues returns decoded values as a comma-separated list
func joinValues(values []any) string {
	strs := make([]string, len(values))
	for idx, value := range values {
		strs[idx] = valueString(value)
	}
	return strings.Join(strs, ", ")
}

func firstParagraph(s string) string {
	paragraph, _, _ := strings.Cut(s, "\n\n")
	return paragraph
}

// writeValidate writes the validate method, which checks every field against its constraints
func (g *goGen) writeValidate(w *bytes.Buffer) {
	var checks bytes.Buffer
	g.eachLeaf(g.root, "c", func(f *field, accessor string) {
		// Custom types are checked by their parse function
		if f.scalar.customGo() {
			return
		}
		g.writeFieldChecks(&checks, f, accessor)
	})

	fmt.Fprintf(w, `
// validate checks c against the constraints in %s.
func (c *%s) validate() error {
`, g.schema, g.root.goName)

	if checks.Len() == 0 {
		w.WriteString("return nil\n}\n")
		return
	}

	g.imports["errors"] = true
	g.imports["fmt"] = true
	w.WriteString("var errs []error\n")
	w.Write(checks.Bytes())
	w.WriteString("return errors.Join(errs...)\n}\n")
}

// writeFieldChecks writes the checks for f.
// Each element of a list is checked, and an optional field is only checked when it's set.
func (g *goGen) writeFieldChecks(w *bytes.Buffer, f *field, accessor string) {
	// Regex variables not named after a definition are named after the field, e.g. c.Db.URL gets reDbURL
	regexName := "re" + strings.ReplaceAll(strings.TrimPrefix(accessor, "c."), ".", "")

	var checks bytes.Buffer
	switch {
	case f.isList:
		g.writeChecks(&checks, f, "v", true, regexName)
		if checks.Len() > 0 {
			fmt.Fprintf(w, "for i, v := range %s {\n%s}\n", accessor, checks.Bytes())
		}
	case f.optional:
		g.writeChecks(&checks, f, accessor, false, regexName)
		if checks.Len() > 0 {
			fmt.Fprintf(w, "if %s != %s {\n%s}\n", accessor, zeroLiteral(f.scalar), checks.Bytes())
		}
	default:
		g.writeChecks(w, f, accessor, false, regexName)
	}
}

// writeChecks writes an if statement for each of f's constraints, which appends to errs when value breaks it.
// inList is set when value is an element of a list, indexed by i.
func (g *goGen) writeChecks(w *bytes.Buffer, f *field, value string, inList bool, regexName string) {
	s := f.scalar

	// Error messages are printf formats, so the flag name needs any % escaped
	prefix := escapePercent(f.flagName())
	var prefixArgs []string
	if inList {
		prefix += "[%d]"
		prefixArgs = []string{"i"}
	}
	addCheck := func(cond, format string, args ...string) {
		err := errorExpr(prefix+": "+format, append(prefixArgs, args...))
		fmt.Fprintf(w, "if %s {\nerrs = append(errs, %s)\n}\n", cond, err)
	}

	if len(s.enum) > 0 {
		g.imports["slices"] = true
		literals := make([]string, len(s.enum))
		for idx, e := range s.enum {
			literals[idx] = valueString(e)
			if str, ok := e.(string); ok {
				literals[idx] = strconv.Quote(str)
			}
		}
		verb := "%v"
		if s.kind == kindString {
			verb = "%q"
		}
		cond := fmt.Sprintf("!slices.Contains([]%s{%s}, %s)", g.scalarType(s), strings.Join(literals, ", "), value)
		addCheck(cond, verb+" is not one of ["+escapePercent(joinValues(s.enum))+"]", value)
	}

	if s.kind == kindInt {
		lower, upper := intBounds(s)
		if lower != nil {
			n := strconv.FormatInt(*lower, 10)
			addCheck(value+" < "+n, "must be >= "+n+", got %v", value)
		}
		if upper != nil {
			n := strconv.FormatInt(*upper, 10)
			addCheck(value+" > "+n, "must be <= "+n+", got %v", value)
		}
	} else {
		if s.min != nil {
			failOp, want := "<", ">="
			if !s.min.inclusive {
				failOp, want = "<=", ">"
			}
			addCheck(value+" "+failOp+" "+s.min.value, "must be "+want+" "+s.min.value+", got %v", value)
		}
		if s.max != nil {
			failOp, want := ">", "<="
			if !s.max.inclusive {
				failOp, want = ">=", "<"
			}
			addCheck(value+" "+failOp+" "+s.max.value, "must be "+want+" "+s.max.value+", got %v", value)
		}
	}

	// An optional scalar is only checked when it isn't empty, so this would never fail
	if s.notEmpty && (f.isList || !f.optional) {
		addCheck(value+` == ""`, "must not be empty")
	}

	for _, re := range s.regexes {
		name := g.regexVar(re, regexName)
		addCheck("!"+name+".MatchString("+value+")", "%q does not match %s", value, name)
	}
}

// regexVar returns the name of the variable holding re, declaring it the first time a pattern is used.
// It's named after re's definition (e.g. reURL for #URL), otherwise fieldRegexName is used.
// A number is added if the name is already taken by another pattern.
func (g *goGen) regexVar(re scalarRegex, fieldRegexName string) string {
	if name, ok := g.regexNames[re.pattern]; ok {
		return name
	}

	base := fieldRegexName
	if re.goName != "" {
		base = "re" + re.goName
	}
	name := base
	for n := 2; g.regexNamesUsed[name]; n++ {
		name = base + strconv.Itoa(n)
	}

	g.imports["regexp"] = true
	g.regexNames[re.pattern] = name
	g.regexNamesUsed[name] = true
	g.regexVars = append(g.regexVars, fmt.Sprintf("%s = regexp.MustCompile(%q)", name, re.pattern))
	return name
}

// errorExpr returns a Go expression creating an error from a printf format and the Go expressions of its args
func errorExpr(format string, args []string) string {
	if len(args) == 0 {
		return fmt.Sprintf("errors.New(%q)", strings.ReplaceAll(format, "%%", "%"))
	}
	return fmt.Sprintf("fmt.Errorf(%q, %s)", format, strings.Join(args, ", "))
}

func escapePercent(s string) string {
	return strings.ReplaceAll(s, "%", "%%")
}

// eachLeaf calls fn for every non-struct field under st, along with the Go expression accessing it, e.g. c.Db.URL
func (g *goGen) eachLeaf(st *structType, accessor string, fn func(f *field, accessor string)) {
	for _, f := range st.fields {
		fieldAccessor := accessor + "." + f.goName
		if f.nested != nil {
			g.eachLeaf(f.nested, fieldAccessor, fn)
			continue
		}
		fn(f, fieldAccessor)
	}
}