-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathenv.go
More file actions
80 lines (64 loc) · 2.44 KB
/
env.go
File metadata and controls
80 lines (64 loc) · 2.44 KB
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
package utils
import (
"fmt"
"os"
"runtime"
"strings"
"sync"
)
// archAliases normalizes common architecture names to Go convention.
var archAliases = map[string]string{
"amd64": "amd64",
"x86_64": "amd64",
"arm64": "arm64",
"aarch64": "arm64",
}
var archWarningOnce sync.Once
// TargetArch returns the target architecture for binary paths and OCI platform.
// If TARGET_ARCH is set, it is normalized to Go convention ("amd64" or "arm64");
// otherwise defaults to the host architecture (runtime.GOARCH).
func TargetArch() string {
if arch := os.Getenv("TARGET_ARCH"); arch != "" {
if normalized, ok := archAliases[arch]; ok {
return normalized
}
archWarningOnce.Do(func() {
fmt.Fprintf(os.Stderr, "WARNING: unrecognized TARGET_ARCH=%q, falling back to %s\n", arch, runtime.GOARCH)
})
return runtime.GOARCH
}
return runtime.GOARCH
}
// RequiredEnv returns the value of the environment variable for key if it is set, non-empty and not only whitespace.
// It panics otherwise.
//
// Pass the envUsageMsg to describe what the environment variable is used for. This will be used in the error message.
func RequiredEnv(key string, envUsageMsg string) string {
value, ok := os.LookupEnv(key)
if !ok {
panic(fmt.Sprintf("Required environment variable \"%s\" (%s) is not set. Please set it to a non-empty value.", key, envUsageMsg))
}
if value == "" {
panic(fmt.Sprintf("Required environment variable \"%s\" (%s) is set but it is empty. Please set it to a non-empty value.", key, envUsageMsg))
}
if strings.TrimSpace(value) == "" {
panic(fmt.Sprintf("Required environment variable \"%s\" (%s) is set but it contains only whitespace. Please set it to a non-empty value.", key, envUsageMsg))
}
return value
}
// OptionalEnv returns the value of the environment variable for key if it is set, non-empty and not only whitespace.
//
// Pass the envUsageMsg to describe what the environment variable is used for.
// This will be used in the message that is printed if the environment variable is not returned.
func OptionalEnv(key string, envUsageMsg string) (string, bool) {
value, ok := os.LookupEnv(key)
if !ok {
fmt.Fprintf(os.Stderr, "Optional environment variable \"%s\" (%s) is not set.\n", key, envUsageMsg)
return "", false
}
if strings.TrimSpace(value) == "" {
fmt.Fprintf(os.Stderr, "Optional environment variable \"%s\" (%s) is set but it contains only whitespace.\n", key, envUsageMsg)
return "", false
}
return value, true
}