-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
310 lines (270 loc) · 9.11 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
)
type Config struct {
Name string `json:"name"`
}
const ver = "1.2.2"
func getConfigFilePath() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
configDir := filepath.Join(homeDir, ".fidy")
if err := os.MkdirAll(configDir, os.ModePerm); err != nil {
return "", err
}
return filepath.Join(configDir, "config.json"), nil
}
func loadConfig() (*Config, error) {
configFilePath, err := getConfigFilePath()
if err != nil {
return nil, err
}
file, err := os.ReadFile(configFilePath)
if err != nil {
if os.IsNotExist(err) {
return &Config{}, nil
}
return nil, err
}
var config Config
err = json.Unmarshal(file, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func saveConfig(config *Config) error {
configFilePath, err := getConfigFilePath()
if err != nil {
return err
}
file, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return os.WriteFile(configFilePath, file, os.ModePerm)
}
func main() {
name := flag.String("name", "", "The user's name")
dir := flag.String("dir", "", "The directory to organize")
help := flag.Bool("help", false, "Show information about fidy")
include := flag.String("include", "", "Comma-separated list of extensions to include")
exclude := flag.String("exclude", "", "Comma-separated list of extensions to exclude")
verbose := flag.Bool("verbose", false, "Enable verbose output")
dryrun := flag.Bool("dryrun", false, "Simulate the file organization without doing any actual changes.")
cleanAll := flag.Bool("cleanAll", false, "Delete all the empty folders and sub-folders in the specified directory after organizing files.")
version := flag.Bool("version", false, "Display Fidy's current version installed in your system.")
custom := flag.String("custom", "", "Comma-separated list of custom directory names for each extension.")
backup := flag.String("backup", "", "The Backup directory to take a backup of all files that would be organized.")
flag.Parse()
config, err := loadConfig()
if err != nil {
fmt.Println("Error loading config:", err)
return
}
// Update the config file with name (if provided)
if *name != "" {
config.Name = *name
if err := saveConfig(config); err != nil {
fmt.Println("Error saving config:", err)
return
}
fmt.Println("Name updated! Nice to meet you", *name)
}
// Default message without flags
if len(os.Args) == 1 {
if config.Name != "" {
fmt.Printf("\nHey, I am Fidy. Nice to see you, %s!\n\n", config.Name)
} else {
fmt.Printf("\nHey, I am Fidy. You can let me know your name by using 'fidy -name YOUR_NAME' for our future conversations!\n\n")
}
}
if *help {
fmt.Println("")
fmt.Println(" ________ _______ _______ ___ ___")
fmt.Println(" / ______/ /__ __/ / _____ \\ / / / /")
fmt.Println(" / /____ / / / / / / / /____/ /")
fmt.Println(" / _____/ / / / / / / /___ ____/")
fmt.Println(" / / __/ /__ / /____/ / / /")
fmt.Println("/_/ /______/ /________/ /__/")
fmt.Println("\n---------- The File Organizer CLI Tool ----------")
fmt.Println("\nFidy helps you organize your files by sorting them into directories based on their extensions.")
fmt.Println("\nUsage:")
fmt.Println("")
fmt.Println(" -help : Show information about Fidy.")
fmt.Println(" -version : Display Fidy's current version installed in your system.")
fmt.Println(" -name <name> : Set your name to personalize Fidy's greetings.")
fmt.Println(" -dir <path> : Specify the directory to organize. Use 'fidy -dir .' for current directory.")
fmt.Println(" -include <exts> : Comma-separated list of extensions to include.")
fmt.Println(" -exclude <exts> : Comma-separated list of extensions to exclude.")
fmt.Println(" -custom <names> : Comma-separated list of custom folder names for each extension, for example '-custom txt=TextFiles,png=Images'")
fmt.Println(" -verbose : Enable verbose output.")
fmt.Println(" -dryrun : Simulate the file organization without doing any actual changes.")
fmt.Println(" -cleanAll : Delete all the empty folders and sub-folders in the specified directory after organizing files.")
fmt.Println(" -backup : The Backup directory to take a backup of all files that would be organized.")
fmt.Println("")
return
}
if *version {
fmt.Printf("\nFidy version %s\n\n", ver)
return
}
if *backup != "" {
if *dir == "" {
fmt.Printf("Error: Please specify the target directory to be organized using '-dir'.") // error if -dir is not specified but -backup is provided
return
}
fmt.Printf("\nBackup directory created at %s/Fidy Backup\n\n", *backup) // Print the backup dir path
}
if *dir != "" {
excludeExtensions := strings.Split(*exclude, ",") // list of excluded extensions
includeExtensions := strings.Split(*include, ",") // list of included extensions
customNames := strings.Split(*custom, ",") // list of custom folder names
createdDirs := make(map[string]bool) // Tracking created directories for verbose/dryrun mode
customDir := make(map[string]string) // Tracking custom folder names, if specified
if *custom != "" {
for _, customName := range customNames {
dirName := strings.Split(customName, "=") // list with ext name and custom dir name for it
if len(dirName) == 2 && dirName[1] != "" { //ensuring proper syntax
customDir[strings.TrimSpace(dirName[0])] = strings.TrimSpace(dirName[1])
} else {
fmt.Printf("\nInvalid custom folder name. Please make sure there are no blank spaces in between the command. \nSample input: fidy -dir YOUR_DIR -custom txt=TextFiles,png=Images \n\n")
return
}
}
}
files, err := os.ReadDir(*dir)
if err != nil {
fmt.Println("Error reading directory: ", err)
os.Exit(1)
}
for _, file := range files {
if !file.IsDir() { // only run the loop for a file, not a folder
ext := filepath.Ext(file.Name())
if ext != "" {
ext = ext[1:] // Removing the dot
// Checking if extension is in exclude list
exc := false
for _, excludeExt := range excludeExtensions {
if ext == excludeExt {
exc = true
break
}
}
if exc {
continue
}
if *include != "" {
inc := false
for _, includeExt := range includeExtensions {
if ext == includeExt {
inc = true
break
}
}
if !inc {
continue
}
}
if *custom != "" {
if _, exists := customDir[ext]; exists {
ext = customDir[ext] // if a custom name is specified, change the folder name (ext) to custom name
}
}
targetDir := filepath.Join(*dir, ext)
if _, err := os.Stat(targetDir); os.IsNotExist(err) {
// checking if directory is already created
if _, exists := createdDirs[targetDir]; !exists {
if *verbose || *dryrun {
fmt.Printf("\nCreating directory %s\n", targetDir)
}
if !*dryrun {
os.Mkdir(targetDir, os.ModePerm) // make the new dir if dryrun is false
}
createdDirs[targetDir] = true
}
}
oldPath := filepath.Join(*dir, file.Name())
newPath := filepath.Join(targetDir, file.Name())
if *backup != "" {
createBackup(*backup, *dryrun, file, oldPath) // Take a backup if specified
}
if *verbose || *dryrun {
fmt.Printf("Moving file: %s -> %s \n", oldPath, newPath)
}
if !*dryrun {
os.Rename(oldPath, newPath)
}
}
}
}
fmt.Printf("\nFiles organized by extension in %s \n\n", *dir)
}
if *cleanAll {
cleanEmptyDirs(*dir, *dryrun)
}
}
func cleanEmptyDirs(dir string, dryrun bool) {
files, err := os.ReadDir(dir)
if err != nil {
fmt.Println("Error reading directory:", err)
return
}
for _, file := range files {
if file.IsDir() {
subDir := filepath.Join(dir, file.Name())
cleanEmptyDirs(subDir, dryrun)
subFiles, err := os.ReadDir(subDir)
if err != nil {
fmt.Println("Error reading subdirectory:", err)
continue
}
if len(subFiles) == 0 {
fmt.Printf("Deleting empty directory: %s\n", subDir)
if !dryrun {
if err := os.Remove(subDir); err != nil {
fmt.Println("Error deleting directory:", err)
}
}
}
}
}
}
func createBackup(dest string, dryrun bool, file fs.DirEntry, oldpath string) {
dest = filepath.Join(dest, "Fidy Backup")
if !dryrun {
err := os.MkdirAll(dest, os.ModePerm)
if err != nil {
fmt.Println("Error creating backup directory:", err)
return
}
source, err := os.Open(oldpath)
if err != nil {
fmt.Println("Error opening source file", file.Name(), "while creating Backup:", err)
return
}
defer source.Close()
dest = filepath.Join(dest, file.Name())
destination, err := os.Create(dest)
if err != nil {
fmt.Println("Error creating destination file while creating Backup:", err)
return
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
fmt.Println("Error copying file while creating Backup:", err)
return
}
}
}