-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.go
235 lines (207 loc) · 4.97 KB
/
cli.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
package cli
import (
"fmt"
"io"
"os"
"strings"
"github.com/goccy/go-yaml"
"github.com/zakuro9715/nzflag"
"github.com/zakuro9715/z/config"
"github.com/zakuro9715/z/log"
"github.com/zakuro9715/z/runner"
)
var exit = os.Exit
var Version string // Set via wain.init
const helpTextBase = `
z - Z Task runner
Usage:
z [OPTIONS] task... [ARGS]
Options:
-c config, --config=config Specify config file [default: z.yaml, env: ZCONFIG]
-v, --verbose Enbale verbose log [env: ZVERBOSE]
--verify-config Only verify config. no task will run
--silent Supress output [env: ZSILENT]
-h, --help Print help
-V, --verison Print version
`
const (
ENV_KEY_ZCONNFIG = "ZCONFIG"
ENV_KEY_ZVERBOSE = "ZVERBOSE"
ENV_KEY_ZSILENT = "ZSILENT"
)
func isHelpFlag(s string) bool {
return s == "-h" || s == "--help"
}
func isEnvValTrue(s string) bool {
return len(s) > 0 && s != "0" && s != "no"
}
func showTextAndExit(code int, text string) {
if code == 0 {
fmt.Println(text)
} else {
fmt.Fprintln(os.Stderr, text)
}
exit(code)
}
func fprintTasks(w io.Writer, tasks map[string]*config.Task) {
fmt.Fprintln(w, "Tasks:")
maxNameLen := 0
for k := range tasks {
if len(k) > maxNameLen {
maxNameLen = len(k)
}
}
for k, t := range tasks {
fmt.Fprintf(w,
" %v%v - %v\n",
k,
strings.Repeat(" ", maxNameLen-len(k)),
t.Description,
)
}
}
func fprintHelp(w io.Writer, config *config.Config) {
var sb strings.Builder
sb.WriteString(helpTextBase)
if config != nil {
sb.WriteString("\n")
fprintTasks(&sb, config.Tasks)
}
fmt.Fprintln(w, sb.String())
}
func fprintTaskHelp(w io.Writer, task *config.Task) {
var sb strings.Builder
sb.WriteString(task.Description)
if len(task.Description) > 0 && task.Description[len(task.Description)-1] != '\n' {
sb.WriteRune('\n')
}
if len(task.Tasks) > 0 {
fprintTasks(&sb, task.Tasks)
}
fmt.Fprint(w, sb.String())
}
func fprintVersion(w io.Writer) {
fmt.Fprintf(w, "z %v\n", Version)
}
// exit_code == -1 means don't exit
func processFlags(nzargs []nzflag.Value) (i int, cfg *config.Config, rconfig *runner.Config, code int) {
configPath := "z.yaml"
if p, ok := os.LookupEnv("ZCONFIG"); ok {
configPath = p
}
helpFlag := false
verboseFlag := isEnvValTrue(os.Getenv(ENV_KEY_ZVERBOSE))
verifyConfigFlag := false
rconfig = &runner.Config{Silent: isEnvValTrue(os.Getenv(ENV_KEY_ZSILENT))}
for ; i < len(nzargs); i++ {
arg := nzargs[i]
if arg.Type() != nzflag.TypeFlag {
break
}
switch {
case isHelpFlag(arg.String()):
helpFlag = true
case arg.Flag().Name == "V" || arg.Flag().Name == "version":
fprintVersion(os.Stdout)
code = 0
return
case arg.Flag().Name == "v" || arg.Flag().Name == "verbose":
verboseFlag = true
case arg.Flag().Name == "c" || arg.Flag().Name == "config":
configPath = arg.Flag().Values[0]
case arg.Flag().Name == "silent":
rconfig.Silent = true
case arg.Flag().Name == "verify-config":
verifyConfigFlag = true
default: // unknow flag
goto parse_end
}
}
parse_end:
if verboseFlag {
log.Default.Level = log.INFO
os.Setenv(ENV_KEY_ZVERBOSE, "1")
}
os.Setenv(ENV_KEY_ZCONNFIG, configPath)
log.Info("flags:")
log.Info(" %v", nzargs[0:i])
cfg, err := config.LoadConfig(configPath)
if err != nil {
fmt.Fprintln(os.Stderr, yaml.FormatError(err, true, true))
code = 1
return
}
if helpFlag && !cfg.DisableHelp {
fprintHelp(os.Stdout, cfg)
code = 0
return
}
if verifyConfigFlag {
// Config is loaded above. So config is valid at here.
code = 0
return
}
code = -1
return
}
func findTask(i *int, nzargs []nzflag.Value, config *config.Config) (task *config.Task, code int) {
task, _ = config.FindTask(config.Default)
{
fullName := ""
i2 := *i
for ; i2 < len(nzargs); i2++ {
arg := nzargs[i2]
if isHelpFlag(arg.String()) && !config.DisableHelp {
fprintTaskHelp(os.Stdout, task)
return nil, 0
}
if arg.String() == "--" {
*i = i2 + 1
break
}
if len(fullName) > 0 {
fullName += "."
}
fullName += arg.String()
if newTask, err := config.FindTask(fullName); err == nil {
*i = i2 + 1
task = newTask
}
}
}
if task == nil {
if *i < len(nzargs) {
fmt.Fprintf(os.Stderr, "Unknown task: %v\n\n", nzargs[*i].String())
}
fprintHelp(os.Stderr, config)
return nil, 1
}
return task, -1
}
func Main(args []string) (code int) {
nzargs := (&nzflag.App{
FlagOption: map[string]nzflag.FlagOption{
"c": nzflag.HasValue,
"config": nzflag.HasValue,
},
}).Normalize(args)
var i int
var task *config.Task
var config *config.Config
var rconfig *runner.Config
if i, config, rconfig, code = processFlags(nzargs); code >= 0 {
return
}
if task, code = findTask(&i, nzargs, config); code >= 0 {
return
}
taskArgs := make([]string, len(nzargs[i:]))
for i, arg := range nzargs[i:] {
taskArgs[i] = arg.String()
}
if err := runner.Run(rconfig, task, taskArgs); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}