github.com/vugu/vugu@v0.3.5/distutil/exec.go (about) 1 package distutil 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "path/filepath" 8 "strings" 9 ) 10 11 // Must panics if error. 12 func Must(err error) { 13 if err != nil { 14 panic(err) 15 } 16 } 17 18 // MustEnvExec is like MustExec but also sets specific environment variables. 19 func MustEnvExec(env2 []string, name string, arg ...string) string { 20 21 env := os.Environ() 22 23 b, err := exec.Command("go", "env", "GOPATH").CombinedOutput() 24 if err != nil { 25 panic(err) 26 } 27 goBinDir := filepath.Join(strings.TrimSpace(string(b)), "bin") 28 _, err = os.Stat(goBinDir) 29 if err == nil { // if dir exists, let's try adding it to PATH env 30 for i := 0; i < len(env); i++ { 31 if strings.HasPrefix(env[i], "PATH=") { 32 env[i] = fmt.Sprintf("%s%c%s", env[i], os.PathListSeparator, goBinDir) 33 goto donePath 34 } 35 } 36 // no path... maybe we shoule add it? pretty strange environment with no path, not putting anything here for now 37 } 38 donePath: 39 40 env = append(env, env2...) 41 42 cmd := exec.Command(name, arg...) 43 cmd.Env = env 44 45 b, err = cmd.CombinedOutput() 46 if err != nil { 47 err2 := fmt.Errorf("error running: %s %v; err=%v; output:\n%s\n", name, arg, err, b) 48 fmt.Print(err2) 49 panic(err2) 50 } 51 52 return string(b) 53 } 54 55 // MustExec wraps exec.Command(...).CombinedOutput() with certain differences. 56 // If `go env GOPATH`/bin exists it is added to the PATH environment variable. 57 // Upon error the output of the command and the error will be printed and it will panic. 58 // Upon success the output is returned as a string. 59 func MustExec(name string, arg ...string) string { 60 return MustEnvExec(nil, name, arg...) 61 }