From 8c3b1aee5a253416523de78877ae03c3868cc62c Mon Sep 17 00:00:00 2001 From: Aria Date: Fri, 3 Feb 2023 15:44:44 +0000 Subject: first version --- db.go | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 db.go (limited to 'db.go') diff --git a/db.go b/db.go new file mode 100644 index 0000000..8111500 --- /dev/null +++ b/db.go @@ -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 +} -- cgit v1.2.3