-
Notifications
You must be signed in to change notification settings - Fork 18
/
main.go
355 lines (317 loc) · 9.94 KB
/
main.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/*
Copyright 2011 Alec Thomas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/alecthomas/kingpin/v2"
)
const usage = `DevTodo2 - a hierarchical command-line task manager
DevTodo is a program aimed specifically at programmers (but usable by anybody
at the terminal) to aid in day-to-day development.
It maintains a list of items that have yet to be completed, one list for each
project directory. This allows the programmer to track outstanding bugs or
items that need to be completed with very little effort.
Items can be prioritised and are displayed in a hierarchy, so that one item may
depend on another.
todo2 [-A]
Display (all) tasks.
todo2 [-p <priority>] -a <text>
Create a new task.
todo2 -d <index>
Mark a task as complete.
todo2 [-p <priority>] -e <task> [<text>]
Edit an existing task.
`
// Actions
var addFlag = kingpin.Flag("add", "Add a task.").Short('a').Bool()
var editFlag = kingpin.Flag("edit", "Edit a task, replacing its text.").Short('e').Bool()
var markDoneFlag = kingpin.Flag("done", "Mark the given tasks as done.").Short('d').Bool()
var markNotDoneFlag = kingpin.Flag("not-done", "Mark the given tasks as not done.").Short('D').Bool()
var removeFlag = kingpin.Flag("remove", "Remove the given tasks.").Bool()
var reparentFlag = kingpin.Flag("reparent", "Reparent task A below task B").Bool()
var titleFlag = kingpin.Flag("title", "Set the task list title.").Bool()
var infoFlag = kingpin.Flag("info", "Show information on a task.").Bool()
var importFlag = kingpin.Flag("import", "Import and synchronise TODO items from source code.").Bool()
var purgeFlag = kingpin.Flag("purge", "Purge completed tasks older than this.").Default("-1s").PlaceHolder("0s").Duration()
// Options
var priorityFlag = kingpin.Flag("priority", "priority of newly created tasks (veryhigh,high,medium,low,verylow)").Short('p').
PlaceHolder("medium").Enum("veryhigh", "high", "medium", "low", "verylow")
var graftFlag = kingpin.Flag("graft", "Task to graft new tasks to.").Short('g').Default("root").String()
var fileFlag = kingpin.Flag("file", "Flie to load task lists from.").Default(".todo2").String()
var legacyFileFlag = kingpin.Flag("legacy-file", "File to load legacy task lists from.").Default(".todo").String()
var allFlag = kingpin.Flag("all", "Show all tasks, even completed ones.").Short('A').Bool()
var summaryFlag = kingpin.Flag("summary", "Summarise tasks to one line.").Short('s').Bool()
var orderFlag = kingpin.Flag("order", "Specify display order of tasks ([-]index,created,completed,text,priority,duration,done)").Default("priority").Enum(orderEnum...)
// Task text.
var taskText = kingpin.Arg("arg", "Task text or index.").Strings()
var orderEnum = []string{
"index", "created", "completed", "text", "priority", "duration", "done",
"-index", "-created", "-completed", "-text", "-priority", "-duration", "-done",
}
func doView(tasks TaskList) {
order, reversed := OrderFromString(*orderFlag)
options := &ViewOptions{
ShowAll: *allFlag,
Summarise: *summaryFlag,
Order: order,
Reversed: reversed,
}
view := NewConsoleView()
view.ShowTree(tasks, options)
}
func doAdd(tasks TaskList, graft TaskNode, priority Priority, text string) {
graft.Create(text, priority)
saveTaskList(tasks)
}
func doEditTask(tasks TaskList, task Task, priority Priority, text string) {
if text != "" {
task.SetText(text)
}
if priority != -1 {
task.SetPriority(priority)
}
saveTaskList(tasks)
}
func doMarkDone(tasks TaskList, references []Task) {
for _, task := range references {
task.SetCompleted()
}
saveTaskList(tasks)
}
func doMarkNotDone(tasks TaskList, references []Task) {
for _, task := range references {
task.SetCompletionTime(time.Time{})
}
saveTaskList(tasks)
}
func doReparent(tasks TaskList, task TaskNode, below TaskNode) {
ReparentTask(task, below)
saveTaskList(tasks)
}
func doRemove(tasks TaskList, references []Task) {
for _, task := range references {
task.Delete()
}
saveTaskList(tasks)
}
func doPurge(tasks TaskList, age time.Duration) {
cutoff := time.Now().Add(-age)
matches := tasks.FindAll(func(task Task) bool {
return !task.CompletionTime().IsZero() && task.CompletionTime().Before(cutoff)
})
for _, m := range matches {
m.Delete()
}
saveTaskList(tasks)
}
func doSetTitle(tasks TaskList, args []string) {
title := strings.Join(args, " ")
tasks.SetTitle(title)
saveTaskList(tasks)
}
func doShowInfo(tasks TaskList, index string) {
task := tasks.Find(index)
if task == nil {
fatalf("no such task %s", index)
}
view := NewConsoleView()
view.ShowTaskInfo(task)
}
func processAction(tasks TaskList) {
priority := PriorityFromString(*priorityFlag)
var graft TaskNode = tasks // -golint
if *graftFlag != "root" {
if graft = tasks.Find(*graftFlag); graft == nil {
fatalf("invalid graft index '%s'", *graftFlag)
}
}
switch {
case *addFlag:
if len(*taskText) == 0 {
fatalf("expected text for new task")
}
text := strings.Join(*taskText, " ")
doAdd(tasks, graft, priority, text)
case *markDoneFlag:
doMarkDone(tasks, resolveTaskReferences(tasks, *taskText))
case *markNotDoneFlag:
doMarkNotDone(tasks, resolveTaskReferences(tasks, *taskText))
case *removeFlag:
doRemove(tasks, resolveTaskReferences(tasks, *taskText))
case *reparentFlag:
if len(*taskText) < 1 {
fatalf("expected <task> [<new-parent>] for reparenting")
}
var below TaskNode
if len(*taskText) == 2 {
below = resolveTaskReference(tasks, (*taskText)[1])
} else {
below = tasks
}
doReparent(tasks, resolveTaskReference(tasks, (*taskText)[0]), below)
case *titleFlag:
doSetTitle(tasks, *taskText)
case *infoFlag:
if len(*taskText) < 1 {
fatalf("expected <task> for info")
}
doShowInfo(tasks, (*taskText)[0])
case *importFlag:
if len(*taskText) < 1 {
fatalf("expected list of files to import")
}
doImport(tasks, *taskText)
case *editFlag:
if len(*taskText) < 1 {
fatalf("expected [-p <priority>] <task> [<text>]")
}
task := tasks.Find((*taskText)[0])
if task == nil {
fatalf("invalid task %s", (*taskText)[0])
}
text := strings.Join((*taskText)[1:], " ")
if *priorityFlag == "" {
priority = -1
}
doEditTask(tasks, task, priority, text)
case *purgeFlag != -1*time.Second:
doPurge(tasks, *purgeFlag)
default:
doView(tasks)
}
}
func resolveTaskReference(tasks TaskList, index string) Task {
task := tasks.Find(index)
if task == nil {
fatalf("invalid task index %s", index)
}
return task
}
func expandRange(indexRange string) []string {
// This whole function makes me sad. This kind of manipulation of strings and
// arrays just should not be this verbose.
//
// For constrast, in Python:
//
// def expand_range(index):
// start_index, end = index.split('-')
// start_index, start = start_index.rsplit('.', 1)
// for i in range(int(start), int(end) + 1):
// yield '%s.%s' % (start_index, str(i))
ranges := strings.Split(indexRange, "-")
if len(ranges) != 2 {
return nil
}
startIndex := strings.Split(ranges[0], ".")
start, err := strconv.Atoi(startIndex[len(startIndex)-1])
if err != nil {
return nil
}
end, err := strconv.Atoi(ranges[1])
if err != nil {
return nil
}
rangeIndexes := []string{}
for i := start; i <= end; i++ {
index := startIndex[:len(startIndex)-1]
index = append(index, fmt.Sprintf("%d", i))
rangeIndexes = append(rangeIndexes, strings.Join(index, "."))
}
return rangeIndexes
}
func resolveTaskReferences(tasks TaskList, indices []string) []Task {
references := make([]Task, 0, len(indices))
for _, index := range indices {
if strings.Index(index, "-") == -1 {
task := resolveTaskReference(tasks, index)
references = append(references, task)
} else {
// Expand ranges. eg. 1.2-5 expands to 1.2 1.3 1.4 1.5
indexes := expandRange(index)
if indexes == nil {
fatalf("invalid task range %s", index)
}
for _, rangeIndex := range indexes {
task := resolveTaskReference(tasks, rangeIndex)
if task != nil {
references = append(references, task)
}
}
}
}
if len(references) == 0 {
fatalf("no tasks provided to mark done")
}
return references
}
func loadTaskList() (tasks TaskList, err error) {
// Try loading new-style task file
if file, err := os.Open(*fileFlag); err == nil {
defer file.Close()
loader := NewJSONIO()
return loader.Deserialize(file)
}
// Try loading legacy task file
if file, err := os.Open(*legacyFileFlag); err == nil {
defer file.Close()
loader := NewLegacyIO()
return loader.Deserialize(file)
}
return nil, nil
}
func saveTaskList(tasks TaskList) {
path := *fileFlag
previous := path + "~"
temp := path + "~~"
var serializeError error
if file, err := os.Create(temp); err == nil {
defer func() {
if err = file.Close(); err != nil {
os.Remove(temp)
} else {
if serializeError != nil {
return
}
if _, err = os.Stat(path); err == nil {
if err = os.Rename(path, previous); err != nil {
fatalf("unable to rename %s to %s", path, previous)
}
}
if err = os.Rename(temp, path); err != nil {
fatalf("unable to rename %s to %s", temp, path)
}
}
}()
writer := NewJSONIO()
if serializeError = writer.Serialize(file, tasks); serializeError != nil {
fatalf(serializeError.Error())
}
}
}
func main() {
kingpin.CommandLine.Help = usage
kingpin.Version("2.2.0").Author("Alec Thomas <[email protected]>")
kingpin.Parse()
tasks, err := loadTaskList()
if err != nil {
fatalf("%s", err)
}
if tasks == nil {
tasks = NewTaskList()
}
processAction(tasks)
}