-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
2052 lines (1687 loc) · 49.8 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
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
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/bitfield/script"
"github.com/cheynewallace/tabby"
cli "github.com/urfave/cli/v2"
)
const (
separator = "-"
)
const (
codecH264 = "h264"
codecH265 = "hevc"
)
const (
encoderH264 = "libx264"
encoderH265 = "libx265"
encoderVP9 = "vp9"
)
const (
eightKPreset = "8k"
fourKPreset = "4k"
qHDPreset = "qhd"
twoKPreset = "2k"
fullHDPreset = "fullhd"
hdPreset = "hd"
sdPreset = "sd"
eightKPreset2 = "4320p"
fourKPreset2 = "2160p"
qHDPreset2 = "1440p"
fullHDPreset2 = "1080p"
hdPreset2 = "720p"
sdPreset2 = "480p"
)
const (
eightKWidth = 7680
eightKHeight = 4320
fourKWidth = 3840
fourKHeight = 2160
qHDWidth = 2560
qHDHeight = 1440
twoKWidth = 2048
twoKHeight = 1080
fullHDWidth = 1920
fullHDHeight = 1080
hdWidth = 1280
hdHeight = 720
sdWidth = 640
sdHeight = 480
)
const (
defaultCodec = encoderH265
defaultPreset = "ultrafast"
)
var (
allowedPresets = []string{"ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow"}
)
type logger struct {
silent bool
history []string
}
func (l *logger) Printf(msg string, args ...interface{}) {
if l.silent {
l.history = append(l.history, fmt.Sprintf(msg, args...))
return
}
log.Printf(msg, args...)
}
func (l *logger) Println(msg ...any) {
if l.silent {
l.history = append(l.history, fmt.Sprintln(msg...))
return
}
log.Println(msg...)
}
var l logger
func safeRename(oldPath, newPath string, forceOverwrite bool) error {
if oldPath == newPath {
l.Printf("no file name change. path: '%s'", newPath)
return nil
}
l.Println(oldPath, " -> ", newPath)
_, err := os.Stat(newPath)
if err == nil || !os.IsNotExist(err) {
if !forceOverwrite {
l.Printf("file already exists. path: %q", newPath)
return err
}
l.Printf("force overwrite. path: %q", newPath)
}
err = os.Rename(oldPath, newPath)
if err != nil {
l.Printf("unexpected error during renaming file. old path: %q, new path: %q, err: %s", oldPath, newPath, err)
}
return err
}
func concat(parts []string, skip int, newPart, ext, separator string) string {
if len(parts) < skip {
panic(fmt.Errorf("unsafe usage of concat. len(parts): %d, skip: %d", len(parts), skip))
}
start := strings.Join(parts[:skip], separator)
if start != "" {
start += separator
}
end := strings.Join(parts[skip:], separator)
if end != "" {
end = separator + end
}
return start + newPart + end + ext
}
func getFileInfoList(filePaths []string, backwardsFlag bool) []os.FileInfo {
if len(filePaths) == 0 {
log.Fatalf("no files provided")
return nil
}
var fileInfoList []os.FileInfo
for _, filePath := range filePaths {
fi, err := os.Stat(filePath)
if err != nil {
log.Fatalf("argument is not a file: %q, err: %s", filePath, err)
}
if fi.IsDir() {
log.Fatalf("file is a directory: %q", filePath)
}
l.Printf("file is okay: %q", filePath)
fileInfoList = append(fileInfoList, fi)
}
if backwardsFlag {
var fis2 []os.FileInfo
for i := len(fileInfoList) - 1; i >= 0; i-- {
fis2 = append(fis2, fileInfoList[i])
}
fileInfoList = fis2
}
return fileInfoList
}
func process(c *cli.Context, argCount int, fn func(*cli.Context, []string, os.FileInfo, bool) error) error {
args := c.Args().Slice()
dryRun := c.Bool(dryRunFlag)
l = logger{
silent: !(c.Bool(verboseFlag) || c.Bool(dryRunFlag)),
}
if argCount > len(args) {
return errors.New("not enough arguments")
}
fileInfoList := getFileInfoList(args[argCount:], c.Bool(backwardsFlag))
for _, fi := range fileInfoList {
l.Printf("file found: %q", fi.Name())
}
args = args[:argCount]
t0 := time.Now()
for _, fi := range fileInfoList {
t1 := time.Now()
err := fn(c, args, fi, dryRun)
if err != nil {
l.Println(err)
}
log.Printf("done in %s.", time.Since(t1).String())
}
log.Printf("all done in %s.", time.Since(t0).String())
return nil
}
func processAll(c *cli.Context, argCount int, fn func(*cli.Context, []string, []os.FileInfo, bool) error) error {
args := c.Args().Slice()
dryRun := c.Bool(dryRunFlag)
l = logger{
silent: !(c.Bool(verboseFlag) || c.Bool(dryRunFlag)),
}
if argCount > len(args) {
return errors.New("not enough arguments")
}
fileInfoList := getFileInfoList(args[argCount:], c.Bool(backwardsFlag))
for _, fi := range fileInfoList {
l.Printf("file found: %q", fi.Name())
}
args = args[:argCount]
t0 := time.Now()
err := fn(c, args, fileInfoList, dryRun)
if err != nil {
l.Println(err)
}
log.Printf("all done in %s.", time.Since(t0).String())
return nil
}
func exec(command string) (string, error) {
p := script.Exec(command)
output, err := p.String()
if err != nil {
l.Println(err)
}
return output, err
}
type App struct{}
func findKeyFrames(fi os.FileInfo) ([]string, error) {
command := fmt.Sprintf(`ffprobe -loglevel error -select_streams v:0 -show_entries packet=pts_time,flags -of csv=print_section=0 %q`, fi.Name())
res, err := script.Exec(command).Match(",K__").FilterLine(func(line string) string {
return strings.Split(line, ",")[0]
}).Slice()
if err != nil {
return nil, fmt.Errorf("unable to retrieve keyframes. err: %w", err)
}
maxCount := 4
var numbers []string
for i, line := range res {
if i >= maxCount {
break
}
if line == "" {
continue
}
n, err := strconv.ParseFloat(line, 32)
if err != nil {
return nil, err
}
numbers = append(numbers, fmt.Sprintf("%.1f", n))
}
return numbers, nil
}
func keyFrames(fi os.FileInfo) error {
numbers, err := findKeyFrames(fi)
if err != nil {
return err
}
l.Printf("file: %s", fi.Name())
l.Printf("indexes: %s...", strings.Join(numbers, ", "))
return nil
}
func (a App) keyFrames(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
return keyFrames(fi)
}
const (
videoCodecKey = "-c:v"
audioCodecKey = "-c:a"
crfKey = "-crf"
bitRateKey = "-b:v"
maxRateKey = "-maxrate"
bufsizeKey = "-bufsize"
presetKey = "-preset"
losslessKey = "-lossless"
hwaccelKey = "-hwaccel"
hwaccelDeviceKey = "-hwaccel_device"
inputKey = "-i"
)
type ReEncoder struct {
lock *sync.Mutex
params map[string]string
order []string
keys []string
boolKeys []string
}
func NewReEncoder() *ReEncoder {
return &ReEncoder{
lock: &sync.Mutex{},
params: make(map[string]string),
keys: []string{videoCodecKey, hwaccelKey, crfKey, losslessKey, presetKey},
boolKeys: []string{losslessKey},
}
}
func (r *ReEncoder) Set(key, value string) *ReEncoder {
r.lock.Lock()
defer r.lock.Unlock()
_, ok := r.params[key]
if ok {
r.params[key] = value
return r
}
r.params[key] = value
r.order = append(r.order, key)
return r
}
func (r *ReEncoder) Delete(key string) *ReEncoder {
r.lock.Lock()
defer r.lock.Unlock()
_, ok := r.params[key]
if !ok {
return r
}
delete(r.params, key)
for i, k := range r.order {
if k == key {
r.order = append(r.order[:i], r.order[i+1:]...)
}
}
return r
}
func (r *ReEncoder) String() string {
r.lock.Lock()
defer r.lock.Unlock()
params := []string{}
for _, key := range r.order {
params = append(params, fmt.Sprintf("%s %q", key, r.params[key]))
}
return strings.Join(params, " ")
}
func (r *ReEncoder) GetPath() string {
r.lock.Lock()
defer r.lock.Unlock()
values := []string{}
for _, key := range r.keys {
if value, ok := r.params[key]; ok {
b := false
for _, bv := range r.boolKeys {
if bv == key {
b = true
break
}
}
if b {
values = append(values, strings.Trim(key, "-"))
} else {
values = append(values, value)
}
}
}
return strings.Join(values, "-")
}
func findPreset(preset string) (string, error) {
for _, p := range allowedPresets {
if p == preset {
return preset, nil
}
}
return "", fmt.Errorf("invalid preset. preset: %s", preset)
}
func getNewBitRates(fi os.FileInfo, encoder string) (string, string, error) {
oldCodec, err := getCodec(fi)
if err != nil {
return "", "", fmt.Errorf("unable to get codec. err: %w", err)
}
rawBitRate, err := getBitRate(fi)
if err != nil {
return "", "", fmt.Errorf("unable to get bitrate. err: %w", err)
}
if rawBitRate == 0 {
vt := info(fi, true)
rawBitRate = vt.width * vt.height / 10 * int64(vt.frameRate)
}
rbr := intToString(rawBitRate, "", "")
l.Printf("file: %s, old codec: %s, encoder: %s, old bit rate: %d, rbr human: %s", fi.Name(), oldCodec, encoder, rawBitRate, rbr)
if encoder == encoderH265 && oldCodec != codecH265 {
rawBitRate = rawBitRate * 6 / 10
}
rbr = intToString(rawBitRate, "", "")
rbr2 := intToString(rawBitRate*2, "", "")
l.Printf("file: %s, old codec: %s, encoder: %s, new bit rate: %d, rbr human: %s", fi.Name(), oldCodec, encoder, rawBitRate, rbr)
return rbr, rbr2, nil
}
func reEncode(fi os.FileInfo, codec string, crf int, preset, hwaccel, hwaccelDevice string, dryRun bool) (string, error) {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
extNew := "mp4"
params := NewReEncoder()
params.
Set(hwaccelKey, "auto").
Set(hwaccelDeviceKey, hwaccelDevice).
Set(inputKey, filePath).
Set(crfKey, fmt.Sprintf("%d", crf)).
Set(presetKey, preset)
switch codec {
case encoderH265:
const x265Params = "-x265-params"
// https://trac.ffmpeg.org/wiki/Encode/H.265
if crf == 0 {
crf = 23
}
preset, err := findPreset(preset)
if err != nil {
return "", err
}
params.
Delete(crfKey).
Set(videoCodecKey, encoderH265).
Set(x265Params, "keyint=1").
Set(presetKey, preset).
Set(crfKey, fmt.Sprintf("%d", crf)).
Set(audioCodecKey, "copy").
Set("-tag:v", "hvc1")
switch hwaccel {
case "qsv":
params.
Delete(presetKey).
Delete(crfKey).
// Set(hwaccelKey, "hevc_qsv").
Set(videoCodecKey, "hevc_qsv")
default:
params.
Delete(hwaccelKey).
Delete(hwaccelDeviceKey)
}
break
case encoderH264:
const x264Params = "-x264-params"
// https://trac.ffmpeg.org/wiki/Encode/H.264
if crf == 0 {
crf = 20
}
preset, err := findPreset(preset)
if err != nil {
return "", err
}
params.
Delete(crfKey).
Set(videoCodecKey, encoderH264).
Set(x264Params, "keyint=1").
Set(presetKey, preset).
Set(crfKey, fmt.Sprintf("%d", crf)).
Set(audioCodecKey, "copy")
switch hwaccel {
case "qsv":
params.
Delete(presetKey).
Delete(crfKey).
// Set(hwaccelKey, "hevc_qsv").
Set(videoCodecKey, "h264_qsv")
default:
params.
Delete(hwaccelKey).
Delete(hwaccelDeviceKey)
}
break
case encoderVP9:
const vp9KeyFrameKey = "-g"
// https://trac.ffmpeg.org/wiki/Encode/VP9
extNew = "mkv"
params.
Delete(presetKey).
Delete(crfKey).
Set(videoCodecKey, encoderVP9).
Set(vp9KeyFrameKey, "1").
Set(crfKey, fmt.Sprintf("%d", crf)).
Set(audioCodecKey, "copy")
if crf == 0 {
params.
Delete(crfKey).
Set(losslessKey, "1")
}
switch hwaccel {
case "qsv":
params.
Delete(presetKey).
Delete(crfKey).
// Set(hwaccelKey, "hevc_qsv").
Set(videoCodecKey, "vp9_qsv")
default:
params.
Delete(hwaccelKey).
Delete(hwaccelDeviceKey)
}
}
if hwaccel != "" {
avgBitRate, maxBitRate, err := getNewBitRates(fi, codec)
if err != nil {
return "", fmt.Errorf("unable to get bit rates. err: %w", err)
}
params.
Set(bitRateKey, avgBitRate).
Set(maxRateKey, maxBitRate).
Set(bufsizeKey, maxBitRate)
}
outputPath := fmt.Sprintf("%s-%s.%s", basePath, params.GetPath(), extNew)
command := fmt.Sprintf(`ffmpeg %s %q`, params.String(), outputPath)
l.Printf("new path: %s", outputPath)
l.Printf("command: %s", command)
if dryRun {
return outputPath, nil
}
output, err := exec(command)
l.Println(output)
return outputPath, err
}
func (a App) reEncode(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
codec := c.String(codecFlag)
crf := c.Int(crfFlag)
preset := c.String(presetFlag)
hwaccel := c.String(hwaccelFlag)
hwaccelDevice := c.String(hwaccelDeviceFlag)
_, err := reEncode(fi, codec, crf, preset, hwaccel, hwaccelDevice, dryRun)
return err
}
func prefix(fi os.FileInfo, newPart string, skip int, forceOverwrite bool, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
parts := strings.Split(basePath, separator)
newPath := concat(parts, skip, newPart, ext, separator)
if dryRun {
l.Println(filePath, " -> ", newPath)
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) prefix(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
if len(args) == 0 {
return nil
}
newPart := args[0]
skip := c.Int(skipPartsFlag)
forceOverwrite := c.Bool(forceFlag)
return prefix(fi, newPart, skip, forceOverwrite, dryRun)
}
func suffix(fi os.FileInfo, newPart string, skip int, forceOverwrite, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
parts := strings.Split(basePath, separator)
if skip > len(parts) {
return fmt.Errorf("more to skip then parts present. file: %q skip: %d, parts: %d", basePath, skip, len(parts))
}
skipInverse := len(parts) - skip
newPath := concat(parts, skipInverse, newPart, ext, separator)
if dryRun {
l.Println(filePath, " -> ", newPath)
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) suffix(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
skip := c.Int(skipPartsFlag)
newPart := args[0]
forceOverwrite := c.Bool(forceFlag)
return suffix(fi, newPart, skip, forceOverwrite, dryRun)
}
func replace(fi os.FileInfo, search, replaceWith string, skip int, forceOverwrite bool, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
parts := strings.Split(basePath, search)
if skip > len(parts)-1 {
return fmt.Errorf("more to skip than found occurances. file: %q, skip: %d, found: %d", basePath, skip, len(parts)-1)
}
if len(parts) <= 1 {
// safe rename is called to handle standard logging
return safeRename(filePath, filePath, false)
}
start := strings.Join(parts[:skip+1], search)
end := strings.Join(parts[skip+1:], search)
newPath := start + replaceWith + end + ext
l.Printf(`%q -> %q, search: %q, replace with: %q`, filePath, newPath, search, replaceWith)
if dryRun {
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) replace(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
if len(args) < 2 {
return nil
}
search := args[0]
replaceWith := args[1]
skip := c.Int(skipFindsFlag)
forceOverwrite := c.Bool(forceFlag)
return replace(fi, search, replaceWith, skip, forceOverwrite, dryRun)
}
func mergeParts(fi os.FileInfo, regularExpression, deleteText string, forceOverwrite, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
if regularExpression == "" {
regularExpression = "([a-z]+)"
} else {
re := strings.Replace(strings.Replace(regularExpression, "(", "", -1), ")", "", -1)
if len(re) < len(regularExpression)-2 {
return errors.New("wrong regular expression received")
}
if len(re) == len(regularExpression) {
regularExpression = `(` + regularExpression + `)`
}
}
r, err := regexp.Compile(`-(\d{1,2})(` + regularExpression + `(-[a-z]+\d*)*)`)
if err != nil {
return err
}
matches := r.FindAllStringSubmatch(basePath, -1)
var (
sum int
extra = make([]string, len(matches))
)
for i := len(matches) - 1; i >= 0; i-- {
m := matches[i]
basePath = basePath[:len(basePath)-len(m[0])]
s, err := strconv.ParseInt(m[1], 10, 32)
if err != nil {
return err
}
sum += int(s)
extra[i] = m[2]
l.Printf("base: %s", basePath)
l.Printf("extra: %#v", extra)
l.Printf("matches: %#v", m)
l.Printf("sum: %d", sum)
l.Println()
}
newPath := fmt.Sprintf("%s-%d%s%s", basePath, sum, strings.Join(extra, "-"), ext)
if deleteText != "" {
newPath = strings.Replace(newPath, deleteText, "", 1)
}
if dryRun {
l.Printf(`%q -> %q`, filePath, newPath)
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) mergeParts(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
regularExpression := c.String(regexpFlag)
deleteText := c.String(deleteTextFlag)
forceOverwrite := c.Bool(forceFlag)
return mergeParts(fi, regularExpression, deleteText, forceOverwrite, dryRun)
}
func deleteRegexp(fi os.FileInfo, regularExpression string, regexpGroup, skipFinds, maxCount int, forceOverwrite, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
if regularExpression == "" {
regularExpression = `-\d+[a-z]+`
}
r, err := regexp.Compile(regularExpression)
if err != nil {
return err
}
matches := r.FindAllStringSubmatch(basePath, -1)
l.Printf("basePath: %s", basePath)
l.Printf("matches: %#v", matches)
if len(matches) == 0 {
return errors.New("no matches")
}
matches = matches[skipFinds:]
for i, m := range matches {
if maxCount > 0 && i >= maxCount {
break
}
basePath = strings.Replace(basePath, m[regexpGroup], "", 1)
}
newPath := basePath + ext
if dryRun {
l.Printf(`%q -> %q`, filePath, newPath)
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) deleteRegexp(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
regularExpression := c.String(regexpFlag)
forceOverwrite := c.Bool(forceFlag)
regexpGroup := c.Int(regexpGroupFlag)
skipFinds := c.Int(skipFindsFlag)
maxCount := c.Int(maxCountFlag)
return deleteRegexp(fi, regularExpression, regexpGroup, skipFinds, maxCount, forceOverwrite, dryRun)
}
func deleteParts(fi os.FileInfo, partsToDelete []int, fromBack, forceOverwrite, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
parts := strings.Split(basePath, "-")
m := make(map[int]struct{}, len(partsToDelete))
for _, p := range partsToDelete {
p2 := p - 1
if fromBack {
p2 = len(parts) - p
}
m[p2] = struct{}{}
}
newParts := make([]string, 0, len(parts))
for i := 0; i < len(parts); i++ {
if _, ok := m[i]; !ok {
newParts = append(newParts, parts[i])
}
}
newPath := strings.Join(newParts, "-") + ext
if dryRun {
l.Printf(`%q -> %q`, filePath, newPath)
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) deleteParts(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
forceOverwrite := c.Bool(forceFlag)
fromBack := c.Bool(fromBackFlag)
strList := strings.Split(args[0], ",")
partsToDelete := make([]int, 0, len(strList))
for _, str := range strList {
num, err := strconv.ParseInt(str, 10, 32)
if err != nil {
panic(err)
}
partsToDelete = append(partsToDelete, int(num))
}
return deleteParts(fi, partsToDelete, fromBack, forceOverwrite, dryRun)
}
func addNumber(fi os.FileInfo, regularExpression string, numberToAdd int64, regexpGroup, skipFinds, maxCount int, forceOverwrite, dryRun bool) error {
filePath := fi.Name()
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}
if regularExpression == "" {
regularExpression = `-(\d+)[a-z]+`
regexpGroup = 1
}
r, err := regexp.Compile(regularExpression)
if err != nil {
return err
}
matches := r.FindAllStringSubmatch(basePath, -1)
l.Printf("basePath: %s", basePath)
l.Printf("matches: %#v", matches)
if len(matches) == 0 {
return errors.New("no matches")
}
matches = matches[skipFinds:]
for i, m := range matches {
if maxCount > 0 && i >= maxCount {
break
}
numberFound, err := strconv.ParseInt(m[regexpGroup], 10, 32)
if err != nil {
return err
}
n1 := strconv.Itoa(int(numberFound))
n2 := strconv.Itoa(int(numberFound + numberToAdd))
replaceWith := strings.Replace(m[0], n1, n2, 1)
basePath = strings.Replace(basePath, m[0], replaceWith, 1)
}
newPath := basePath + ext
if dryRun {
l.Printf(`%q -> %q`, filePath, newPath)
return nil
}
return safeRename(filePath, newPath, forceOverwrite)
}
func (a App) addNumber(c *cli.Context, args []string, fi os.FileInfo, dryRun bool) error {
regularExpression := c.String(regexpFlag)
forceOverwrite := c.Bool(forceFlag)
regexpGroup := c.Int(regexpGroupFlag)
skipFinds := c.Int(skipFindsFlag)
maxCount := c.Int(maxCountFlag)
numberToAdd, err := strconv.ParseInt(args[0], 10, 32)
if err != nil {
return err
}
return addNumber(fi, regularExpression, numberToAdd, regexpGroup, skipFinds, maxCount, forceOverwrite, dryRun)
}
func insertBefore(fi os.FileInfo, regularExpression, insertText string, skipDuplicate, skipDashPrefix, forceOverwrite, dryRun bool) error {
filePath := fi.Name()
if regularExpression == "" {
regularExpression = "\\d+[a-z]+"
}
if skipDuplicate && strings.Contains(filePath, insertText) {
l.Printf(`skipping as duplicate is found. needle: %q, haystack: %q`, insertText, filePath)
return nil
}
basePath := filepath.Base(filePath)
ext := filepath.Ext(filePath)
if ext != "" {
basePath = basePath[:len(basePath)-len(ext)]
}