-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgodockerize.go
203 lines (182 loc) · 5.03 KB
/
godockerize.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
package main
import (
"bytes"
"errors"
"fmt"
"go/build"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strings"
"github.com/urfave/cli/v2"
)
const baseDockerImage = "alpine:3.12"
func main() {
app := &cli.App{
Name: "godockerize",
Usage: "build Docker images from Go packages",
Version: "0.0.2",
Commands: []*cli.Command{
{
Name: "build",
Usage: "build a Docker image from Go packages",
ArgsUsage: "[packages]",
Description: "Build compiles and installs the packages by the import paths to /usr/local/bin\n in the docker image. The first package is used as the entrypoint.",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "tag",
Aliases: []string{"t"},
Usage: "output Docker image name and optionally a tag in the 'name:tag' format",
},
&cli.StringFlag{
Name: "base",
Usage: "base Docker image name",
Value: baseDockerImage,
},
&cli.StringSliceFlag{
Name: "env",
Usage: "additional environment variables for the Dockerfile",
},
&cli.BoolFlag{
Name: "dry-run",
Usage: "only print generated Dockerfile",
},
},
Action: doBuild,
},
},
}
app.Run(os.Args)
}
func doBuild(c *cli.Context) error {
wd, err := os.Getwd()
if err != nil {
return err
}
args := c.Args()
if args.Len() < 1 {
return errors.New(`"godockerize build" requires 1 or more arguments`)
}
tmpdir, err := ioutil.TempDir("", "godockerize")
if err != nil {
return err
}
defer os.RemoveAll(tmpdir)
fset := token.NewFileSet()
packages := []string{}
env := c.StringSlice("env")
expose := []string{}
install := []string{"ca-certificates", "mailcap", "tini"} // mailcap is for /etc/mime.types
run := []string{}
for _, pkgName := range args.Slice() {
pkg, err := build.Import(pkgName, wd, 0)
if err != nil {
return err
}
packages = append(packages, pkg.ImportPath)
for _, name := range pkg.GoFiles {
f, err := parser.ParseFile(fset, filepath.Join(pkg.Dir, name), nil, parser.ParseComments)
if err != nil {
return err
}
for _, cg := range f.Comments {
for _, c := range cg.List {
if strings.HasPrefix(c.Text, "//docker:") {
parts := strings.SplitN(c.Text[9:], " ", 2)
switch parts[0] {
case "env":
env = append(env, strings.Fields(parts[1])...)
case "expose":
expose = append(expose, strings.Fields(parts[1])...)
case "install":
install = append(install, strings.Fields(parts[1])...)
case "run":
run = append(run, parts[1])
default:
return fmt.Errorf("%s: invalid docker comment: %s", fset.Position(c.Pos()), c.Text)
}
}
}
}
}
}
var dockerfile bytes.Buffer
fmt.Fprintf(&dockerfile, " FROM %s\n", c.String("base"))
for _, pkg := range install {
if strings.HasSuffix(pkg, "@edge") {
fmt.Fprintf(&dockerfile, " RUN echo -e \"@edge http://dl-cdn.alpinelinux.org/alpine/edge/main\\n@edge http://dl-cdn.alpinelinux.org/alpine/edge/community\" >> /etc/apk/repositories\n")
break
}
}
if len(install) != 0 {
fmt.Fprintf(&dockerfile, " RUN apk add --no-cache %s\n", strings.Join(sortedStringSet(install), " "))
}
for _, cmd := range run {
fmt.Fprintf(&dockerfile, " RUN %s\n", cmd)
}
if len(env) != 0 {
fmt.Fprintf(&dockerfile, " ENV %s\n", strings.Join(sortedStringSet(env), " "))
}
if len(expose) != 0 {
fmt.Fprintf(&dockerfile, " EXPOSE %s\n", strings.Join(sortedStringSet(expose), " "))
}
fmt.Fprintf(&dockerfile, " ENTRYPOINT [\"/sbin/tini\", \"--\", \"/usr/local/bin/%s\"]\n", path.Base(packages[0]))
for _, importPath := range packages {
fmt.Fprintf(&dockerfile, " ADD %s /usr/local/bin/\n", path.Base(importPath))
}
fmt.Println("godockerize: Generated Dockerfile:")
fmt.Print(dockerfile.String())
if c.Bool("dry-run") {
return nil
}
ioutil.WriteFile(filepath.Join(tmpdir, "Dockerfile"), dockerfile.Bytes(), 0777)
if err != nil {
return err
}
for _, importPath := range packages {
fmt.Printf("godockerize: Building Go binary %s...\n", path.Base(importPath))
cmd := exec.Command("go", "build", "-buildmode", "exe", "-tags", "dist", "-a", "-o", filepath.Join(tmpdir, path.Base(importPath)), importPath)
cmd.Env = append(os.Environ(),
"GOARCH=amd64",
"GOOS=linux",
"CGO_ENABLED=0",
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
}
fmt.Println("godockerize: Building Docker image...")
dockerArgs := []string{"build"}
if tag := c.String("tag"); tag != "" {
dockerArgs = append(dockerArgs, "-t", tag)
}
dockerArgs = append(dockerArgs, ".")
cmd := exec.Command("docker", dockerArgs...)
cmd.Dir = tmpdir
cmd.Env = os.Environ()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
return nil
}
func sortedStringSet(in []string) []string {
set := make(map[string]struct{})
for _, s := range in {
set[s] = struct{}{}
}
var out []string
for s := range set {
out = append(out, s)
}
sort.Strings(out)
return out
}