-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
563 lines (469 loc) · 14.4 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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
package main
import (
"errors"
"flag"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
quickgo "github.com/Nigel2392/quickgo/v2/quickgo"
"github.com/Nigel2392/quickgo/v2/quickgo/config"
"github.com/Nigel2392/quickgo/v2/quickgo/js"
"github.com/Nigel2392/quickgo/v2/quickgo/logger"
)
type Flagger struct {
// Optional overrides for the project.
Project config.Project
// Optional overrides for the config.
Config config.QuickGo
// Files to exclude from the project.
Exclude arrayFlags
// The target directory to write the project to.
TargetDir string
// Used to pass in the quickgo template
Save bool
// Used to pass in the quickgo template
Use string
// List the projects available for use
ListProjects bool
// List the commands available for all projects
ListCommands bool
// Save a global command for this user.
SaveCommand string
// Write an example project configuration
Example bool
// Serve the project over HTTP
Serve bool
// Lock the project configuration.
// 1: Lock the project configuration.
// 0: Unlock the project configuration.
Lock int
}
func (f *Flagger) CopyProject(proj *config.Project) {
if f.Project.Name != "" {
proj.Name = f.Project.Name
}
if f.Project.DelimLeft != "" {
proj.DelimLeft = f.Project.DelimLeft
}
if f.Project.DelimRight != "" {
proj.DelimRight = f.Project.DelimRight
}
if f.Project.Exclude != nil {
proj.Exclude = f.Project.Exclude
}
}
func (f *Flagger) CopyConfig(conf *config.QuickGo) {
if f.Config.Host != "" {
conf.Host = f.Config.Host
}
if f.Config.Port != "" {
conf.Port = f.Config.Port
}
if f.Config.TLSKey != "" {
conf.TLSKey = f.Config.TLSKey
}
if f.Config.TLSCert != "" {
conf.TLSCert = f.Config.TLSCert
}
}
type arrayFlags []string
func (a *arrayFlags) String() string {
var b strings.Builder
for i, v := range *a {
b.WriteString(v)
if i < len(*a)-1 {
b.WriteString(", ")
}
}
return b.String()
}
func (i *arrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
func main() {
var (
err error
flagger Flagger
flagSet = flag.NewFlagSet("quickgo", flag.ExitOnError)
qg *quickgo.App
)
logger.Setup(&logger.Logger{
Level: logger.InfoLevel,
Prefix: "quickgo",
OutputTime: true,
WrapPrefix: quickgo.ColoredLogWrapper,
})
logger.SetOutput(
logger.OutputAll,
quickgo.Logfile(os.Stdout),
)
flagSet.StringVar(&flagger.Project.Name, "name", "", "The name of the project.")
flagSet.StringVar(&flagger.Project.DelimLeft, "delim-left", "", "The left delimiter for the project templates.")
flagSet.StringVar(&flagger.Project.DelimRight, "delim-right", "", "The right delimiter for the project templates.")
flagSet.StringVar(&flagger.Config.Host, "host", "localhost", "The host to run the server on.")
flagSet.StringVar(&flagger.Config.Port, "port", "8080", "The port to run the server on.")
flagSet.StringVar(&flagger.Config.TLSKey, "tls-key", "", "The path to the TLS key.")
flagSet.StringVar(&flagger.Config.TLSCert, "tls-cert", "", "The path to the TLS certificate.")
flagSet.Var(&flagger.Exclude, "e", "A list of files to exclude from the project in glob format.")
flagSet.StringVar(&flagger.TargetDir, "d", "", "The target directory to write the project to.")
flagSet.BoolVar(&flagger.Save, "save", false, "Import the project from the current directory.")
flagSet.StringVar(&flagger.Use, "use", "", "Use the specified project configuration.")
flagSet.BoolVar(&flagger.Example, "example", false, "Print an example project configuration.")
flagSet.BoolVar(&flagger.ListProjects, "list", false, "List the projects available for use.")
flagSet.BoolVar(&flagger.ListCommands, "list-commands", false, "List the commands available for all projects.")
flagSet.StringVar(&flagger.SaveCommand, "save-command", "", "Save a global command for this user by providing a path to a JS file.")
flagSet.BoolVar(&flagger.Serve, "serve", false, "Serve the project over HTTP.")
flagSet.IntVar(&flagger.Lock, "lock", -1, "Lock the project configuration. 1=Lock, 0=Unlock.")
flagSet.BoolFunc("v", "Enable verbose logging.", enableVerboseLogging)
flagSet.Usage = func() {
fmt.Println(quickgo.Craft(quickgo.CMD_Cyan, "QuickGo: A simple project generator and server."))
fmt.Println("Usage: quickgo [-flags | exec <command> | <project-command>] [?args]")
fmt.Println("Available application flags:")
flagSet.VisitAll(func(f *flag.Flag) {
var name = f.Name
if f.DefValue != "" {
name = fmt.Sprintf("%s=%s", name, f.DefValue)
}
fmt.Printf(
" -%s: %s\n",
quickgo.BuildColorString(
quickgo.CMD_Cyan,
quickgo.CMD_Bold,
name,
),
f.Usage,
)
})
var commands, err = qg.ListJSFiles()
if err != nil {
logger.Warn(1, fmt.Errorf("failed to list commands: %w", err))
}
if len(commands) > 0 {
fmt.Println(
quickgo.Craft(quickgo.CMD_Blue, "Available commands:"),
)
for _, cmd := range commands {
fmt.Printf(" - %s\n", quickgo.Craft(
quickgo.CMD_Cyan, cmd,
))
}
}
// Try to load the project configuration.
// It might contain some more commands! :D
if qg.ProjectConfig == nil {
err = qg.LoadCurrentProject(".")
}
if err != nil && errors.Is(err, config.ErrProjectMissing) {
// No project found in the current directory.
fmt.Println(quickgo.Craft(quickgo.CMD_Red, "No project found in the current directory."))
fmt.Println("Run 'quickgo -example' to create an example project configuration.")
} else if err == nil {
// Project found, commands is map -> sort to slice.
var commands = make([]*config.ProjectCommand, 0, len(qg.ProjectConfig.Commands))
for _, v := range qg.ProjectConfig.Commands {
commands = append(commands, v)
}
slices.SortFunc(commands, func(a, b *config.ProjectCommand) int {
return strings.Compare(a.Name, b.Name)
})
if len(commands) == 0 {
fmt.Println(quickgo.Craft(
quickgo.CMD_Yellow,
"No commands found in the project.",
))
return
}
fmt.Println(
quickgo.Craft(
quickgo.CMD_Blue,
"Available project commands:",
),
)
for _, c := range commands {
if c.Description == "" {
fmt.Printf(" - %s\n", quickgo.Craft(quickgo.CMD_Cyan, c.Name))
continue
}
fmt.Printf(" - %s: %s\n", quickgo.Craft(quickgo.CMD_Cyan, c.Name), c.Description)
}
}
}
quickgo.PrintLogo()
if len(os.Args) < 2 {
logger.Fatal(1, "no command provided, run 'quickgo -h' for more information.")
}
// Initially load the application.
qg, err = quickgo.LoadApp()
if err != nil {
logger.Fatal(1, err)
}
err = flagSet.Parse(os.Args[1:])
if err != nil {
logger.Fatal(1, err)
}
switch {
case flagger.Save: // Save a project configuration from the current working / a specified directory.
if flagger.TargetDir == "" {
flagger.TargetDir = "."
}
err = qg.LoadCurrentProject(flagger.TargetDir)
if err != nil {
fmt.Println(err)
if !errors.Is(err, config.ErrProjectMissing) {
logger.Fatal(1, fmt.Errorf("failed to read project config: %w", err))
}
var ctx = parseCommandlineContext(flagSet.Args(), false)
var abs, _ = filepath.Abs(flagger.TargetDir)
_, err = qg.NewProject(quickgo.SimpleProject{
Name: filepath.Base(abs),
DelimLeft: flagger.Project.DelimLeft,
DelimRight: flagger.Project.DelimRight,
Context: ctx,
Exclude: flagger.Exclude,
})
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to create project: %w", err))
}
}
err = qg.ProjectConfig.Load(flagger.TargetDir)
if err != nil {
logger.Fatal(1, err)
}
flagger.CopyProject(
qg.ProjectConfig,
)
flagger.CopyConfig(
qg.Config,
)
if err = qg.ProjectConfig.Validate(); err != nil {
logger.Fatal(1, fmt.Errorf("failed to validate project config: %w", err))
}
err = qg.WriteProjectConfig(qg.ProjectConfig)
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to write project config: %w", err))
}
case flagger.Use != "": // Use a saved project configuration and it's files.
// Parse optional extra context provided by CLI arguments.
var (
ctx = parseCommandlineContext(flagSet.Args(), false)
proj, close, err = qg.ReadProjectConfig(flagger.Use)
)
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to read project config: %w", err))
}
// Copy over the CLI context to the project context.
if proj.Context == nil {
proj.Context = ctx
} else {
maps.Copy(proj.Context, ctx)
}
defer close()
flagger.CopyProject(
proj,
)
err = qg.WriteProject(proj, flagger.TargetDir, false)
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to write project: %w", err))
}
case flagger.Example: // Write an example project configuration to the target directory.
var example = config.ExampleProjectConfig()
flagger.CopyProject(
example,
)
if err = config.IsLocked(flagger.TargetDir); err != nil {
logger.Fatal(1, err)
}
if s, err := os.Stat(filepath.Join(flagger.TargetDir, config.PROJECT_CONFIG_NAME)); err == nil {
var abs, _ = filepath.Abs(s.Name())
fmt.Printf("Project configuration file already exists at '%s'\n", abs)
var overwrite string
for overwrite != "y" && overwrite != "n" {
fmt.Print("Overwrite? [y/n]: ")
fmt.Scanln(&overwrite)
}
if overwrite == "n" {
os.Exit(1)
}
}
err = config.WriteYaml(
example,
filepath.Join(
flagger.TargetDir,
config.PROJECT_CONFIG_NAME,
),
)
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to write example project config: %w", err))
}
case flagger.ListProjects: // List all available (saved) projects.
var projects, err = qg.ListProjects()
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to list projects: %w", err))
}
fmt.Println(quickgo.Craft(quickgo.CMD_Red, "Projects:"))
for _, proj := range projects {
fmt.Printf(" - %s\n", quickgo.Craft(
quickgo.CMD_Blue, proj,
))
}
case flagger.Lock == 1 || flagger.Lock == 0: // Lock or unlock the project configuration.
if err = qg.LoadCurrentProject(flagger.TargetDir); err != nil && errors.Is(err, config.ErrProjectMissing) {
logger.Fatal(1, "Cannot lock/unlock project outside of a project.")
} else if err != nil {
logger.Fatal(1, fmt.Errorf("failed to read project config: %w", err))
}
var action string
if flagger.Lock == 1 {
err = config.LockProject(flagger.TargetDir)
action = "lock"
} else {
err = config.UnlockProject(flagger.TargetDir)
action = "unlock"
}
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to %s project: %w", action, err))
}
logger.Infof("Project was %sed.", action)
case flagger.Serve: // Serve the project over HTTP.
flagger.CopyConfig(
qg.Config,
)
var addr = fmt.Sprintf(
"%s:%s",
qg.Config.Host,
qg.Config.Port,
)
var server = &http.Server{
Addr: addr,
Handler: qg.HttpHandler(),
}
if qg.Config.TLSKey != "" && qg.Config.TLSCert != "" {
logger.Infof("Serving on https://%s", addr)
err = server.ListenAndServeTLS(
qg.Config.TLSCert,
qg.Config.TLSKey,
)
} else {
logger.Infof("Serving on http://%s", addr)
err = server.ListenAndServe()
}
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to start server: %w", err))
}
case flagger.ListCommands: // List all available (global) javascript commands.
var commands, err = qg.ListJSFiles()
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to list commands: %w", err))
}
if len(commands) == 0 {
fmt.Println(quickgo.Craft(quickgo.CMD_Yellow, "No commands found."))
return
}
fmt.Println(quickgo.Craft(quickgo.CMD_Red, "Commands:"))
for _, cmd := range commands {
fmt.Printf(" - %s\n", quickgo.Craft(
quickgo.CMD_Blue, cmd,
))
}
case flagger.SaveCommand != "": // Save a global command (js file with `main` function) for this user.
var err = qg.SaveJS(flagger.SaveCommand)
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to save command: %w", err))
}
default:
// Parse commands for the project itself.
// Optionally execute global javascript commands if the first argument is 'exec'.
var args = flagSet.Args()
if len(args) == 0 {
flagSet.Usage()
os.Exit(1)
}
// Execute app JS files if the command is 'exec'.
var isExec = strings.ToLower(args[0]) == "exec"
if isExec && len(args) > 1 {
var (
fn = args[1]
ctx = parseCommandlineContext(args[2:], true)
)
logger.Infof(
"Executing global command: '%s'", fn,
)
// Try to load the project.
// It does not matter if it fails, we can still execute the command.
if err = qg.LoadCurrentProject(flagger.TargetDir); err != nil {
logger.Warnf("failed to read project config: %s", err)
}
err = qg.ExecJS(
flagger.TargetDir, fn, args[2:], ctx,
)
if err != nil && !errors.Is(err, js.ErrExitCode) {
logger.Fatal(1, fmt.Errorf("failed to execute command: %w", err))
}
return
} else if isExec {
logger.Fatal(1, "no function provided to execute")
}
// It was not a global 'exec' command.
// Look for commands for this project specifically.
var (
cmd *config.ProjectCommand
command = args[0]
ctx = parseCommandlineContext(args[1:], true)
err = qg.LoadCurrentProject(flagger.TargetDir)
)
if err != nil && !errors.Is(err, config.ErrProjectMissing) {
logger.Fatal(1, fmt.Errorf("failed to read project config: %w", err))
} else if err != nil {
logger.Fatal(1, "Cannot execute project commands outside of a project.")
}
cmd, err = qg.ProjectConfig.Command(command, nil)
if err != nil && errors.Is(err, config.ErrCommandMissing) {
logger.Fatal(1, fmt.Errorf("command '%s' not found", command))
} else if err != nil {
logger.Fatal(1, fmt.Errorf("failed to get command: %w", err))
}
err = cmd.Execute(ctx)
if err != nil {
logger.Fatal(1, fmt.Errorf("failed to execute command: %w", err))
}
}
}
func enableVerboseLogging(b string) error {
var boolVal, err = strconv.ParseBool(b)
if err != nil {
return err
}
if boolVal {
logger.Info("Enabling verbose logging.")
logger.SetLevel(logger.DebugLevel)
} else {
logger.SetLevel(logger.InfoLevel)
}
return nil
}
func parseCommandlineContext(args []string, parseCtxImmediately bool) map[string]any {
var ctx = make(map[string]any)
for _, arg := range args {
arg = strings.TrimSpace(arg)
if parseCtxImmediately {
var args = strings.Split(arg, "=")
if len(args) == 2 {
ctx[args[0]] = args[1]
} else {
ctx[arg] = true
}
continue
}
if arg == "/" {
parseCtxImmediately = true
continue
}
}
return ctx
}