-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroot.go
More file actions
987 lines (858 loc) · 24.8 KB
/
root.go
File metadata and controls
987 lines (858 loc) · 24.8 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
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
package main
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/boltdb/bolt"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "task [command]",
Short: "A CLI for managing your TODOs",
// Long: ``
}
// Subcommands
func newAddCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "add [task]",
Short: "Add a new task to your TODO list",
Run: func(cmd *cobra.Command, args []string) {
tags, parsed := parseTags(strings.Join(args, " "))
if parsed == "" {
fmt.Fprintf(out, "Error: Empty task\n")
return
}
var tag = ""
if len(tags) >= 1 {
// For now, only add the first tag to a task
tag = tags[0]
}
err := insert(mgr.db, TASKS_BUCKET, parsed, tag)
check(err)
fmt.Fprintf(out, "Added task: '%s'\n", parsed)
},
}
}
func newDoCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
doCmd := &cobra.Command{
Use: "do [taskID]",
Short: "Mark a task on your TODO list as complete",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
db := mgr.db
var keys []int
if len(args) == 0 {
return fmt.Errorf("Must provide a task ID")
}
for _, v := range args {
id, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf(`Invalid task ID "%s"`, v)
}
keys = append(keys, id)
er := completeTask(id, db)
if er != nil {
return er
}
fmt.Fprintf(out, "Completed task %d\n", id)
}
if DeleteOnDo {
// add the specified tasks to the archive ->
// remove _only_ the specified tasks from the
// tasks bucket
var tasks []Task
for _, k := range keys {
task, _ := getTask(db, k)
tasks = append(tasks, task)
}
addToArchive(db, tasks)
deleteKeys(keys, db, TASKS_BUCKET)
}
fmt.Fprintln(out)
tp := getTasks(db, TASKS_BUCKET)
fmt.Fprintln(out, formatTasks(tp))
return nil
},
}
doCmd.Flags().BoolVarP(&DeleteOnDo, "finish", "f", false, "Complete and finish the specified tasks")
return doCmd
}
func newUpdateCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "update [taskID] [-ds]",
Short: "Update a task",
// SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
// Setting this to true at the start of the RunE instead of the cmd itself
// ensures that flag parsing errors will still display the usage message
cmd.SilenceUsage = true
db := mgr.db
// Make sure exactly 1 argument is passed in
if len(args) != 1 {
return errors.New("Must specify a single task to update")
}
// Make sure the argument is an int
id, err := strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("Argument should be an integer\n\"%s\" is not an integer", args[0])
}
// Make sure the input number is a valid taskID
taskCount := getCount(db, TASKS_BUCKET)
if id > taskCount || id == 0 {
return (fmt.Errorf("Invalid task ID, %d tasks exist", taskCount))
}
// Return early if there's no update to make
if UpdatedDesc == "" && !UpdateStatus {
cmd.SilenceUsage = false
return errors.New("Did not make any updates, try using a flag")
}
t, _ := getTask(db, id)
// Flip the task status
if UpdateStatus {
if t.Status == STATUS.COMPLETE {
t.Status = STATUS.INCOMPLETE
t.Completed = ""
} else {
t.Status = STATUS.COMPLETE
t.Completed = time.Now().Format(RFC3339)
}
}
// Update the task description
if UpdatedDesc != "" {
// Update the tag if a tag is present in the input
tags, s := parseTags(UpdatedDesc)
if s == "" {
return errors.New("Must provide a task description")
}
if len(tags) >= 1 {
t.Tag = tags[0]
}
t.Desc = s
}
// Finally, update the task in the db
if err := updateTask(db, id, t); err != nil {
return err
}
fmt.Fprintf(out, "Updated task %d\n", id)
// Print the updated tasks
tp := getTasks(db, TASKS_BUCKET)
fmt.Fprintln(out, formatTasks(tp))
return nil
},
}
cmd.Flags().StringVarP(&UpdatedDesc, "des", "d", "", "New task description. If a tag is present in the new description, the old tag will be replaced")
cmd.Flags().BoolVarP(&UpdateStatus, "status", "s", false, "Flip the completion status of the task")
return cmd
}
func newListCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
lCmd := &cobra.Command{
Use: "list -[te]",
Short: "List all of your incomplete tasks",
Run: func(cmd *cobra.Command, args []string) {
var exclude []string
var include []string
exclude = strings.Split(ExcludeTags, ",")
// Avoids buggy behavior when user inputs "-e" or "-e="
if len(exclude) == 1 && exclude[0] == "" {
exclude = []string{}
}
input := strings.Join(args, " ")
if len(input) >= 1 {
include, _ = parseTags(input)
}
if len(include) > 0 && len(exclude) > 0 {
fmt.Fprintln(out, "Can't use tag filtering in combination with exclude flag")
return
}
tasks := getTasks(mgr.db, TASKS_BUCKET)
tasks = filterTasks(tasks, include, exclude)
if len(tasks) == 0 {
fmt.Fprintln(out, "No tasks")
return
}
fmt.Fprintln(out, formatTasks(tasks))
},
}
lCmd.Flags().BoolVarP(&ShowTags, "tag", "t", false, "Show tag associated with each task")
lCmd.Flags().StringVarP(&ExcludeTags, "exclude", "e", "", "Exclude tasks with listed tags. The tags should be comma seperated. Example: -e=tag1,tag2,tag3")
return lCmd
}
func newFinishCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "finish",
Short: "Delete all completed tasks",
Run: func(cmd *cobra.Command, args []string) {
db := mgr.db
deletedTasks, err := finish(db)
check(err)
if len(deletedTasks) == 0 {
fmt.Fprintln(out, "No completed tasks to finish")
return
}
fmt.Fprintf(out, "Deleted all completed tasks\n")
// Print the updated task list
tp := getTasks(db, TASKS_BUCKET)
if len(tp) == 0 {
return
}
fmt.Fprintln(out, formatTasks(tp))
},
}
}
func newClearCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "clear",
Short: "Delete all tasks",
Run: func(cmd *cobra.Command, args []string) {
mgr.db.Update(func(tx *bolt.Tx) error {
tx.DeleteBucket(TASKS_BUCKET)
return nil
})
fmt.Fprintln(out, "Deleted all tasks")
},
}
}
func newDeleteCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "delete",
Short: "Delete a task",
Run: func(cmd *cobra.Command, args []string) {
db := mgr.db
var ids []int
taskCount := getCount(db, TASKS_BUCKET)
for _, s := range args {
id, err := strconv.Atoi(s)
if err != nil {
fmt.Fprintln(out, "Arguments should only be numbers")
fmt.Fprintf(out, "%s is not a number\n", args[0])
os.Exit(1)
}
if id > taskCount {
fmt.Fprintf(out, "%d is out of range, only %d tasks exist\n", id, taskCount)
return
}
ids = append(ids, id)
}
if len(ids) == 1 {
er := deleteKey(ids[0], db, TASKS_BUCKET)
check(er)
fmt.Fprintf(out, "Deleted task %d\n", ids[0])
tp := getTasks(db, TASKS_BUCKET)
fmt.Fprintln(out, formatTasks(tp))
return
}
deleteKeys(ids, db, TASKS_BUCKET)
for _, n := range ids {
fmt.Fprintln(out, "Deleted Task ", n)
}
fmt.Fprintln(out)
tp := getTasks(db, TASKS_BUCKET)
fmt.Fprintln(out, formatTasks(tp))
},
}
}
func newArchiveCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
arCmd := &cobra.Command{
Use: "archive -[c]",
Short: "View all previously completed tasks",
Run: func(cmd *cobra.Command, args []string) {
db := mgr.db
if ClearArchive {
db.Update(func(tx *bolt.Tx) error {
er := tx.DeleteBucket(ARCHIVE_BUCKET)
check(er)
return nil
})
fmt.Fprintln(out, "Cleared the archive")
return
}
db.View(func(tx *bolt.Tx) error {
archive := tx.Bucket(ARCHIVE_BUCKET)
if archive == nil || archive.Stats().KeyN == 0 {
fmt.Fprintln(out, "Archive is empty, finish a task to add it to the archive")
return nil
}
archive.ForEach(func(k, v []byte) error {
var task Task
json.Unmarshal(v, &task)
idx := binary.BigEndian.Uint64(k)
fmt.Fprintf(out, "%d: %s\n", idx, task.Desc)
return nil
})
return nil
})
},
}
arCmd.Flags().BoolVarP(&ClearArchive, "clear", "c", false, "Delete all archive entries")
return arCmd
}
func newStatsCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
sCmd := &cobra.Command{
Use: "stats",
Short: "See statistics on your task completion",
Run: func(cmd *cobra.Command, args []string) {
db := mgr.db
// Define the expected date format
mmddyyyy := "01/02/2006"
var startDate time.Time
var endDate time.Time
var mustInputStart bool
var err error
// Attempt to parse using mm/dd/yyy format
endDate, err = time.Parse(mmddyyyy, EndTime)
if err == nil {
mustInputStart = true
} else {
// Defaults to now
endDate = time.Now()
}
// Attempt to parse using mm/dd/yyy format
startDate, err = time.Parse(mmddyyyy, StartTime)
if err != nil && mustInputStart {
// User input an end but no start
fmt.Fprintln(out, "Must specify a start date")
return
}
if err != nil {
// Defaults to last 24hrs
startDate, err = time.Parse(RFC3339, time.Now().Add(-24*time.Hour).Format(RFC3339))
if err != nil {
fmt.Fprintln(out, "Error parsing start date:", err)
return
}
}
if endDate.Before(startDate) {
fmt.Fprintln(out, "Error: End date occured prior to the Start date")
return
}
if OnDay != "" {
day, err := time.Parse(mmddyyyy, OnDay)
if err != nil {
fmt.Fprintln(out, "Error parsing date:", err)
return
}
startDate = day
endDate = day
}
// If the user inputs the same start and end date, then set the end date to the last tick (12:59) of that day.
if startDate.Equal(endDate) {
endDate = lastTick(endDate)
}
var filtered []TaskPosition
tasks := getTasks(db, ARCHIVE_BUCKET)
for _, t := range tasks {
completed, err := time.Parse(RFC3339, t.task.Completed)
if err != nil {
fmt.Fprintln(out, "Error parsing completed date:", err)
return
}
if completed.After(startDate) && completed.Before(endDate) {
filtered = append(filtered, t)
// Useful for debugging
// fmt.Fprintln(out, completed)
}
}
if ShowCompleted {
fmt.Fprintln(out, formatTasks(filtered))
}
sy, sm, sd := startDate.Date()
ey, em, ed := endDate.Date()
numCompleted := max(len(filtered), 0)
fmt.Fprintf(out, "\nYou completed %d tasks from %d/%d/%d to %d/%d/%d\n", numCompleted, sm, sd, sy, em, ed, ey)
if ShowAverage {
diff := endDate.Sub(startDate)
numDays := diff.Hours() / 24
avg := float64(numCompleted) / numDays
fmt.Fprintf(out, "Average: %.1f/day\n", avg)
}
},
}
sCmd.Flags().StringVarP(&StartTime, "start", "s", "", "mm/dd/yyyy formated date to specify the start period")
sCmd.Flags().StringVarP(&EndTime, "end", "e", "", "mm/dd/yyyy formated date to specify the end window")
sCmd.Flags().StringVarP(&OnDay, "on", "o", "", "mm/dd/yyyy formated date. Shorthand for setting the start and end date to the same day. Note that the on flag cannot be used with the start or end flags")
sCmd.Flags().BoolVarP(&ShowCompleted, "verbose", "v", false, "Show the completed tasks")
sCmd.Flags().BoolVarP(&ShowAverage, "average", "a", false, "Show the average tasks completed/day")
sCmd.MarkFlagsMutuallyExclusive("start", "on")
sCmd.MarkFlagsMutuallyExclusive("end", "on")
return sCmd
}
func newCountCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "count",
Short: "Print the number of existing tasks",
Run: func(cmd *cobra.Command, args []string) {
num := getCount(mgr.db, TASKS_BUCKET)
fmt.Fprintf(out, "%d tasks\n", num)
},
}
}
func newTagsCmd(mgr *connectionManager, out io.Writer) *cobra.Command {
return &cobra.Command{
Use: "tags",
Short: "Print existing tags",
Run: func(cmd *cobra.Command, args []string) {
tags := getAllTags(mgr.db)
fmt.Fprintln(out, strings.Join(tags, ","))
},
}
}
func getAllTags(db *bolt.DB) []string {
var tags []string
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(TASKS_BUCKET)
return b.ForEach(func(k, v []byte) error {
t := bToTask(v)
if t.Tag != "" && !slices.Contains(tags, t.Tag) {
tags = append(tags, t.Tag)
}
return nil
})
})
return tags
}
// Flags
// $ archive
var ClearArchive bool
// $ list
var ShowTags bool
var ExcludeTags string
// $ update
var UpdatedDesc string
var UpdateStatus bool
// $ do
var DeleteOnDo bool
// $ stats
var StartTime string
var EndTime string
var OnDay string
var ShowCompleted bool
var ShowAverage bool
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.task-cli.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
var TASKS_BUCKET = []byte("tasks")
var ARCHIVE_BUCKET = []byte("archive")
var STATUS = TaskStatus{"complete", "incomplete"}
var RFC3339 = "2006-01-02T15:04:05Z07:00"
type BoltManager interface {
Database() *bolt.DB
Ping() error
Close() error
}
// Implements BoltManager. Note that db is initially nil
type connectionManager struct {
db *bolt.DB
}
// Returns the currently connected db instance
func (c *connectionManager) Database() *bolt.DB {
return c.db
}
// Validates the connection to db
func (c *connectionManager) Ping() error {
db := c.db.String()
if db == `DB<"">` {
return fmt.Errorf("Could not establish connection. Pinged db: %s", db)
}
return nil
}
// Closes connection to the database
func (c *connectionManager) Close() error {
return c.db.Close()
}
func newBoltManager() (*connectionManager, error) {
var connErr error
mgr := &connectionManager{}
mgr.db = newBoltConnection()
if err := mgr.Ping(); err != nil {
connErr = err
}
return mgr, connErr
}
// Returns a db instance
func newBoltConnection() *bolt.DB {
hDir, e := os.UserHomeDir()
check(e)
// default is "/task"
path := hDir + "/task"
// creates the `task` dir if it doesn't exist
dErr := os.MkdirAll(path, 0777)
check(dErr)
// default is "/tasks.db"
db, err := bolt.Open(path+"/tasks.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
check(err)
return db
}
type TaskStatus struct {
COMPLETE string
INCOMPLETE string
}
type Task struct {
Desc string
Status string
Created string
Completed string
Tag string
}
type TaskPosition struct {
task Task
dbKey int
}
func check(e error) {
if e != nil {
panic(e)
}
}
// Parse any tags in the form "+tag". Returns a slice of tags found and the original string with the
// tags removed. If no tags are found, returns an empty slice and the original string. Always returns ([]tags, s)
func parseTags(s string) ([]string, string) {
// Matches substrings in the form "+text" Captures "text".
re := regexp.MustCompile(`\+([^ ]+)`)
var tags []string
parsed := s
// match[0] is the entire match, match[1] is the capture group
matches := re.FindAllStringSubmatch(s, -1)
for _, m := range matches {
if m != nil && len(m) >= 2 {
tags = append(tags, m[1])
// remove extra whitespace when a tag is the the middle of a string. ex "a +b c" -> "a c"
spaceBefore := " " + m[0]
if strings.Contains(s, spaceBefore) {
b, a, _ := strings.Cut(parsed, spaceBefore)
parsed = b + a
} else {
parsed = strings.Replace(parsed, m[0], "", 1)
}
}
}
return tags, strings.TrimSpace(parsed)
}
// Opens an Update transaction with `db`, creates a Task from `s` and inserts the task into `bucket`
func insert(db *bolt.DB, bucket []byte, s string, tag string) error {
err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists(bucket)
if err != nil {
return err
}
// create an id and convert it to a []byte
id, _ := b.NextSequence()
byteId := itob(int(id))
task := Task{
Desc: s,
Status: STATUS.INCOMPLETE,
Created: time.Now().Format(RFC3339),
Completed: "",
Tag: tag,
}
// Marshal Task data into bytes.
buf, err := json.Marshal(task)
if err != nil {
return err
}
return b.Put(byteId, buf)
})
return err
}
// Returns a slice containing all tasks in the database along with their respective positions.
func getTasks(db *bolt.DB, bucket []byte) []TaskPosition {
var tasks []TaskPosition
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
return b.ForEach(func(k, v []byte) error {
t := bToTask(v)
tasks = append(tasks, TaskPosition{
task: t,
dbKey: btoi(k),
})
return nil
})
})
return tasks
}
// Retrieve a task by key. Returns an error if the task bucket does not exist or if the key does not exist.
func getTask(db *bolt.DB, key int) (Task, error) {
var t Task
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(TASKS_BUCKET)
if b == nil {
return errors.New("Task bucket does not exist")
}
buf := b.Get(itob(key))
if buf == nil {
return errors.New("Key does not exist")
}
t = bToTask(buf)
return nil
})
return t, err
}
// Update a task in the db. Returns an error if the tasks bucket does not exist,
// if failed to marshal the task, or if failed to update the task in the db. If taskId does not exist
// in the db, a new task will be created
func updateTask(db *bolt.DB, taskId int, updated Task) error {
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(TASKS_BUCKET)
if b == nil {
return errors.New("Tasks bucket does not exist")
}
t, jsonErr := json.Marshal(updated)
if jsonErr != nil {
return errors.New("Failed to marshal updated task")
}
return b.Put(itob(taskId), t)
})
}
// Filter tasks by tag. Returns a slice of tasks whose tag is present in `include`.
// One of the []string must be empty i.e. can only include or exclude, can't do both.
func filterTasks(tp []TaskPosition, include, exclude []string) []TaskPosition {
// no tags to filter by, return tp
if len(include) == 0 && len(exclude) == 0 {
return tp
}
var filtered []TaskPosition
// First filter out any unwanted tasks
excludeNoTag := slices.Contains(exclude, "none")
for _, t := range tp {
if slices.Contains(exclude, t.task.Tag) {
continue
}
if t.task.Tag == "" && excludeNoTag {
continue
}
filtered = append(filtered, t)
}
var finalFilter []TaskPosition
// "none" tag can be used to filter tasks with no tag
includeNoTag := slices.Contains(include, "none")
for _, t := range filtered {
if t.task.Tag == "" && includeNoTag {
finalFilter = append(finalFilter, t)
}
if slices.Contains(include, t.task.Tag) {
finalFilter = append(finalFilter, t)
}
}
if len(include) > 0 {
return finalFilter
}
return filtered
}
// Format the tasks in db, return the formatted string
func formatTasks(tp []TaskPosition) string {
var builder strings.Builder
for idx, t := range tp {
s := "🔴"
if t.task.Status == STATUS.COMPLETE {
s = "✅"
}
// Build the task strings.
// format: num. [tag: ] desc status [\n]
builder.WriteString(fmt.Sprintf("%d: ", t.dbKey))
if ShowTags {
builder.WriteString(fmt.Sprintf("%s: ", t.task.Tag))
}
builder.WriteString(fmt.Sprintf("%s %s", t.task.Desc, s))
// Add a newline if it's not the last task
if idx < len(tp)-1 {
builder.WriteString("\n")
}
}
return builder.String()
}
// Opens a View transaction with `db` and returns the number of entries in `bucket`
func getCount(db *bolt.DB, bucket []byte) int {
var count int
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
if b == nil {
count = 0
return nil
}
count = b.Stats().KeyN
return nil
})
return count
}
// Opens an Update transaction with `db` and deletes the entry from `bucket`
// whose key matches `key`. Returns an error if the bucket does not exist, failed to delete an entry
// or failed to renumber the remaining entries
func deleteKey(k int, db *bolt.DB, bucket []byte) error {
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
if b == nil {
return fmt.Errorf("Could not find the `%s` bucket", string(bucket))
}
err := b.Delete(itob(k))
if err != nil {
return err
}
return renumberEntires(b)
})
}
// Remove the specified keys by filtering the bucket, deleting the bucket and
// inserting the filtered items into a new bucket with the same name.
// O(n), filter n items, insert n items
func deleteKeys(toDelete []int, db *bolt.DB, bucket []byte) {
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bucket)
if b == nil {
fmt.Printf("`%s` bucket does not exist", string(bucket))
os.Exit(1)
}
var filtered [][]byte
b.ForEach(func(k, v []byte) error {
ignore := slices.Contains(toDelete, btoi(k))
if !ignore {
filtered = append(filtered, v)
}
return nil
})
tx.DeleteBucket(bucket)
// Create a new bucket, insert the filtered tasks and renumber
newBucket, _ := tx.CreateBucket(bucket)
for _, t := range filtered {
k, _ := newBucket.NextSequence()
newBucket.Put(itob(int(k)), t)
}
return renumberEntires(newBucket)
})
}
// Update the specified tasks status to `completed`
func completeTask(taskID int, db *bolt.DB) error {
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(TASKS_BUCKET)
if b == nil {
return fmt.Errorf("Could not find a tasks database")
}
byteId := itob(taskID)
val := b.Get(byteId)
if val == nil {
return fmt.Errorf("Task %d does not exist\n", taskID)
}
var t Task
json.Unmarshal(val, &t)
if t.Status == STATUS.COMPLETE {
fmt.Printf("You already finished task %d\n", taskID)
return nil
}
t.Status = STATUS.COMPLETE
t.Completed = time.Now().Format(RFC3339)
updatedTask, err := json.Marshal(t)
if err != nil {
return err
}
// update the `tasks` bucket with the completed task
b.Put(byteId, updatedTask)
return nil
})
}
// Filter out completed tasks from the `tasks` bucket
func finish(db *bolt.DB) ([]Task, error) {
var deletedTasks []Task
updateErr := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(TASKS_BUCKET)
if b == nil {
return errors.New("No tasks exist")
}
archive, _ := tx.CreateBucketIfNotExists(ARCHIVE_BUCKET)
var filtered [][]byte
err := b.ForEach(func(k, v []byte) error {
t := bToTask(v)
if t.Status != STATUS.COMPLETE {
filtered = append(filtered, v)
return nil
}
// add the completed tasks to the archive bucket
idx, _ := archive.NextSequence()
deletedTasks = append(deletedTasks, t)
return archive.Put(itob(int(idx)), v)
})
if err != nil {
return err
}
// Delete the old tasks bucket, create a new bucket and
// insert the filtered tasks
tx.DeleteBucket(TASKS_BUCKET)
newBucket, _ := tx.CreateBucket(TASKS_BUCKET)
for _, v := range filtered {
k, _ := newBucket.NextSequence()
newBucket.Put(itob(int(k)), v)
}
return nil
})
return deletedTasks, updateErr
}
// Renumber bucket entries in ascending order.
// Especially useful after deleting an entry in the middle of the bucket
func renumberEntires(bucket *bolt.Bucket) error {
// can ignore errors if this is called in an Update() call:
// Delete() can't fail in an Update() call,
// Put() shouldn't fail since the items already existed in the db
idx := 0
bucket.ForEach(func(k, v []byte) error {
idx++
bucket.Delete(k)
bucket.Put(itob(idx), v)
return nil
})
// update the Sequence to match the number of remaining entries
er := bucket.SetSequence(uint64(idx))
return er
}
// Adds each task in the slice to the archive bucket
func addToArchive(db *bolt.DB, tasks []Task) {
db.Update(func(tx *bolt.Tx) error {
b, _ := tx.CreateBucketIfNotExists(ARCHIVE_BUCKET)
for _, t := range tasks {
k, _ := b.NextSequence()
buf, _ := json.Marshal(t)
b.Put(itob(int(k)), buf)
}
return nil
})
}
// Convert an int to a byte slice
func itob(v int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
return b
}
// Convert a byte slice to an int
func btoi(b []byte) int {
return int(binary.BigEndian.Uint64(b))
}
// Unmarshal a byte slice to a Task struct
func bToTask(b []byte) Task {
var task Task
err := json.Unmarshal(b, &task)
check(err)
return task
}
// Returns the last tick of the provided time in the form:
// yyyy-mm-dd 23:59:59.999999999
func lastTick(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d+1, 0, 0, 0, -1, t.Location())
}