-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnaming.go
366 lines (323 loc) · 10 KB
/
naming.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
)
const (
formulaOption = "formula"
ignoreOption = "ignore"
pathOption = "path"
rollbackOption = "rollback"
startOption = "start"
isFileOnlyOption = "fileOnly"
isFolderOnlyOption = "folderOnly"
isListAllOption = "listAll"
isSkipErrorOption = "skipError"
formattedIncrementOption = "formatIncrement"
namingTypeFile = "file_only"
namingTypeFolder = "folder_only"
namingTypeAll = "file_and_folder"
formulaIncrement = "{increment}"
formulaCurrent = "{current}"
defaultIncrement = 1
defaultFormattedIncrement = 4
)
var formulas = []string{formulaIncrement, formulaCurrent}
func main() {
fmt.Println("Naming your files & folders quickly\n")
var increment int
path, formula, namingType, isListAll, isRollback, isSkipError, ignoreList, startIncrement, formattedIncrement, err := readArgs()
if err != nil {
log.Fatal(err)
}
if isListAll != nil && *isListAll {
fmt.Println("List All files & folders in tree")
if err = list(path); err != nil {
log.Fatal(err)
}
return
}
if isRollback != nil && *isRollback {
fmt.Println("Rollback files")
increment, err = execRollback(formula, path, startIncrement, namingType, ignoreList)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Successfully rollback %d items for %s", increment-1, namingType)
os.Exit(0)
return
}
increment, err = exec(formula, path, startIncrement, namingType, ignoreList, *isSkipError, formattedIncrement)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Successfully naming %d items for %s", increment-1, namingType)
os.Exit(0)
}
func exec(formula, path string, increment int, namingType string, ignoreList []string, isSkipError bool, formattedIncrement int) (int, error) {
files, folders, err := readAll(path)
if err != nil {
return 0, err
}
prefixPath := path + "/"
if namingType == namingTypeFile || namingType == namingTypeAll {
if increment, err = naming(files, increment, formula, path, ignoreList, isSkipError, formattedIncrement); err != nil {
return 0, err
}
}
if namingType == namingTypeFolder || namingType == namingTypeAll {
if increment, err = naming(folders, increment, formula, path, ignoreList, isSkipError, formattedIncrement); err != nil {
return 0, err
}
if _, folders, err = readAll(path); err != nil {
return 0, err
}
}
for _, folder := range folders {
if increment, err = exec(formula, prefixPath+folder, increment, namingType, ignoreList, isSkipError, formattedIncrement); err != nil {
return 0, err
}
}
return increment, nil
}
func execRollback(formula, path string, increment int, namingType string, ignoreList []string) (int, error) {
files, folders, err := readAll(path)
if err != nil {
return 0, err
}
prefixPath := path + "/"
if namingType == namingTypeFile || namingType == namingTypeAll {
if increment, err = rollback(files, increment, formula, path, ignoreList); err != nil {
return 0, err
}
}
if namingType == namingTypeFolder || namingType == namingTypeAll {
if increment, err = rollback(folders, increment, formula, path, ignoreList); err != nil {
return 0, err
}
if _, folders, err = readAll(path); err != nil {
return 0, err
}
}
for _, folder := range folders {
if increment, err = execRollback(formula, prefixPath+folder, increment, namingType, ignoreList); err != nil {
return 0, err
}
}
return increment, nil
}
func list(path string) (err error) {
var files, folders []string
if files, folders, err = readAll(path); err != nil {
return
}
prefixPath := path + "/"
for _, file := range files {
fmt.Println(prefixPath + file)
}
for _, folder := range folders {
if err = list(prefixPath + folder); err != nil {
return
}
}
return
}
func naming(src []string, increment int, formula, path string, ignoreList []string, isSkipError bool, formattedIncrement int) (lastIncrement int, err error) {
prefixPath := path + "/"
for _, s := range src {
destName := readFormula(formula, s, increment, formattedIncrement)
if okToRename(s, ignoreList) {
if err = rename(prefixPath+s, prefixPath+destName); err == nil {
increment++
}
if err != nil && !isSkipError {
return
}
}
}
lastIncrement = increment
return
}
func rollback(src []string, increment int, formula, path string, ignoreList []string) (lastIncrement int, err error) {
prefixPath := path + "/"
for _, s := range src {
destName := readFormulaRollback(formula, s, increment)
if okToRename(s, ignoreList) {
if err = rename(prefixPath+s, prefixPath+destName); err != nil {
return
}
increment++
}
}
lastIncrement = increment
return
}
func readArgs() (pathDir, formulaNaming, namingType string, isListAll, isRollback, isSkipError *bool, ignoreList []string, startIncrement, formattedIncrement int, err error) {
formula := flag.String(formulaOption, "", `[mandatory] formula for naming files/folders. i.e: --formula="A{slash}B{slash}finance{increment} - {current} | output: A/B/finance1 - How to manage money"`)
path := flag.String(pathOption, ".", "[optional] read path")
start := flag.Int(startOption, defaultIncrement, "[optional] start increment value")
formattedIncr := flag.Int(formattedIncrementOption, defaultFormattedIncrement, "[optional] increment format. i.e: 4. it will print increment like this format 0001, 0002, 0003")
isRollback = flag.Bool(rollbackOption, false, "[optional] for rollback only")
isFileOnly := flag.Bool(isFileOnlyOption, false, "[optional] naming for files only")
isFolderOnly := flag.Bool(isFolderOnlyOption, false, "[optional] naming for folders only")
isListAll = flag.Bool(isListAllOption, false, "[optional] for listing all files and folders")
isSkipError = flag.Bool(isSkipErrorOption, false, "[optional] ignore error whenever it's failed to rename one of the file")
ignores := flag.String(ignoreOption, "", `[optional] ignore list, comma-separated. i.e --ignore="Desktop.ini,*.exe" | * means all`)
flag.Parse()
ignoreList = strings.Split(*ignores, ",")
if len(ignoreList) == 0 && *ignores != "" {
ignoreList = append(ignoreList, *ignores)
}
pathDir = *path
namingType = getNamingType(*isFileOnly, *isFolderOnly)
if isListAll != nil && *isListAll {
return
}
if formula == nil || *formula == "" {
err = fmt.Errorf("%s is Mandatory", formulaOption)
return
}
formulaNaming = *formula
startIncrement = *start
formattedIncrement = *formattedIncr
return
}
func getNamingType(isFileOnly, isFolderOnly bool) string {
if isFileOnly {
return namingTypeFile
}
if isFolderOnly {
return namingTypeFolder
}
return namingTypeAll
}
func readAll(pathDir string) (fileNames, folderNames []string, err error) {
var (
files []os.FileInfo
stat os.FileInfo
)
if stat, err = os.Stat(pathDir); err != nil || !stat.IsDir() {
err = fmt.Errorf("Wrong path - %v", err)
return
}
if files, err = ioutil.ReadDir(pathDir); err != nil {
return
}
for _, f := range files {
if f.IsDir() {
folderNames = append(folderNames, f.Name())
continue
}
fileNames = append(fileNames, f.Name())
}
return
}
func rename(src, dst string) error {
err := os.Rename(src, dst)
if err != nil {
return err
}
return nil
}
// format i.e: 4
func getFormattedInt(format int, val int) string {
stringFormat := "%" + fmt.Sprint(format) + "d"
out := fmt.Sprintf(stringFormat, val)
out = strings.ReplaceAll(out, " ", "0")
return out
}
func readFormula(in, currentName string, index, formattedIncrement int) string {
if strings.Contains(in, formulaIncrement) {
in = strings.ReplaceAll(in, formulaIncrement, getFormattedInt(formattedIncrement, index))
}
if strings.Contains(in, formulaCurrent) {
in = strings.ReplaceAll(in, formulaCurrent, currentName)
}
return in
}
func readFormulaRollback(formula, currentName string, index int) string {
increment := getIncrementString(formula, currentName)
formula = strings.ReplaceAll(formula, formulaIncrement, increment)
realFilename := getRealFilename(formula, currentName)
return realFilename
}
func getIncrementString(formula, filename string) string {
if !strings.Contains(formula, formulaIncrement) {
return ""
}
formula = strings.Replace(formula, formulaCurrent, "", -1)
return stringBetween(filename, stringBefore(formula, formulaIncrement), stringAfter(formula, formulaIncrement))
}
func getRealFilename(formula, filename string) string {
if !strings.Contains(formula, formulaCurrent) {
return ""
}
formula = strings.Replace(formula, formulaIncrement, "", -1)
before := stringBefore(formula, formulaCurrent)
after := stringAfter(formula, formulaCurrent)
filename = strings.Replace(filename, before, "", 1)
filename = strings.Replace(filename, after, "", 1)
return filename
}
func stringSliceContains(in []string, v string) bool {
for _, s := range in {
if s == v {
return true
}
}
return false
}
func okToRename(v string, ignoreList []string) bool {
if stringSliceContains(ignoreList, v) {
return false
}
for _, ignore := range ignoreList {
if strings.Contains(ignore, "*.") {
splitted := strings.Split(ignore, "*.")
ignoreExtension := splitted[len(splitted)-1]
if extension, err := getFileExtension(v); err == nil {
if extension == ignoreExtension {
return false
}
}
}
}
return true
}
func getFileExtension(fileName string) (string, error) {
splitted := strings.Split(fileName, ".")
if len(splitted) > 0 {
extension := splitted[len(splitted)-1]
return extension, nil
}
return "", fmt.Errorf("No file extension!")
}
func stringBetween(value string, a string, b string) string {
if !strings.Contains(value, a) || !strings.Contains(value, b) {
return ""
}
value = strings.Replace(value, a, "", 1)
return stringBefore(value, b)
}
func stringAfter(value string, a string) string {
pos := strings.LastIndex(value, a)
if pos == -1 {
return ""
}
adjustedPos := pos + len(a)
if adjustedPos >= len(value) {
return ""
}
return value[adjustedPos:len(value)]
}
func stringBefore(value string, a string) (out string) {
slices := strings.Split(value, a)
if len(slices) < 2 {
return
}
return slices[0]
}