-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_all.go
More file actions
85 lines (73 loc) · 1.97 KB
/
Copy pathremove_all.go
File metadata and controls
85 lines (73 loc) · 1.97 KB
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
package fs
import (
"context"
"errors"
"lesiw.io/fs/path"
)
// A RemoveAllFS is a file system with the RemoveAll method.
//
// If not implemented, RemoveAll falls back to recursive removal using
// RemoveFS, StatFS, and ReadDirFS.
type RemoveAllFS interface {
FS
// RemoveAll removes name and any children it contains.
RemoveAll(ctx context.Context, name string) error
}
// RemoveAll removes name and any children it contains.
// Analogous to: [os.RemoveAll], rm -rf.
//
// Requires: [RemoveAllFS] ||
// ([RemoveFS] && [StatFS] && ([ReadDirFS] || [WalkFS]))
func RemoveAll(ctx context.Context, fsys FS, name string) (err error) {
if name, err = localizePath(ctx, fsys, name); err != nil {
return err
}
// Check for efficient RemoveAll implementation first
if rafs, ok := fsys.(RemoveAllFS); ok {
err := rafs.RemoveAll(ctx, name)
if err != nil && !errors.Is(err, ErrUnsupported) {
return err
}
if err == nil {
return nil
}
// Fall through to fallback if ErrUnsupported
}
// Check if fallback is possible - requires RemoveFS, StatFS, ReadDirFS
rfs, hasRemove := fsys.(RemoveFS)
_, hasStat := fsys.(StatFS)
_, hasReadDir := fsys.(ReadDirFS)
if !hasRemove || !hasStat || !hasReadDir {
return &PathError{
Op: "remove",
Path: name,
Err: ErrUnsupported,
}
}
// Try to remove it directly first
err = rfs.Remove(ctx, name)
if err == nil || errors.Is(err, ErrNotExist) {
return nil
}
// If removal failed, check if it's a directory with contents
info, statErr := Stat(ctx, fsys, name)
if statErr != nil {
return statErr
}
if !info.IsDir() {
return err
}
// It's a directory - read contents to remove children
// Remove all children
for entry, readErr := range ReadDir(ctx, fsys, name) {
if readErr != nil {
return readErr
}
childPath := path.Join(name, entry.Name())
if removeErr := RemoveAll(ctx, fsys, childPath); removeErr != nil {
return removeErr
}
}
// Now remove the empty directory
return rfs.Remove(ctx, name)
}