aboutsummaryrefslogtreecommitdiff
path: root/internal/ioutil/ioutil.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/ioutil/ioutil.go')
-rw-r--r--internal/ioutil/ioutil.go56
1 files changed, 56 insertions, 0 deletions
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
+}