-
Notifications
You must be signed in to change notification settings - Fork 47
/
util.go
265 lines (218 loc) · 4.89 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package dstask
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"os/exec"
"runtime"
"strings"
"unicode"
"unicode/utf8"
"github.com/gofrs/uuid"
"github.com/mattn/go-isatty"
"golang.org/x/sys/unix"
)
func ExitFail(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, "\033[31m"+format+"\033[0m\n", a...)
os.Exit(1)
}
func ConfirmOrAbort(format string, a ...interface{}) {
fmt.Fprintf(os.Stderr, format+" [y/n] ", a...)
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
if input == "y\n" {
return
}
ExitFail("Aborted.")
}
func MustGetUUID4String() string {
// does not match docs...
u, err := uuid.NewV4()
if err != nil {
panic(err)
}
return u.String()
}
func IsValidUUID4String(str string) bool {
_, err := uuid.FromString(str)
return err == nil
}
func IsValidPriority(priority string) bool {
return map[string]bool{
PRIORITY_CRITICAL: true,
PRIORITY_HIGH: true,
PRIORITY_NORMAL: true,
PRIORITY_LOW: true,
}[priority]
}
func IsValidStatus(status string) bool {
return StrSliceContains(ALL_STATUSES, status)
}
func SumInts(vals ...int) int {
var total int
for _, v := range vals {
total += v
}
return total
}
func RunCmd(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// MakeTempFilename encodes the task ID and a truncated portion of a task
// summary into a string suitable for passing to ioutil.TempFile.
func MakeTempFilename(id int, summary, ext string) string {
truncated := make([]rune, utf8.RuneCountInString(summary))
i := 0
for _, r := range summary {
// If our utf8 grapheme cannot be encoded in a single byte, skip.
if utf8.RuneLen(r) != 1 {
continue // 👋
}
if unicode.IsPunct(r) {
continue
}
// If we're not a letter, number, or even printable, or we're
// a space char, convert to hyphen.
if (!unicode.IsLetter(r) && !unicode.IsNumber(r)) || unicode.IsSpace(r) {
r = rune('-')
// Do not allow two "-" hyphens in a row
if i > 0 {
if truncated[i-1] == rune('-') {
continue
}
} else {
continue
}
}
truncated[i] = r
if i > 20 {
break
}
i++
}
truncated = truncated[:i]
loweredWithID := strings.ToLower(fmt.Sprintf("%v-%s", id, string(truncated)))
return fmt.Sprintf("dstask.*.%s.%s", loweredWithID, ext)
}
func MustEditBytes(data []byte, tmpFilename string) []byte {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
tmpfile, err := ioutil.TempFile("", tmpFilename)
if err != nil {
ExitFail("Could not create temporary file to edit")
}
defer os.Remove(tmpfile.Name())
_, err = tmpfile.Write(data)
tmpfile.Close()
if err != nil {
ExitFail("Could not write to temporary file to edit")
}
err = RunCmd(editor, tmpfile.Name())
if err != nil {
ExitFail("Failed to run $EDITOR")
}
data, err = ioutil.ReadFile(tmpfile.Name())
if err != nil {
ExitFail("Could not read back temporary edited file")
}
return data
}
func StrSliceContains(haystack []string, needle string) bool {
for _, item := range haystack {
if item == needle {
return true
}
}
return false
}
// generics pls...
func IntSliceContains(haystack []int, needle int) bool {
for _, item := range haystack {
if item == needle {
return true
}
}
return false
}
func StrSliceContainsAll(subset, superset []string) bool {
for _, have := range subset {
foundInSuperset := false
for _, want := range superset {
if have == want {
foundInSuperset = true
break
}
}
if !foundInSuperset {
return false
}
}
return true
}
func IsValidStateTransition(from string, to string) bool {
for _, transition := range VALID_STATUS_TRANSITIONS {
if from == transition[0] && to == transition[1] {
return true
}
}
return false
}
func MustOpenBrowser(url string) {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
ExitFail("unsupported platform")
}
if err != nil {
ExitFail("Failed to open browser")
}
}
func DeduplicateStrings(s []string) []string {
seen := make(map[string]struct{}, len(s))
j := 0
for _, v := range s {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
s[j] = v
j++
}
return s[:j]
}
func MustGetTermSize() (int, int) {
if FAKE_PTY {
return 80, 24
}
ws, err := unix.IoctlGetWinsize(int(os.Stdout.Fd()), unix.TIOCGWINSZ)
if err != nil {
ExitFail("Not a TTY")
}
return int(ws.Col), int(ws.Row)
}
func StdoutIsTTY() bool {
isTTY := isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())
return isTTY || FAKE_PTY
}
func WriteStdout(data []byte) error {
if _, err := os.Stdout.Write(data); err != nil {
return err
}
return nil
}