Home

gen @e423ae92176cc817abac3a983cb7990c809d063e - refs - log -
-
https://git.jolheiser.com/gen.git
Generate Go flags and Nix module
gen / model.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
package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"maps"
	"slices"
	"strings"

	"cuelang.org/go/cue"
)

// kind is the base type of a scalar
type kind int

const (
	kindBool kind = iota
	kindInt
	kindFloat
	kindNumber
	kindString
)

func (k kind) String() string {
	return []string{"bool", "int", "float", "number", "string"}[k]
}

// scalar is a single bool, number, or string value, along with its constraints
type scalar struct {
	kind kind

	// Constraints from the schema
	enum     []any
	min      *bound
	max      *bound
	regexes  []scalarRegex
	notEmpty bool

	// @go(type, parse, import)
	goType    string
	goParse   string
	goImports []string

	// @nix(type, apply, import)
	nixType    string
	nixApply   string
	nixImports []string
}

// scalarRegex is a regex constraint on a scalar
type scalarRegex struct {
	pattern string
	// goName is the Go name of the definition the regex is written in, e.g. URL for #URL, or empty if there isn't one
	goName string
}

// customGo reports whether the scalar uses a custom Go type with its own parse function
func (s scalar) customGo() bool {
	return s.goParse != ""
}

// field is a single field of a struct.
// It is either a nested struct, a list of scalars, or a scalar.
type field struct {
	label    string
	path     []string
	goName   string
	doc      string
	optional bool

	// nested is set if the field is a struct.
	// Otherwise scalar describes the field, or each element if isList is set.
	nested *structType
	isList bool
	scalar scalar

	defaultValue any
	hasDefault   bool

	nixSkip       bool
	nixDefault    any
	hasNixDefault bool
	nixImports    []string
	// On a list field, @nix(type) and @nix(apply) are for the whole list rather than each element
	nixListType  string
	nixListApply string
}

// flagName returns the dotted path of the field, e.g. ssh.clone-url
func (f *field) flagName() string {
	return strings.Join(f.path, ".")
}

// errorf returns an error prefixed with the field's flag name
func (f *field) errorf(format string, args ...any) error {
	return fmt.Errorf("%s: %w", f.flagName(), fmt.Errorf(format, args...))
}

// structType is a CUE struct, generated as a Go struct type
type structType struct {
	goName string
	fields []*field
}

// builder builds the model from a CUE value, making sure generated Go names don't collide
type builder struct {
	names      namer
	typeSuffix string
	// typeOwners maps each Go struct type name to the flag name of the field that uses it
	typeOwners map[string]string
}

// buildModel validates v and builds the model for it, with the root struct named rootType
func buildModel(v cue.Value, rootType, typeSuffix string, names namer) (*structType, error) {
	if err := v.Validate(); err != nil {
		return nil, err
	}

	b := &builder{
		names:      names,
		typeSuffix: typeSuffix,
		typeOwners: map[string]string{
			rootType: "(root)",
		},
	}
	return b.buildStruct(v, nil, rootType)
}

// buildStruct builds the struct at path, including all of its fields
func (b *builder) buildStruct(v cue.Value, path []string, goName string) (*structType, error) {
	if v.LookupPath(cue.MakePath(cue.AnyString)).Exists() {
		return nil, fmt.Errorf("%s: structs with pattern constraints ([string]: T) are not supported", pathString(path))
	}

	iter, err := v.Fields(cue.Optional(true))
	if err != nil {
		return nil, fmt.Errorf("%s: %w", pathString(path), err)
	}

	st := &structType{goName: goName}
	// fieldOwners maps each Go field name to the flag name that uses it
	fieldOwners := make(map[string]string)
	for iter.Next() {
		fieldPath := append(slices.Clone(path), iter.Selector().Unquoted())
		f, err := b.buildField(iter.Value(), fieldPath, iter.IsOptional())
		if err != nil {
			return nil, err
		}

		if owner, ok := fieldOwners[f.goName]; ok {
			return nil, fmt.Errorf("%s: Go field name %s is also used by %s; set @go(name=...)", f.flagName(), f.goName, owner)
		}
		fieldOwners[f.goName] = f.flagName()

		st.fields = append(st.fields, f)
	}
	return st, nil
}

// buildField builds the field at path
func (b *builder) buildField(v cue.Value, path []string, optional bool) (*field, error) {
	f := &field{
		label:    path[len(path)-1],
		path:     path,
		doc:      docText(v),
		optional: optional,
	}

	goAttrs, err := readAttrs(v, "go", "name", "type", "parse", "import")
	if err != nil {
		return nil, f.errorf("%w", err)
	}
	nixAttrs, err := readAttrs(v, "nix", "type", "apply", "import", "default", "skip")
	if err != nil {
		return nil, f.errorf("%w", err)
	}

	f.goName = goAttrs["name"]
	if f.goName == "" {
		f.goName, err = b.names.fieldName(f.label)
		if err != nil {
			return nil, f.errorf("%w", err)
		}
	}
	_, f.nixSkip = nixAttrs["skip"]

	switch v.IncompleteKind() {
	case cue.StructKind:
		if err := b.buildStructField(v, f, goAttrs, nixAttrs); err != nil {
			return nil, err
		}
		return f, nil
	case cue.ListKind:
		err = b.buildListField(v, f, goAttrs, nixAttrs)
	default:
		err = b.buildScalarField(v, f, goAttrs, nixAttrs)
	}
	if err != nil {
		return nil, err
	}

	if err := setNixImports(f, nixAttrs); err != nil {
		return nil, err
	}
	if err := setDefaults(v, f, nixAttrs); err != nil {
		return nil, err
	}
	return f, nil
}

// buildStructField fills in f as a nested struct
func (b *builder) buildStructField(v cue.Value, f *field, goAttrs, nixAttrs map[string]string) error {
	if goAttrs["parse"] != "" || goAttrs["import"] != "" {
		return f.errorf("@go(parse) and @go(import) are not allowed on structs")
	}
	for _, key := range []string{"default", "apply", "import"} {
		if _, ok := nixAttrs[key]; ok {
			return f.errorf("@nix(%s) is not allowed on structs; set it on the fields", key)
		}
	}

	typeName := goAttrs["type"]
	if typeName == "" {
		var err error
		typeName, err = b.names.typeName(f.label, b.typeSuffix)
		if err != nil {
			return f.errorf("%w", err)
		}
	}
	if owner, ok := b.typeOwners[typeName]; ok {
		return f.errorf("Go type %s is also used by %s; set @go(type=...)", typeName, owner)
	}
	b.typeOwners[typeName] = f.flagName()

	nested, err := b.buildStruct(v, f.path, typeName)
	if err != nil {
		return err
	}
	f.nested = nested
	return nil
}

// buildListField fills in f as a list of scalars
func (b *builder) buildListField(v cue.Value, f *field, goAttrs, nixAttrs map[string]string) error {
	f.isList = true

	elem := listElem(v)
	if !elem.Exists() {
		return f.errorf("only open lists ([...T]) are supported")
	}
	if elemKind := elem.IncompleteKind(); elemKind == cue.ListKind || elemKind == cue.StructKind {
		return f.errorf("lists of %v are not supported", elemKind)
	}

	s, err := b.buildScalar(elem, goAttrs)
	if err != nil {
		return f.errorf("%w", err)
	}
	f.scalar = s
	f.nixListType = nixAttrs["type"]
	f.nixListApply = nixAttrs["apply"]
	return nil
}

// buildScalarField fills in f as a scalar
func (b *builder) buildScalarField(v cue.Value, f *field, goAttrs, nixAttrs map[string]string) error {
	s, err := b.buildScalar(v, goAttrs)
	if err != nil {
		return f.errorf("%w", err)
	}

	// The field's own @nix attributes win over any from a definition
	if nixType := nixAttrs["type"]; nixType != "" {
		s.nixType = nixType
	}
	if nixApply := nixAttrs["apply"]; nixApply != "" {
		s.nixApply = nixApply
	}

	f.scalar = s
	return nil
}

// setNixImports collects the names f's Nix type and apply use, and makes sure each can be a Nix function argument
func setNixImports(f *field, nixAttrs map[string]string) error {
	f.nixImports = f.scalar.nixImports
	if imports := nixAttrs["import"]; imports != "" {
		f.nixImports = append(strings.Fields(imports), f.nixImports...)
	}

	for _, name := range f.nixImports {
		if !nixIdent.MatchString(name) || nixKeywords[name] || nixReserved[name] {
			return f.errorf("@nix(import): %q can't be a Nix function argument", name)
		}
	}
	return nil
}

// setDefaults sets f's schema default, and its Nix default if @nix(default) is set
func setDefaults(v cue.Value, f *field, nixAttrs map[string]string) error {
	if def, ok := concreteDefault(v); ok {
		value, err := decode(def)
		if err != nil {
			return f.errorf("default: %w", err)
		}
		f.defaultValue = value
		f.hasDefault = true
	}

	if raw, ok := nixAttrs["default"]; ok {
		value, err := parseNixDefault(v, f, raw)
		if err != nil {
			return f.errorf("@nix(default=%s): %w", raw, err)
		}
		f.nixDefault = value
		f.hasNixDefault = true
	}
	return nil
}

// parseNixDefault parses the value of @nix(default=...) and checks it against the schema.
// For string fields the raw text is the value, otherwise it's parsed as CUE.
func parseNixDefault(v cue.Value, f *field, raw string) (any, error) {
	var def cue.Value
	if !f.isList && f.scalar.kind == kindString {
		def = v.Context().Encode(raw)
	} else {
		def = v.Context().CompileString(raw)
	}
	if err := def.Err(); err != nil {
		return nil, err
	}

	unified := v.Unify(def)
	if err := unified.Validate(cue.Concrete(true)); err != nil {
		return nil, err
	}
	return decode(unified)
}

// listElem returns the element type of an open list ([...T]), or a non-existent value if v isn't one.
//
// v may be wrapped, or be a disjunction such as [...int] | *[1, 2] when the list has a default,
// so up to a few layers are looked through to find the list.
func listElem(v cue.Value) cue.Value {
	anyIndex := cue.MakePath(cue.AnyIndex)
	for range 4 {
		if elem := v.LookupPath(anyIndex); elem.Exists() {
			return elem
		}

		op, args := v.Expr()
		switch {
		case op == cue.NoOp && len(args) == 1:
			v = args[0]
		case op == cue.OrOp:
			// Only one side of the disjunction may be an open list
			var elems []cue.Value
			for _, arg := range args {
				if elem := arg.LookupPath(anyIndex); elem.Exists() {
					elems = append(elems, elem)
				}
			}
			if len(elems) != 1 {
				return cue.Value{}
			}
			return elems[0]
		default:
			return cue.Value{}
		}
	}
	return cue.Value{}
}

// concreteDefault returns v's default, or v itself if it's already a concrete value
func concreteDefault(v cue.Value) (cue.Value, bool) {
	if def, ok := v.Default(); ok && def.IsConcrete() {
		return def, true
	}
	if v.IsConcrete() && v.Validate(cue.Concrete(true)) == nil {
		return v, true
	}
	return cue.Value{}, false
}

// buildScalar builds the scalar for v, along with its constraints.
//
// @go and @nix attributes are also read from any definitions v references (e.g. #Duration).
// fieldGoAttrs are the field's own @go attributes, which win over those of the definitions.
func (b *builder) buildScalar(v cue.Value, fieldGoAttrs map[string]string) (scalar, error) {
	var s scalar
	switch k := v.IncompleteKind(); k {
	case cue.BoolKind:
		s.kind = kindBool
	case cue.IntKind:
		s.kind = kindInt
	case cue.FloatKind:
		s.kind = kindFloat
	case cue.NumberKind:
		s.kind = kindNumber
	case cue.StringKind:
		s.kind = kindString
	default:
		return s, fmt.Errorf("unsupported type %v", k)
	}

	var c constraints
	if err := c.collect(v, "", 0); err != nil {
		return s, err
	}
	s.min = c.min
	s.max = c.max
	for _, re := range c.regexes {
		sr := scalarRegex{pattern: re.pattern}
		if re.definition != "" {
			// A definition that can't be a Go name just falls back to the field's name
			sr.goName, _ = b.names.fieldName(re.definition)
		}
		s.regexes = append(s.regexes, sr)
	}
	s.notEmpty = c.notEmpty
	for _, e := range c.enum {
		value, err := decode(e)
		if err != nil {
			return s, err
		}
		s.enum = append(s.enum, value)
	}

	goAttrs := make(map[string]string)
	maps.Copy(goAttrs, fieldGoAttrs)
	// Definitions are nearest first, so the first one to set an attribute wins
	for _, def := range c.definitions {
		defGoAttrs, err := readAttrs(def, "go", "type", "parse", "import")
		if err != nil {
			return s, err
		}
		defNixAttrs, err := readAttrs(def, "nix", "type", "apply", "import")
		if err != nil {
			return s, err
		}

		for key, val := range defGoAttrs {
			if _, ok := goAttrs[key]; !ok {
				goAttrs[key] = val
			}
		}
		if s.nixType == "" {
			s.nixType = defNixAttrs["type"]
		}
		if s.nixApply == "" {
			s.nixApply = defNixAttrs["apply"]
		}
		s.nixImports = append(s.nixImports, strings.Fields(defNixAttrs["import"])...)
	}

	s.goType = goAttrs["type"]
	s.goParse = goAttrs["parse"]
	if (s.goType == "") != (s.goParse == "") {
		return s, errors.New("@go(type) and @go(parse) must be set together")
	}
	s.goImports = strings.Fields(goAttrs["import"])

	return s, nil
}

// readAttrs returns the key=value arguments of the @name(...) attribute on v, or nil if there isn't one.
// A key without a value, such as @nix(skip), maps to an empty string. Any key not in known is an error.
func readAttrs(v cue.Value, name string, known ...string) (map[string]string, error) {
	attr := v.Attribute(name)
	if attr.Err() != nil {
		return nil, nil
	}

	attrs := make(map[string]string)
	for idx := range attr.NumArgs() {
		key, val := attr.Arg(idx)
		key = strings.TrimSpace(key)
		if !slices.Contains(known, key) {
			return nil, fmt.Errorf("unknown key %q in @%s (known: %s)", key, name, strings.Join(slices.Sorted(slices.Values(known)), ", "))
		}
		attrs[key] = strings.TrimSpace(val)
	}
	return attrs, nil
}

// docText returns v's doc comments, one paragraph per comment group
func docText(v cue.Value) string {
	var paragraphs []string
	for _, group := range v.Doc() {
		if text := strings.TrimSpace(group.Text()); text != "" {
			paragraphs = append(paragraphs, text)
		}
	}
	return strings.Join(paragraphs, "\n\n")
}

// decode converts a concrete CUE value to a Go value, keeping numbers as json.Number so they print as written
func decode(v cue.Value) (any, error) {
	data, err := v.MarshalJSON()
	if err != nil {
		return nil, err
	}

	dec := json.NewDecoder(bytes.NewReader(data))
	dec.UseNumber()
	var out any
	if err := dec.Decode(&out); err != nil {
		return nil, err
	}
	return out, nil
}

// valueString returns a decoded value as plain text, e.g. for usage and error messages
func valueString(v any) string {
	switch v := v.(type) {
	case string:
		return v
	case json.Number:
		return v.String()
	default:
		return fmt.Sprint(v)
	}
}

// pathString returns path as a flag name, or (root) for the root struct
func pathString(path []string) string {
	if len(path) == 0 {
		return "(root)"
	}
	return strings.Join(path, ".")
}