-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
brename.go
1383 lines (1211 loc) · 39.5 KB
/
brename.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © 2013-2024 Wei Shen <shenwei356@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/fatih/color"
"github.com/mattn/go-colorable"
"github.com/shenwei356/breader"
"github.com/shenwei356/go-logging"
"github.com/shenwei356/natsort"
"github.com/shenwei356/util/pathutil"
"github.com/spf13/cobra"
)
var log *logging.Logger
var VERSION = "2.14.1"
var app = "brename"
var LastOpDetailFile = ".brename_detail.txt"
// for detecting one case where two or more files are renamed to same new path
var pathTree map[string]struct{}
// Options is the struct containing all global options
type Options struct {
Quiet bool
Verbose int
Version bool
DryRun bool
Pattern string
PatternRe *regexp.Regexp
Replacement string
Recursive bool
IncludingDir bool
OnlyDir bool
MaxDepth int
IgnoreCase bool
IgnoreExt bool
IgnoreErr bool
IncludeFilters []string
SkipFilters []string
ExcludeFilters []string
IncludeFilterRes []*regexp.Regexp
SkipFilterRes []*regexp.Regexp
ExcludeFilterRes []*regexp.Regexp
ListPath bool
ListPathSep string
ListAbsPath bool
NatureSort bool
ReplaceWithNR bool
StartNum int
NRFormat string
ReplaceWithKV bool
KVs map[string]string
KVFile string
KeepKey bool
KeyCaptIdx int
KeyMissRepl string
OverwriteMode int
PathCaseInsensitive bool
Undo bool
ForceUndo bool
LastOpDetailFile string
DisableUndo bool
ClearOpDetailFiles bool
}
var reNR = regexp.MustCompile(`\{(NR|nr)\}`)
var reKV = regexp.MustCompile(`\{(KV|kv)\}`)
func getOptions(cmd *cobra.Command) *Options {
dryrun := getFlagBool(cmd, "dry-run")
quiet := getFlagBool(cmd, "quiet")
if dryrun && quiet {
quiet = false
}
undo := getFlagBool(cmd, "undo")
forceUndo := getFlagBool(cmd, "force-undo")
if undo || forceUndo {
return &Options{
Undo: true, // set it true even only force-undo given
Quiet: quiet,
ForceUndo: forceUndo,
LastOpDetailFile: LastOpDetailFile,
}
}
clearLastOpDetailFiles := getFlagBool(cmd, "clear")
if clearLastOpDetailFiles {
return &Options{
ClearOpDetailFiles: true,
Quiet: quiet,
LastOpDetailFile: LastOpDetailFile,
Recursive: getFlagBool(cmd, "recursive"),
}
}
disableUndo := getFlagBool(cmd, "disable-undo")
version := getFlagBool(cmd, "version")
if version {
checkVersion()
return &Options{Version: version}
}
pattern := getFlagString(cmd, "pattern")
if pattern == "" {
log.Errorf(`flag -p/--pattern needed. type "brename -h" for usage and examples.`)
os.Exit(1)
}
p := pattern
ignoreCase := getFlagBool(cmd, "ignore-case")
if ignoreCase {
p = "(?i)" + p
}
re, err := regexp.Compile(p)
if err != nil {
log.Errorf("illegal regular expression for search pattern: %s", pattern)
os.Exit(1)
}
rewildcard := regexp.MustCompile(`^\*`)
infilters := getFlagStringSlice(cmd, "include-filters")
infilterRes := make([]*regexp.Regexp, 0, 10)
for _, infilter := range infilters {
if infilter == "" {
log.Errorf("value of flag -f/--include-filters missing")
os.Exit(1)
}
if rewildcard.MatchString(infilter) {
log.Warningf("Are you using wildcard for -f/--include-filters? It should be regular expression: %s", infilter)
}
if !(infilter == "./" || infilter == "." || infilter == "..") {
existed, err := pathutil.Exists(infilter)
if err != nil {
log.Warningf("something wrong when trying to check whether %s is a existed file", infilter)
}
if existed {
log.Warning("Seems you are using wildcard for -f/--include-filters? Make sure using regular expression: %s", infilter)
}
}
var infilterRe *regexp.Regexp
if ignoreCase {
infilterRe, err = regexp.Compile("(?i)" + infilter)
} else {
infilterRe, err = regexp.Compile(infilter)
}
if err != nil {
log.Errorf("illegal regular expression for include filter: %s", infilter)
os.Exit(1)
}
infilterRes = append(infilterRes, infilterRe)
}
skipfilters := getFlagStringSlice(cmd, "skip-filters")
skipRes := make([]*regexp.Regexp, 0, 10)
for _, skipfilter := range skipfilters {
if skipfilter == "" {
log.Errorf("value of flag -S/--skip-filters missing")
os.Exit(1)
}
if rewildcard.MatchString(skipfilter) {
log.Warningf("Are you using wildcard for -S/--skip-filters? It should be regular expression: %s", skipfilter)
}
var exfilterRe *regexp.Regexp
if ignoreCase {
exfilterRe, err = regexp.Compile("(?i)" + skipfilter)
} else {
exfilterRe, err = regexp.Compile(skipfilter)
}
if err != nil {
log.Errorf("illegal regular expression for skip filter: %s", skipfilter)
os.Exit(1)
}
skipRes = append(skipRes, exfilterRe)
}
exfilters := getFlagStringSlice(cmd, "exclude-filters")
exfilterRes := make([]*regexp.Regexp, 0, 10)
for _, exfilter := range exfilters {
if exfilter == "" {
log.Errorf("value of flag -F/--exclude-filters missing")
os.Exit(1)
}
if rewildcard.MatchString(exfilter) {
log.Warningf("Are you using wildcard for -F/--exclude-filters? It should be regular expression: %s", exfilter)
}
if !(exfilter == "./" || exfilter == "." || exfilter == "..") {
existed, err := pathutil.Exists(exfilter)
if err != nil {
log.Warningf("something wrong when trying to check whether %s is a existed file", exfilter)
}
if existed {
log.Warningf("Seems you are using wildcard for -F/--exclude-filters? Make sure using regular expression: %s", exfilter)
}
}
var exfilterRe *regexp.Regexp
if ignoreCase {
exfilterRe, err = regexp.Compile("(?i)" + exfilter)
} else {
exfilterRe, err = regexp.Compile(exfilter)
}
if err != nil {
log.Errorf("illegal regular expression for exclude filter: %s", exfilter)
os.Exit(1)
}
exfilterRes = append(exfilterRes, exfilterRe)
}
replacement := getFlagString(cmd, "replacement")
kvFile := getFlagString(cmd, "kv-file")
if kvFile != "" {
if len(replacement) == 0 {
checkError(fmt.Errorf("flag -r/--replacement needed when given flag -k/--kv-file"))
}
if !reKV.MatchString(replacement) {
checkError(fmt.Errorf(`replacement symbol "{kv}"/"{KV}" not found in value of flag -r/--replacement when flag -k/--kv-file given`))
}
}
var replaceWithNR bool
if reNR.MatchString(replacement) {
replaceWithNR = true
}
var replaceWithKV bool
var kvs map[string]string
keepKey := getFlagBool(cmd, "keep-key")
keyMissRepl := getFlagString(cmd, "key-miss-repl")
if reKV.MatchString(replacement) {
replaceWithKV = true
if !regexp.MustCompile(`\(.+\)`).MatchString(pattern) {
checkError(fmt.Errorf(`value of -p/--pattern must contains "(" and ")" to capture data which is used specify the KEY`))
}
if kvFile == "" {
checkError(fmt.Errorf(`since replacement symbol "{kv}"/"{KV}" found in value of flag -r/--replacement, tab-delimited key-value file should be given by flag -k/--kv-file`))
}
if keepKey && keyMissRepl != "" && !quiet {
log.Warning("flag -m/--key-miss-repl ignored when flag -K/--keep-key given")
}
if !quiet {
log.Infof("read key-value file: %s", kvFile)
}
kvs, err = readKVs(kvFile, ignoreCase)
if err != nil {
checkError(fmt.Errorf("read key-value file: %s", err))
}
if len(kvs) == 0 {
checkError(fmt.Errorf("no valid data in key-value file: %s", kvFile))
}
if !quiet {
log.Infof("%d pairs of key-value loaded", len(kvs))
}
}
verbose := getFlagNonNegativeInt(cmd, "verbose")
if verbose > 2 {
log.Errorf("illegal value of flag --verbose: %d, only 0/1/2 allowed", verbose)
os.Exit(1)
}
overwriteMode := getFlagNonNegativeInt(cmd, "overwrite-mode")
overwriteModes := []string{"reporting error", "overwrite", "do not rename"}
if overwriteMode > 2 {
log.Errorf("illegal value of flag -o/--overwrite-mode: %d, only 0/1/2 allowed", overwriteMode)
os.Exit(1)
}
if !quiet && verbose == 0 {
log.Infof("brename v%s", VERSION)
log.Infof("https://github.com/shenwei356/brename")
log.Info()
}
pathCaseInsensitive := getFlagBool(cmd, "case-insensitive-path")
pathCaseSensitive := getFlagBool(cmd, "case-sensitive-path")
if !pathCaseInsensitive {
if runtime.GOOS == "windows" {
if !pathCaseSensitive {
if !quiet && verbose <= 1 {
log.Warning()
log.Warning("The flag -w/--case-insensitive-path is switched on Windows by default, ")
log.Warning("where the path is case-insensitive in file systems like FAT32 and NTFS.")
log.Warning("If you are using a file system in which paths are case-insensitive,")
log.Warning("please use -W/--case-sensitive-path.")
log.Warning()
}
pathCaseInsensitive = true
} else {
if !quiet && verbose <= 1 {
log.Info()
log.Info("You've switched on the flag -W/--case-sensitive-path, which means")
log.Info("you believe that the paths are case-insensitive.")
log.Info()
}
}
} else {
if !pathCaseSensitive && !quiet && verbose <= 1 {
log.Warning()
log.Warning("If the file system where the search path locates is FAT32 or NTFS (most on Windows),")
log.Warning("please use -w/--case-insensitive-path to correctly check file overwrites!")
log.Warning()
}
}
} else if pathCaseSensitive {
checkError(fmt.Errorf("the flag -w/--case-insensitive-path and -W/--case-sensitive-path are incompatible"))
}
recursive := getFlagBool(cmd, "recursive")
includingDir := getFlagBool(cmd, "including-dir")
onlyDir := getFlagBool(cmd, "only-dir")
maxDepth := getFlagNonNegativeInt(cmd, "max-depth")
onlyList := getFlagBool(cmd, "list")
if !quiet && verbose == 0 {
log.Info("---------------- main options ------------------------")
log.Info()
log.Info("search mode:")
log.Infof(" recursively rename: %v", recursive)
log.Infof(" maximum depth: %d (0 for no limit)", maxDepth)
log.Infof(" include directory: %v", includingDir)
log.Infof(" only directory: %v", onlyDir)
log.Info()
log.Info("path filters and search pattern:")
log.Infof(" search pattern: %s", p)
log.Infof(" replacement: %s", replacement)
log.Infof(" ignore case: %v", ignoreCase)
log.Info()
if len(infilters) > 0 {
log.Infof(" skip filters: %s", strings.Join(skipfilters, ", "))
}
if len(exfilters) > 0 {
log.Infof(" exclude filters: %s", strings.Join(exfilters, ", "))
}
if len(infilters) > 0 {
log.Infof(" include filters: %s", strings.Join(infilters, ", "))
}
log.Info()
log.Info("path overwrite checking:")
log.Infof(" case-insensitive path: %v", pathCaseInsensitive)
log.Infof(" overwrite mode: %d (%s)", overwriteMode, overwriteModes[overwriteMode])
log.Info()
log.Info("miscellaneous:")
log.Infof(" disable undo: %v", disableUndo)
log.Infof(" only list paths: %v", onlyList)
log.Infof(" dry run: %v", dryrun)
log.Info()
}
return &Options{
Quiet: quiet,
Verbose: verbose,
Version: version,
DryRun: dryrun,
Pattern: pattern,
PatternRe: re,
Replacement: replacement,
Recursive: recursive,
IncludingDir: includingDir,
OnlyDir: onlyDir,
MaxDepth: maxDepth,
IgnoreCase: ignoreCase,
IgnoreExt: getFlagBool(cmd, "ignore-ext"),
IgnoreErr: getFlagBool(cmd, "ignore-err"),
IncludeFilters: infilters,
IncludeFilterRes: infilterRes,
SkipFilters: skipfilters,
SkipFilterRes: skipRes,
ExcludeFilters: infilters,
ExcludeFilterRes: exfilterRes,
ListPath: onlyList,
ListPathSep: getFlagString(cmd, "list-sep"),
ListAbsPath: getFlagBool(cmd, "list-abs"),
NatureSort: getFlagBool(cmd, "nature-sort"),
ReplaceWithNR: replaceWithNR,
StartNum: getFlagNonNegativeInt(cmd, "start-num"),
NRFormat: fmt.Sprintf("%%0%dd", getFlagPositiveInt(cmd, "nr-width")),
ReplaceWithKV: replaceWithKV,
KVs: kvs,
KVFile: kvFile,
KeepKey: keepKey,
KeyCaptIdx: getFlagPositiveInt(cmd, "key-capt-idx"),
KeyMissRepl: keyMissRepl,
OverwriteMode: overwriteMode,
PathCaseInsensitive: pathCaseInsensitive,
Undo: false,
LastOpDetailFile: LastOpDetailFile,
DisableUndo: disableUndo,
}
}
func init() {
// logFormat := logging.MustStringFormatter(`%{color}[%{level:.4s}]%{color:reset} %{message}`)
logFormat := logging.MustStringFormatter(`%{message}`)
var stderr io.Writer = os.Stderr
if runtime.GOOS == "windows" {
stderr = colorable.NewColorableStderr()
}
backend := logging.NewLogBackend(stderr, "", 0)
backendFormatter := logging.NewBackendFormatter(backend, logFormat)
logging.SetBackend(backendFormatter)
log = logging.MustGetLogger(app)
RootCmd.Flags().BoolP("quiet", "q", false, "be quiet, do not show any information and warning")
RootCmd.Flags().IntP("verbose", "v", 2, "verbose level (0 for all, 1 for warning, error and renamed files, 2 for only error and renamed files)")
RootCmd.Flags().BoolP("version", "V", false, "print version information and check for update")
RootCmd.Flags().BoolP("dry-run", "d", false, "print rename operations but do not run")
RootCmd.Flags().StringP("pattern", "p", "", "search pattern (regular expression)")
RootCmd.Flags().StringP("replacement", "r", "", `replacement. capture variables supported. e.g. $1 or ${1} (prefered) represents the first submatch. ATTENTION: for *nix OS, use SINGLE quote NOT double quotes or use the \ escape character. Ascending integer is also supported by "{nr}"`)
RootCmd.Flags().BoolP("recursive", "R", false, "rename recursively")
RootCmd.Flags().BoolP("including-dir", "D", false, "rename directories")
RootCmd.Flags().BoolP("only-dir", "", false, "only rename directories")
RootCmd.Flags().IntP("max-depth", "", 0, "maximum depth for recursive search (0 for no limit)")
RootCmd.Flags().BoolP("ignore-case", "i", false, "ignore case of -p/--pattern, -f/--include-filters and -F/--exclude-filters")
RootCmd.Flags().BoolP("ignore-ext", "e", false, "ignore file extension. i.e., replacement does not change file extension")
RootCmd.Flags().BoolP("ignore-err", "E", false, "ignore director reading errors")
RootCmd.Flags().StringSliceP("include-filters", "f", []string{"."}, `include file filter(s) (regular expression, NOT wildcard). multiple values supported, e.g., -f ".html" -f ".htm", but ATTENTION: each comma in the filter is treated as the separator of multiple filters, please use double quotation marks for patterns containing comma, e.g., -p '"A{2,}"'`)
RootCmd.Flags().StringSliceP("skip-filters", "S", []string{`^\.`}, `skip file filter(s) (regular expression, NOT wildcard). multiple values supported, e.g., -S "^\." for skipping files starting with a dot, but ATTENTION: each comma in the filter is treated as the separator of multiple filters, please use double quotation marks for patterns containing comma, e.g., -p '"A{2,}"'`)
RootCmd.Flags().StringSliceP("exclude-filters", "F", []string{}, `exclude file filter(s) (regular expression, NOT wildcard). multiple values supported, e.g., -F ".html" -F ".htm", but ATTENTION: each comma in the filter is treated as the separator of multiple filters, please use double quotation marks for patterns containing comma, e.g., -p '"A{2,}"'`)
RootCmd.Flags().BoolP("list", "l", false, `only list paths that match pattern`)
RootCmd.Flags().StringP("list-sep", "s", "\n", `separator for list of found paths`)
RootCmd.Flags().BoolP("list-abs", "a", false, `list absolute path, using along with -l/--list`)
RootCmd.Flags().BoolP("nature-sort", "N", false, `sort paths in nature order for renaming or listing`)
RootCmd.Flags().StringP("kv-file", "k", "",
`tab-delimited key-value file for replacing key with value when using "{kv}" in -r (--replacement)`)
RootCmd.Flags().BoolP("keep-key", "K", false, "keep the key as value when no value found for the key")
RootCmd.Flags().IntP("key-capt-idx", "I", 1, "capture variable index of key (1-based)")
RootCmd.Flags().StringP("key-miss-repl", "m", "", "replacement for key with no corresponding value")
RootCmd.Flags().IntP("start-num", "n", 1, `starting number when using {nr} in replacement`)
RootCmd.Flags().IntP("nr-width", "", 1, `minimum width for {nr} in flag -r/--replacement. e.g., formating "1" to "001" by --nr-width 3`)
RootCmd.Flags().IntP("overwrite-mode", "o", 0, "overwrite mode (0 for reporting error, 1 for overwrite, 2 for not renaming) (default 0)")
RootCmd.Flags().BoolP("case-insensitive-path", "w", false, "the file system (e.g., FAT32 or NTFS) is case-insensitive. It's automatically swiched on on Windows")
RootCmd.Flags().BoolP("case-sensitive-path", "W", false, "believing that the file system is case-sensitive. Please use this to disable the flag -w/--case-insensitive-path, which is switched on by default on Windows")
RootCmd.Flags().BoolP("undo", "u", false, "undo the LAST successful operation")
RootCmd.Flags().BoolP("force-undo", "U", false, "continue undo even when some operations failed")
RootCmd.Flags().BoolP("disable-undo", "x", false, "do not create .brename_detail.txt file for undo")
RootCmd.Flags().BoolP("clear", "", false, `remove all .brename_detail.txt" file, you may need to add -R/--recursive to recursively clear all files in the given path`)
RootCmd.Example = ` 1. dry run and showing potential dangerous operations (-d)
brename -p "abc" -d
2. dry run and only show operations that will cause error (-v)
brename -p "abc" -d -v 2
3. only renaming specific paths via include filters (-f)
brename -p ":" -r "-" -f ".htm$" -f ".html$"
4. renaming all .jpeg files to .jpg in all subdirectories (-R)
brename -p "\.jpeg" -r ".jpg" -R dir
5. using capture variables, e.g., $1, $2 ...
brename -p "(a)" -r "\$1\$1"
or brename -p "(a)" -r '$1$1' in Linux/Mac OS X
6. renaming directory too (-D)
brename -p ":" -r "-" -R -D pdf-dirs
7. using key-value file (-k)
brename -p "(.+)" -r "{kv}" -k kv.tsv
8. do not touch file extension (-e)
brename -p ".+" -r "{nr}" -f .mkv -f .mp4 -e
9. only list paths that match pattern (-l)
brename -i -f '.docx?$' -p . -R -l
10. undo the LAST successful operation (-u)
brename -u
11. disable undo if you do not want to create .brename_detail.txt (-x)
brename -p xxx -r yyy -x
12. clear/remove all .brename_detail.txt files (--clear)
brename --clear -R
13. also operate on hidden files: empty -S (default: ^\.)
brename -p xxx -r yyy -S ""
More examples: https://github.com/shenwei356/brename`
RootCmd.SetUsageTemplate(`Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}} {{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsagesWrapped 110 | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsagesWrapped 110 | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`)
pathTree = make(map[string]struct{}, 1024)
}
func main() {
if err := RootCmd.Execute(); err != nil {
log.Error(err)
os.Exit(1)
}
}
func checkError(err error) {
if err != nil {
log.Error(err)
os.Exit(1)
}
}
func getFileList(args []string) []string {
files := []string{}
if len(args) == 0 {
files = append(files, "./")
} else {
for _, file := range args {
if file == "./" || file == "." || file == ".." {
continue
}
if _, err := os.Stat(file); os.IsNotExist(err) {
log.Errorf("given search paths not existed: %s", file)
}
files = append(files, file)
}
if len(args) == 0 {
files = append(files, "./")
}
}
return files
}
func getFlagBool(cmd *cobra.Command, flag string) bool {
value, err := cmd.Flags().GetBool(flag)
checkError(err)
return value
}
func getFlagString(cmd *cobra.Command, flag string) string {
value, err := cmd.Flags().GetString(flag)
checkError(err)
return value
}
func getFlagStringSlice(cmd *cobra.Command, flag string) []string {
value, err := cmd.Flags().GetStringSlice(flag)
checkError(err)
return value
}
func getFlagPositiveInt(cmd *cobra.Command, flag string) int {
value, err := cmd.Flags().GetInt(flag)
checkError(err)
if value <= 0 {
checkError(fmt.Errorf("value of flag --%s should be greater than 0", flag))
}
return value
}
func getFlagNonNegativeInt(cmd *cobra.Command, flag string) int {
value, err := cmd.Flags().GetInt(flag)
checkError(err)
if value < 0 {
checkError(fmt.Errorf("value of flag --%s should be greater than or equal to 0", flag))
}
return value
}
func checkVersion() {
fmt.Printf("%s v%s\n", app, VERSION)
fmt.Println("\nChecking new version...")
resp, err := http.Get(fmt.Sprintf("https://github.com/shenwei356/%s/releases/latest", app))
if err != nil {
checkError(fmt.Errorf("Network error"))
}
items := strings.Split(resp.Request.URL.String(), "/")
var v string
if items[len(items)-1] == "" {
v = items[len(items)-2]
} else {
v = items[len(items)-1]
}
if v == "v"+VERSION {
fmt.Printf("You are using the latest version of %s\n", app)
} else {
fmt.Printf("New version available: %s %s at %s\n", app, v, resp.Request.URL.String())
}
}
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: app,
Short: "a cross-platform command-line tool for safely batch renaming files/directories via regular expression",
Long: fmt.Sprintf(`
brename: a practical cross-platform command-line tool for safely batch renaming files/directories via regular expression
Version: %s
Author: Wei Shen <shenwei356@gmail.com>
Homepage: https://github.com/shenwei356/brename
Warnings:
1. The path in file systems like FAT32 or NTFS is case-insensitive, so you should switch on the flag
-w/--case-insensitive-path to correctly check file overwrites.
2. The flag -w/--case-insensitive-path is switched on by default on Windows, please use
-W/--case-sensitive-path to disable it if the file system is indeed case-sensitive.
3. New paths ending with periods of spaces, being error-prone, are not allowed.
Three path filters:
1. -S/--skip-filters black list default value: ^\. (skipping paths starting with ".")
2. -F/--exclude-filters black list no default value
3. -f/--include-filters white list default value: . (anything)
Notes:
1. Paths starting with "." are ignored by default, disable this with -S "".
2. These options support multiple values, e.g., -f ".html" -f ".htm".
But ATTENTION: each comma in filters is treated as a separator of multiple filters.
Please use double quotation marks for patterns containing comma, e.g., -p '"A{2,}"'
3. The three filters are performed in order of -S, -F, -f.
4. -F/--exclude-filters is prefered for excluding path, cause it has no default value.
Setting -S/--skip-filters will overwrite its default value.
Special replacement symbols:
{nr} Ascending integer
{kv} Corresponding value of the key (captured variable $n) by key-value file,
n can be specified by flag -I/--key-capt-idx (default: 1)
Special cases of replacement string:
*1. Capture variables should be in the format of '${1}' to reduce errors.
a). If the capture variable is followed with space or other simple, it's OK:
-r '$1 abc'
b). If followed by numbers, characters, or underscore. That is ambiguous:
-r '$1abc' actually refers to the variable '1abc', please use '${1}abc'.
-r '$2_$1' actually refers to the variable '2_', please use '${2}_${1}'.
2. Want to replace with a charactor '$',
a). If using '{kv}', you need use '$$$$' instead of a single '$':
-r '{kv}' -k <(sed 's/\$/$$$$/' kv.txt)
b). If not, use '$$'. e.g., adding '$' to all numbers:
-p '(\d+)' -d -r '$$${1}'
`, VERSION),
Run: func(cmd *cobra.Command, args []string) {
timeStart := time.Now()
// var err error
opt := getOptions(cmd)
if opt.Version {
return
}
// ------------------------------------------------
// clear
if opt.ClearOpDetailFiles {
paths := getFileList(args)
for _, path := range paths {
checkError(clear(opt, path, 1))
}
return
}
// ------------------------------------------------
// undo
var delimiter = "\t_shenwei356-brename_\t"
if opt.Undo {
existed, err := pathutil.Exists(opt.LastOpDetailFile)
checkError(err)
if !existed {
if !opt.Quiet {
log.Infof("no brename operation to undo")
}
return
}
history := make([]operation, 0, 1000)
fn := func(line string) (interface{}, bool, error) {
line = strings.TrimRight(line, "\n")
if line == "" || line[0] == '#' { // ignoring blank line and comment line
return "", false, nil
}
items := strings.Split(line, delimiter)
if len(items) != 2 {
return items, false, nil
}
return operation{source: items[0], target: items[1], code: 0}, true, nil
}
var reader *breader.BufferedReader
reader, err = breader.NewBufferedReader(opt.LastOpDetailFile, 2, 100, fn)
checkError(err)
var op operation
for chunk := range reader.Ch {
checkError(chunk.Err)
for _, data := range chunk.Data {
op = data.(operation)
history = append(history, op)
}
}
if len(history) == 0 {
if !opt.Quiet {
log.Infof("no brename operation to undo")
}
return
}
n := 0
if !opt.Quiet {
log.Infof(bold("Renaming paths back..."))
log.Info()
}
for i := len(history) - 1; i >= 0; i-- {
op = history[i]
err = os.Rename(op.target, op.source)
if err != nil {
log.Errorf(` [%s] %s -> %s: %s`, red("ERROR"), op.source, op.target, err)
if !opt.ForceUndo {
if !opt.Quiet {
log.Infof("%d path(s) renamed back in %.3f seconds", n, time.Since(timeStart).Seconds())
}
os.Exit(1)
}
}
n++
if !opt.Quiet {
log.Infof(" [%s] %s -> %s", green("DONE"), op.target, op.source)
}
}
if !opt.Quiet {
log.Info()
log.Infof("%d path(s) renamed back in %.3f seconds", n, time.Since(timeStart).Seconds())
}
checkError(os.Remove(opt.LastOpDetailFile))
return
}
// ------------------------------------------------
// rename
ops := make([]operation, 0, 1024)
opCH := make(chan operation, 1024)
done := make(chan int)
var hasErr bool
var n, nErr int
var outPath string
var err error
go func() {
first := true
verbose := !opt.Quiet || opt.DryRun
for op := range opCH {
if opt.ListPath {
if opt.ListAbsPath {
outPath, err = filepath.Abs(op.source)
checkError(err)
} else {
outPath = op.source
}
if first {
fmt.Print(outPath)
first = false
} else {
fmt.Print(opt.ListPathSep + outPath)
}
continue
}
if int(op.code) >= opt.Verbose || opt.DryRun {
switch op.code {
case codeOK:
if verbose {
log.Infof(" %s\n", op)
}
case codeUnchanged:
if verbose {
log.Warningf(" %s\n", op)
}
case codeExisted, codeOverwriteNewPath:
switch opt.OverwriteMode {
case 0: // report error
log.Errorf(" %s\n", op)
case 1: // overwrite
if verbose {
log.Warningf(" %s (will be overwrited)\n", op)
}
case 2: // no renaming
if verbose {
log.Warningf(" %s (will NOT be overwrited)\n", op)
}
}
case codeEndingWithPeriod, codeEndingWithSpace:
if verbose {
log.Errorf(" %s\n", op)
}
case codeMissingTarget:
log.Errorf(" %s\n", op)
}
}
switch op.code {
case codeOK:
ops = append(ops, op)
n++
case codeUnchanged:
case codeExisted, codeOverwriteNewPath:
switch opt.OverwriteMode {
case 0: // report error
hasErr = true
nErr++
continue
case 1: // overwrite
ops = append(ops, op)
n++
case 2: // no renaming
}
default:
hasErr = true
nErr++
continue
}
}
if opt.ListPath {
fmt.Println()
}
done <- 1
}()
paths := getFileList(args)
if !opt.Quiet && opt.Verbose == 0 {
log.Info("------------------------------------------------------")
log.Info()
log.Infof("search paths: %s", strings.Join(paths, ", "))
log.Info()
}
if (!opt.Quiet || opt.DryRun) && !opt.ListPath {
log.Info(bold("Searching for paths to rename..."))
log.Info()
}
for _, path := range paths {
err = walk(opt, opCH, path, 1)
if err != nil {
close(opCH)
checkError(err)
}
}
if !opt.Quiet && !opt.DryRun && !opt.ListPath {
fmt.Fprintf(os.Stderr, "\r %-78s\n", green("Done searching."))
}
close(opCH)
<-done
if hasErr {
log.Info()
log.Errorf("%d potential error(s) detected, please check", nErr)
os.Exit(1)
}
if opt.ListPath {
return
}
if opt.DryRun || (!opt.Quiet && opt.Verbose == 0) || n == 0 {
log.Info()
log.Infof("%d path(s) to be renamed", n)
}
if n == 0 {
return
}
if opt.DryRun {
return
}
var fh *os.File
var bfh *bufio.Writer
if !opt.DisableUndo {
fh, err = os.Create(opt.LastOpDetailFile)
checkError(err)
bfh = bufio.NewWriter(fh)
defer func() {
checkError(bfh.Flush())
fh.Close()
}()
}
var n2 int
var targetDir string
var targetDirExisted bool
if !opt.Quiet {
log.Info()
log.Info(bold("Renaming paths..."))
log.Info()
}
for _, op := range ops {
targetDir = filepath.Dir(op.target)
targetDirExisted, err = pathutil.DirExists(targetDir)
if err != nil {
log.Errorf(` [%s] %s -> %s`, red("ERROR"), op.source, op.target)
os.Exit(1)
}
if !targetDirExisted {
os.MkdirAll(targetDir, 0755)
}
err = os.Rename(op.source, op.target)
if err != nil {
log.Errorf(` [%s] %s -> %s: %s`, red("ERROR"), op.source, op.target, err)
os.Exit(1)
}
if !opt.Quiet {
log.Infof(" [%s] %s -> %s", green("DONE"), op.source, op.target)
}
if !opt.DisableUndo {
bfh.WriteString(fmt.Sprintf("%s%s%s\n", op.source, delimiter, op.target))
}
n2++
}
if !opt.Quiet {
log.Info()
log.Infof("%d path(s) renamed in %.3f seconds", n2, time.Since(timeStart).Seconds())
}
},
}