-
Notifications
You must be signed in to change notification settings - Fork 292
/
ast.go
255 lines (218 loc) · 5.86 KB
/
ast.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
package dockerfile
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
"github.com/docker/distribution/reference"
"github.com/moby/buildkit/frontend/dockerfile/command"
"github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb"
"github.com/moby/buildkit/frontend/dockerfile/instructions"
"github.com/moby/buildkit/frontend/dockerfile/parser"
"github.com/pkg/errors"
"github.com/windmilleng/tilt/internal/container"
)
type AST struct {
directives map[string]string
result *parser.Result
}
func ParseAST(df Dockerfile) (AST, error) {
result, err := parser.Parse(newReader(df))
if err != nil {
return AST{}, errors.Wrap(err, "dockerfile.ParseAST")
}
return AST{
directives: dockerfile2llb.ParseDirectives(newReader(df)),
result: result,
}, nil
}
// Find all images referenced in this dockerfile and call the visitor function.
// If the visitor function returns a new image, subsitute that image into the dockerfile.
func (a AST) traverseImageRefs(visitor func(node *parser.Node, ref reference.Named) reference.Named) error {
return a.Traverse(func(node *parser.Node) error {
switch node.Value {
case command.From:
if node.Next == nil {
return nil
}
ref, err := container.ParseNamed(node.Next.Value)
if err != nil {
return nil // drop the error, we don't care about malformed images
}
newRef := visitor(node, ref)
if newRef != nil {
node.Next.Value = container.FamiliarString(newRef)
}
case command.Copy:
if len(node.Flags) == 0 {
return nil
}
inst, err := instructions.ParseInstruction(node)
if err != nil {
return nil // ignore parsing error
}
copyCmd, ok := inst.(*instructions.CopyCommand)
if !ok {
return nil
}
ref, err := container.ParseNamed(copyCmd.From)
if err != nil {
return nil // drop the error, we don't care about malformed images
}
newRef := visitor(node, ref)
if newRef != nil {
for i, flag := range node.Flags {
if strings.HasPrefix(flag, "--from=") {
node.Flags[i] = fmt.Sprintf("--from=%s", container.FamiliarString(newRef))
}
}
}
}
return nil
})
}
func (a AST) InjectImageDigest(selector container.RefSelector, ref reference.NamedTagged) (bool, error) {
modified := false
err := a.traverseImageRefs(func(node *parser.Node, toReplace reference.Named) reference.Named {
if selector.Matches(toReplace) {
modified = true
return ref
}
return nil
})
return modified, err
}
// Post-order traversal of the Dockerfile AST.
// Halts immediately on error.
func (a AST) Traverse(visit func(*parser.Node) error) error {
return a.traverseNode(a.result.AST, visit)
}
func (a AST) traverseNode(node *parser.Node, visit func(*parser.Node) error) error {
for _, c := range node.Children {
err := a.traverseNode(c, visit)
if err != nil {
return err
}
}
return visit(node)
}
func (a AST) Print() (Dockerfile, error) {
buf := bytes.NewBuffer(nil)
currentLine := 1
directiveFmt := "# %s = %s\n"
for _, k := range sortedKeys(a.directives) {
// order of directives in a docker makes no semantic difference; we
// rehydrate directives in sorted order so output is deterministic
v := a.directives[k]
_, err := fmt.Fprintf(buf, directiveFmt, k, v)
if err != nil {
return "", err
}
currentLine++
}
for _, node := range a.result.AST.Children {
for currentLine < node.StartLine {
_, err := buf.Write([]byte("\n"))
if err != nil {
return "", err
}
currentLine++
}
err := a.printNode(node, buf)
if err != nil {
return "", err
}
currentLine = node.StartLine + 1
if node.Next != nil && node.Next.StartLine != 0 {
currentLine = node.Next.StartLine + 1
}
}
return Dockerfile(buf.String()), nil
}
// Loosely adapted from
// https://github.com/jessfraz/dockfmt/blob/master/format.go
func (a AST) printNode(node *parser.Node, writer io.Writer) error {
var v string
// format per directive
switch node.Value {
// all the commands that use parseMaybeJSON
// https://github.com/moby/buildkit/blob/2ec7d53b00f24624cda0adfbdceed982623a93b3/frontend/dockerfile/parser/parser.go#L152
case command.Cmd, command.Entrypoint, command.Run, command.Shell:
v = fmtCmd(node)
case command.Label:
v = fmtLabel(node)
default:
v = fmtDefault(node)
}
_, err := fmt.Fprintln(writer, v)
if err != nil {
return err
}
return nil
}
func getCmd(n *parser.Node) []string {
if n == nil {
return nil
}
cmd := []string{strings.ToUpper(n.Value)}
if len(n.Flags) > 0 {
cmd = append(cmd, n.Flags...)
}
return append(cmd, getCmdArgs(n)...)
}
func getCmdArgs(n *parser.Node) []string {
if n == nil {
return nil
}
cmd := []string{}
for node := n.Next; node != nil; node = node.Next {
cmd = append(cmd, node.Value)
if len(node.Flags) > 0 {
cmd = append(cmd, node.Flags...)
}
}
return cmd
}
func fmtCmd(node *parser.Node) string {
if node.Attributes["json"] {
cmd := []string{strings.ToUpper(node.Value)}
if len(node.Flags) > 0 {
cmd = append(cmd, node.Flags...)
}
encoded := []string{}
for _, c := range getCmdArgs(node) {
encoded = append(encoded, fmt.Sprintf("%q", c))
}
return fmt.Sprintf("%s [%s]", strings.Join(cmd, " "), strings.Join(encoded, ", "))
}
cmd := getCmd(node)
return strings.Join(cmd, " ")
}
func fmtDefault(node *parser.Node) string {
cmd := getCmd(node)
return strings.Join(cmd, " ")
}
func fmtLabel(node *parser.Node) string {
cmd := getCmd(node)
assignments := []string{cmd[0]}
for i := 1; i < len(cmd); i += 2 {
if i+1 < len(cmd) {
assignments = append(assignments, fmt.Sprintf("%s=%s", cmd[i], cmd[i+1]))
} else {
assignments = append(assignments, fmt.Sprintf("%s", cmd[i]))
}
}
return strings.Join(assignments, " ")
}
func newReader(df Dockerfile) io.Reader {
return bytes.NewBufferString(string(df))
}
func sortedKeys(m map[string]string) []string {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}