mirror of
https://github.com/golang/go
synced 2024-11-22 01:24:42 -07:00
f259f6ba0a
This removes exec.Run and replaces exec.Cmd with a new implementation. The new exec.Cmd represents both a currently-running command and also a command being prepared. It has a good zero value. You can Start + Wait on a Cmd, or simply Run it. Start (and Run) deal with copying stdout, stdin, and stderr between the Cmd's io.Readers and io.Writers. There are convenience methods to capture a command's stdout and/or stderr. R=r, n13m3y3r, rsc, gustavo, alex.brainman, dsymonds, r, adg, duzy.chan, mike.rosset, kevlar CC=golang-dev https://golang.org/cl/4552052
74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
// Copyright 2011 The Go Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"exec"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
// run is a simple wrapper for exec.Run/Close
|
|
func run(envv []string, dir string, argv ...string) os.Error {
|
|
if *verbose {
|
|
log.Println("run", argv)
|
|
}
|
|
argv = useBash(argv)
|
|
cmd := exec.Command(argv[0], argv[1:]...)
|
|
cmd.Dir = dir
|
|
cmd.Env = envv
|
|
cmd.Stderr = os.Stderr
|
|
return cmd.Run()
|
|
}
|
|
|
|
// runLog runs a process and returns the combined stdout/stderr,
|
|
// as well as writing it to logfile (if specified).
|
|
func runLog(envv []string, logfile, dir string, argv ...string) (output string, exitStatus int, err os.Error) {
|
|
if *verbose {
|
|
log.Println("runLog", argv)
|
|
}
|
|
argv = useBash(argv)
|
|
|
|
b := new(bytes.Buffer)
|
|
var w io.Writer = b
|
|
if logfile != "" {
|
|
f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
w = io.MultiWriter(f, b)
|
|
}
|
|
|
|
cmd := exec.Command(argv[0], argv[1:]...)
|
|
cmd.Dir = dir
|
|
cmd.Env = envv
|
|
cmd.Stdout = w
|
|
cmd.Stderr = w
|
|
|
|
err = cmd.Run()
|
|
output = b.String()
|
|
if err != nil {
|
|
if ws, ok := err.(*os.Waitmsg); ok {
|
|
exitStatus = ws.ExitStatus()
|
|
}
|
|
return
|
|
}
|
|
return
|
|
}
|
|
|
|
// useBash prefixes a list of args with 'bash' if the first argument
|
|
// is a bash script.
|
|
func useBash(argv []string) []string {
|
|
// TODO(brainman): choose a more reliable heuristic here.
|
|
if strings.HasSuffix(argv[0], ".bash") {
|
|
argv = append([]string{"bash"}, argv...)
|
|
}
|
|
return argv
|
|
}
|