-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
117 lines (108 loc) · 2.32 KB
/
exec.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
package operation
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/sirupsen/logrus"
"github.com/takutakahashi/snip/pkg/global"
"github.com/urfave/cli/v2"
)
func CommandExec() *cli.Command {
return &cli.Command{
Name: "exec",
Description: "execute command from templates",
Action: DoExec,
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "set",
Usage: "set variables. multiple value",
},
&cli.BoolFlag{
Name: "quiet",
Aliases: []string{"q"},
Usage: "execute with all prompt `yes`",
},
&cli.BoolFlag{
Name: "dry-run",
Aliases: []string{"d"},
Usage: "only output, not execute",
},
},
}
}
func DoExec(c *cli.Context) error {
sets := c.StringSlice("set")
path := c.Args().First()
dryRun := c.Bool("dry-run")
quiet := c.Bool("quiet")
data := map[string]string{}
for _, s := range sets {
sp := strings.Split(s, "=")
if len(sp) != 2 {
return errors.New("invalid args")
}
data[sp[0]] = sp[1]
}
s, err := global.LoadSetting(c.String("config"))
if err != nil {
return err
}
op, err := New(s)
if err != nil {
return err
}
return op.Exec(path, data, dryRun, quiet)
}
func (op Operation) Exec(path string, data map[string]string, dryRun, quiet bool) error {
out, err := op.Export(ExportOpt{
Path: path,
OutputDirPath: "",
Data: data,
})
if err != nil {
return err
}
if _, ok := out.Files["stdout"]; !ok {
return errors.New("Executable command is not found. use stdout snippets")
}
f, err := ioutil.TempFile(op.g.Setting.BaseDir, "tmp-")
if err != nil {
return err
}
defer os.Remove(f.Name())
_, err = f.Write(out.Files["stdout"].Data)
if err != nil {
return err
}
if dryRun {
logrus.Infof("bash %s", string(out.Files["stdout"].Data))
return nil
}
if !quiet {
logrus.Info("You are attempt to exec below script:")
logrus.Infof("\n---\n%s\n---", string(out.Files["stdout"].Data))
if !confirm() {
return errors.New("execution was declined.")
}
}
stdout, err := exec.Command("bash", f.Name()).CombinedOutput()
fmt.Print(string(stdout))
return err
}
func confirm() bool {
var s string
fmt.Printf("(y/N): ")
_, err := fmt.Scan(&s)
if err != nil {
panic(err)
}
s = strings.TrimSpace(s)
s = strings.ToLower(s)
if s == "y" || s == "yes" {
return true
}
return false
}