-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
instructions.go
68 lines (60 loc) · 2.04 KB
/
instructions.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
package dockerfile
import (
"encoding/json"
"fmt"
"strings"
"github.com/docker/docker/builder/command"
)
// A KeyValue can be used to build ordered lists of key-value pairs.
type KeyValue struct {
Key string
Value string
}
// Env builds an ENV Dockerfile instruction from the mapping m. Keys and values
// are serialized as JSON strings to ensure compatibility with the Dockerfile
// parser.
func Env(m []KeyValue) (string, error) {
return keyValueInstruction(command.Env, m)
}
// From builds a FROM Dockerfile instruction referring the base image image.
func From(image string) (string, error) {
return unquotedArgsInstruction(command.From, image)
}
// Label builds a LABEL Dockerfile instruction from the mapping m. Keys and
// values are serialized as JSON strings to ensure compatibility with the
// Dockerfile parser.
func Label(m []KeyValue) (string, error) {
return keyValueInstruction(command.Label, m)
}
// keyValueInstruction builds a Dockerfile instruction from the mapping m. Keys
// and values are serialized as JSON strings to ensure compatibility with the
// Dockerfile parser. Syntax:
// COMMAND "KEY"="VALUE" "may"="contain spaces"
func keyValueInstruction(cmd string, m []KeyValue) (string, error) {
s := []string{strings.ToUpper(cmd)}
for _, kv := range m {
// Marshal kv.Key and kv.Value as JSON strings to cover cases
// like when the values contain spaces or special characters.
k, err := json.Marshal(kv.Key)
if err != nil {
return "", err
}
v, err := json.Marshal(kv.Value)
if err != nil {
return "", err
}
s = append(s, fmt.Sprintf("%s=%s", k, v))
}
return strings.Join(s, " "), nil
}
// unquotedArgsInstruction builds a Dockerfile instruction that takes unquoted
// string arguments. Syntax:
// COMMAND single unquoted argument
// COMMAND value1 value2 value3 ...
func unquotedArgsInstruction(cmd string, args ...string) (string, error) {
s := []string{strings.ToUpper(cmd)}
for _, arg := range args {
s = append(s, strings.Split(arg, "\n")...)
}
return strings.TrimRight(strings.Join(s, " "), " "), nil
}