forked from KurokuLabs/margo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
101 lines (90 loc) · 2.04 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
package margo
import (
"flag"
"fmt"
"github.com/urfave/cli"
"margo.sh/mgcli"
"margo.sh/sublime"
"os"
)
var (
cmdList = []mgcli.Commands{
sublime.Commands,
}
cmdNames []string
cmdMap map[string]mgcli.Commands
buildCmd = cli.Command{
Name: "build",
Description: "build the specified agent (see COMMANDS)",
}
runCmd = cli.Command{
Name: "run",
Description: "run the specified agent (see COMMANDS)",
}
startCmd = cli.Command{
Name: "start",
Description: "`build` and `run` the specified agent (see COMMANDS)",
}
)
func init() {
cmdMap = map[string]mgcli.Commands{}
buildNames := []string{}
runNames := []string{}
for _, mc := range cmdList {
cmdNames = append(cmdNames, mc.Name)
cmdMap[mc.Name] = mc
if mc.Build != nil {
buildNames = append(buildNames, mc.Name)
appendSubCmd(&buildCmd, mc, *mc.Build)
}
if mc.Run != nil {
runNames = append(runNames, mc.Name)
appendSubCmd(&runCmd, mc, *mc.Run)
}
appendSubCmd(&startCmd, mc, cli.Command{
Action: startAction,
SkipFlagParsing: true,
SkipArgReorder: true,
})
}
}
func Main() {
app := mgcli.NewApp()
app.Commands = []cli.Command{
buildCmd,
runCmd,
startCmd,
devCmd,
ciCmd,
}
app.RunAndExitOnError()
}
func appendSubCmd(cmd *cli.Command, cmds mgcli.Commands, subCmd cli.Command) {
if subCmd.Name == "" {
subCmd.Name = cmds.Name
}
cmd.Subcommands = append(cmd.Subcommands, subCmd)
}
func startAction(cx *cli.Context) error {
mc := cmdMap[cx.Command.Name]
app := &mgcli.NewApp().App
app.Name = mc.Name
app.ExitErrHandler = func(_ *cli.Context, _ error) {}
newCtx := func(args []string) *cli.Context {
flags := flag.NewFlagSet(mc.Name, 0)
flags.Usage = func() {}
flags.Parse(append([]string{mc.Name}, args...))
return cli.NewContext(app, flags, cx)
}
if mc.Build != nil {
err := mc.Build.Run(newCtx(nil))
if err != nil {
e := fmt.Sprintf("%s build failed: %s", mc.Name, err)
os.Setenv("MARGO_BUILD_ERROR", e)
}
}
if mc.Run != nil {
return mc.Run.Run(newCtx(cx.Args()))
}
return nil
}