github.com/deiscc/workflow-e2e@v0.0.0-20181208071258-117299af888f/shims/system.go (about) 1 package shims 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "strings" 8 ) 9 10 type Shim struct { 11 OutFile *os.File 12 ShimFile *os.File 13 } 14 15 func CreateSystemShim(toShim string) (Shim, error) { 16 tempDir := strings.TrimSuffix(os.TempDir(), "/") 17 // create out file for shim to write to 18 outFile, err := ioutil.TempFile(tempDir, fmt.Sprintf("%s.out", toShim)) 19 if err != nil { 20 return Shim{}, err 21 } 22 23 // create shim file 24 shimLogic := []byte(fmt.Sprintf("#!/bin/sh\necho $@ > %s", outFile.Name())) 25 shimFileName := fmt.Sprintf("%s/%s", tempDir, toShim) 26 err = ioutil.WriteFile(shimFileName, shimLogic, 0777) 27 if err != nil { 28 return Shim{}, err 29 } 30 shimFile, err := os.Open(shimFileName) 31 if err != nil { 32 return Shim{}, err 33 } 34 35 return Shim{OutFile: outFile, ShimFile: shimFile}, nil 36 } 37 38 func RemoveShim(shim Shim) { 39 os.Remove(shim.OutFile.Name()) 40 os.Remove(shim.ShimFile.Name()) 41 } 42 43 func SubstituteEnvVar(env []string, envKey string, envValue string) []string { 44 // create clone of env provided 45 newEnv := make([]string, len(env)) 46 copy(newEnv, env) 47 48 // find and delete key/value in question 49 for i, e := range newEnv { 50 pair := strings.Split(e, "=") 51 if pair[0] == envKey { 52 newEnv = append(newEnv[:i], newEnv[i+1:]...) 53 } 54 } 55 // substitute new key/value 56 newEnv = append(newEnv, fmt.Sprintf("%s=%s", envKey, envValue)) 57 58 return newEnv 59 } 60 61 func PrependPath(env []string, prefix string) []string { 62 path := os.Getenv("PATH") 63 return SubstituteEnvVar(env, "PATH", fmt.Sprintf("%s:%s", prefix, path)) 64 }