-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_set.go
335 lines (310 loc) · 7.47 KB
/
command_set.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
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"strings"
"text/template"
)
var (
DefaultShell = []string{"/bin/sh"}
EnvVarPrefix = "ILC_INPUT_"
)
type CommandSet struct {
Config Config
Commands []ConfigCommand
Args []string
ErrorHandling flag.ErrorHandling
}
func (cs CommandSet) String() string {
var names []string
for _, c := range cs.Commands {
if c.Name != "" {
names = append(names, c.Name)
}
}
return strings.Join(names, " ")
}
func (cs CommandSet) Description() string {
for i := len(cs.Commands) - 1; i >= 0; {
command := cs.Commands[i]
return command.Description
}
return ""
}
func (cs CommandSet) Subcommands() []ConfigCommand {
for i := len(cs.Commands) - 1; i >= 0; {
command := cs.Commands[i]
return command.Commands
}
return []ConfigCommand{}
}
func (cs CommandSet) Pure() bool {
for i := len(cs.Commands) - 1; i >= 0; {
command := cs.Commands[i]
return command.Pure
}
return false
}
func (cs CommandSet) Shell() []string {
for i := len(cs.Commands) - 1; i >= 0; i-- {
shell := cs.Commands[i].Shell
if len(shell) > 0 {
return shell
}
}
return DefaultShell
}
func (cs CommandSet) Inputs() []ConfigInput {
inputs := make([]ConfigInput, 0, len(cs.Commands))
for _, command := range cs.Commands {
inputs = append(inputs, command.Inputs...)
}
return inputs
}
func (cs CommandSet) Env() EnvMap {
em := NewEnvMap([]string{})
for _, command := range cs.Commands {
em = em.Merge(command.Env)
}
return em
}
func (cs CommandSet) RenderEnv(data TemplateData) (EnvMap, error) {
env := cs.Env()
for name, template := range env {
if value, err := RenderTemplate(template, data); err != nil {
return env, fmt.Errorf("template error for environment variable: '%s' - %v", name, err)
} else {
env[name] = value
}
}
return env, nil
}
func (cs CommandSet) RenderScript(data TemplateData) (string, error) {
var tmpl *template.Template
for _, command := range cs.Commands {
var err error
if command.Run == "" {
continue
}
if tmpl == nil {
tmpl = template.New(command.Name).Funcs(data.Funcs())
} else {
tmpl = tmpl.New(command.Name)
}
tmpl, err = tmpl.Parse(command.Run)
if err != nil {
return "", fmt.Errorf("template error: %v", err)
}
}
if tmpl == nil {
return "", fmt.Errorf("no script present")
}
if script, err := RenderTemplate(tmpl, data); err != nil {
return script, fmt.Errorf("script error: %v", err)
} else {
return script, err
}
}
func (cs CommandSet) RenderScriptToTemp(data TemplateData) (string, error) {
var file *os.File
script, err := cs.RenderScript(data)
if err != nil {
return "", err
}
file, err = os.CreateTemp("", "*")
if err != nil {
return "", fmt.Errorf("failed to create temporary script file: %v", err)
}
if _, err := file.Write([]byte(script)); err != nil {
return "", fmt.Errorf("failed to write to temporary script file: %v", err)
}
if err := file.Close(); err != nil {
return "", fmt.Errorf("failed to close temporary script file: %v", err)
}
logger.Printf("Created temporary script: %s\n", file.Name())
return file.Name(), nil
}
func (cs CommandSet) ParseArgs(values *map[string]any) error {
fs := flag.NewFlagSet(cs.String(), flag.ContinueOnError)
fs.Usage = func() {
// Don't do anything here. We just want the error.
}
for _, input := range cs.Inputs() {
fs.String(input.Name, input.DefaultValue, input.Description)
}
if err := fs.Parse(cs.Args); err != nil {
return err
}
fs.Visit(func(f *flag.Flag) {
if v, ok := f.Value.(flag.Getter); ok {
(*values)[f.Name] = v.Get()
}
})
return nil
}
func (cs CommandSet) Validate(values map[string]any) error {
for _, input := range cs.Inputs() {
found := false
for k, value := range values {
if input.Name == k {
found = true
if !input.Valid(value) {
return fmt.Errorf("invalid input: %s", input.Name)
}
break
}
}
if !found {
return fmt.Errorf("missing input: %s", input.Name)
}
}
return nil
}
func (cs CommandSet) AskInputs(values *map[string]any) error {
for _, input := range cs.Inputs() {
found := false
for k := range *values {
if input.Name == k {
found = true
break
}
}
if found {
continue
}
if val, err := askInput(input); err != nil {
return err
} else {
(*values)[input.Name] = val
}
}
return nil
}
func (cs CommandSet) ParseEnv(values *map[string]any, environ []string) {
inputs := cs.Inputs()
inputsMap := make(map[string]*ConfigInput, len(inputs))
for _, input := range inputs {
inputsMap[input.Name] = &input
}
for _, item := range environ {
if !strings.HasPrefix(item, EnvVarPrefix) {
continue
}
entry := strings.SplitN(item, "=", 2)
name := strings.TrimPrefix(entry[0], EnvVarPrefix)
if input, ok := inputsMap[name]; !ok {
continue
} else {
logger.Printf("Found value for input in environment: %s\n", input.Name)
(*values)[input.Name] = entry[1]
}
}
}
func (cs CommandSet) getInputsEnv(data TemplateData) EnvMap {
inputs := cs.Inputs()
env := make(EnvMap, len(inputs))
for _, input := range inputs {
value := data.getInput(input.Name)
key := fmt.Sprintf("%s%s", EnvVarPrefix, input.SafeName())
env[key] = fmt.Sprintf("%s", value)
}
return env
}
func (cs CommandSet) Cmd(data TemplateData, moreEnviron []string) (*exec.Cmd, error) {
var scriptFile string
var env EnvMap
var err error
shell := cs.Shell()
scriptFile, err = cs.RenderScriptToTemp(data)
if err != nil {
return nil, err
}
env, err = cs.RenderEnv(data)
if err != nil {
return nil, err
}
env = cs.getInputsEnv(data).Merge(env)
if !cs.Pure() {
env = NewEnvMap(moreEnviron).Merge(env)
}
shell = append(shell, scriptFile)
cmd := exec.Command(shell[0], shell[1:]...)
cmd.Env = env.ToList()
return cmd, nil
}
func (cs CommandSet) Runnable() bool {
for i := len(cs.Commands) - 1; i >= 0; {
command := cs.Commands[i]
return command.Run != ""
}
return false
}
func (cs CommandSet) Selected() bool {
for i := len(cs.Commands) - 1; i >= 0; {
command := cs.Commands[i]
return len(command.Commands) == 0
}
return false
}
func (cs CommandSet) AskCommands() (CommandSet, error) {
for i := len(cs.Commands) - 1; i >= 0 && !cs.Selected(); i = len(cs.Commands) - 1 {
command := cs.Commands[i]
if subcommand, err := selectCommand(command); err != nil {
return cs, err
} else {
cs.Commands = append(cs.Commands, subcommand)
}
}
return cs, nil
}
func NewCommandSet(config Config, args []string) (CommandSet, error) {
var cursor ConfigCommand
cs := CommandSet{
Config: config,
Args: args,
Commands: []ConfigCommand{
{
Name: "",
Description: config.Description,
Run: config.Run,
Shell: config.Shell,
Env: config.Env,
Pure: config.Pure,
Inputs: config.Inputs,
Commands: config.Commands,
},
},
ErrorHandling: flag.ContinueOnError,
}
for len(cs.Args) > 0 {
cursor = cs.Commands[len(cs.Commands)-1]
if cursor.Run != "" || len(cursor.Commands) == 0 {
break
}
if cs.Args[0][0] == '-' {
break
}
next := cursor.Commands.Get(cs.Args[0])
if next == nil {
return cs, fmt.Errorf("invalid subcommand: %s", args[0])
}
cs.Commands = append(cs.Commands, *next)
cs.Args = cs.Args[1:]
}
if hasHelp(cs.Args) {
logger.Println("Detected help flag whilst parsing arguments for command")
return cs, flag.ErrHelp
} else {
return cs, nil
}
}
func hasHelp(args []string) bool {
for _, arg := range args {
if arg == "-h" || arg == "--h" || arg == "-help" || arg == "--help" {
return true
}
}
return false
}