This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
209 lines (176 loc) · 4.65 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
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"sync"
"syscall"
)
type Info struct {
props map[string]string
stages []string
externalRepo bool
}
func main() {
// Prepend docker if the command got replaced
args := os.Args[1:]
if len(args) == 0 || args[0] != "docker" {
args = append([]string{"docker"}, args...)
}
if len(args) == 1 {
os.Exit(execCmd(strings.Join(args, " ")))
return
}
switch args[1] {
case "build":
info := findInfo(args)
dockerPull(info)
os.Exit(dockerBuild(info))
case "push":
info := findInfo(args)
os.Exit(dockerPush(info))
default:
os.Exit(execCmd(strings.Join(args, " ")))
}
}
func findInfo(args []string) Info {
info := Info{
props: map[string]string{
"cachePrefix": "cache-",
},
}
rtag, _ := regexp.Compile(" (-t|--tag)[ =]([^ ]+)")
// Action
info.props["action"] = args[1]
// Tags
switch info.props["action"] {
case "build":
info.props["targetTag"] = rtag.FindStringSubmatch(strings.Join(args, " "))[2]
case "push":
info.props["targetTag"] = args[len(args)-1]
}
r, _ := regexp.Compile("([^:]*:)?(.*)")
info.props["tagTemplate"] = r.ReplaceAllString(info.props["targetTag"], "$1%s")
info.externalRepo = strings.Contains(info.props["targetTag"], "/")
if info.props["action"] == "build" {
cmd := strings.Join(append(
args[0:len(args)-1], // base command
"%s", // template
args[len(args)-1], // build directory
), " ")
info.props["buildTemplate"] = rtag.ReplaceAllString(cmd, "")
}
// Dockerfile
switch info.props["action"] {
case "build":
info.props["dockerfile"] = findDockerfile(args[len(args)-1])
case "push":
info.props["dockerfile"] = findDockerfile(".")
}
// Stages
info.stages = getStages(info.props["dockerfile"])
return info
}
func dockerPull(info Info) int {
var wg sync.WaitGroup
wg.Add(len(info.stages) + 1)
for _, stage := range info.stages {
go func(pullCmd string) {
defer wg.Done()
execCmd(pullCmd)
}(fmt.Sprintf("docker pull %s", fmt.Sprintf(info.props["tagTemplate"], info.props["cachePrefix"]+stage)))
}
go func(pullCmd string) {
defer wg.Done()
execCmd(pullCmd)
}(fmt.Sprintf("docker pull %s", fmt.Sprintf(info.props["tagTemplate"], "cache")))
wg.Wait()
return execCmd(fmt.Sprintf("docker pull %s", info.props["targetTag"]))
}
func dockerBuild(info Info) int {
for _, stage := range info.stages {
cacheTag := fmt.Sprintf(info.props["tagTemplate"], info.props["cachePrefix"]+stage)
// Set new cache tag
extraArgs := fmt.Sprintf("-t %s", cacheTag)
// Target to build
extraArgs += fmt.Sprintf(" --target %s", stage)
execCmd(fmt.Sprintf(info.props["buildTemplate"], extraArgs))
}
extraMainArgs := fmt.Sprintf("-t %s -t %s", info.props["targetTag"], fmt.Sprintf(info.props["tagTemplate"], "cache"))
return execCmd(fmt.Sprintf(info.props["buildTemplate"], extraMainArgs))
}
func dockerPush(info Info) int {
exitCode := execCmd(fmt.Sprintf("docker push %s", info.props["targetTag"]))
var wg sync.WaitGroup
wg.Add(len(info.stages) + 1)
for _, stage := range info.stages {
go func(pushCmd string) {
defer wg.Done()
execCmd(pushCmd)
}(fmt.Sprintf("docker push %s", fmt.Sprintf(info.props["tagTemplate"], info.props["cachePrefix"]+stage)))
}
go func(pushCmd string) {
defer wg.Done()
execCmd(pushCmd)
}(fmt.Sprintf("docker push %s", fmt.Sprintf(info.props["tagTemplate"], "cache")))
wg.Wait()
return exitCode
}
func execCmd(cmdString string) int {
fmt.Printf("\n# %s\n", cmdString)
if os.Getenv("DEBUG") == "" {
cmdSlice := strings.Split(cmdString, " ")
cmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
ws := exitError.Sys().(syscall.WaitStatus)
return ws.ExitStatus()
}
return 1
}
}
return 0
}
func findDockerfile(path string) string {
fi, err := os.Stat(path)
if err != nil {
fmt.Println("Could not find Dockerfile")
return ""
}
if fi.Mode().IsRegular() {
return path
}
if fi.Mode().IsDir() {
return findDockerfile(path + "/Dockerfile")
}
fmt.Println("Could not find Dockerfile")
return ""
}
func getStages(dockerfile string) []string {
file, err := os.Open(dockerfile)
if err != nil {
return []string{}
}
defer file.Close()
r, _ := regexp.Compile("(?i)^FROM\\s+.*\\s+AS\\s+(.*)")
scanner := bufio.NewScanner(file)
stages := []string{}
for scanner.Scan() {
matches := r.FindStringSubmatch(scanner.Text())
if len(matches) == 2 {
stages = append(stages, matches[1])
}
}
if err := scanner.Err(); err != nil {
fmt.Println(err)
return []string{}
}
return stages
}