-
Notifications
You must be signed in to change notification settings - Fork 1
/
task.go
87 lines (75 loc) · 1.94 KB
/
task.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
package main
import (
"fmt"
"io/ioutil"
"gopkg.in/yaml.v2"
"strings"
"os"
"os/exec"
"path/filepath"
)
type Task struct {
options []string
Name string `yaml:"name"`
Image string `yaml:"image"`
Executable bool `yaml:"executable"`
Workdir string `yaml:"workdir"`
Volumes []string `yaml:"volumes"`
Environment []string `yaml:"environment"`
}
func (t *Task) Run(args []string) error {
if len(args) == 0 {
return fmt.Errorf("command too short")
}
t.readConfig(args[0])
if len(t.Image) == 0 {
return fmt.Errorf("unknown command: %q", args[0])
}
t.options = append(t.options, "run")
t.options = append(t.options, "--rm")
t.options = append(t.options, "--tty")
t.options = append(t.options, "--interactive")
t.addOptional("workdir", t.Workdir)
if len(t.Volumes) > 0 {
for _, vol := range t.Volumes {
t.addOptional("volume", vol)
}
}
if len(t.Environment) > 0 {
for _, env := range t.Environment {
t.addOptional("env", env)
}
}
t.options = append(t.options, t.Image)
if t.Executable == true {
t.options = append(t.options, args[1:]...)
} else {
t.options = append(t.options, args...)
}
return t.execute()
}
func (t *Task) readConfig(command string) {
file := filepath.Join(cacheDirectory(), fmt.Sprintf("%v.yml", command))
yamlFile, _ := ioutil.ReadFile(file)
yaml.Unmarshal(yamlFile, t)
}
func (t *Task) addOptional(name string, value string) {
if value != "" {
value = os.ExpandEnv(value)
t.options = append(t.options, fmt.Sprintf("--%s=%s", name, strings.TrimSpace(value)))
}
}
func (t *Task) execute() error {
pwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("unable to determine current directory: %v", err)
}
cmd := exec.Command("docker", t.options...)
cmd.Dir = pwd
cmd.Env = os.Environ()
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
fmt.Println(fmt.Sprintf("Running command: %q", strings.Join(cmd.Args, " ")))
return cmd.Run()
}