-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
359 lines (297 loc) · 7.28 KB
/
main.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
)
func catchPanic() {
e := recover()
if e != nil {
fmt.Fprintln(os.Stderr, e)
}
}
type FlagType uint
const (
StringFlagType FlagType = iota
BoolFlagType
StringToStringType
)
func (typ FlagType) AllowsMultiple() bool {
return typ == StringToStringType
}
type Flag struct {
Type FlagType
Short string
Long string
ParameterName string
Target any // Really a pointer.
Description string
}
func main() {
debug := os.Getenv("DEBUG")
if debug == "" {
// Avoid printing stack trace by default.
defer catchPanic()
}
var templatePathFlag string
var outputPathFlag string
var formatFlag string
var promptValueFlags map[string]string
var metaKeyFlag string
var leftDelimFlag string
var rightDelimFlag string
var caseFlag string
var overwriteFlag bool
rootCmd := cobra.Command{
Use: "qveen",
Short: "Generate files from templates.",
// TODO: Long description.
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
opts := RenderOptions{
ParamsPath: args[0],
ParamsFormat: formatFlag,
TemplatePath: templatePathFlag,
OutputPath: outputPathFlag,
MetaKey: metaKeyFlag,
PromptValues: promptValueFlags,
Overwrite: overwriteFlag,
TemplateLeftDelim: leftDelimFlag,
TemplateRightDelim: rightDelimFlag,
TemplateCase: caseFlag,
}
Render(opts)
},
}
// We use this array to build with "usage" section when helping, and
// also as a base to actually register the flags with `cobra`.
flags := []Flag{
{
Type: StringFlagType,
Short: "t",
Long: "template",
ParameterName: "template-file",
Target: &templatePathFlag,
Description: "Go template file to use (placeholders allowed).",
},
{
Type: StringFlagType,
Short: "o",
Long: "output",
ParameterName: "output-file",
Target: &outputPathFlag,
Description: "Destination file name (placeholders allowed).",
},
{
Type: StringFlagType,
Short: "f",
Long: "format",
ParameterName: "toml | yaml",
Target: &formatFlag,
Description: "Set the parameter file format. Will check the extension by default.",
},
{
Type: StringToStringType,
Short: "p",
Long: "prompt-value",
ParameterName: "key=val",
Target: &promptValueFlags,
Description: "Sets a value for a prompt upfront.",
},
{
Type: StringFlagType,
Short: "m",
Long: "meta",
ParameterName: "meta-key",
Target: &metaKeyFlag,
Description: "Key to look for meta information, instead of `meta`.",
},
{
Type: StringFlagType,
Short: "l",
Long: "left-delim",
ParameterName: "delim",
Target: &leftDelimFlag,
Description: "String to use as the left delimiter for the template instead of `{{`.",
},
{
Type: StringFlagType,
Short: "r",
Long: "right-delim",
ParameterName: "delim",
Target: &rightDelimFlag,
Description: "String to use as the right delimiter for the template instead of `}}`.",
},
{
Type: StringFlagType,
Short: "c",
Long: "case",
ParameterName: "turkish | azeri",
Target: &caseFlag,
Description: "Will use the corresponding casing rules in templates if set.",
},
{
Type: BoolFlagType,
Short: "y",
Long: "overwrite",
Target: &overwriteFlag,
Description: "If set, won't ask for confirmation when overwriting files.",
},
}
for _, flag := range flags {
registerFlag(&rootCmd, flag)
}
// Add information for `--help` so it shows up in the usage, but
// don't really add it since it is created automatically.
var null bool
flags = append(flags, Flag{
Type: BoolFlagType,
Short: "h",
Long: "help",
Target: &null,
Description: "Show this message and exit.",
})
rootCmd.SetUsageFunc(usage(flags))
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func registerFlag(cmd *cobra.Command, flag Flag) {
switch flag.Type {
case StringFlagType:
target := flag.Target.(*string)
cmd.Flags().StringVarP(
target,
flag.Long,
flag.Short,
"",
flag.Description,
)
case BoolFlagType:
target := flag.Target.(*bool)
cmd.Flags().BoolVarP(
target,
flag.Long,
flag.Short,
false,
flag.Description,
)
case StringToStringType:
target := flag.Target.(*map[string]string)
cmd.Flags().StringToStringVarP(
target,
flag.Long,
flag.Short,
make(map[string]string),
flag.Description,
)
}
}
func usage(flags []Flag) func(cmd *cobra.Command) error {
return func(cmd *cobra.Command) error {
// Not a hard limit. Will not break line if not in a good
// position to do so. A bit lower than usual to compensate.
const maxLineLength = 70
var builder strings.Builder
// Characters since last line break.
// Used for wrapping.
rowLen := 0
// Assumes no line break inside `str`!
writeLine := func(str string) {
builder.WriteString(str)
rowLen += len(str)
}
breakLine := func() {
builder.WriteRune('\n')
rowLen = 0
}
writeLine("Usage:")
breakLine()
writeLine(" ")
writeLine(os.Args[0])
writeLine(" ")
// Column at which flags start.
// Basically makes indentation go here on line break when
// using `maybeLineBreak` specifically.
baseColumn := rowLen - 1
writeFlag := func(flag Flag) {
writeLine("[-")
writeLine(flag.Short)
writeLine(" | --")
writeLine(flag.Long)
if flag.ParameterName != "" {
writeLine(" <")
writeLine(flag.ParameterName)
writeLine(">")
}
if flag.Type.AllowsMultiple() {
builder.WriteString(" ...")
}
writeLine("]")
}
maybeBreakLine := func() bool {
if rowLen >= maxLineLength-1 {
breakLine()
for rowLen < baseColumn {
writeLine(" ")
}
return true
}
return false
}
flag := flags[0]
writeFlag(flag)
maybeBreakLine()
for _, flag := range flags[1:] {
writeLine(" ")
writeFlag(flag)
maybeBreakLine()
}
writeLine(" <params-file>")
breakLine()
breakLine()
writeLine("Options:")
breakLine()
optionHeader := func(flag Flag) string {
var builder strings.Builder
builder.WriteString("-")
builder.WriteString(flag.Short)
builder.WriteString(", --")
builder.WriteString(flag.Long)
return builder.String()
}
descriptionHeaders := make([]string, 0, len(flags))
// Column at which description starts.
baseColumn = 0
for _, flag := range flags {
header := optionHeader(flag)
descriptionHeaders = append(descriptionHeaders, header)
if len(header) > baseColumn {
baseColumn = len(header)
}
}
baseColumn += 3 // Account for spaces we put at the start.
for i, flag := range flags {
writeLine(" ")
writeLine(descriptionHeaders[i])
for rowLen < baseColumn {
writeLine(" ")
}
words := strings.Fields(flag.Description)
writeLine(words[0])
for _, word := range words[1:] {
broke := maybeBreakLine()
if !broke {
writeLine(" ")
}
writeLine(word)
}
breakLine()
}
breakLine()
fmt.Fprint(cmd.OutOrStderr(), builder.String())
return nil
}
}