-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
97 lines (92 loc) · 2.19 KB
/
main.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
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/monochromegane/go-gitignore"
)
var SEP = string(os.PathSeparator)
func main() {
// check args
if len(os.Args) < 2 {
fmt.Println("Usage: clean.exe <dir>")
return
}
dir, err := filepath.Abs(os.Args[1])
if err != nil {
fmt.Println(err)
return
}
dirInfo, err := os.Stat(dir)
if err != nil {
fmt.Println("No such file or directory")
return
}
if !dirInfo.IsDir() {
fmt.Println("Must be directory")
return
}
ignoreFilePath := dir + SEP + ".gitignore"
matcher, err := gitignore.NewGitIgnore(ignoreFilePath)
if err != nil {
fmt.Println(err)
return
}
xx := walkDir(dir, []string{}, []string{}, matcher)
deleteWaitlist := []string{}
for _, file := range xx {
fileinfo, err := os.Stat(file)
if err != nil {
fmt.Println(err)
continue
}
if matcher.Match(file, fileinfo.IsDir()) {
fmt.Println(file)
deleteWaitlist = append(deleteWaitlist, file)
}
}
if len(deleteWaitlist) == 0 {
fmt.Println("No files to delete")
return
}
// ask usr if confirm to delete
fmt.Println("Do you want to delete these files? (y/n)")
var input string
fmt.Scanln(&input)
if input == "y" {
for _, file := range deleteWaitlist {
err := os.RemoveAll(file)
if err != nil {
fmt.Println(err)
}
}
}
}
// walk dir, if match gitignore, skip ignored sub folder
func walkDir(dir string, domain []string, collections []string, mathcer gitignore.IgnoreMatcher) []string {
// copy domain
domainCopy := make([]string, len(domain)+1)
copy(domainCopy, domain)
domainCopy[len(domainCopy)-1] = dir
path := strings.Join(domainCopy, SEP) + SEP
files, err := os.ReadDir(path)
if err != nil {
fmt.Println(err)
return collections
}
for _, file := range files {
// domain + sub
domainCopyCopy := make([]string, len(domainCopy)+1)
copy(domainCopyCopy, domainCopy)
domainCopyCopy[len(domainCopyCopy)-1] = file.Name()
filePath := strings.Join(domainCopyCopy, SEP)
collections = append(collections, filePath)
// if exculde, skip sub folder
isDir := file.IsDir()
if isDir && !mathcer.Match(filePath, isDir) {
collections = walkDir(file.Name(), domainCopy, collections, mathcer)
}
}
return collections
}