-
Notifications
You must be signed in to change notification settings - Fork 351
/
directory.go
98 lines (85 loc) · 2.06 KB
/
directory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package pyramid
import (
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"sync"
)
// directory synchronizes between file operations that might change (create/delete) directories
type directory struct {
// ceilingDir is the root directory of the FS - shouldn't never be deleted
ceilingDir string
mu sync.Mutex
}
// deleteDirRecIfEmpty deletes the given directory if it is empty.
// It will continue to delete all parents directory if they are empty, until the ceilingDir.
// Passed dir path isn't checked for malicious referencing (e.g. "../../../usr") and should never be
// controlled by any user input.
func (d *directory) deleteDirRecIfEmpty(dir string) error {
d.mu.Lock()
defer d.mu.Unlock()
for dir != d.ceilingDir {
empty, err := isDirEmpty(dir)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if !empty {
return nil
}
if err := os.Remove(dir); err != nil {
return err
}
// move up to the parent dir
dir = path.Dir(dir)
}
return nil
}
func isDirEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer func() {
_ = f.Close()
}()
_, err = f.Readdirnames(1)
if errors.Is(err, io.EOF) {
return true, nil
}
return false, err
}
// createFile creates the file under the path and creates all parent dirs if missing.
func (d *directory) createFile(path string) (*os.File, error) {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.ensureParentDir(path); err != nil {
return nil, err
}
return os.Create(path)
}
// renameFile will move the src file to dst location and creates all parent dirs if missing.
func (d *directory) renameFile(src, dst string) error {
d.mu.Lock()
defer d.mu.Unlock()
if err := d.ensureParentDir(dst); err != nil {
return err
}
return os.Rename(src, dst)
}
func (d *directory) ensureParentDir(path string) error {
parentDir := filepath.Dir(path)
if parentDir == d.ceilingDir {
return nil
}
err := os.MkdirAll(parentDir, os.ModePerm)
if err != nil {
return fmt.Errorf("creating dir: %w", err)
}
return nil
}