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
|
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/bubbles/list"
)
var rootDirectory string
func validateName(name string) error {
return nil // TODO
}
func setupDB() error {
rootDirectory = os.ExpandEnv("$HOME/.doe/")
stat, err := os.Lstat(rootDirectory)
if err != nil {
err := os.Mkdir(rootDirectory, 0750)
if err != nil {
return fmt.Errorf("error creating root directory: %s", err)
}
} else if !stat.Mode().IsDir() {
return fmt.Errorf("~/.doe exists, but is not a directory")
}
return nil
}
func saveSnippet(snippet snippetDetails) error {
if snippet.name != snippet.prevName && snippet.prevName != "" {
err := deleteItem(item{title: snippet.prevName, contents: ""})
if err != nil {
return err
}
}
fullPath := filepath.Join(rootDirectory, snippet.name)
parentDirectory, _ := filepath.Split(fullPath)
stat, err := os.Lstat(parentDirectory)
if err != nil || !stat.Mode().IsDir() {
err = os.MkdirAll(parentDirectory, 0750)
if err != nil {
return fmt.Errorf("error creating parent directory: %s", err)
}
}
f, err := os.Create(fullPath)
if err != nil {
return fmt.Errorf("error creating new file: %s", err)
}
defer f.Close()
err = f.Chmod(0750)
if err != nil {
return fmt.Errorf("error setting file mode: %s", err)
}
n, err := f.WriteString(snippet.contents)
if err != nil || n != len(snippet.contents) {
return fmt.Errorf("error writing snippet contents: %s", err)
}
return nil
}
func getItems() ([]list.Item, error) {
items := []list.Item{}
err := filepath.WalkDir(rootDirectory, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
} else {
contents, err := os.ReadFile(path)
if err != nil {
return err
}
items = append(items, item{
title: strings.TrimPrefix(path, rootDirectory),
contents: string(contents),
})
return nil
}
})
if err != nil {
return nil, err
}
return items, nil
}
func deleteItem(item item) error {
err := os.Remove(filepath.Join(rootDirectory, item.title))
if err != nil {
return fmt.Errorf("error removing old file: %s", err)
}
return nil
}
|