-
Notifications
You must be signed in to change notification settings - Fork 37
/
main.go
862 lines (710 loc) · 21.3 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
package main
import (
"crypto/md5"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/jessevdk/go-flags"
"github.com/kr/text"
"github.com/laurent22/go-trash"
uuid "github.com/nu7hatch/gouuid"
)
var flagParser_ *flags.Parser
var newline_ string
const (
APPNAME = "massren"
LINE_LENGTH = 80
KIND_RENAME = 1
KIND_DELETE = 2
)
type CommandLineOptions struct {
DryRun bool `short:"n" long:"dry-run" description:"Don't rename anything but show the operation that would have been performed."`
Verbose bool `short:"v" long:"verbose" description:"Enable verbose output."`
Config bool `short:"c" long:"config" description:"Set or list configuration values. For more info, type: massren --config --help"`
Undo bool `short:"u" long:"undo" description:"Undo a rename operation. Currently delete operations cannot be undone (though files can be recovered from the trash in OSX and Windows). eg. massren --undo [path]"`
Version bool `short:"V" long:"version" description:"Displays version information."`
}
type FileAction struct {
oldPath string
newPath string
intermediatePath string
kind int
}
type DeleteOperationsFirst []*FileAction
func (a DeleteOperationsFirst) Len() int { return len(a) }
func (a DeleteOperationsFirst) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a DeleteOperationsFirst) Less(i, j int) bool { return a[i].kind == KIND_DELETE }
func NewFileAction() *FileAction {
output := new(FileAction)
output.kind = KIND_RENAME
return output
}
func (this *FileAction) FullOldPath() string {
return normalizePath(this.oldPath)
}
func (this *FileAction) FullNewPath() string {
return normalizePath(filepath.Join(filepath.Dir(this.oldPath), filepath.Dir(this.newPath), filepath.Base(this.newPath)))
}
func (this *FileAction) String() string {
return fmt.Sprintf("Kind: %d; Old: \"%s\"; New: \"%s\"", this.kind, this.oldPath, this.newPath)
}
func stringHash(s string) string {
h := md5.New()
io.WriteString(h, s)
return fmt.Sprintf("%x", h.Sum(nil))
}
func tempFolder() string {
output := filepath.Join(profileFolder(), "temp")
err := os.MkdirAll(output, PROFILE_PERM)
if err != nil {
panic(err)
}
return output
}
func criticalError(err error) {
logError("%s", err)
logInfo("Run '%s --help' for usage\n", APPNAME)
os.Exit(1)
}
func watchFile(filePath string) error {
initialStat, err := os.Stat(filePath)
if err != nil {
return err
}
for {
stat, err := os.Stat(filePath)
if err != nil {
return err
}
if stat.Size() != initialStat.Size() || stat.ModTime() != initialStat.ModTime() {
return nil
}
time.Sleep(1 * time.Second)
}
}
func newline() string {
if newline_ != "" {
return newline_
}
if runtime.GOOS == "windows" {
newline_ = "\r\n"
} else {
newline_ = "\n"
}
return newline_
}
func guessEditorCommand() (string, error) {
switch runtime.GOOS {
case "windows":
// The default editor for a given file extension is stored in a registry key: HKEY_CLASSES_ROOT/.txt/ShellNew/ItemName
// See this for hwo to in GO: http://stackoverflow.com/questions/18425465/enumerating-registry-values-in-go-golang
return "notepad.exe", nil
default: // assumes a POSIX system
// Get it from EDITOR environment variable, if present
editorEnv := strings.Trim(os.Getenv("EDITOR"), "\n\t\r ")
if editorEnv != "" {
return editorEnv, nil
}
// Otherwise, try to detect various text editors
editors := []string{
"nano",
"vim",
"emacs",
"vi",
"ed",
}
for _, editor := range editors {
err := exec.Command("type", editor).Run()
if err == nil {
return editor, nil
} else {
err = exec.Command("sh", "-c", "type "+editor).Run()
if err == nil {
return editor, nil
}
}
}
}
return "", errors.New("could not guess editor command")
}
// Returns the executable path and arguments
func parseEditorCommand(editorCmd string) (string, []string, error) {
var args []string
state := "start"
current := ""
quote := "\""
for i := 0; i < len(editorCmd); i++ {
c := editorCmd[i]
if state == "quotes" {
if string(c) != quote {
current += string(c)
} else {
args = append(args, current)
current = ""
state = "start"
}
continue
}
if c == '"' || c == '\'' {
state = "quotes"
quote = string(c)
continue
}
if state == "arg" {
if c == ' ' || c == '\t' {
args = append(args, current)
current = ""
state = "start"
} else {
current += string(c)
}
continue
}
if c != ' ' && c != '\t' {
state = "arg"
current += string(c)
}
}
if state == "quotes" {
return "", []string{}, errors.New(fmt.Sprintf("Unclosed quote in command line: %s", editorCmd))
}
if current != "" {
args = append(args, current)
}
if len(args) <= 0 {
return "", []string{}, errors.New("Empty command line")
}
if len(args) == 1 {
return args[0], []string{}, nil
}
return args[0], args[1:], nil
}
func editFile(filePath string) error {
var err error
editorCmd := config_.String("editor")
if editorCmd == "" {
editorCmd, err = guessEditorCommand()
setupInfo := fmt.Sprintf("Run `%s --config editor \"name-of-editor\"` to set up the editor. eg. `%s --config editor \"vim\"`", APPNAME, APPNAME)
if err != nil {
criticalError(errors.New(fmt.Sprintf("No text editor defined in configuration, and could not guess a text editor.\n%s", setupInfo)))
} else {
logInfo("No text editor defined in configuration. Using \"%s\" as default.\n%s", editorCmd, setupInfo)
}
}
commandString, args, err := parseEditorCommand(editorCmd)
if err != nil {
return err
}
args = append(args, filePath)
// Run the properly formed command
cmd := exec.Command(commandString, args[0:]...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err = cmd.Run()
if err != nil {
return err
}
return nil
}
func filePathsFromArgs(args []string, includeDirectories bool) ([]string, error) {
var output []string
var err error
if len(args) == 0 || args[0] == "." {
output, err = filepath.Glob("*")
if err != nil {
return []string{}, err
}
} else {
for _, arg := range args {
if strings.Index(arg, "*") < 0 && strings.Index(arg, "?") < 0 {
output = append(output, arg)
continue
}
matches, err := filepath.Glob(arg)
if err != nil {
return []string{}, err
}
for _, match := range matches {
output = append(output, match)
}
}
}
if !includeDirectories {
var temp []string
for _, path := range output {
f, err := os.Stat(path)
if err == nil && f.IsDir() {
continue
}
temp = append(temp, path)
}
output = temp
}
sort.Strings(output)
return output, nil
}
func stripBom(s string) string {
if len(s) < 3 {
return s
}
if s[0] != 239 || s[1] != 187 || s[2] != 191 {
return s
}
return s[3:]
}
func filePathsFromString(content string) []string {
var output []string
lines := strings.Split(content, newline())
for i, line := range lines {
line := strings.Trim(line, "\n\r")
if i == 0 {
line = stripBom(line)
}
if line == "" {
continue
}
if len(line) >= 2 && line[0:2] == "//" {
continue
}
output = append(output, line)
}
return output
}
func filePathsFromListFile(filePath string) ([]string, error) {
contentB, err := ioutil.ReadFile(filePath)
if err != nil {
return []string{}, err
}
return filePathsFromString(string(contentB)), nil
}
func printHelp(subMenu string) {
var info string
if subMenu == "" {
flagParser_.WriteHelp(os.Stdout)
info = `
Examples:
Process all the files in the current directory:
% APPNAME
Process all the JPEGs in the specified directory:
% APPNAME /path/to/photos/*.jpg
Undo the changes done by the previous operation:
% APPNAME --undo /path/to/photos/*.jpg
Set VIM as the default text editor:
% APPNAME --config editor vim
List config values:
% APPNAME --config
`
} else if subMenu == "config" {
info = `
Config commands:
Set a value:
% APPNAME --config <name> <value>
List all the values:
% APPNAME --config
Delete a value:
% APPNAME --config <name>
Possible key/values:
editor: The editor to use when editing the list of files.
Default: auto-detected.
use_trash: Whether files should be moved to the trash/recycle bin
after deletion. Possible values: 0 or 1. Default: 1.
include_directories: Whether to include the directories in the file buffer.
Possible values: 0 or 1. Default: 1.
include_header: Whether to show the header in the file buffer. Possible
values: 0 or 1. Default: 1.
Examples:
Set Sublime as the default text editor:
% APPNAME --config editor "subl -n -w"
Don't move files to trash:
% APPNAME --config use_trash 0
`
}
fmt.Println(strings.Replace(info, "APPNAME", APPNAME, -1))
}
func fileActions(originalFilePaths []string, changedContent string) ([]*FileAction, error) {
if len(originalFilePaths) == 0 {
return []*FileAction{}, nil
}
lines := strings.Split(changedContent, newline())
fileIndex := 0
var actionKind int
var output []*FileAction
for i, line := range lines {
line := strings.Trim(line, "\n\r")
if i == 0 {
line = stripBom(line)
}
if line == "" {
continue
}
oldBasePath := filepath.Base(originalFilePaths[fileIndex])
newBasePath := ""
if len(line) >= 2 && line[0:2] == "//" {
// Check if it is a comment or a file being deleted.
newBasePath = strings.Trim(line[2:], " \t")
if newBasePath != strings.Trim(oldBasePath, " \t") {
// This is not a file being deleted, it's
// just a regular comment.
continue
}
newBasePath = ""
actionKind = KIND_DELETE
} else {
newBasePath = line
actionKind = KIND_RENAME
}
if actionKind == KIND_RENAME && newBasePath == oldBasePath {
// Found a match but nothing to actually rename
} else {
action := NewFileAction()
action.kind = actionKind
action.oldPath = originalFilePaths[fileIndex]
action.newPath = newBasePath
output = append(output, action)
}
fileIndex++
if fileIndex >= len(originalFilePaths) {
break
}
}
// Sanity check
if fileIndex != len(originalFilePaths) {
return []*FileAction{}, errors.New("not all files had a match")
}
// Loop through the actions and check that rename operations don't
// overwrite existing files.
for _, action := range output {
if action.kind != KIND_RENAME {
continue
}
if fileInfo1, err := os.Stat(action.FullNewPath()); err == nil {
// Destination exists. Now check if the destination is also going to be
// renamed to something else (in which case, there is no error). Also
// OK if existing destination is going to be deleted.
ok := false
for _, action2 := range output {
if action2.kind == KIND_RENAME && action2.FullOldPath() == action.FullNewPath() {
ok = true
break
}
if action2.kind == KIND_DELETE && action2.FullOldPath() == action.FullNewPath() {
ok = true
break
}
}
// Also OK if new path and old path are in fact the same file (for example if
// "/path/to/abcd" is going to be renamed to "/path/to/ABCD" on a case
// insensitive file system).
fileInfo2, err := os.Stat(action.FullOldPath())
if err != nil {
return []*FileAction{}, errors.New(fmt.Sprintf("cannot stat \"%s\"", action.FullOldPath()))
}
if os.SameFile(fileInfo1, fileInfo2) {
ok = true
}
if !ok {
return []*FileAction{}, errors.New(fmt.Sprintf("\"%s\" cannot be renamed to \"%s\": destination already exists", action.FullOldPath(), action.FullNewPath()))
}
}
}
// Loop through the actions and check that no two files are being
// renamed to the same name.
duplicateMap := make(map[string]bool)
for _, action := range output {
if action.kind != KIND_RENAME {
continue
}
if _, ok := duplicateMap[action.FullNewPath()]; ok {
return []*FileAction{}, errors.New(fmt.Sprintf("two files are being renamed to the same name: \"%s\"", action.FullNewPath()))
} else {
duplicateMap[action.FullNewPath()] = true
}
}
return output, nil
}
func deleteTempFiles() error {
tempFiles, err := filepath.Glob(filepath.Join(tempFolder(), "*"))
if err != nil {
return err
}
for _, p := range tempFiles {
os.Remove(p)
}
return nil
}
func processFileActions(fileActions []*FileAction, dryRun bool) error {
var doneActions []*FileAction
var conflictActions []*FileAction // Actions that need a conflict resolution
defer func() {
err := saveHistoryItems(doneActions)
if err != nil {
logError("Could not save history items: %s", err)
}
}()
var deleteWaitGroup sync.WaitGroup
var deleteChannel = make(chan int, 100)
useTrash := config_.BoolD("use_trash", true)
// Do delete operations first to avoid problems when file0 is renamed to
// existing file1, then file1 is deleted.
sort.Sort(DeleteOperationsFirst(fileActions))
for _, action := range fileActions {
switch action.kind {
case KIND_RENAME:
if dryRun {
logInfo("\"%s\" => \"%s\"", action.oldPath, action.newPath)
} else {
logDebug("\"%s\" => \"%s\"", action.oldPath, action.newPath)
if _, err := os.Stat(action.FullNewPath()); err == nil {
u, _ := uuid.NewV4()
action.intermediatePath = action.FullNewPath() + "-" + u.String()
conflictActions = append(conflictActions, action)
} else {
os.MkdirAll(filepath.Dir(action.FullNewPath()), 0755)
err := os.Rename(action.FullOldPath(), action.FullNewPath())
if err != nil {
return err
}
}
}
break
case KIND_DELETE:
filePath := action.FullOldPath()
if dryRun {
logInfo("\"%s\" => <Deleted>", filePath)
} else {
logDebug("\"%s\" => <Deleted>", filePath)
deleteWaitGroup.Add(1)
go func(filePath string, deleteChannel chan int, useTrash bool) {
var err error
deleteChannel <- 1
defer deleteWaitGroup.Done()
if useTrash {
_, err = trash.MoveToTrash(filePath)
} else {
err = os.RemoveAll(filePath)
}
if err != nil {
logError("%s", err)
}
<-deleteChannel
}(filePath, deleteChannel, useTrash)
}
break
default:
panic("Invalid action type")
break
}
doneActions = append(doneActions, action)
}
deleteWaitGroup.Wait()
// Conflict resolution:
// - First rename all the problem paths to an intermediate name
// - Then rename all the intermediate one to the final name
for _, action := range conflictActions {
if action.kind != KIND_RENAME {
continue
}
err := os.Rename(action.FullOldPath(), action.intermediatePath)
if err != nil {
return err
}
}
for _, action := range conflictActions {
if action.kind != KIND_RENAME {
continue
}
err := os.Rename(action.intermediatePath, action.FullNewPath())
if err != nil {
return err
}
doneActions = append(doneActions, action)
}
return nil
}
func createListFileContent(filePaths []string, includeHeader bool) string {
output := ""
header := ""
if includeHeader {
// NOTE: kr/text.Wrap returns lines separated by \n for all platforms.
// So here hard-code \n too. Later it will be changed to \r\n for Windows.
header = text.Wrap("Please change the filenames that need to be renamed and save the file. Lines that are not changed will be ignored (no file will be renamed).", LINE_LENGTH-3)
header += "\n"
header += "\n" + text.Wrap("You may delete a file by putting \"//\" at the beginning of the line. Note that this operation cannot be undone (though the file can be recovered from the trash on Windows and OSX).", LINE_LENGTH-3)
header += "\n"
header += "\n" + text.Wrap("Please do not swap the order of lines as this is what is used to match the original filenames to the new ones. Also do not delete lines as the rename operation will be cancelled due to a mismatch between the number of filenames before and after saving the file. You may test the effect of the rename operation using the --dry-run parameter.", LINE_LENGTH-3)
header += "\n"
header += "\n" + text.Wrap("Caveats: "+APPNAME+" expects filenames to be reasonably sane. Filenames that include newlines or non-printable characters for example will probably not work.", LINE_LENGTH-3)
headerLines := strings.Split(header, "\n")
temp := ""
for _, line := range headerLines {
if temp != "" {
temp += newline()
}
// If empty line we don't want white-space
if line == "" {
temp += "//"
} else {
temp += "// "
}
temp += line
}
header = temp + newline() + newline()
}
for _, filePath := range filePaths {
output += filepath.Base(filePath) + newline()
}
return header + output
}
func onExit() {
deleteTempFiles()
deleteOldHistoryItems(time.Now().Unix() - 60*60*24*7)
profileClose()
}
func main() {
minLogLevel_ = 1
// -----------------------------------------------------------------------------------
// Handle SIGINT (Ctrl + C)
// -----------------------------------------------------------------------------------
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, os.Kill)
go func() {
<-signalChan
logInfo("Operation has been aborted.")
onExit()
os.Exit(2)
}()
defer onExit()
// -----------------------------------------------------------------------------------
// Parse arguments
// -----------------------------------------------------------------------------------
var opts CommandLineOptions
flagParser_ = flags.NewParser(&opts, flags.HelpFlag|flags.PassDoubleDash)
args, err := flagParser_.Parse()
if err != nil {
t := err.(*flags.Error).Type
if t == flags.ErrHelp {
subMenu := ""
if opts.Config {
subMenu = "config"
}
printHelp(subMenu)
return
} else {
criticalError(err)
}
}
if opts.Verbose {
minLogLevel_ = 0
}
err = profileOpen()
if err != nil {
logError(fmt.Sprintf("%s", err))
}
// -----------------------------------------------------------------------------------
// Handle selected command
// -----------------------------------------------------------------------------------
var commandName string
if opts.Config {
commandName = "config"
} else if opts.Undo {
commandName = "undo"
} else if opts.Version {
commandName = "version"
} else {
commandName = "rename"
}
var commandErr error
switch commandName {
case "config":
commandErr = handleConfigCommand(&opts, args)
case "undo":
commandErr = handleUndoCommand(&opts, args)
case "version":
commandErr = handleVersionCommand(&opts, args)
}
if commandErr != nil {
criticalError(commandErr)
}
if commandName != "rename" {
return
}
filePaths, err := filePathsFromArgs(args, config_.BoolD("include_directories", true))
if err != nil {
criticalError(err)
}
if len(filePaths) == 0 {
criticalError(errors.New("no file to rename"))
}
// -----------------------------------------------------------------------------------
// Build file list
// -----------------------------------------------------------------------------------
listFileContent := createListFileContent(filePaths, config_.BoolD("include_header", true))
filenameUuid, _ := uuid.NewV4()
listFilePath := filepath.Join(tempFolder(), filenameUuid.String()+".files.txt")
ioutil.WriteFile(listFilePath, []byte(listFileContent), PROFILE_PERM)
// -----------------------------------------------------------------------------------
// Watch for changes in file list
// -----------------------------------------------------------------------------------
waitForFileChange := make(chan bool)
waitForCommand := make(chan bool)
go func(doneChan chan bool) {
defer func() {
doneChan <- true
}()
logInfo("Waiting for file list to be saved... (Press Ctrl + C to abort)")
err := watchFile(listFilePath)
if err != nil {
criticalError(err)
}
}(waitForFileChange)
// -----------------------------------------------------------------------------------
// Launch text editor
// -----------------------------------------------------------------------------------
go func(doneChan chan bool) {
defer func() {
doneChan <- true
}()
err := editFile(listFilePath)
if err != nil {
criticalError(err)
}
}(waitForCommand)
<-waitForCommand
<-waitForFileChange
// -----------------------------------------------------------------------------------
// Check that the filenames have not been changed while the list was being edited
// -----------------------------------------------------------------------------------
for _, filePath := range filePaths {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
criticalError(errors.New("Filenames have been changed or some files have been deleted or moved while the list was being edited. To avoid any data loss, the operation has been aborted. You may resume it by running the same command."))
}
}
// -----------------------------------------------------------------------------------
// Get new filenames from list file
// -----------------------------------------------------------------------------------
changedContent, err := ioutil.ReadFile(listFilePath)
if err != nil {
criticalError(err)
}
actions, err := fileActions(filePaths, string(changedContent))
if err != nil {
criticalError(err)
}
// -----------------------------------------------------------------------------------
// Process the files
// -----------------------------------------------------------------------------------
err = processFileActions(actions, opts.DryRun)
if err != nil {
criticalError(err)
}
}