Skip to content

Commit b2da097

Browse files
committedAug 5, 2018
initial commit
0 parents  commit b2da097

File tree

6 files changed

+1270
-0
lines changed

6 files changed

+1270
-0
lines changed
 

‎exec.go

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"os"
7+
"os/exec"
8+
"strings"
9+
"sync"
10+
11+
"gopkg.in/errgo.v2/fmt/errors"
12+
)
13+
14+
func runCmd(dir string, name string, args ...string) (string, error) {
15+
var outData, errData bytes.Buffer
16+
if *printCommands {
17+
printShellCommand(dir, name, args)
18+
}
19+
c := exec.Command(name, args...)
20+
c.Stdout = &outData
21+
c.Stderr = &errData
22+
c.Dir = dir
23+
err := c.Run()
24+
if err == nil {
25+
return outData.String(), nil
26+
}
27+
if _, ok := err.(*exec.ExitError); ok && errData.Len() > 0 {
28+
return "", errors.New(strings.TrimSpace(errData.String()))
29+
}
30+
return "", fmt.Errorf("cannot run %q: %v", append([]string{name}, args...), err)
31+
}
32+
33+
var (
34+
outputDirMutex sync.Mutex
35+
outputDir string
36+
)
37+
38+
func printShellCommand(dir, name string, args []string) {
39+
outputDirMutex.Lock()
40+
defer outputDirMutex.Unlock()
41+
if dir != outputDir {
42+
fmt.Fprintf(os.Stderr, "cd %s\n", shquote(dir))
43+
outputDir = dir
44+
}
45+
var buf bytes.Buffer
46+
buf.WriteString(name)
47+
for _, arg := range args {
48+
buf.WriteString(" ")
49+
buf.WriteString(shquote(arg))
50+
}
51+
fmt.Fprintf(os.Stderr, "%s\n", buf.Bytes())
52+
}
53+
54+
func shquote(s string) string {
55+
// single-quote becomes single-quote, double-quote, single-quote, double-quote, single-quote
56+
return `'` + strings.Replace(s, `'`, `'"'"'`, -1) + `'`
57+
}

0 commit comments

Comments
 (0)
Please sign in to comment.