-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
88 lines (83 loc) · 1.87 KB
/
runner.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
package main
import (
"flag"
"fmt"
"os"
// "os/exec"
)
type Runner struct {
Config Config
Args []string
Env []string
Stdin *os.File
Stdout *os.File
Stderr *os.File
Entrypoint []string
NonInteractive bool
}
func (r *Runner) printUsage(cs CommandSet) {
u := NewUsage(mainFlagSet.Output()).ImportCommandSet(cs)
u.Entrypoint = append([]string{}, r.Entrypoint...)
if s := cs.String(); s != "" {
u.Entrypoint = append(u.Entrypoint, s)
}
u.Description = cs.Description()
u.Print()
os.Exit(0)
}
func (r *Runner) Run() error {
if r.NonInteractive {
logger.Println("Running in non-interactive mode")
}
cs, err := NewCommandSet(r.Config, r.Args)
if err == flag.ErrHelp {
r.printUsage(cs)
}
if err != nil {
return fmt.Errorf("failed to select command: %v", err)
}
if !r.NonInteractive {
cs, err = cs.AskCommands()
if err != nil {
return fmt.Errorf("failed to select command: %v", err)
}
}
if !cs.Runnable() {
return fmt.Errorf("no command specified")
}
values := make(map[string]any)
cs.ParseEnv(&values, r.Env)
if err = cs.ParseArgs(&values); err == flag.ErrHelp {
r.printUsage(cs)
} else if err != nil {
return fmt.Errorf("failed parsing arguments: %v", err)
}
if !r.NonInteractive {
if err = cs.AskInputs(&values); err != nil {
return fmt.Errorf("failed getting input values: %v", err)
}
}
if err = cs.Validate(values); err != nil {
return err
}
data := NewTemplateData(values, r.Env)
cmd, err := cs.Cmd(data, r.Env)
if err != nil {
return fmt.Errorf("failed generating script: %v", err)
}
cmd.Stdin = r.Stdin
cmd.Stdout = r.Stdout
cmd.Stderr = r.Stderr
return cmd.Run()
}
func NewRunner(config Config, args []string) *Runner {
r := Runner{
Config: config,
Args: args,
Env: os.Environ(),
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
return &r
}