-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
124 lines (107 loc) · 2.28 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"path"
"strings"
)
func Command(name string, args ...string) *exec.Cmd {
cmd := exec.Command(name, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd
}
func DefaultStr(val string, def ...string) string {
if val != "" {
return val
}
for _, d := range def {
if d != "" {
return d
}
}
return ""
}
func parseCommand(command string) ([]string, error) {
var args []string
state := "start"
current := ""
quote := "\""
escapeNext := true
for _, c := range command {
if state == "quotes" {
if string(c) != quote {
current += string(c)
} else {
args = append(args, current)
current = ""
state = "start"
}
continue
}
if escapeNext {
current += string(c)
escapeNext = false
continue
}
if c == '\\' {
escapeNext = true
continue
}
if c == '"' || c == '\'' {
state = "quotes"
quote = string(c)
continue
}
if state == "arg" {
if c == ' ' || c == '\t' {
args = append(args, current)
current = ""
state = "start"
} else {
current += string(c)
}
continue
}
if c != ' ' && c != '\t' {
state = "arg"
current += string(c)
}
}
if state == "quotes" {
return []string{}, fmt.Errorf("unclosed quote in command line: %s", command)
}
if current != "" {
args = append(args, current)
}
return args, nil
}
// JoinPaths is just like path.Join method, but doesn't remove the last path separator from the joined paths.
// e.g., JoinPaths("a","b/") returns "a/b/" insted of "a/b"
func JoinPaths(elem ...string) string {
lastElem := elem[len(elem)-1]
appenPathSeparator := len(lastElem) != 0 && lastElem[len(lastElem)-1] == os.PathSeparator
res := path.Join(elem...)
if appenPathSeparator {
res = res + string(os.PathSeparator)
}
return res
}
func EndsWithDirectoryPath(path string) bool {
return len(path) != 0 && path[len(path)-1] == os.PathSeparator
}
func BoolPrompt(r io.Reader, w io.Writer, msg string) (bool, error) {
if _, err := fmt.Fprint(w, msg); err != nil {
return false, err
}
resBytes, err := bufio.NewReader(r).ReadBytes('\n')
if err != nil {
return false, err
}
res := strings.ToLower(string(resBytes[:len(resBytes)-1]))
return res == "" || res == "y" || res == "yes", nil
}