-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
collapsedirs.go
41 lines (33 loc) · 949 Bytes
/
collapsedirs.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
package fsutil
import (
"fmt"
"os"
"path"
)
// CollapseSubdirectory recursively moves the subdir up towards parent and removes any (newly empty) directories on the way.
func CollapseSubdirectory(p, subdir string) (string, error) {
if p == subdir {
return p, nil
}
dir := path.Dir(subdir)
ents, err := os.ReadDir(dir)
if err != nil {
return "", fmt.Errorf("read dir %q: %w", dir, err)
}
base := path.Base(subdir)
for _, ent := range ents {
if ent.Name() != base && ent.Name() != "." && ent.Name() != ".." {
return subdir, nil
}
}
if err := os.Rename(subdir, dir+".tmp"); err != nil {
return "", fmt.Errorf("rename %q to %q: %w", subdir, dir+".tmp", err)
}
if err := os.Remove(dir); err != nil {
return "", fmt.Errorf("remove %q: %w", dir, err)
}
if err := os.Rename(dir+".tmp", base); err != nil {
return "", fmt.Errorf("rename %q to %q: %w", dir+".tmp", base, err)
}
return CollapseSubdirectory(p, dir)
}