-
Notifications
You must be signed in to change notification settings - Fork 4
/
shell.go
175 lines (154 loc) · 4.98 KB
/
shell.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
package script
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"text/template"
"github.com/Masterminds/sprig"
"github.com/k-kinzal/aliases/pkg/types"
"github.com/k-kinzal/aliases/pkg/aliases/context"
"github.com/k-kinzal/aliases/pkg/aliases/yaml"
"github.com/k-kinzal/aliases/pkg/docker"
"github.com/k-kinzal/aliases/pkg/posix"
)
var content = `
{{- if .binary }}
DOCKER_BINARY_PATH="{{ .binary.path }}/{{ .binary.filename }}"
if [ ! -f "${DOCKER_BINARY_PATH}" ]; then
{{ .binary.command }} >/dev/null
fi
{{- end }}
{{- if .envPrefix }}
TEMPDIR="{{ .temporaryPath }}"
{{- range $prefix := .envPrefix }}
if [ -z "${ALIASES_PWD}" ]; then
echo "" > ${TEMPDIR}/{{ $prefix | lower | trimSuffix "_" }}.env
for line in $(env | grep "^{{ $prefix }}"); do
echo "${line#{{ $prefix }}}" >> ${TEMPDIR}/{{ $prefix | lower | trimSuffix "_" }}.env
done
fi
{{- end }}
{{- end }}
{{- if .debug }}
echo "\033[0;90m{{ .command | replace "\\n" "\\\\n" | replace "\r" "\\r" | quote }}\033[0m"
{{- end }}
if [ -p /dev/stdin ]; then
cat - | {{ .command }} "$@"
exit $?
elif [ -f /dev/stdin ]; then
{{ .command }} "$@" </dev/stdin
exit $?
elif [ -t 0 ]; then
{{ .command }} "$@"
exit $?
else
echo "" >/dev/null | {{ .command }} "$@"
exit $?
fi
`
// ShellAdapter adapts shell script from spec to a form that can be used in aliases.
type ShellAdapter yaml.Option
// Command returns a command to aliases script.
func (adpt *ShellAdapter) Command(client *docker.Client, overrideArgs []string, overrideOption docker.RunOption, debug bool) (*posix.ShellScript, error) {
spec := (*yaml.Option)(adpt)
bin := adaptDockerBinary(*spec)
runner := adaptDockerRun(*spec)
// extend entrypoint
if overrideOption.Entrypoint == nil && spec.Entrypoint != nil && strings.HasPrefix(strings.Trim(*spec.Entrypoint, " \t\r\n"), "#!") {
body := strings.Trim(*spec.Entrypoint, " \t\r\n")
hash := types.MD5(body)
entrypoint := fmt.Sprintf("/%s", hash)
path := filepath.Join(context.ExportPath(), "entrypoint", hash)
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, err
}
if err := ioutil.WriteFile(path, []byte(body), 0755); err != nil {
return nil, err
}
overrideOption.Entrypoint = &entrypoint
overrideOption.Volume = append(overrideOption.Volume, fmt.Sprintf("%s:%s", path, entrypoint))
}
// docker info
if spec.Docker != nil {
if overrideOption.Env == nil {
overrideOption.Env = make(map[string]string)
}
overrideOption.Env["ALIASES_PWD"] = "${ALIASES_PWD:-$PWD}"
if sock := client.Sock(); sock != nil {
// unix socket
overrideOption.Privileged = (func(str string) *string { return &str })("true")
overrideOption.Volume = append(overrideOption.Volume, fmt.Sprintf("%s:%s", context.HomePath(), context.HomePath()))
overrideOption.Volume = append(overrideOption.Volume, "${DOCKER_BINARY_PATH}:/usr/local/bin/docker")
overrideOption.Volume = append(overrideOption.Volume, fmt.Sprintf("%s:/var/run/docker.sock", *sock))
} else {
// tcp, http...
overrideOption.Network = (func(str string) *string { return &str })("host")
overrideOption.Env["DOCKER_HOST"] = client.Host()
}
}
//
for _, prefix := range spec.EnvPrefix {
overrideOption.EnvFile = append(overrideOption.EnvFile, "${TEMPDIR}/"+strings.Trim(strings.ToLower(prefix), "_")+".env")
}
// resolve dependency commands
for _, dependency := range spec.Dependencies {
path := filepath.Join(context.ExportPath(), dependency.Namespace(), dependency.Path.Base())
if spec.Path == dependency.Path {
// command1:
// ...
// dependencies:
// - command1
continue
}
overrideOption.Volume = append(overrideOption.Volume, fmt.Sprintf("%s:%s", path, dependency.Path.Name()))
if _, err := os.Stat(path); !os.IsNotExist(err) {
// command1:
// ...
// dependencies:
// - command2:
// ...
// dependencies:
// - command1
continue
}
if err := NewScript(*dependency).Write(client); err != nil {
return nil, err
}
}
funcs := template.FuncMap{
"quote": strconv.Quote,
"replace": func(old string, new string, s string) string {
return strings.Replace(s, old, new, -1)
},
}
tmpl := template.Must(template.New(adpt.Path.Name()).Funcs(sprig.TxtFuncMap()).Funcs(funcs).Parse(content))
data := map[string]interface{}{
"command": runner.Command(client, overrideArgs, overrideOption).String(),
"envPrefix": spec.EnvPrefix,
"dependencies": len(spec.Dependencies) > 0,
"binary": nil,
"debug": debug,
"temporaryPath": context.TemporaryPath(),
}
if spec.Docker != nil {
data["binary"] = map[string]string{
"command": bin.Command(client).String(),
"filename": bin.FileName(),
"path": context.BinaryPath(),
}
}
var tpl bytes.Buffer
if err := tmpl.Execute(&tpl, data); err != nil {
return nil, err
}
return posix.Shell(tpl.String()), nil
}
// adaptShell returns ShellAdapter.
func adaptShell(spec yaml.Option) *ShellAdapter {
return (*ShellAdapter)(&spec)
}