/
directory.go
156 lines (133 loc) · 3.63 KB
/
directory.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
package library
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
// Initiate Directory Function
func InitiateDirectoryFunction(flags Flag) {
/** Directory Stats */
if *flags.Dir && *flags.Stats {
DirectoryStats(*flags.Path, true)
}
/** remove Directories Older than days matching regex */
if *flags.Dir && *flags.Remove && *flags.OlderThan && *flags.Days > 0 {
RemoveDirectoriesOlderThan(*flags.Path, *flags.Days, *flags.Level, *flags.Exclude, *flags.DryRun)
}
}
// Create a helper function to determine the depth of a directory.
func GetDepth(path string, dirPath string) int {
rel, err := filepath.Rel(path, dirPath)
if err != nil {
return -1 // Error in determining depth.
}
return len(strings.Split(rel, "/")) - 1 // Return the depth.
}
/** Directory Stats */
func DirectoryStats(path string, print bool) (int, int64, int64, map[string]int, int, int) {
if path == "" {
CurrentDirectory, _ := os.Getwd()
path = CurrentDirectory
}
var count int
var totalSize int64
extCount := make(map[string]int)
var lineCount int
var wordCount int
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println("❌ Error:", err)
return err
}
if !info.IsDir() {
count++
totalSize += info.Size()
ext := filepath.Ext(path)
ext = strings.ToLower(ext)
extCount[ext]++
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lineCount++
wordCount += len(strings.Fields(scanner.Text()))
}
}
return nil
})
if err != nil {
fmt.Println("❌ Error:", err)
return 0, 0, 0, nil, 0, 0
}
var averageSize int64
if count > 0 {
averageSize = totalSize / int64(count)
}
if print {
currentTime := time.Now()
fmt.Println("🗓️ Generated at : ", currentTime.String())
fmt.Println("📈 Total Files:", count)
fmt.Println("📊 Total Size:", totalSize)
fmt.Println("💽 Average Size:", averageSize)
fmt.Println("📝 Total Lines:", lineCount)
fmt.Println("💬 Total Words:", wordCount)
fmt.Println("🏺 No of files by extensions :")
for ext, count := range extCount {
fmt.Println(" 📟", ext, ":", count)
}
}
return count, totalSize, averageSize, extCount, lineCount, wordCount
}
// Remove directory older than.
func RemoveDirectoriesOlderThan(path string, retentionDays int, level int, exclude []string, dryrun bool) error {
if path == "" {
// If path is empty, use the current working directory.
currentDir, err := os.Getwd()
if err != nil {
return err
}
path = currentDir
}
// Get the current time.
currentTime := time.Now()
// Calculate the cutoff date for retention.
cutoffDate := currentTime.AddDate(0, 0, -retentionDays)
// Walk through the directories in the provided path.
err := filepath.Walk(path, func(dirPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Check if the directory should be ignored
for _, excludeDir := range exclude {
if strings.Contains(dirPath, excludeDir) {
return nil
}
}
// Check if the directory is within the specified depth.
if GetDepth(path, dirPath) <= level {
// Check if the directory is older than the retention cutoff date.
if info.IsDir() && info.ModTime().Before(cutoffDate) {
if !dryrun {
fmt.Println("✅ Successfully remove directories older than", retentionDays, "days in", dirPath)
err := os.RemoveAll(dirPath)
if err != nil {
return err
}
} else {
fmt.Println("✅ Dry run, will remove", dirPath)
}
}
}
return nil
})
if err != nil {
return err
}
return nil
}