forked from naggie/dstask
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.go
More file actions
286 lines (227 loc) · 5.81 KB
/
util.go
File metadata and controls
286 lines (227 loc) · 5.81 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package dstask
import (
"bufio"
"fmt"
"os"
"os/exec"
"runtime"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/gofrs/uuid"
"github.com/mattn/go-isatty"
)
func ExitFail(format string, a ...any) {
fmt.Fprintf(os.Stderr, "\033[31m"+format+"\033[0m\n", a...)
os.Exit(1)
}
func ConfirmOrAbort(format string, a ...any) {
fmt.Fprintf(os.Stderr, format+" [y/n] ", a...)
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
panic(err)
}
// Normalize input: remove CR/LF/whitespace and compare in lowercase
normalized := strings.ToLower(strings.TrimSpace(input))
if normalized == "y" || normalized == "yes" {
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 ParseDueDateArg(dueStr string) (dateFilter string, dueDate time.Time) {
parts := strings.SplitN(dueStr, ":", 2)
if len(parts) != 2 {
ExitFail("Invalid due query format: " + dueStr + "\n" +
"Expected format: due:YYYY-MM-DD, due:MM-DD, due:DD, due:next-monday, due:today, etc.")
}
if parts[1] == "overdue" {
dateFilter = "before"
dueDate = startOfDay(time.Now())
return dateFilter, dueDate
}
tagParts := strings.SplitN(parts[0], ".", 2)
if len(tagParts) == 2 {
dateFilter = tagParts[1]
dateFilters := map[string]struct{}{"after": {}, "before": {}, "on": {}, "in": {}}
_, ok := dateFilters[dateFilter]
if !ok && dateFilter != "" {
ExitFail("Invalid date filter format: " + dateFilter + "\n" +
"Valid filters are: after, before, on, in")
}
} else {
dateFilter = ""
}
dueDate = ParseStrToDate(parts[1])
return dateFilter, dueDate
}
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 := strings.Fields(os.Getenv("EDITOR"))
if len(editor) == 0 {
editor = []string{"vim"}
}
tmpfile, err := os.CreateTemp("", tmpFilename)
if err != nil {
ExitFail("Could not create temporary file to edit")
}
defer func() {
if err := os.Remove(tmpfile.Name()); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to remove temporary file: %v\n", err)
}
}()
_, err = tmpfile.Write(data)
if err != nil {
ExitFail("Could not write to temporary file to edit")
}
if err := tmpfile.Close(); err != nil {
ExitFail("Could not close temporary file to edit")
}
err = RunCmd(editor[0], append(editor[1:], tmpfile.Name())...)
if err != nil {
ExitFail("Failed to run $EDITOR")
}
data, err = os.ReadFile(tmpfile.Name())
if err != nil {
ExitFail("Could not read back temporary edited file")
}
return data
}
func StrSliceContains(haystack []string, needle string) bool {
return slices.Contains(haystack, needle)
}
// generics pls...
func IntSliceContains(haystack []int, needle int) bool {
return slices.Contains(haystack, needle)
}
func StrSliceContainsAll(subset, superset []string) bool {
for _, have := range subset {
foundInSuperset := slices.Contains(superset, have)
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]
}
// MustGetTermSize is implemented per-OS in util_unix.go and util_windows.go
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
}