-
Notifications
You must be signed in to change notification settings - Fork 6
/
file_renamer.go
127 lines (102 loc) · 2.01 KB
/
file_renamer.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
package main
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"github.com/go-git/go-billy/v5"
"github.com/h2non/filetype"
"github.com/h2non/filetype/types"
)
type fileRenamer struct {
fileSystem billy.Filesystem
stderr io.Writer
}
func newFileRenamer(fs billy.Filesystem, stderr io.Writer) *fileRenamer {
return &fileRenamer{fs, stderr}
}
func (r *fileRenamer) Rename(tr textRenamer, path string, baseDir string, verbose bool) error {
p, err := r.renamePath(tr, path, baseDir)
if err != nil {
return err
}
if p != path {
if verbose {
err := r.print("Moving", path)
if err != nil {
return err
}
}
err = r.fileSystem.Rename(path, p)
if err != nil {
return err
}
}
ok, err := r.isTextFile(p)
if err != nil {
return err
} else if !ok {
return nil
}
f, err := r.fileSystem.OpenFile(p, os.O_RDWR, 0)
if err != nil {
return err
}
defer f.Close()
bs, err := io.ReadAll(f)
if err != nil {
return err
}
bbs := []byte(tr.Rename(string(bs)))
if bytes.Equal(bs, bbs) {
return nil
}
if verbose {
err := r.print("Writing", path)
if err != nil {
return err
}
}
err = f.Truncate(0)
if err != nil {
return err
}
_, err = f.Seek(0, 0)
if err != nil {
return err
}
_, err = f.Write(bbs)
return err
}
func (r *fileRenamer) isTextFile(path string) (bool, error) {
f, err := r.fileSystem.Open(path)
if err != nil {
return false, err
}
defer f.Close()
bs := make([]byte, fileTypeDetectionBufferSize)
_, err = f.Read(bs)
if err != nil && err != io.EOF {
return false, err
}
t, err := filetype.Match(bs)
if err != nil {
return false, err
}
return t == types.Unknown, nil
}
func (r *fileRenamer) renamePath(tr textRenamer, path, baseDir string) (string, error) {
if baseDir == "" {
return path, nil
}
b, err := filepath.Rel(baseDir, path)
if err != nil {
return "", err
}
return filepath.Join(baseDir, tr.Rename(b)), nil
}
func (r *fileRenamer) print(xs ...interface{}) error {
_, err := fmt.Fprintln(r.stderr, xs...)
return err
}