Home

gen @e423ae92176cc817abac3a983cb7990c809d063e - refs - log -
-
https://git.jolheiser.com/gen.git
Generate Go flags and Nix module
gen / testdata / kitchen.go.golden
- 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
// Code generated by gen from kitchen.cue; DO NOT EDIT.

package kitchen

import (
	"errors"
	"flag"
	"fmt"
	"regexp"
	"slices"
	"strconv"
	"time"
)

var (
	reTags    = regexp.MustCompile("^[a-z]+$")
	reWebhook = regexp.MustCompile("^https://")
	reID      = regexp.MustCompile("^\\d+$")
)

type config struct {
	// Service name, shown in logs.
	//
	// A second paragraph only goes into the Nix description.
	Name string
	// Worker count.
	Workers int
	// Retries; negative means forever.
	Retries int
	// Sampling ratio.
	Ratio float64
	// Any number.
	Scale float64
	// Request timeout.
	Timeout time.Duration
	// Backoff steps.
	Backoff []time.Duration
	// Priority.
	Priority int
	Level    string
	// Tags to attach.
	Tags []string
	// Ports to probe.
	Probes []int
	// Optional webhook.
	Webhook string
	// Uses an RE2-only pattern.
	ID string
	// Optional, with a field-level Nix type and apply.
	Owner string
	// Ends up in Go only.
	Secret string
	With   withConfig
	Db     dbConfig
}

type withConfig struct {
	// A Nix keyword as a key, and an `if` below it.
	If bool
	// A key that needs quoting in Nix.
	HasSpace string
}

type dbConfig struct {
	// Database URL.
	URL string
}

// defaultArgs returns the defaults from kitchen.cue.
func defaultArgs() config {
	return config{
		Workers:  4,
		Retries:  3,
		Ratio:    0.5,
		Scale:    1,
		Timeout:  mustParse(time.ParseDuration, "30s"),
		Backoff:  []time.Duration{mustParse(time.ParseDuration, "1s"), mustParse(time.ParseDuration, "5s")},
		Priority: 2,
		Level:    "low",
		Probes:   []int{80, 443},
		ID:       "1",
		With: withConfig{
			HasSpace: "x",
		},
		Db: dbConfig{
			URL: "postgres://localhost/app",
		},
	}
}

// registerFlags defines a flag for every field of c, using c's current
// values as flag defaults.
func registerFlags(fs *flag.FlagSet, c *config) {
	fs.StringVar(&c.Name, "name", c.Name, "Service name, shown in logs.")
	fs.IntVar(&c.Workers, "workers", c.Workers, "Worker count.")
	fs.IntVar(&c.Retries, "retries", c.Retries, "Retries; negative means forever.")
	fs.Float64Var(&c.Ratio, "ratio", c.Ratio, "Sampling ratio.")
	fs.Float64Var(&c.Scale, "scale", c.Scale, "Any number.")
	fs.Func("timeout", "Request timeout. (default: 30s)", func(s string) error {
		v, err := time.ParseDuration(s)
		if err != nil {
			return err
		}
		c.Timeout = v
		return nil
	})
	{
		set := false
		fs.Func("backoff", "Backoff steps. (repeatable; default: 1s, 5s)", func(s string) error {
			v, err := time.ParseDuration(s)
			if err != nil {
				return err
			}
			if !set {
				c.Backoff, set = nil, true
			}
			c.Backoff = append(c.Backoff, v)
			return nil
		})
	}
	fs.IntVar(&c.Priority, "priority", c.Priority, "Priority. (one of: 1, 2, 3)")
	fs.StringVar(&c.Level, "level", c.Level, "(one of: low, mid, high)")
	{
		set := false
		fs.Func("tags", "Tags to attach. (repeatable)", func(s string) error {
			v := s
			if !set {
				c.Tags, set = nil, true
			}
			c.Tags = append(c.Tags, v)
			return nil
		})
	}
	{
		set := false
		fs.Func("probes", "Ports to probe. (repeatable; default: 80, 443)", func(s string) error {
			v, err := strconv.Atoi(s)
			if err != nil {
				return err
			}
			if !set {
				c.Probes, set = nil, true
			}
			c.Probes = append(c.Probes, v)
			return nil
		})
	}
	fs.StringVar(&c.Webhook, "webhook", c.Webhook, "Optional webhook.")
	fs.StringVar(&c.ID, "id", c.ID, "Uses an RE2-only pattern.")
	fs.StringVar(&c.Owner, "owner", c.Owner, "Optional, with a field-level Nix type and apply.")
	fs.StringVar(&c.Secret, "secret", c.Secret, "Ends up in Go only.")
	fs.BoolVar(&c.With.If, "with.if", c.With.If, "A Nix keyword as a key, and an `if` below it.")
	fs.StringVar(&c.With.HasSpace, "with.has space", c.With.HasSpace, "A key that needs quoting in Nix.")
	fs.StringVar(&c.Db.URL, "db.url", c.Db.URL, "Database URL.")
}

// validate checks c against the constraints in kitchen.cue.
func (c *config) validate() error {
	var errs []error
	if c.Workers < 1 {
		errs = append(errs, fmt.Errorf("workers: must be >= 1, got %v", c.Workers))
	}
	if c.Workers > 64 {
		errs = append(errs, fmt.Errorf("workers: must be <= 64, got %v", c.Workers))
	}
	if c.Retries < -1 {
		errs = append(errs, fmt.Errorf("retries: must be >= -1, got %v", c.Retries))
	}
	if c.Ratio <= 0 {
		errs = append(errs, fmt.Errorf("ratio: must be > 0, got %v", c.Ratio))
	}
	if c.Ratio > 1 {
		errs = append(errs, fmt.Errorf("ratio: must be <= 1, got %v", c.Ratio))
	}
	if !slices.Contains([]int{1, 2, 3}, c.Priority) {
		errs = append(errs, fmt.Errorf("priority: %v is not one of [1, 2, 3]", c.Priority))
	}
	if !slices.Contains([]string{"low", "mid", "high"}, c.Level) {
		errs = append(errs, fmt.Errorf("level: %q is not one of [low, mid, high]", c.Level))
	}
	for i, v := range c.Tags {
		if !reTags.MatchString(v) {
			errs = append(errs, fmt.Errorf("tags[%d]: %q does not match %s", i, v, reTags))
		}
	}
	for i, v := range c.Probes {
		if v < 1 {
			errs = append(errs, fmt.Errorf("probes[%d]: must be >= 1, got %v", i, v))
		}
		if v > 65535 {
			errs = append(errs, fmt.Errorf("probes[%d]: must be <= 65535, got %v", i, v))
		}
	}
	if c.Webhook != "" {
		if !reWebhook.MatchString(c.Webhook) {
			errs = append(errs, fmt.Errorf("webhook: %q does not match %s", c.Webhook, reWebhook))
		}
	}
	if !reID.MatchString(c.ID) {
		errs = append(errs, fmt.Errorf("id: %q does not match %s", c.ID, reID))
	}
	return errors.Join(errs...)
}

// 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
}