-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
139 lines (107 loc) · 2.36 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"os"
"path/filepath"
"strings"
)
// ProcessFile recursively renames files and directories using the defined format
func ProcessFile(name string) (err error) {
fullpath, err := filepath.Abs(name)
if err != nil {
return
}
newname := getNewname(fullpath)
err = rename(fullpath, newname)
if err != nil {
return
}
dir, err := isDir(newname)
if err != nil {
return
}
if !dir {
return
}
filenames, dirnames, err := sift(newname)
if err != nil {
return
}
// rename files
for _, n := range filenames {
newname := getNewname(n)
err = rename(n, newname)
if err != nil {
return
}
}
var newDirnames []string
// rename dirs
for _, d := range dirnames {
newdirname := getNewname(d)
err = rename(d, newdirname)
if err != nil {
return
}
newDirnames = append(newDirnames, newdirname)
}
for _, d := range newDirnames {
err = ProcessFile(d)
if err != nil {
return
}
}
return
}
// rename mv file to new name if new name is different from previous name
func rename(prevname, newname string) (err error) {
if newname == prevname {
return
}
err = os.Rename(prevname, newname)
return
}
// getNewname get new full file name renamed using the defined format
func getNewname(name string) (newname string) {
// get the dir
dir, filename := filepath.Split(name)
// get the ext
ext := filepath.Ext(name)
// get the base
basename := getBasename(filename)
// rename
newbasename := Format(basename) + ext
newname = filepath.Join(dir, newbasename)
return
}
// getBasename get file name without extension
func getBasename(filename string) string {
return strings.TrimSuffix(filename, filepath.Ext(filename))
}
// isDir check if a file represented by `path` is a directory
func isDir(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
return false, err
}
return fileInfo.IsDir(), err
}
// sift inspects a directory and returns a list of filenames, a list of dirnames and an error
func sift(dir string) (filenames, dirnames []string, err error) {
fullpath, err := filepath.Abs(dir)
if err != nil {
return
}
files, err := os.ReadDir(fullpath)
if err != nil {
return
}
for _, file := range files {
name := filepath.Join(fullpath, file.Name())
if file.IsDir() {
dirnames = append(dirnames, name)
} else {
filenames = append(filenames, name)
}
}
return
}