forked from datastack-net/dockerized
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
307 lines (267 loc) · 7.91 KB
/
main.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
package main
import (
"fmt"
"github.com/compose-spec/compose-go/types"
. "github.com/datastack-net/dockerized/pkg"
"github.com/datastack-net/dockerized/pkg/help"
util "github.com/datastack-net/dockerized/pkg/util"
"github.com/docker/compose/v2/pkg/api"
"github.com/fatih/color"
"github.com/moby/term"
"os"
"path/filepath"
"strings"
)
var Version string
var contains = util.Contains
var hasKey = util.HasKey
func main() {
err, exitCode := RunCli(os.Args[1:])
if err != nil {
fmt.Printf("%s\n", err)
}
os.Exit(exitCode)
}
func RunCli(args []string) (err error, exitCode int) {
dockerizedOptions, commandName, commandVersion, commandArgs := parseArguments(args)
var optionHelp = hasKey(dockerizedOptions, OptionHelp) || hasKey(dockerizedOptions, ShortOptionHelp)
var optionVerbose = hasKey(dockerizedOptions, OptionVerbose) || hasKey(dockerizedOptions, ShortOptionVerbose)
var optionShell = hasKey(dockerizedOptions, OptionShell)
var optionBuild = hasKey(dockerizedOptions, OptionBuild)
var optionBuildPull = hasKey(dockerizedOptions, OptionBuildPull)
var optionBuildNoCache = hasKey(dockerizedOptions, OptionBuildNoCache)
var optionVersion = hasKey(dockerizedOptions, OptionVersion)
var optionPort = hasKey(dockerizedOptions, ShortOptionPort)
var optionEntrypoint = hasKey(dockerizedOptions, OptionEntrypoint)
if !optionBuild {
if optionBuildPull {
return fmt.Errorf("%s option requires %s option", OptionBuildPull, OptionBuild), 1
}
if optionBuildNoCache {
return fmt.Errorf("%s option requires %s option", OptionBuildNoCache, OptionBuild), 1
}
}
dockerizedRoot := GetDockerizedRoot()
NormalizeEnvironment(dockerizedRoot)
if optionVerbose {
fmt.Printf("Dockerized root: %s\n", dockerizedRoot)
}
if optionVersion {
fmt.Printf("dockerized %s\n", Version)
return nil, 0
}
hostCwd, _ := os.Getwd()
err = LoadEnvFiles(hostCwd, optionVerbose)
if err != nil {
return err, 1
}
composeFilePaths := GetComposeFilePaths(dockerizedRoot)
if optionVerbose {
fmt.Printf("Compose files: %s\n", strings.Join(composeFilePaths, ", "))
}
if commandName == "" || optionHelp {
err := help.Help(composeFilePaths)
if err != nil {
return err, 1
}
if optionHelp {
return nil, 0
} else {
return nil, 1
}
}
if commandVersion != "" {
if commandVersion == "?" {
err = PrintCommandVersions(composeFilePaths, commandName, optionVerbose)
if err != nil {
return err, 1
} else {
return nil, 0
}
} else {
SetCommandVersion(composeFilePaths, commandName, optionVerbose, commandVersion)
}
}
project, err := GetProject(composeFilePaths)
if err != nil {
return err, 1
}
hostName, _ := os.Hostname()
hostCwdDirName := filepath.Base(hostCwd)
containerCwd := "/host"
if hostCwdDirName != "\\" {
containerCwd += "/" + hostCwdDirName
}
runOptions := api.RunOptions{
Service: commandName,
Environment: []string{
"HOST_HOSTNAME=" + hostName,
},
Command: commandArgs,
AutoRemove: true,
Tty: term.IsTerminal(os.Stdout.Fd()),
WorkingDir: containerCwd,
}
var serviceOptions []func(config *types.ServiceConfig) error
if optionPort {
var port = dockerizedOptions["-p"]
if port == "" {
return fmt.Errorf("port option requires a port number"), 1
}
if optionVerbose {
fmt.Printf("Mapping port: %s\n", port)
}
serviceOptions = append(serviceOptions, func(config *types.ServiceConfig) error {
if !strings.ContainsRune(port, ':') {
port = port + ":" + port
}
portConfig, err := types.ParsePortConfig(port)
if err != nil {
return err
}
config.Ports = portConfig
return nil
})
}
volumes := []types.ServiceVolumeConfig{
{
Type: "bind",
Source: hostCwd,
Target: containerCwd,
}}
if optionBuild {
if optionVerbose {
fmt.Printf("Building container image for %s...\n", commandName)
}
err := DockerComposeBuild(composeFilePaths, api.BuildOptions{
Services: []string{commandName},
Pull: optionBuildPull,
NoCache: optionBuildNoCache,
})
if err != nil {
return err, 1
}
}
if optionShell && optionEntrypoint {
return fmt.Errorf("--shell and --entrypoint are mutually exclusive"), 1
}
if optionShell {
if optionVerbose {
fmt.Printf("Opening shell in container for %s...\n", commandName)
if len(commandArgs) > 0 {
fmt.Printf("Passing arguments to shell: %s\n", commandArgs)
}
}
var ps1 = fmt.Sprintf(
"%s %s:\\w \\$ ",
color.BlueString("dockerized %s", commandName),
color.New(color.FgHiBlue).Add(color.Bold).Sprintf("\\u@\\h"),
)
var welcomeMessage = "Welcome to dockerized shell. Type 'exit' or press Ctrl+D to exit.\n"
welcomeMessage += "Mounted volumes:\n"
for _, volume := range volumes {
welcomeMessage += fmt.Sprintf(" %s -> %s\n", volume.Source, volume.Target)
}
service, err := project.GetService(commandName)
if err == nil {
for _, volume := range service.Volumes {
welcomeMessage += fmt.Sprintf(" %s -> %s\n", volume.Source, volume.Target)
}
}
welcomeMessage = strings.ReplaceAll(welcomeMessage, "\\", "\\\\")
shells := []string{
"bash",
"zsh",
"sh",
}
var shellDetectionCommands []string
for _, shell := range shells {
shellDetectionCommands = append(shellDetectionCommands, "command -v "+shell)
}
for _, shell := range shells {
shellDetectionCommands = append(shellDetectionCommands, "which "+shell)
}
var cmdPrintWelcome = fmt.Sprintf("echo '%s'", color.YellowString(welcomeMessage))
var cmdLaunchShell = fmt.Sprintf("$(%s)", strings.Join(shellDetectionCommands, " || "))
runOptions.Environment = append(runOptions.Environment, "PS1="+ps1)
runOptions.Entrypoint = []string{"/bin/sh"}
if len(commandArgs) > 0 {
runOptions.Command = []string{"-c", fmt.Sprintf("%s; %s \"%s\"", cmdPrintWelcome, cmdLaunchShell, strings.Join(commandArgs, "\" \""))}
} else {
runOptions.Command = []string{"-c", fmt.Sprintf("%s; %s", cmdPrintWelcome, cmdLaunchShell)}
}
}
if optionEntrypoint {
var entrypoint = dockerizedOptions["--entrypoint"]
if optionVerbose {
fmt.Printf("Setting entrypoint to %s\n", entrypoint)
}
runOptions.Entrypoint = strings.Split(entrypoint, " ")
}
if !contains(project.ServiceNames(), commandName) {
image := "r.j3ss.co/" + commandName
if optionVerbose {
fmt.Printf("Service %s not found in compose file(s). Fallback to: %s.\n", commandName, image)
fmt.Printf(" This command, if it exists, will not support version switching.\n")
fmt.Printf(" See: https://github.com/jessfraz/dockerfiles\n")
}
return DockerRun(image, runOptions, volumes)
}
return DockerComposeRun(project, runOptions, volumes, serviceOptions...)
}
func parseArguments(args []string) (map[string]string, string, string, []string) {
var options = []string{
OptionBuild,
OptionBuildPull,
OptionBuildNoCache,
OptionHelp,
ShortOptionHelp,
ShortOptionPort,
OptionShell,
OptionEntrypoint,
ShortOptionVerbose,
OptionVerbose,
OptionVersion,
}
var optionsWithParameters = []string{
"-p",
"--entrypoint",
}
commandName := ""
var commandArgs []string
var dockerizedOptions []string
var commandVersion string
var optionMap = make(map[string]string)
var optionBefore = ""
for _, arg := range args {
if arg[0] == '-' && commandName == "" {
if util.Contains(options, arg) {
var option = arg
dockerizedOptions = append(dockerizedOptions, option)
optionBefore = option
optionMap[option] = ""
} else {
fmt.Println("Unknown option:", arg)
os.Exit(1)
}
} else {
if contains(optionsWithParameters, optionBefore) {
optionMap[optionBefore] = arg
} else if commandName == "" {
commandName = arg
} else {
commandArgs = append(commandArgs, arg)
}
optionBefore = ""
}
}
if strings.ContainsRune(commandName, ':') {
commandSplit := strings.Split(commandName, ":")
commandName = commandSplit[0]
commandVersion = commandSplit[1]
if commandVersion == "" {
commandVersion = "?"
}
}
return optionMap, commandName, commandVersion, commandArgs
}