-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
parse.go
91 lines (77 loc) · 2.52 KB
/
parse.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
package opts
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/docker/docker/api/types/container"
)
// ReadKVStrings reads a file of line terminated key=value pairs, and overrides any keys
// present in the file with additional pairs specified in the override parameter
func ReadKVStrings(files []string, override []string) ([]string, error) {
return readKVStrings(files, override, nil)
}
// ReadKVEnvStrings reads a file of line terminated key=value pairs, and overrides any keys
// present in the file with additional pairs specified in the override parameter.
// If a key has no value, it will get the value from the environment.
func ReadKVEnvStrings(files []string, override []string) ([]string, error) {
return readKVStrings(files, override, os.LookupEnv)
}
func readKVStrings(files []string, override []string, emptyFn func(string) (string, bool)) ([]string, error) {
var variables []string
for _, ef := range files {
parsedVars, err := parseKeyValueFile(ef, emptyFn)
if err != nil {
return nil, err
}
variables = append(variables, parsedVars...)
}
// parse the '-e' and '--env' after, to allow override
variables = append(variables, override...)
return variables, nil
}
// ConvertKVStringsToMap converts ["key=value"] to {"key":"value"}
func ConvertKVStringsToMap(values []string) map[string]string {
result := make(map[string]string, len(values))
for _, value := range values {
k, v, _ := strings.Cut(value, "=")
result[k] = v
}
return result
}
// ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"}
// but set unset keys to nil - meaning the ones with no "=" in them.
// We use this in cases where we need to distinguish between
//
// FOO= and FOO
//
// where the latter case just means FOO was mentioned but not given a value
func ConvertKVStringsToMapWithNil(values []string) map[string]*string {
result := make(map[string]*string, len(values))
for _, value := range values {
k, v, ok := strings.Cut(value, "=")
if !ok {
result[k] = nil
} else {
result[k] = &v
}
}
return result
}
// ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
func ParseRestartPolicy(policy string) (container.RestartPolicy, error) {
p := container.RestartPolicy{}
if policy == "" {
return p, nil
}
k, v, _ := strings.Cut(policy, ":")
if v != "" {
count, err := strconv.Atoi(v)
if err != nil {
return p, fmt.Errorf("invalid restart policy format: maximum retry count must be an integer")
}
p.MaximumRetryCount = count
}
p.Name = k
return p, nil
}