diff options
author | Aria <me@aria.rip> | 2023-02-03 15:44:44 +0000 |
---|---|---|
committer | Aria <me@aria.rip> | 2023-02-03 15:44:44 +0000 |
commit | 8c3b1aee5a253416523de78877ae03c3868cc62c (patch) | |
tree | f51e8d0049ad439bea7f4c32c714f4ce29e41e2c /db.go | |
parent | a6c9dba25ad9204ebde302728eb2a75532497f37 (diff) |
first version
Diffstat (limited to 'db.go')
-rw-r--r-- | db.go | 109 |
1 files changed, 109 insertions, 0 deletions
@@ -0,0 +1,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 +} |