github.imxd.top/openshift/source-to-image@v1.2.0/pkg/scripts/environment.go (about) 1 package scripts 2 3 import ( 4 "bufio" 5 "errors" 6 "fmt" 7 "os" 8 "path/filepath" 9 "strings" 10 11 "github.com/openshift/source-to-image/pkg/api" 12 "github.com/openshift/source-to-image/pkg/api/constants" 13 ) 14 15 // GetEnvironment gets the .s2i/environment file located in the sources and 16 // parse it into EnvironmentList. 17 func GetEnvironment(path string) (api.EnvironmentList, error) { 18 envPath := filepath.Join(path, ".s2i", constants.Environment) 19 if _, err := os.Stat(envPath); os.IsNotExist(err) { 20 return nil, errors.New("no environment file found in application sources") 21 } 22 23 f, err := os.Open(envPath) 24 if err != nil { 25 return nil, errors.New("unable to read custom environment file") 26 } 27 defer f.Close() 28 29 result := api.EnvironmentList{} 30 31 scanner := bufio.NewScanner(f) 32 for scanner.Scan() { 33 s := scanner.Text() 34 // Allow for comments in environment file 35 if strings.HasPrefix(s, "#") { 36 continue 37 } 38 result.Set(s) 39 } 40 41 log.V(1).Infof("Setting %d environment variables provided by environment file in sources", len(result)) 42 return result, scanner.Err() 43 } 44 45 // ConvertEnvironmentList converts the EnvironmentList to "key=val" strings. 46 func ConvertEnvironmentList(env api.EnvironmentList) (result []string) { 47 for _, e := range env { 48 result = append(result, fmt.Sprintf("%s=%s", e.Name, e.Value)) 49 } 50 return 51 } 52 53 // ConvertEnvironmentToDocker converts the EnvironmentList into Dockerfile format. 54 func ConvertEnvironmentToDocker(env api.EnvironmentList) (result string) { 55 for i, e := range env { 56 if i == 0 { 57 result += fmt.Sprintf("ENV %s=\"%s\"", e.Name, escape(e.Value)) 58 } else { 59 result += fmt.Sprintf(" \\\n %s=\"%s\"", e.Name, escape(e.Value)) 60 } 61 } 62 result += "\n" 63 return 64 } 65 66 // escape returns the passed-in value, escaped so that it will not undergo 67 // expansion in an ENV instruction. 68 func escape(value string) string { 69 result := "" 70 for _, ch := range value { 71 if strings.ContainsRune(`$"\`, ch) { 72 result += `\` 73 } 74 result += string(ch) 75 } 76 return result 77 }