forked from grosser/go-testcov
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
83 lines (73 loc) · 1.88 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"sort"
"strconv"
"strings"
"syscall"
)
// blow up on errors without extra conditionals everywhere
func check(e error) {
if e != nil {
panic(e)
}
}
// "" => [] "foo" => ["foo"]
func splitWithoutEmpty(string string, delimiter rune) []string {
return strings.FieldsFunc(string, func(c rune) bool { return c == delimiter })
}
// Run a command and stream output to stdout/err, but return an exit code
// https://stackoverflow.com/questions/10385551/get-exit-code-go
func runCommand(name string, args ...string) (exitCode int) {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
// try to get the exit code
if exitError, ok := err.(*exec.ExitError); ok {
ws := exitError.Sys().(syscall.WaitStatus)
exitCode = ws.ExitStatus()
} else {
// This will happen (in OSX) if `name` is not available in $PATH,
// in this situation, exit code could not be get
fmt.Fprintf(os.Stderr, "Could not get exit code for failed program: %v, %v\n", name, args)
exitCode = 1
}
} else {
// success, exitCode should be 0 if go is ok
ws := cmd.ProcessState.Sys().(syscall.WaitStatus)
exitCode = ws.ExitStatus()
}
return
}
// read a file into a string
func readFile(path string) (content string) {
data, err := ioutil.ReadFile(path)
check(err)
return string(data)
}
// iterate a map by going through it via by it's sorted keys
func iterateSorted(data map[string][]Section, fn func(string, []Section)) {
keys := make([]string, len(data))
i := 0
for k := range data {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
fn(k, data[k])
}
}
func joinPath(parts ...string) string {
return strings.Join(parts, string(os.PathSeparator))
}
func stringToInt(string string) int {
converted, err := strconv.Atoi(string)
check(err)
return converted
}