This repository has been archived by the owner on Aug 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.go
105 lines (97 loc) · 2.39 KB
/
util.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"bytes"
"errors"
"log"
"os/exec"
"os/user"
"runtime"
"strings"
"time"
)
// Combines string and error into new error.
func newErr(input string, err error) error {
err = errors.New(input + " " + err.Error())
log.Print(err)
return err
}
// handle logs errors and information at runtime. Used for easier error tracing
// up the call stack.
func handle(input string, err error) error {
if err == nil {
return err
}
pc, fn, line, ok := runtime.Caller(1)
if input[len(input)-1:] != "." { // Add a period.
input += "."
}
input += " " + err.Error()
if !ok {
log.Printf("[error] %s", input)
return errors.New(input)
}
p := strings.Split(fn, "/")
fn = p[len(p)-1]
log.Printf("[error] in %s[%s:%d] %s",
runtime.FuncForPC(pc).Name(), fn, line, input)
return errors.New(input)
}
// Outputs a system command to log with all output on error.
func commandVerboseOnErr(input string) (string, string, error) {
stdout, stderr, err := commandWithOutput(input)
if err != nil {
log.Print("Command: " + input)
if stdout != "" {
log.Print(stdout)
}
if stderr != "" {
log.Print(stderr)
}
err = newErr("Error in running command.", err)
log.Print(err)
}
return stdout, stderr, err
}
// Outputs a system command to log with stdout, stderr, and err output.
func commandVerbose(input string) (string, string, error) {
log.Print("Command: " + input)
stdout, stderr, err := commandWithOutput(input)
if stdout != "" {
log.Print(stdout)
}
if stderr != "" {
log.Print(stderr)
}
if err != nil {
err = newErr("Error in running command.", err)
log.Print(err)
} else {
log.Print("Command ran with no errors.")
}
return stdout, stderr, err
}
// Executes a shell command and returns the stdout, stderr, and err
func commandWithOutput(input string) (string, string, error) {
cmd := exec.Command("sh", "-cx", input)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
outResp := stdout.String()
errResp := stderr.String()
return outResp, errResp, err
}
// Used for time benchmarking.
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.Printf("%s took %s", name, elapsed)
}
// getUserHome gets the full path of the user's home directory.
func getUserHome() string {
usr, err := user.Current()
if err != nil {
log.Print("Couldn't get user's home directory.")
log.Fatal(err)
}
return usr.HomeDir
}