about summary refs log tree commit diff stats
path: root/internal/file/utils.go
diff options
context:
space:
mode:
authorAlan Pearce2024-05-09 16:24:45 +0200
committerAlan Pearce2024-05-09 16:27:19 +0200
commit967f6fdf5c1693d3aa27079b3ae28768fb7356c6 (patch)
treee878af655584faca476f4ba2cf8d96cba7383d7e /internal/file/utils.go
parent453ae8569ab58fcc4ad61c461adc4489b9443cf8 (diff)
downloadsearchix-967f6fdf5c1693d3aa27079b3ae28768fb7356c6.tar.lz
searchix-967f6fdf5c1693d3aa27079b3ae28768fb7356c6.tar.zst
searchix-967f6fdf5c1693d3aa27079b3ae28768fb7356c6.zip
feat: make configuration optional
Diffstat (limited to 'internal/file/utils.go')
-rw-r--r--internal/file/utils.go53
1 files changed, 53 insertions, 0 deletions
diff --git a/internal/file/utils.go b/internal/file/utils.go
new file mode 100644
index 0000000..efcf0f6
--- /dev/null
+++ b/internal/file/utils.go
@@ -0,0 +1,53 @@
+package file
+
+import (
+	"io"
+	"io/fs"
+	"os"
+
+	"github.com/pkg/errors"
+)
+
+func Mkdirp(dir string) error {
+	err := os.MkdirAll(dir, os.ModeDir|os.ModePerm)
+	if err != nil {
+		return errors.WithMessagef(err, "could not create directory %s", dir)
+	}
+
+	return nil
+}
+
+func NeedNotExist(err error) error {
+	if err != nil && !errors.Is(err, fs.ErrNotExist) {
+		return err
+	}
+
+	return nil
+}
+
+func StatIfExists(file string) (fs.FileInfo, error) {
+	stat, err := os.Stat(file)
+
+	return stat, NeedNotExist(err)
+}
+
+func Exists(file string) (bool, error) {
+	stat, err := StatIfExists(file)
+
+	return stat != nil, err
+}
+
+func WriteToFile(path string, body io.Reader) error {
+	file, err := os.Create(path)
+	if err != nil {
+		return errors.WithMessagef(err, "error creating file at %s", path)
+	}
+	defer file.Close()
+
+	_, err = io.Copy(file, body)
+	if err != nil {
+		return errors.WithMessagef(err, "error downloading file %s", path)
+	}
+
+	return nil
+}