From e18d36ebae30536c77c61cd5da123991e0ca1629 Mon Sep 17 00:00:00 2001 From: Rasmus Dahlberg Date: Sun, 31 Dec 2023 09:39:25 +0100 Subject: Add drafty prototype --- internal/ioutil/ioutil.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 internal/ioutil/ioutil.go (limited to 'internal/ioutil/ioutil.go') diff --git a/internal/ioutil/ioutil.go b/internal/ioutil/ioutil.go new file mode 100644 index 0000000..7fe6cfc --- /dev/null +++ b/internal/ioutil/ioutil.go @@ -0,0 +1,56 @@ +package ioutil + +import ( + "encoding/json" + "fmt" + "os" +) + +func CommitData(path string, data []byte) error { + return os.WriteFile(path, data, 0644) // FIXME: use safefile package for atomic file writes +} + +func ReadData(path string) ([]byte, error) { + return os.ReadFile(path) +} + +func CommitJSON(path string, obj any) error { + b, err := json.MarshalIndent(obj, "", " ") + if err != nil { + return err + } + return CommitData(path, b) +} + +func ReadJSON(path string, obj any) error { + b, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("%s: %v", path, err) + } + return json.Unmarshal(b, obj) +} + +func CreateDirectories(paths []string) error { + for _, path := range paths { + if err := os.Mkdir(path, 0755); err != nil { + return err + } + } + return nil +} + +func DirectoriesExist(paths []string) error { + for _, path := range paths { + info, err := os.Stat(path) + if os.IsNotExist(err) { + return fmt.Errorf("directory does not exist: %s", path) + } + if err != nil { + return err + } + if !info.IsDir() { + return fmt.Errorf("%s: is not a directory", path) + } + } + return nil +} -- cgit v1.2.3