-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenvironment.go
More file actions
85 lines (72 loc) · 1.94 KB
/
Copy pathenvironment.go
File metadata and controls
85 lines (72 loc) · 1.94 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
81
82
83
84
85
package pnpminstall
import (
"fmt"
"os"
"strconv"
"strings"
"github.com/BurntSushi/toml"
)
type Environment struct {
store map[string]string
}
func ParseEnvironment(path string, variables []string) (env Environment, err error) {
file, err := os.Open(path)
if err != nil {
return Environment{}, fmt.Errorf("failed to read \"buildpack.toml\": %w", err)
}
defer func() {
if closeErr := file.Close(); closeErr != nil {
// if there is already an error, it takes priority to avoid overwriting it.
if err == nil {
err = fmt.Errorf("failed to close \"buildpack.toml\": %w", closeErr)
}
}
}()
var configuration struct {
Metadata struct {
Configurations []struct {
Default string `toml:"default,omitempty"`
Description string `toml:"description"`
Name string `toml:"name"`
} `toml:"configurations"`
} `toml:"metadata"`
}
_, err = toml.NewDecoder(file).Decode(&configuration)
if err != nil {
return Environment{}, fmt.Errorf("failed to parse \"buildpack.toml\": %w", err)
}
store := make(map[string]string)
for _, configuration := range configuration.Metadata.Configurations {
store[configuration.Name] = configuration.Default
}
environ := make(map[string]string)
for _, variable := range variables {
if key, value, found := strings.Cut(variable, "="); found {
environ[key] = value
}
}
for key, def := range store {
if value, ok := environ[key]; ok {
store[key] = value
} else {
if def == "" {
delete(store, key)
}
}
}
return Environment{store: store}, nil
}
func (e Environment) Lookup(key string) (string, bool) {
value, found := e.store[key]
return value, found
}
func (e Environment) LookupBool(key string) (bool, error) {
if value, found := e.Lookup(key); found {
result, err := strconv.ParseBool(value)
if err != nil {
return false, fmt.Errorf("failed to parse boolean environment variable %q: %w", key, err)
}
return result, nil
}
return false, nil
}