-
Notifications
You must be signed in to change notification settings - Fork 0
/
moonshot.go
59 lines (49 loc) · 1.26 KB
/
moonshot.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
package moonshot
import (
"context"
"fmt"
"io/fs"
"github.com/go-chi/chi"
"github.com/spf13/cobra"
"github.com/spy16/moonshot/log"
)
// App represents an instance of app command. Invoke App.Launch()
// in `main()`.
type App struct {
Name string
Short string
Long string
CfgPtr interface{}
Routes func(r *chi.Mux) error
StaticFS fs.FS
}
func (app *App) Launch(ctx context.Context, cmds ...*cobra.Command) int {
root := &cobra.Command{
Use: fmt.Sprintf("%s <command> [flags] <args>", app.Name),
Short: app.Short,
Long: app.Long,
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: true,
},
}
flags := root.PersistentFlags()
var logLevel, logFormat string
flags.StringP("config", "c", "", "Config file path override")
flags.StringVar(&logLevel, "log-level", "info", "Log level")
flags.StringVar(&logFormat, "log-format", "text", "Log format (json/text)")
root.PersistentPreRun = func(cmd *cobra.Command, args []string) {
log.Setup(logLevel, logFormat)
if err := app.loadConfigs(cmd); err != nil {
log.Fatalf(ctx, "failed to load configs: %v", err)
}
}
root.AddCommand(cmds...)
root.AddCommand(
app.cmdServe(ctx),
app.cmdShowConfigs(ctx),
)
if err := root.Execute(); err != nil {
return 1
}
return 0
}