forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
variable.go
89 lines (77 loc) · 2.12 KB
/
variable.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
package variable
import (
"fmt"
"os"
"strings"
"github.com/openshift/origin/pkg/version"
)
// KeyFunc returns the value associated with the provided key or false if no
// such key exists.
type KeyFunc func(key string) (string, bool)
// Expand expands a string and ignores any errors that occur - keys that are
// not recognized are replaced with the empty string.
func Expand(s string, fns ...KeyFunc) string {
val, _ := ExpandStrict(s, append(fns, Empty)...)
return val
}
// ExpandStrict expands a string using a series of common format functions
func ExpandStrict(s string, fns ...KeyFunc) (string, error) {
unmatched := []string{}
result := os.Expand(s, func(key string) string {
for _, fn := range fns {
val, ok := fn(key)
if !ok {
continue
}
return val
}
unmatched = append(unmatched, key)
return ""
})
switch len(unmatched) {
case 0:
return result, nil
case 1:
return "", fmt.Errorf("the key %q in %q is not recognized", unmatched[0], s)
default:
return "", fmt.Errorf("multiple keys in %q were not recognized: %s", s, strings.Join(unmatched, ", "))
}
}
// Empty is a KeyFunc which always returns true and the empty string.
func Empty(s string) (string, bool) {
return "", true
}
// Identity is a KeyFunc that returns the same format rules.
func Identity(key string) (string, bool) {
return fmt.Sprintf("${%s}", key), true
}
// Versions is a KeyFunc for retrieving information about the current version.
func Versions(key string) (string, bool) {
switch key {
case "shortcommit":
s := OverrideVersion.GitCommit
if len(s) > 7 {
s = s[:7]
}
return s, true
case "version":
s := OverrideVersion.LastSemanticVersion()
return s, true
default:
return "", false
}
}
// Env is a KeyFunc which always returns a string
func Env(key string) (string, bool) {
return os.Getenv(key), true
}
// EnvPresent is a KeyFunc which returns an environment variable if it is present.
func EnvPresent(key string) (string, bool) {
s := os.Getenv(key)
if len(s) == 0 {
return "", false
}
return s, true
}
// OverrideVersion is the latest version, exposed for testing.
var OverrideVersion = version.Get()