Commit
Author: Kevin Schoon [me@kevinschoon.com]
Hash: a383a2f083779c13fc58c598af28255677869482
Timestamp: Sat, 04 Jun 2022 00:07:24 +0000 (2 years ago)

+58 -3 +/-2 browse
add rm
1diff --git a/pkg/cmd/app.go b/pkg/cmd/app.go
2index a669c41..f1e255f 100644
3--- a/pkg/cmd/app.go
4+++ b/pkg/cmd/app.go
5 @@ -124,10 +124,17 @@ data structure. It uses SQLite to store note content and metadata.
6 Flags: []cli.Flag{
7 &cli.BoolFlag{
8 Name: "recursive",
9- Aliases: []string{"-r"},
10+ Aliases: []string{"r"},
11 Usage: "delete any sibling notes recursively",
12 },
13 },
14+ Action: func(ctx *cli.Context) error {
15+ path := ctx.Args().First()
16+ if path == "" {
17+ return fmt.Errorf("no path specified")
18+ }
19+ return hierarchy.Remove(*cfg, path, ctx.Bool("recursive"))
20+ },
21 },
22 {
23 Name: "cat",
24 @@ -141,6 +148,18 @@ data structure. It uses SQLite to store note content and metadata.
25 Usage: "output format",
26 },
27 },
28+ Action: func(ctx *cli.Context) error {
29+ path := ctx.Args().First()
30+ if path == "" {
31+ return fmt.Errorf("no path specified")
32+ }
33+ note, err := hierarchy.Find(*cfg, path)
34+ if err != nil {
35+ return err
36+ }
37+ fmt.Println(note.Content)
38+ return nil
39+ },
40 },
41 {
42 Name: "mount",
43 diff --git a/pkg/hierarchy/database.go b/pkg/hierarchy/database.go
44index 540aaef..6e672eb 100644
45--- a/pkg/hierarchy/database.go
46+++ b/pkg/hierarchy/database.go
47 @@ -3,7 +3,6 @@ package hierarchy
48 import (
49 "database/sql"
50 _ "embed"
51- "fmt"
52
53 _ "github.com/mattn/go-sqlite3"
54 "kevinschoon.com/hierarchy/pkg/config"
55 @@ -157,7 +156,6 @@ ON CONFLICT DO NOTHING
56
57 func Save(cfg config.Config, path, content string) error {
58 np := ReadPath(path)
59- fmt.Println(content, np.String())
60 return With(cfg.Database, func(tx *sql.Tx) error {
61 _, err := tx.Exec(`
62 UPDATE notes
63 @@ -169,3 +167,41 @@ WHERE
64 return err
65 })
66 }
67+
68+ func Remove(cfg config.Config, path string, recurse bool) error {
69+ np := ReadPath(path)
70+ return With(cfg.Database, func(tx *sql.Tx) error {
71+ row := tx.QueryRow(`
72+ SELECT
73+ id, parent
74+ FROM notes
75+ WHERE
76+ name = ?
77+ `, np.String())
78+ var (
79+ id, parent = new(int64), new(int64)
80+ )
81+ err := row.Scan(&id, &parent)
82+ if err != nil {
83+ return err
84+ }
85+ if !recurse {
86+ parent = nil
87+ }
88+ _, err = tx.Exec(`
89+ WITH RECURSIVE
90+ with_decendants(id, parent, level) AS (
91+ VALUES(?, ?, 0)
92+ UNION ALL
93+ SELECT
94+ notes.id,
95+ notes.parent,
96+ with_decendants.level+1
97+ FROM notes, with_decendants
98+ WHERE notes.parent=with_decendants.id
99+ )
100+ DELETE FROM notes WHERE id IN (SELECT id FROM with_decendants);
101+ `, id, parent)
102+ return err
103+ })
104+ }