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 }