summaryrefslogtreecommitdiff
path: root/internal/file/directory.go
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2026-07-04 22:29:49 +0300
committerPaul Buetow <paul@buetow.org>2026-07-04 22:29:49 +0300
commit49e4dbf6ee07b13790231091ef8f73f025841a19 (patch)
tree1be5171ca564c1f651886a59391caedfee7253b6 /internal/file/directory.go
parent2381c8712ebafa8060f0d2feacadd85bef280eb0 (diff)
add more file types
Diffstat (limited to 'internal/file/directory.go')
-rw-r--r--internal/file/directory.go57
1 files changed, 57 insertions, 0 deletions
diff --git a/internal/file/directory.go b/internal/file/directory.go
new file mode 100644
index 0000000..052af06
--- /dev/null
+++ b/internal/file/directory.go
@@ -0,0 +1,57 @@
+package file
+
+import (
+ "fmt"
+ "log"
+ "os"
+)
+
+// haveDirectory ensures f.path exists as a directory with the desired mode and
+// ownership. It is idempotent: an existing directory only has its attributes
+// re-enforced, and an existing non-directory is an error.
+func (f *File) haveDirectory() error {
+ log.Printf("processing directory: %s", f.path)
+
+ info, err := os.Lstat(f.path)
+ switch {
+ case err == nil:
+ if !info.IsDir() {
+ return fmt.Errorf("%s exists and is not a directory", f.path)
+ }
+ log.Printf("directory %s already exists", f.path)
+
+ case os.IsNotExist(err):
+ log.Printf("creating directory %s with mode %v", f.path, f.mode)
+ if err := os.MkdirAll(f.path, f.mode); err != nil {
+ return fmt.Errorf("failed to create directory %s: %w", f.path, err)
+ }
+
+ default:
+ return fmt.Errorf("failed to stat %s: %w", f.path, err)
+ }
+
+ return f.applyAttributes()
+}
+
+// haveAbsent removes f.path if it exists. It is idempotent: a missing path is
+// not an error. By default non-empty directories are not removed; combine with
+// PruneDirectory() to remove a directory and its contents recursively.
+func (f *File) haveAbsent() error {
+ log.Printf("ensuring absent: %s", f.path)
+
+ remove := os.Remove
+ if f.pruneDirectory {
+ remove = os.RemoveAll
+ }
+
+ if err := remove(f.path); err != nil {
+ if os.IsNotExist(err) {
+ log.Printf("%s already absent", f.path)
+ return nil
+ }
+ return fmt.Errorf("failed to remove %s: %w", f.path, err)
+ }
+
+ log.Printf("removed %s", f.path)
+ return nil
+}