github.com/paketo-buildpacks/packit@v1.3.2-0.20211206231111-86b75c657449/environment.go (about) 1 package packit 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 ) 8 9 // Environment provides a key-value store for declaring environment variables. 10 type Environment map[string]string 11 12 // Append adds a key-value pair to the environment as an appended value 13 // according to the specification: 14 // https://github.com/buildpacks/spec/blob/main/buildpack.md#append. 15 func (e Environment) Append(name, value, delim string) { 16 e[name+".append"] = value 17 18 delete(e, name+".delim") 19 if delim != "" { 20 e[name+".delim"] = delim 21 } 22 } 23 24 // Default adds a key-value pair to the environment as a default value 25 // according to the specification: 26 // https://github.com/buildpacks/spec/blob/main/buildpack.md#default. 27 func (e Environment) Default(name, value string) { 28 e[name+".default"] = value 29 } 30 31 // Override adds a key-value pair to the environment as an overridden value 32 // according to the specification: 33 // https://github.com/buildpacks/spec/blob/main/buildpack.md#override. 34 func (e Environment) Override(name, value string) { 35 e[name+".override"] = value 36 } 37 38 // Prepend adds a key-value pair to the environment as a prepended value 39 // according to the specification: 40 // https://github.com/buildpacks/spec/blob/main/buildpack.md#prepend. 41 func (e Environment) Prepend(name, value, delim string) { 42 e[name+".prepend"] = value 43 44 delete(e, name+".delim") 45 if delim != "" { 46 e[name+".delim"] = delim 47 } 48 } 49 50 func newEnvironmentFromPath(path string) (Environment, error) { 51 envFiles, err := filepath.Glob(filepath.Join(path, "*")) 52 if err != nil { 53 return Environment{}, fmt.Errorf("failed to match env directory files: %s", err) 54 } 55 56 environment := Environment{} 57 for _, file := range envFiles { 58 switch filepath.Ext(file) { 59 case ".delim", ".prepend", ".append", ".default", ".override": 60 contents, err := os.ReadFile(file) 61 if err != nil { 62 return Environment{}, fmt.Errorf("failed to load environment variable: %s", err) 63 } 64 65 environment[filepath.Base(file)] = string(contents) 66 } 67 } 68 69 return environment, nil 70 }