-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerator.go
342 lines (311 loc) · 7.87 KB
/
generator.go
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
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 (
"flag"
"fmt"
"os"
"strings"
"time"
)
// {{ .ConfigType }} represents all configuration options.
type {{ .ConfigType }} struct {
{{- range .Args }}
// {{ .ShortHelp }}
{{ .Name }} {{ .Type }}
{{- end }}
{{- range .Flags }}
// {{ .ShortHelp }}
{{ .Name }} {{ .Type }}
{{- 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 eq .Type "string" }}
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 fmt.Errorf(msg)
}
func usage(msg string) {
fmt.Fprintf(os.Stderr, msg)
}
`
const htmlTemplate = `
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
text-align: left;
}
.col-cli { width: 30%; }
.col-usage { width: 70%; }
</style>
</head>
<body>
<table>
<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>
</body>
</html>
`
// 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"
}
}
// 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: 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 {
// Write the markdown table header.
_, err := w.Write([]byte("| Flag | Usage |\n|-|-|\n"))
if err != nil {
return err
}
// Write each flag as a row in the table.
for _, flag := range g.flags {
builder := strings.Builder{}
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")
_, err = w.Write([]byte(builder.String()))
if err != nil {
return err
}
}
return nil
}
func (g *Generator) doHTML(w io.Writer) error {
// Parse the template.
tmpl, err := template.New("htmlTable").Funcs(template.FuncMap{
"html": func(s string) string {
return template.HTMLEscapeString(s)
},
}).Parse(htmlTemplate)
if err != nil {
return fmt.Errorf("Error parsing HTML template: %v", err)
}
// Execute the template with the flags data.
var output bytes.Buffer
if err := tmpl.Execute(&output, struct {
Flags []Flag
}{Flags: g.flags}); err != nil {
return fmt.Errorf("Error executing HTML template: %v", err)
}
if _, err := w.Write(output.Bytes()); err != nil {
return fmt.Errorf("Error writing HTML file: %v", err)
}
return nil
}
// escapeMarkdown escapes markdown special characters.
func escapeMarkdown(text string) string {
text = strings.ReplaceAll(text, "|", "\\|")
text = strings.ReplaceAll(text, "\n", "<br>")
return text
}