forked from kluctl/go-embed-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanup_python.go
More file actions
100 lines (91 loc) · 1.81 KB
/
cleanup_python.go
File metadata and controls
100 lines (91 loc) · 1.81 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package internal
import (
"github.com/gobwas/glob"
"io/fs"
"os"
"path/filepath"
)
var DefaultPythonRemovePatterns = []glob.Glob{
glob.MustCompile("__pycache__"),
glob.MustCompile("**/__pycache__"),
glob.MustCompile("**.a"),
glob.MustCompile("**.pdb"),
glob.MustCompile("**.pyc"),
glob.MustCompile("**/test_*.py"),
glob.MustCompile("**/*.dist-info"),
}
func CleanupPythonDir(dir string, keepPatterns []glob.Glob) error {
var removes []string
err := filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
relPath, err := filepath.Rel(dir, path)
if err != nil {
return err
}
for _, p := range DefaultPythonRemovePatterns {
if p.Match(relPath) {
removes = append(removes, path)
}
}
if len(keepPatterns) != 0 && !info.Mode().IsDir() {
keep := false
for _, p := range keepPatterns {
if p.Match(relPath) {
keep = true
break
}
}
if !keep {
removes = append(removes, path)
}
}
return nil
})
for _, r := range removes {
err = os.RemoveAll(r)
if err != nil && !os.IsNotExist(err) {
return err
}
}
err = removeEmptyDirs(dir)
if err != nil {
return err
}
return err
}
func removeEmptyDirs(dir string) error {
for true {
didRemove, err := removeEmptyDirs2(dir)
if err != nil {
return err
}
if !didRemove {
break
}
}
return nil
}
func removeEmptyDirs2(dir string) (bool, error) {
var removes []string
err := filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error {
if info.IsDir() {
des, err := os.ReadDir(path)
if err != nil {
return err
}
if len(des) == 0 {
removes = append(removes, path)
}
}
return nil
})
if err != nil {
return false, err
}
for _, r := range removes {
err = os.Remove(r)
if err != nil {
return false, err
}
}
return len(removes) != 0, nil
}