-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
279 lines (249 loc) · 7.02 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
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"sync"
"time"
)
type Config struct {
DirectoriesToRemove []string `json:"directories_to_remove"`
FileExtensionsToRemove []string `json:"file_extensions_to_remove"`
ExcludeDirectories []string `json:"exclude_directories"`
ExcludeFiles []string `json:"exclude_files"`
MatchRegex bool `json:"matchRegex"`
}
func main() {
rootDir := flag.String("root", ".", "Root directory to scan")
configFile := flag.String("config", "cleaner_config.json", "Path to the JSON configuration file")
verbose := flag.Bool("verbose", true, "Enable verbose console output")
saveLog := flag.Bool("save-log", true, "Enable saving logs to file")
dryRun := flag.Bool("dry-run", false, "Simulate the cleaning process without deleting files")
logFormat := flag.String("log-format", "text", "Log format: 'text' or 'json'")
flag.Parse()
if _, err := os.Stat(*rootDir); os.IsNotExist(err) {
log.Fatalf("Root directory does not exist: %s\n", *rootDir)
}
config, err := loadConfig(*configFile)
if err != nil {
fmt.Printf("Warning: %v\n", err)
fmt.Println("Using default configuration.")
config = getDefaultConfig()
}
var logger *log.Logger
if *saveLog {
logFile := "cleaned_source.txt"
f, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("Failed to open log file: %v", err)
}
defer f.Close()
logger = log.New(f, "", 0)
}
var wg sync.WaitGroup
maxGoroutines := runtime.NumCPU()
semaphore := make(chan struct{}, maxGoroutines)
var logMutex sync.Mutex
var consoleMutex sync.Mutex
var totalSize int64
var totalSizeMutex sync.Mutex
var paths []string
wg.Add(1)
go walkDir(*rootDir, config, *verbose, *dryRun, *logFormat, &wg, semaphore, logger, &logMutex, &consoleMutex, &totalSize, &totalSizeMutex, &paths)
wg.Wait()
if *dryRun {
fmt.Printf("Total cleanable size: %.2f MB\n", float64(totalSize)/(1024*1024))
fmt.Println("Paths that would be removed:", paths)
} else {
fmt.Println("Cleaning process completed.")
}
}
func getDefaultConfig() *Config {
return &Config{
DirectoriesToRemove: []string{
"node_modules",
"dist",
"build",
"bin",
".next",
".turbo",
".idea",
".cache",
},
FileExtensionsToRemove: []string{".DS_Store", "__debug_bin"},
ExcludeDirectories: []string{".git", ".svn"},
ExcludeFiles: []string{},
MatchRegex: true,
}
}
func loadConfig(configPath string) (*Config, error) {
file, err := os.Open(configPath)
if err != nil {
return nil, fmt.Errorf("unable to open config file: %v", err)
}
defer file.Close()
var config Config
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
return nil, fmt.Errorf("unable to decode config JSON: %v", err)
}
return &config, nil
}
func walkDir(
dir string,
config *Config,
verbose, dryRun bool,
logFormat string,
wg *sync.WaitGroup,
semaphore chan struct{},
logger *log.Logger,
logMutex, consoleMutex *sync.Mutex,
totalSize *int64,
totalSizeMutex *sync.Mutex,
paths *[]string, // New parameter to collect paths during dry-run
) {
defer wg.Done()
semaphore <- struct{}{}
defer func() { <-semaphore }()
entries, err := os.ReadDir(dir)
if err != nil {
consoleMutex.Lock()
fmt.Fprintf(os.Stderr, "Failed to read directory %s: %v\n", dir, err)
consoleMutex.Unlock()
return
}
for _, entry := range entries {
entryName := entry.Name()
entryPath := filepath.Join(dir, entryName)
if entry.IsDir() {
if isExcluded(entryName, config.ExcludeDirectories) {
continue
}
if shouldRemoveDir(entryName, config.DirectoriesToRemove) {
dirSize := calculateSize(entryPath)
totalSizeMutex.Lock()
*totalSize += dirSize
totalSizeMutex.Unlock()
if dryRun {
if verbose {
consoleMutex.Lock()
fmt.Printf("[Dry Run] Would remove directory: %s (Size: %.2f MB)\n", entryPath, float64(dirSize)/(1024*1024))
consoleMutex.Unlock()
}
*paths = append(*paths, entryPath)
if logger != nil {
logEntry(logger, logMutex, logFormat, "[Dry Run] Would remove directory", entryPath)
}
} else {
err := os.RemoveAll(entryPath)
if err != nil {
consoleMutex.Lock()
fmt.Fprintf(os.Stderr, "Failed to remove directory %s: %v\n", entryPath, err)
consoleMutex.Unlock()
} else if logger != nil {
logEntry(logger, logMutex, logFormat, "Removed directory", entryPath)
}
}
} else {
wg.Add(1)
go walkDir(entryPath, config, verbose, dryRun, logFormat, wg, semaphore, logger, logMutex, consoleMutex, totalSize, totalSizeMutex, paths)
}
} else {
if isExcluded(entryName, config.ExcludeFiles) {
continue
}
if shouldRemoveFile(entryName, config.FileExtensionsToRemove, config.MatchRegex) {
fileSize := calculateSize(entryPath)
totalSizeMutex.Lock()
*totalSize += fileSize
totalSizeMutex.Unlock()
if dryRun {
if verbose {
consoleMutex.Lock()
fmt.Printf("[Dry Run] Would remove file: %s (Size: %.2f KB)\n", entryPath, float64(fileSize)/1024)
consoleMutex.Unlock()
}
*paths = append(*paths, entryPath)
if logger != nil {
logEntry(logger, logMutex, logFormat, "[Dry Run] Would remove file", entryPath)
}
} else {
err := os.Remove(entryPath)
if err != nil {
consoleMutex.Lock()
fmt.Fprintf(os.Stderr, "Failed to remove file %s: %v\n", entryPath, err)
consoleMutex.Unlock()
} else if logger != nil {
logEntry(logger, logMutex, logFormat, "Removed file", entryPath)
}
}
}
}
}
}
func calculateSize(path string) int64 {
var size int64
filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err == nil && info != nil {
size += info.Size()
}
return nil
})
return size
}
func shouldRemoveDir(dirName string, dirsToRemove []string) bool {
for _, name := range dirsToRemove {
if dirName == name {
return true
}
}
return false
}
func shouldRemoveFile(fileName string, extensions []string, matchRegex bool) bool {
if matchRegex {
for _, pattern := range extensions {
matched, err := regexp.MatchString(pattern, fileName)
if err != nil {
fmt.Printf("Error in regex pattern %s: %v\n", pattern, err)
continue
}
if matched {
return true
}
}
} else {
for _, ext := range extensions {
if strings.HasSuffix(fileName, ext) {
return true
}
}
}
return false
}
func isExcluded(name string, excludeList []string) bool {
for _, exclude := range excludeList {
if name == exclude {
return true
}
}
return false
}
func logEntry(logger *log.Logger, logMutex *sync.Mutex, format, action, path string) {
logMutex.Lock()
defer logMutex.Unlock()
timestamp := time.Now().Format(time.RFC3339)
if format == "json" {
logMessage := fmt.Sprintf(`{"timestamp":"%s","action":"%s","path":"%s"}`, timestamp, action, path)
logger.Println(logMessage)
} else {
logMessage := fmt.Sprintf("%s - %s: %s", timestamp, action, path)
logger.Println(logMessage)
}
}