-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.go
154 lines (120 loc) · 2.4 KB
/
cleanup.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main
import (
"errors"
"flag"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"sort"
)
const (
version = "1.0.1"
)
var (
limit int
displayVersion bool
)
func Limit() int {
return limit
}
func Path() string {
return flag.Arg(0)
}
func isDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
return false
}
return fileInfo.IsDir()
}
func filterDirectories(files []fs.FileInfo) []fs.FileInfo {
filtered := make([]fs.FileInfo, 0)
for _, file := range files {
if file.IsDir() {
filtered = append(filtered, file)
}
}
return filtered
}
func handleDirectory(path string, limit int) (int, error) {
count := 0
removed := 0
files, err := ioutil.ReadDir(path)
if err != nil {
return 0, err
}
directories := filterDirectories(files)
sort.Slice(directories, func(i, j int) bool {
return directories[i].ModTime().Unix() > directories[j].ModTime().Unix()
})
for _, directory := range directories {
count++
if count > limit {
err := os.RemoveAll(filepath.Join(path, directory.Name()))
if err != nil {
return removed, err
}
removed++
}
}
return removed, nil
}
func runCommand(path string, limit int) (string, error) {
if !isDirectory(path) {
return "", errors.New(fmt.Sprintf("Not a directory or path \"%s\" does not exist!", path))
}
removed, err := handleDirectory(path, limit)
if err != nil {
return "", err
}
if removed > 0 {
if removed == 1 {
return fmt.Sprint("Removed a single directory."), nil
} else {
return fmt.Sprintf("Removed %d directories.", removed), nil
}
}
return "", nil
}
func realMain(out io.Writer) int {
flag.BoolVar(&displayVersion, "v", false, "Release version of the utility script")
flag.IntVar(&limit, "l", 5, "Limit of the latest directories to keep")
flag.Usage = func() {
_, err := fmt.Fprintln(out, "Usage: cleanup -l 5 path/to/dir")
if err != nil {
return
}
flag.CommandLine.SetOutput(out)
flag.PrintDefaults()
}
flag.Parse()
if displayVersion {
fmt.Fprintln(out, "Cleanup utility version:", version)
return 0
}
if flag.NArg() < 1 {
flag.Usage()
return 0
}
text, err := runCommand(Path(), Limit())
if err != nil {
_, err := fmt.Fprint(out, err)
if err != nil {
return 1
}
return 1
}
if text != "" {
_, err := fmt.Fprintln(out, text)
if err != nil {
return 1
}
}
return 0
}
func main() {
os.Exit(realMain(os.Stdout))
}