forked from openshift/source-to-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
environment.go
83 lines (73 loc) · 2.17 KB
/
environment.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
package scripts
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/golang/glog"
"github.com/openshift/source-to-image/pkg/api"
)
// Environment represents a single environment variable definition
type Environment struct {
Name string
Value string
}
// GetEnvironment gets the .s2i/environment file located in the sources and
// parse it into []environment
func GetEnvironment(config *api.Config) ([]Environment, error) {
envPath := filepath.Join(config.WorkingDir, api.Source, ".s2i", api.Environment)
if _, err := os.Stat(envPath); os.IsNotExist(err) {
// TODO: Remove this when the '.sti/environment' is deprecated.
envPath = filepath.Join(config.WorkingDir, api.Source, ".sti", api.Environment)
if _, err := os.Stat(envPath); os.IsNotExist(err) {
return nil, errors.New("no environment file found in application sources")
}
glog.Infof("DEPRECATED: Use .s2i/environment instead of .sti/environment")
}
f, err := os.Open(envPath)
if err != nil {
return nil, errors.New("unable to read custom environment file")
}
defer f.Close()
result := []Environment{}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
s := scanner.Text()
// Allow for comments in environment file
if strings.HasPrefix(s, "#") {
continue
}
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
continue
}
e := Environment{
Name: strings.TrimSpace(parts[0]),
Value: strings.TrimSpace(parts[1]),
}
result = append(result, e)
}
glog.Infof("Setting %d environment variables provided by environment file in sources", len(result))
return result, scanner.Err()
}
// ConvertEnvironment converts the []Environment to "key=val" strings
func ConvertEnvironment(env []Environment) (result []string) {
for _, e := range env {
result = append(result, fmt.Sprintf("%s=%s", e.Name, e.Value))
}
return
}
// ConvertEnvironmentToDocker converts the []Environment into Dockerfile format
func ConvertEnvironmentToDocker(env []Environment) (result string) {
for i, e := range env {
if i == 0 {
result += fmt.Sprintf("ENV %s=\"%s\"", e.Name, e.Value)
} else {
result += fmt.Sprintf(" \\\n\t%s=\"%s\"", e.Name, e.Value)
}
}
result += "\n"
return
}