-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmain.go
More file actions
482 lines (427 loc) · 13.1 KB
/
Copy pathmain.go
File metadata and controls
482 lines (427 loc) · 13.1 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package main
import (
"context"
"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/v3"
)
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.Command{
Name: "scaffold",
Usage: "scaffold projects and files from your terminal",
Version: build(),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "scaffoldrc",
Usage: "path to scaffoldrc file",
Value: appdirs.RCFilepath(),
Sources: cli.EnvVars("SCAFFOLDRC"),
},
&cli.StringSliceFlag{
Name: "scaffold-dir",
Usage: "paths to directories containing scaffold templates",
Value: []string{"./.scaffold"},
Sources: cli.EnvVars("SCAFFOLD_DIR"),
},
&cli.StringFlag{
Name: "cache",
Usage: "path to the local scaffold directory default",
Value: appdirs.CacheDir(),
Sources: cli.EnvVars("SCAFFOLD_CACHE"),
},
&cli.StringFlag{
Name: "log-level",
Usage: "log level (debug, info, warn, error, fatal, panic)",
Value: "warn",
Sources: cli.EnvVars("SCAFFOLD_LOG_LEVEL", "SCAFFOLD_SETTINGS_LOG_LEVEL"),
},
&cli.StringFlag{
Name: "log-file",
Usage: "log file to write to (use 'stdout' for stdout)",
Sources: cli.EnvVars("SCAFFOLD_SETTINGS_LOG_FILE"),
},
&cli.StringFlag{
Name: "theme",
Usage: "theme to use for the scaffold output",
Value: "scaffold",
Sources: cli.EnvVars("SCAFFOLD_SETTINGS_THEME", "SCAFFOLD_THEME"),
},
&cli.StringFlag{
Name: "run-hooks",
Usage: "run hooks (never, always, prompt) when provided overrides scaffold rc",
Sources: cli.EnvVars("SCAFFOLD_SETTINGS_RUN_HOOKS"),
},
},
Before: func(ctx context.Context, c *cli.Command) (context.Context, error) {
ctrl.Flags = commands.Flags{
Cache: c.String("cache"),
ScaffoldRCPath: c.String("scaffoldrc"),
ScaffoldDirs: c.StringSlice("scaffold-dir"),
}
dir := filepath.Dir(ctrl.Flags.ScaffoldRCPath)
if err := os.MkdirAll(dir, 0o755); err != nil {
return ctx, 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 ctx, fmt.Errorf("failed to create scaffoldrc file: %w", err)
}
}
if err := os.MkdirAll(c.String("cache"), 0o755); err != nil {
return ctx, 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 ctx, 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 ctx, err
}
}
//
// Override Settings with Flags
//
if c.IsSet("theme") {
rc.Settings.Theme = styles.HuhTheme(c.String("theme"))
}
if c.IsSet("run-hooks") {
rc.Settings.RunHooks = scaffoldrc.ParseRunHooksOption(c.String("run-hooks"))
}
if c.IsSet("log-level") {
level, err := zerolog.ParseLevel(c.String("log-level"))
if err != nil {
return ctx, fmt.Errorf("failed to parse log level: %w", err)
}
log.Logger = log.Level(level)
}
if c.IsSet("log-file") {
rc.Settings.LogFile = c.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 ctx, 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 ctx, 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 ctx, 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 ctx, nil
},
Commands: []*cli.Command{
{
Name: "new",
Usage: "create a new project from a scaffold",
UsageText: "scaffold new [flags] [scaffold (url | path)] [variables...]",
Description: `Create a new project from a scaffold template.
Pass variables via CLI using key[:type]=value format:
• key=value - string (default)
• key:int=123 - integer
• key:bool=true - boolean
• key:[]string=a,b,c - array (escape commas: a\,b)
• key:json={...} - JSON object
Examples:
scaffold new github.com/hay-kot/scaffold-go-cli
scaffold new mytemplate Project=MyApp Port:int=8080
scaffold new --preset dev mytemplate Project=MyApp Features:[]string=auth,api
Note: CLI variables override preset values.`,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "no-prompt",
Usage: "disable interactive mode (use with --preset and/or CLI variables)",
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: "overwrite",
Usage: "overwrite existing files",
Sources: cli.EnvVars("SCAFFOLD_OVERWRITE"),
},
&cli.BoolFlag{
Name: "force",
Usage: "allow scaffolding when git working tree is dirty",
Value: true,
Sources: cli.EnvVars("SCAFFOLD_FORCE"),
},
&cli.StringFlag{
Name: "output-dir",
Usage: "scaffold output directory (use ':memory:' for in-memory filesystem)",
Value: ".",
Sources: cli.EnvVars("SCAFFOLD_OUT"),
},
&cli.BoolFlag{
Name: "dry-run",
Usage: "validate and show what files would be created without writing (outputs JSON)",
Value: false,
},
},
Action: func(ctx context.Context, c *cli.Command) error {
return ctrl.New(c.Args().Slice(), commands.FlagsNew{
NoPrompt: c.Bool("no-prompt"),
Preset: c.String("preset"),
Snapshot: c.String("snapshot"),
Overwrite: c.Bool("overwrite"),
ForceApply: c.Bool("force"),
OutputDir: c.String("output-dir"),
DryRun: c.Bool("dry-run"),
})
},
},
{
Name: "list",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "cwd",
Usage: "current working directory to list scaffolds for",
Value: ".",
},
&cli.BoolFlag{
Name: "json",
Usage: "output in JSON format for programmatic use",
Value: false,
},
},
Aliases: []string{"ls"},
Usage: "list available scaffolds",
Action: func(ctx context.Context, c *cli.Command) error {
return ctrl.List(commands.FlagsList{
OutputDir: c.String("cwd"),
JSON: c.Bool("json"),
})
},
},
{
Name: "update",
Usage: "update the local cache of scaffolds",
Action: ctrl.Update,
},
{
Name: "inspect",
Usage: "inspect a scaffold and output its structure as JSON",
UsageText: "scaffold inspect [scaffold (url | path)]",
Description: `Inspect a scaffold and output its structure as JSON.
This command is useful for programmatic access to scaffold metadata,
including questions, presets, computed values, and features.
Examples:
scaffold inspect mytemplate
scaffold inspect github.com/hay-kot/scaffold-go-cli
scaffold inspect ./path/to/scaffold`,
Action: func(ctx context.Context, c *cli.Command) error {
path := c.Args().First()
if path == "" {
return errors.New("scaffold path is required")
}
return ctrl.Inspect(commands.FlagsInspect{
Path: path,
})
},
},
{
Name: "lint",
Usage: "lint a scaffoldrc file",
UsageText: "scaffold lint [scaffold file]",
Action: func(ctx context.Context, c *cli.Command) error {
pfpath := c.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",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "stealth",
Usage: "add .scaffold to .git/info/exclude (user-local, not committed)",
Value: false,
},
},
Action: ctrl.Init,
},
{
Name: "schema",
Usage: "output JSON schema for scaffold configuration files",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "type",
Usage: "schema type: 'scaffold' for scaffold.yaml or 'scaffoldrc' for scaffoldrc.yml",
Value: "scaffold",
},
},
Action: ctrl.Schema,
},
{
Name: "dev",
Hidden: true,
Usage: "development commands for testing",
Commands: []*cli.Command{
{
Name: "printer",
Usage: "demos the printer",
Action: func(ctx context.Context, c *cli.Command) 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 context.Context, c *cli.Command) 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 context.Context, c *cli.Command) error {
err := appdirs.MigrateLegacyPaths()
if err != nil {
return err
}
log.Info().Msg("migrated legacy paths")
return nil
},
},
},
},
},
}
if err := app.Run(context.Background(), 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)
}
}