summaryrefslogtreecommitdiff
path: root/cmds.go
blob: 233a08fee846801d8cf39dcff4c507872f0b5708 (plain)
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
package main

import (
	"encoding/binary"
	"encoding/json"
	"fmt"

	"go.etcd.io/bbolt"
)

type taskType struct {
	What  string `json:"what"`
	Done  bool   `json:"done"`
	Index uint64 `json:"index"`
}

// itob returns an 8-byte big endian representation of v.
func itob(v uint64) []byte {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, v)
	return b
}

func (ctrl controller) cmdAdd(task string) error {
	return ctrl.db.Update(func(tx *bbolt.Tx) error {
		taskBucket := tx.Bucket(ctrl.tasksBucketName)

		// Update call, so ignore the error check. See
		// pkg.go.dev/go.etcd.io/bbolt#section-readme
		index, _ := taskBucket.NextSequence()
		t := taskType{
			What:  task,
			Done:  false,
			Index: index,
		}

		buf, err := json.Marshal(t)
		if err != nil {
			return fmt.Errorf("can't marshal: %w", err)
		}

		return taskBucket.Put(itob(index), buf)
	})
}

func (ctrl controller) cmdDo(taskIndex int) error {
	return ctrl.db.Update(func(tx *bbolt.Tx) error {
		taskBucket := tx.Bucket(ctrl.tasksBucketName)
		ttBytes := taskBucket.Get(itob(uint64(taskIndex)))

		var tt taskType
		if err := json.Unmarshal(ttBytes, &tt); err != nil {
			return fmt.Errorf("can't unmarshal: %w", err)
		}

		tt.Done = true

		buf, err := json.Marshal(tt)
		if err != nil {
			return fmt.Errorf("can't marshal: %w", err)
		}

		return taskBucket.Put(itob(uint64(taskIndex)), buf)
	})
}

func (ctrl controller) cmdList() error {
	return ctrl.db.View(func(tx *bbolt.Tx) error {
		// Assume bucket exists and has keys
		b := tx.Bucket([]byte(ctrl.tasksBucketName))

		b.ForEach(func(k, v []byte) error {
			index := binary.BigEndian.Uint64(k)

			fmt.Printf("%d. %s\n", index, v)
			return nil
		})

		return nil
	})
}