From e0e6d43095e93d65833dcebe79ec85778c29eb32 Mon Sep 17 00:00:00 2001 From: demo Date: Fri, 29 May 2026 11:27:00 -0400 Subject: wip: implement business logic (rough draft) There are a ton of visual warts, but the actual logic seems sound so far. --- cmds.go | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 68 insertions(+), 9 deletions(-) (limited to 'cmds.go') diff --git a/cmds.go b/cmds.go index 26cded5..241897c 100644 --- a/cmds.go +++ b/cmds.go @@ -1,20 +1,79 @@ package main import ( + "encoding/binary" + "encoding/json" "fmt" + + "go.etcd.io/bbolt" ) -func cmdAdd(task string) error { - fmt.Println("added task: ", task) - return nil +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 cmdDo(taskIndex int) error { - fmt.Println("completed task: ", taskIndex) - return nil +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 cmdList() error { - fmt.Println("listed pending tasks") - return nil +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 { + fmt.Printf("%s. %s\n", k, v) + return nil + }) + + return nil + }) } -- cgit v1.2.3