-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
412 lines (363 loc) · 10.7 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
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
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/glamour"
"github.com/hay-kot/scaffold/app/commands"
"github.com/hay-kot/scaffold/app/core/engine"
"github.com/hay-kot/scaffold/app/scaffold/scaffoldrc"
"github.com/hay-kot/scaffold/internal/appdirs"
"github.com/hay-kot/scaffold/internal/printer"
"github.com/hay-kot/scaffold/internal/styles"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
)
var (
// Build information. Populated at build-time via -ldflags flag.
version = "dev"
commit = "HEAD"
date = "now"
)
var ErrLinterErrors = errors.New("scaffold errors found")
func build() string {
short := commit
if len(commit) > 7 {
short = commit[:7]
}
return fmt.Sprintf("%s (%s) %s", version, short, date)
}
func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Level(zerolog.WarnLevel)
ctrl := &commands.Controller{
Version: version,
}
console := printer.New(os.Stdout)
app := &cli.App{
Name: "scaffold",
Usage: "scaffold projects and files from your terminal",
Version: build(),
Flags: []cli.Flag{
&cli.PathFlag{
Name: "scaffoldrc",
Usage: "path to scaffoldrc file",
Value: appdirs.RCFilepath(),
EnvVars: []string{"SCAFFOLDRC"},
},
&cli.StringSliceFlag{
Name: "scaffold-dir",
Usage: "paths to directories containing scaffold templates",
Value: cli.NewStringSlice("./.scaffold"),
EnvVars: []string{"SCAFFOLD_DIR"},
},
&cli.PathFlag{
Name: "cache",
Usage: "path to the local scaffold directory default",
Value: appdirs.CacheDir(),
EnvVars: []string{"SCAFFOLD_CACHE"},
},
&cli.StringFlag{
Name: "log-level",
Usage: "log level (debug, info, warn, error, fatal, panic)",
Value: "warn",
EnvVars: []string{"SCAFFOLD_LOG_LEVEL", "SCAFFOLD_SETTINGS_LOG_LEVEL"},
},
&cli.StringFlag{
Name: "log-file",
Usage: "log file to write to (use 'stdout' for stdout)",
EnvVars: []string{"SCAFFOLD_SETTINGS_LOG_FILE"},
},
&cli.StringFlag{
Name: "theme",
Usage: "theme to use for the scaffold output",
Value: "scaffold",
EnvVars: []string{"SCAFFOLD_SETTINGS_THEME", "SCAFFOLD_THEME"},
},
&cli.StringFlag{
Name: "run-hooks",
Usage: "run hooks (never, always, prompt) when provided overrides scaffold rc",
EnvVars: []string{"SCAFFOLD_SETTINGS_RUN_HOOKS"},
},
},
Before: func(ctx *cli.Context) error {
ctrl.Flags = commands.Flags{
Cache: ctx.String("cache"),
ScaffoldRCPath: ctx.String("scaffoldrc"),
ScaffoldDirs: ctx.StringSlice("scaffold-dir"),
}
dir := filepath.Dir(ctrl.Flags.ScaffoldRCPath)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("failed to create scaffoldrc directory: %w", err)
}
if _, err := os.Stat(ctrl.Flags.ScaffoldRCPath); os.IsNotExist(err) {
if err := os.WriteFile(ctrl.Flags.ScaffoldRCPath, []byte{}, 0o644); err != nil {
return fmt.Errorf("failed to create scaffoldrc file: %w", err)
}
}
if err := os.MkdirAll(ctx.String("cache"), 0o755); err != nil {
return fmt.Errorf("failed to create cache directory: %w", err)
}
// Parse scaffoldrc file
scaffoldrcFile, err := os.Open(ctrl.Flags.ScaffoldRCPath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to open scaffoldrc file: %w", err)
}
log.Debug().Msg("scaffoldrc file does not exist, skipping")
}
rc := scaffoldrc.Default()
if scaffoldrcFile != nil {
rc, err = scaffoldrc.New(scaffoldrcFile)
if err != nil {
return err
}
}
//
// Override Settings with Flags
//
if ctx.IsSet("theme") {
rc.Settings.Theme = styles.HuhTheme(ctx.String("theme"))
}
if ctx.IsSet("run-hooks") {
rc.Settings.RunHooks = scaffoldrc.ParseRunHooksOption(ctx.String("run-hooks"))
}
if ctx.IsSet("log-level") {
level, err := zerolog.ParseLevel(ctx.String("log-level"))
if err != nil {
return fmt.Errorf("failed to parse log level: %w", err)
}
log.Logger = log.Level(level)
}
if ctx.IsSet("log-file") {
rc.Settings.LogFile = ctx.String("log-file")
if !strings.HasPrefix(rc.Settings.LogFile, "/") {
// If the file path is not absolute, we want to make it absolute
// so that it is relative to the cwd and not the scaffoldrc file.
absLogFilePath, err := filepath.Abs(rc.Settings.LogFile)
if err != nil {
return err
}
rc.Settings.LogFile = absLogFilePath
}
}
//
// Validate Runtime Config
//
err = rc.Validate()
if err != nil {
scaferrs := scaffoldrc.RcValidationErrors{}
switch {
case errors.As(err, &scaferrs):
errlist := make([]printer.KeyValueError, 0, len(scaferrs))
for _, err := range scaferrs {
errlist = append(errlist, printer.KeyValueError{Key: err.Key, Message: err.Cause.Error()})
}
console.KeyValueValidationError("ScaffoldRC Errors", errlist)
default:
return fmt.Errorf("unexpected error return from validator: %w", err)
}
}
if rc.Settings.LogFile != "stdout" {
logpath := rc.Settings.LogFile
if !strings.HasPrefix(ctrl.Flags.ScaffoldRCPath, "/") {
// Assume that the path is relative to the scaffold rc file
logpath = filepath.Join(dir, rc.Settings.LogFile)
}
f, err := os.OpenFile(logpath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return fmt.Errorf("failed to open log file: %w", err)
}
log.Logger = log.Output(zerolog.ConsoleWriter{
Out: f,
NoColor: true,
})
}
styles.SetGlobalStyles(rc.Settings.Theme)
console = console.WithBase(styles.Base).WithLight(styles.Light)
ctrl.Prepare(engine.New(), rc)
return nil
},
Commands: []*cli.Command{
{
Name: "new",
Usage: "create a new project from a scaffold",
UsageText: "scaffold new [flags] [scaffold (url | path)]",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "no-prompt",
Usage: "disable interactive mode",
Value: false,
},
&cli.StringFlag{
Name: "preset",
Usage: "preset to use for the scaffold",
Value: "",
},
&cli.StringFlag{
Name: "snapshot",
Usage: "path or `stdout` to save the output ast",
Value: "",
},
&cli.BoolFlag{
Name: "no-clobber",
Usage: "do not overwrite existing files",
EnvVars: []string{"SCAFFOLD_NO_CLOBBER"},
Value: true,
},
&cli.BoolFlag{
Name: "force",
Usage: "apply changes when git tree is dirty",
Value: true,
EnvVars: []string{"SCAFFOLD_FORCE"},
},
&cli.StringFlag{
Name: "output-dir",
Usage: "scaffold output directory (use ':memory:' for in-memory filesystem)",
Value: ".",
EnvVars: []string{"SCAFFOLD_OUT"},
},
},
Action: func(ctx *cli.Context) error {
return ctrl.New(ctx.Args().Slice(), commands.FlagsNew{
NoPrompt: ctx.Bool("no-prompt"),
Preset: ctx.String("preset"),
Snapshot: ctx.String("snapshot"),
NoClobber: ctx.Bool("no-clobber"),
ForceApply: ctx.Bool("force"),
OutputDir: ctx.String("output-dir"),
})
},
},
{
Name: "list",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "cwd",
Usage: "current working directory to list scaffolds for",
Value: ".",
},
},
Aliases: []string{"ls"},
Usage: "list available scaffolds",
Action: func(ctx *cli.Context) error {
return ctrl.List(commands.FlagsList{
OutputDir: ctx.String("cwd"),
})
},
},
{
Name: "update",
Usage: "update the local cache of scaffolds",
Action: ctrl.Update,
},
{
Name: "lint",
Usage: "lint a scaffoldrc file",
UsageText: "scaffold lint [scaffold file]",
Action: func(ctx *cli.Context) error {
pfpath := ctx.Args().First()
if pfpath == "" {
return errors.New("no file provided")
}
err := ctrl.Lint(pfpath)
if err != nil {
errlist, ok := err.(commands.ErrList) // nolint: errorlint
if !ok {
return err
}
items := make([]printer.StatusListItem, 0, len(errlist))
for _, e := range errlist {
items = append(items, printer.StatusListItem{Ok: false, Status: e.Error()})
}
console.StatusList("Scaffold Errors", items)
return ErrLinterErrors
}
return nil
},
},
{
Name: "init",
Usage: "initialize a new scaffold in the current directory for template scaffolds",
Action: ctrl.Init,
},
{
Name: "dev",
Hidden: true,
Usage: "development commands for testing",
Subcommands: []*cli.Command{
{
Name: "printer",
Usage: "demos the printer",
Action: func(ctx *cli.Context) error {
console.Title(" --- Unknown Error ---")
console.LineBreak()
console.FatalError(errors.New("this is a basic error's message"))
console.LineBreak()
console.Title(" --- List ---")
console.LineBreak()
console.List("List Items", []string{"item 1", "item 2", "item 3"})
console.LineBreak()
console.Title(" --- StatusList ---")
console.LineBreak()
console.StatusList("Status Items", []printer.StatusListItem{
{Ok: true, Status: "Status 1"},
{Ok: false, Status: "Status 2"},
{Ok: true, Status: "Status 3"},
})
console.LineBreak()
console.Title(" --- Key Value Error ---")
console.LineBreak()
console.KeyValueValidationError("Key Value Errors", []printer.KeyValueError{
{Key: "alias.gh", Message: "invalid choice for key_1"},
{Key: "settings.theme", Message: "invalid theme 'x-theme'"},
})
return nil
},
},
{
Name: "dump",
Action: func(ctx *cli.Context) error {
rcyml, err := ctrl.RuntimeConfigYAML()
if err != nil {
return err
}
rcmd := "# Scaffold RC\n\n ```yaml\n" + rcyml + "\n```"
s, err := glamour.RenderWithEnvironmentConfig(rcmd)
if err != nil {
return err
}
fmt.Print(s)
return nil
},
},
{
Name: "migrate",
Action: func(ctx *cli.Context) error {
err := appdirs.MigrateLegacyPaths()
if err != nil {
return err
}
log.Info().Msg("migrated legacy paths")
return nil
},
},
},
},
},
}
if err := app.Run(os.Args); err != nil {
errstr := err.Error()
switch {
// ignore these errors, urfave/cli does not provide any way to hanldle them
// without direct string comparison :(
case strings.HasPrefix(errstr, "flag provided but not defined"), errors.Is(err, ErrLinterErrors):
// ignore
default:
console.FatalError(err)
}
os.Exit(1)
}
}