-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
120 lines (99 loc) · 2.14 KB
/
utils.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
package main
import (
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
type organizer struct {
Files []fs.DirEntry
NewDirs []string
From string
To string
Recursive bool
Regex string
}
func CleanInput(input *string) {
if strings.HasPrefix(*input, ".\\") {
*input = strings.TrimPrefix(*input, ".")
current, _ := os.Getwd()
*input = current + *input
} else if strings.HasSuffix(*input, "\\") || strings.HasSuffix(*input, "/") {
*input = (*input)[:len(*input)-1]
} else if *input == "." {
*input, _ = os.Getwd()
}
}
func (o *organizer) DirExists() {
err := os.Chdir(o.To) //Return err?
if err != nil && os.IsNotExist(err) {
log.Fatalf("Folder %s does not exist", o.To)
}
}
func (o *organizer) GetEntries() {
entries, err := os.ReadDir(o.From)
if err != nil {
fmt.Println("The program will continue with the value it could collect before the error.", err)
}
for _, entry := range entries {
if !entry.IsDir() {
o.Files = append(o.Files, entry)
}
}
}
func (o *organizer) recursive() {
filepath.WalkDir(o.From, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
o.From = path
o.GetEntries()
o.ParseFiles()
o.MakeDirs()
o.Move()
}
o.Files = nil
o.NewDirs = nil
return nil
})
}
func (o *organizer) ParseFiles() {
re := regexp.MustCompile(o.Regex)
for _, f := range o.Files {
match := re.FindStringSubmatch(f.Name())
if len(match) >= 2 {
value := match[1]
// TODO: Check if there's repeated values in o.NewDirs
o.NewDirs = append(o.NewDirs, value)
}
}
}
func (o *organizer) MakeDirs() {
err := os.Chdir(o.To)
if err != nil {
log.Fatal(err)
}
for _, dir := range o.NewDirs {
err := os.Mkdir(dir, os.ModeDir)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
}
}
func (o *organizer) Move() {
re := regexp.MustCompile(o.Regex)
for _, f := range o.Files {
match := re.FindStringSubmatch(f.Name())
if len(match) >= 2 {
// TODO: Rewrite
value := match[1]
old := o.From + "\\" + f.Name()
new := o.To + "\\" + value + "\\" + f.Name()
err := os.Rename(old, new)
if err != nil {
fmt.Println(err)
}
}
}
}