-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerator.go
More file actions
407 lines (370 loc) · 10.4 KB
/
Copy pathgenerator.go
File metadata and controls
407 lines (370 loc) · 10.4 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
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
package flagforge
import (
"bytes"
"fmt"
"go/format"
"io"
"strings"
"text/template"
"time"
)
const flagTemplate = `
// Code generated by go generate; DO NOT EDIT.
package {{ .Pkg }}
import (
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
)
// {{ .ConfigType }} represents all configuration options.
type {{ .ConfigType }} struct {
{{- range .Args }}
// {{ .ShortHelp }}
{{ .Name }} {{ .Type }}
{{- end }}
{{- range .Flags }}
// {{ .ShortHelp }}
{{- if eq .Type "filepath" }}
{{ .Name }} string ` + "`filepath:\"true\"`" + `
{{- else }}
{{ .Name }} {{ .Type }}
{{- end }}
{{- end }}
}
// Forge sets up and parses command-line flags.
func Forge(arguments []string) (*flag.FlagSet, *{{ .ConfigType }}, error) {
config := &{{ .ConfigType }}{}
fs := flag.NewFlagSet("{{ .FSName }}", flag.{{ .FSErrorHandling }})
{{- range $index, $element := .Args }}
if len(arguments) <= {{ $index }} {
return nil, nil, fmtError("missing required argument: {{ $element.Name }}")
}
{{- end }}
{{- range .Flags }}
{{- if or (eq .Type "string") (eq .Type "filepath") }}
fs.StringVar(&config.{{ .Name }}, "{{ .CLI }}", "{{ .Default }}", "{{ .ShortHelp }}")
{{- else if eq .Type "bool" }}
fs.BoolVar(&config.{{ .Name }}, "{{ .CLI }}", {{ .Default }}, "{{ .ShortHelp }}")
{{- else if eq .Type "int" }}
fs.IntVar(&config.{{ .Name }}, "{{ .CLI }}", {{ .Default }}, "{{ .ShortHelp }}")
{{- else if eq .Type "uint64" }}
fs.Uint64Var(&config.{{ .Name }}, "{{ .CLI }}", {{ .Default }}, "{{ .ShortHelp }}")
{{- else if eq .Type "int64" }}
fs.Int64Var(&config.{{ .Name }}, "{{ .CLI }}", {{ .Default }}, "{{ .ShortHelp }}")
{{- else if eq .Type "time.Duration" }}
fs.DurationVar(&config.{{ .Name }}, "{{ .CLI }}", mustParseDuration("{{ .Default }}"), "{{ .ShortHelp }}")
{{- else if eq .Type "[]string" }}
var tmp{{ .Name }} string
fs.StringVar(&tmp{{ .Name }}, "{{ .CLI }}", "{{ .Default }}", "{{ .ShortHelp }}")
{{- end }}
{{- end }}
{{- if .FSUsage }}
fs.Usage = func() {
usage("{{ .FSUsage }}")
fs.PrintDefaults()
}
{{- end }}
if err := fs.Parse(arguments); err != nil {
return nil, nil, err
}
{{- range $index, $element := .Args }}
{{- if eq .Type "string" }}
config.{{ .Name }} = fs.Arg({{ $index }})
{{- end }}
{{- end }}
{{- range $index, $element := .Flags }}
{{- if eq .Type "[]string" }}
config.{{ .Name }} = splitString(tmp{{ .Name }}, "{{ .Delimiter }}")
{{- end }}
{{- end }}
return fs, config, nil
}
func mustParseDuration(d string) time.Duration {
td, err := time.ParseDuration(d)
if err != nil {
panic(err)
}
return td
}
func splitString(s, sep string) []string {
if s == "" {
return nil
}
return strings.Split(s, sep)
}
func fmtError(msg string) error {
return errors.New(msg)
}
func usage(msg string) {
fmt.Fprintf(os.Stderr, "%s", msg)
}
`
// htmlSectionTemplate renders a single section: an optional Markdown heading
// followed by a table of that section's flags. The output is a fragment, not a
// complete HTML document, so that it can be embedded directly in a page which
// supplies its own styling -- the table carries the "rq-flags" class for that
// purpose. Headings are Markdown rather than <h2> so that a static site
// generator treats them as real headings, and so gives them anchors and a place
// in the page's table of contents.
const htmlSectionTemplate = `{{ if .Name }}## {{ .Name }}
{{ end }}<table class="rq-flags">
<tr>
<th class="col-cli">Flag</th>
<th class="col-usage">Usage</th>
</tr>
{{- range .Flags }}
<tr>
<td><code>-{{ .CLI | html }}</code></td>
<td>{{ .ShortHelp | html }}.
{{- if .LongHelp }}
<br><br>{{ .LongHelp | html }}
{{- end }}</td>
</tr>
{{- end }}
</table>
`
// Format represents the output format of the generator.
type Format int
const (
Go Format = iota
Markdown
HTML
)
// String returns the string representation of the format.
func (f Format) String() string {
switch f {
case Go:
return "Go"
case Markdown:
return "Markdown"
case HTML:
return "HTML"
default:
return "Unknown"
}
}
// visibleFlags returns a copy of flags with hidden entries removed.
func visibleFlags(flags []Flag) []Flag {
var out []Flag
for _, f := range flags {
if !f.Hide {
out = append(out, f)
}
}
return out
}
// Generator represents a flag, HTML, or Markdown generator.
type Generator struct {
pkg string
configTypeName string
flagSetUsage string
flagSetName string
flagSetErrorHandling string
args []Argument
flags []Flag
}
// NewGenerator creates a new generator with the given package name, name, and
// path to the TOML configuration file.
func NewGenerator(cfg *ParsedConfig) (*Generator, error) {
return &Generator{
pkg: cfg.GoConfig.Package,
configTypeName: cfg.GoConfig.ConfigTypeName,
flagSetUsage: cfg.GoConfig.FlagSetUsage,
flagSetName: cfg.GoConfig.FlagSetName,
flagSetErrorHandling: cfg.GoConfig.FlagErrorHandling,
args: cfg.Arguments,
flags: cfg.Flags,
}, nil
}
// Execute generates the output in the given format and writes it to the given
// writer.
func (g *Generator) Execute(f Format, w io.Writer) error {
switch f {
case Go:
return g.doGo(w)
case Markdown:
return g.doMarkdown(w)
case HTML:
return g.doHTML(w)
default:
return fmt.Errorf("unsupported format: %s", f)
}
}
func (g *Generator) doGo(w io.Writer) error {
// Parse the template.
tmpl, err := template.New("flags").Parse(flagTemplate)
if err != nil {
return fmt.Errorf("failed to parse template: %w", err)
}
// Perform some checks of the flags.
for i, flag := range g.flags {
if flag.Type == "time.Duration" {
if flag.Default == nil {
g.flags[i].Default = 0
} else {
s, ok := flag.Default.(string)
if !ok {
return fmt.Errorf("time.Duration flag %s has non-string default", flag.Name)
}
if _, err := time.ParseDuration(s); err != nil {
return fmt.Errorf("time.Duration flag %s has invalid default: %v", flag.Name, err)
}
}
}
if flag.Type == "[]string" {
if flag.Delimiter == "" {
g.flags[i].Delimiter = ","
}
if flag.Default == nil {
g.flags[i].Default = ""
}
}
}
// Execute the template with the flags data.
var output bytes.Buffer
if err := tmpl.Execute(&output, struct {
Pkg string
FSUsage string
FSName string
FSErrorHandling string
ConfigType string
Args []Argument
Flags []Flag
}{
Pkg: g.pkg,
FSUsage: g.flagSetUsage,
FSName: g.flagSetName,
FSErrorHandling: g.flagSetErrorHandling,
ConfigType: g.configTypeName,
Args: g.args,
Flags: visibleFlags(g.flags),
}); err != nil {
return fmt.Errorf("failed to execute template: %w", err)
}
// Format the Go source.
formatted, err := format.Source(output.Bytes())
if err != nil {
return fmt.Errorf("failed to format source: %w", err)
}
// Write the output to flags.go.
_, err = w.Write(formatted)
return err
}
func (g *Generator) doMarkdown(w io.Writer) error {
sections, err := groupBySection(visibleFlags(g.flags))
if err != nil {
return err
}
for i, section := range sections {
builder := strings.Builder{}
if i > 0 {
builder.WriteString("\n")
}
if section.Name != "" {
builder.WriteString(fmt.Sprintf("## %s\n\n", section.Name))
}
// Write the markdown table header.
builder.WriteString("| Flag | Usage |\n|-|-|\n")
// Write each flag as a row in the table.
for _, flag := range section.Flags {
builder.WriteString("|")
builder.WriteString(escapeMarkdown(flag.CLI))
builder.WriteString("|")
builder.WriteString(escapeMarkdown(flag.ShortHelp))
if flag.Default != nil {
if !strings.HasSuffix(flag.ShortHelp, ".") {
builder.WriteString(".")
}
builder.WriteString(fmt.Sprintf(" %s", escapeMarkdown(flag.LongHelp)))
}
builder.WriteString("|\n")
}
if _, err := w.Write([]byte(builder.String())); err != nil {
return err
}
}
return nil
}
func (g *Generator) doHTML(w io.Writer) error {
sections, err := groupBySection(visibleFlags(g.flags))
if err != nil {
return err
}
// Parse the template.
tmpl, err := template.New("htmlTable").Funcs(template.FuncMap{
"html": func(s string) string {
return template.HTMLEscapeString(s)
},
}).Parse(htmlSectionTemplate)
if err != nil {
return fmt.Errorf("failed to parse HTML template: %w", err)
}
// Execute the template once per section, separating each from the last with
// a blank line.
var output bytes.Buffer
for i, section := range sections {
if i > 0 {
output.WriteString("\n")
}
if err := tmpl.Execute(&output, section); err != nil {
return fmt.Errorf("failed to execute HTML template: %w", err)
}
}
if _, err := w.Write(output.Bytes()); err != nil {
return fmt.Errorf("failed to write HTML: %w", err)
}
return nil
}
// section is a named group of flags, used by the documentation generators.
type section struct {
Name string
Flags []Flag
}
// groupBySection groups flags by their section key, ordering the sections by
// first appearance in the configuration file. If no flag declares a section a
// single anonymous section holding every flag is returned, so that output for
// configuration files which don't use sections is unchanged.
//
// Declaring a section on some flags but not others is an error. Silently
// sweeping the remainder into a catch-all group would mean that every flag
// added from then on would quietly land there, which is exactly the drift
// sections exist to prevent.
func groupBySection(flags []Flag) ([]section, error) {
var unassigned []string
assigned := false
for _, flag := range flags {
if flag.Section == "" {
unassigned = append(unassigned, flag.CLI)
} else {
assigned = true
}
}
if !assigned {
return []section{{Flags: flags}}, nil
}
if len(unassigned) > 0 {
return nil, fmt.Errorf("some flags declare a section but these do not: %s",
strings.Join(unassigned, ", "))
}
var sections []section
indexes := make(map[string]int)
for _, flag := range flags {
i, ok := indexes[flag.Section]
if !ok {
i = len(sections)
indexes[flag.Section] = i
sections = append(sections, section{Name: flag.Section})
}
sections[i].Flags = append(sections[i].Flags, flag)
}
return sections, nil
}
// escapeMarkdown escapes markdown special characters.
func escapeMarkdown(text string) string {
text = strings.ReplaceAll(text, "|", "\\|")
text = strings.ReplaceAll(text, "\n", "<br>")
return text
}