-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
241 lines (197 loc) · 5.04 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
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"github.com/iancoleman/strcase"
flag "github.com/spf13/pflag"
)
const Version string = "v0.1.2"
type CLI struct {
outStream, errStream io.Writer
}
type Substitution struct {
re *regexp.Regexp
to string
}
func getAllFiles(paths []string) ([]string, error) {
var args []string
args = append(args, "ls-files")
args = append(args, "-z")
args = append(args, paths...)
cmd := exec.Command("git", args...)
out, err := cmd.Output()
exitCode := cmd.ProcessState.ExitCode()
if exitCode != 1 && err != nil {
return []string{}, err
}
lines := strings.Split(string(out), "\x00")
return lines, nil
}
func runSubstitionsAndRenames(substitutions map[string]Substitution, rename bool, path string) error {
if path == "" {
return nil
}
info, err := os.Stat(path)
if err != nil {
return err
}
if info.IsDir() {
return err
}
content, err := ioutil.ReadFile(path)
if err != nil {
return err
}
replaced := false
for _, sub := range substitutions {
if sub.re.Match(content) {
replaced = true
content = sub.re.ReplaceAll(content, []byte(sub.to))
}
}
if replaced {
ioutil.WriteFile(path, content, os.ModePerm)
}
if rename {
for _, sub := range substitutions {
// TODO PERF
newpath := sub.re.ReplaceAllString(path, sub.to)
if newpath != path {
os.MkdirAll(filepath.Dir(newpath), os.ModePerm)
os.Rename(path, newpath)
}
}
}
return nil
}
func getMaxProcs() (int, error) {
var maxProcs int
mp := os.Getenv("GIT_GSUB_MAX_PROCS")
if mp == "" {
maxProcs = 100
} else {
i, err := strconv.Atoi(mp)
if err != nil {
return 0, err
}
maxProcs = i
}
return maxProcs, nil
}
func ToRubyDirectory(str string) string {
result := strcase.ToSnake(str)
return strings.Replace(result, "::", "/", -1)
}
func ToRubyModule(str string) string {
result := strcase.ToCamel(str)
return strings.Replace(result, "/", "::", -1)
}
func addSub(substitutions *map[string]Substitution, from string, to string, conv func(string) string) {
f := conv(from)
t := conv(to)
(*substitutions)[f] = Substitution{regexp.MustCompile(f), t}
}
func (cli *CLI) Run(_args []string) int {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
flag.CommandLine.SortFlags = false
var snake = flag.Bool("snake", false, "Substitute snake-cased expressions")
var kebab = flag.Bool("kebab", false, "Substitute kebab-cased expressions")
var camel = flag.Bool("camel", false, "Substitute (upper) camel-cased expressions")
var upperCamel = flag.Bool("upper-camel", false, "Substitute upper-camel-cased expressions")
var lowerCamel = flag.Bool("lower-camel", false, "Substitute lower-camel-cased expressions")
var all = flag.BoolP("all", "a", false, "Substitute (snake|kebab|camel)-cased expressions")
var ruby = flag.Bool("ruby", false, "Substitute Ruby module and directory expressions")
var rename = flag.BoolP("rename", "r", false, "Rename files with expression")
var fgrep = flag.BoolP("fgrep", "F", false, "Interpret given pattern as a fixed string")
var version = flag.BoolP("version", "v", false, "Show version")
flag.CommandLine.Parse(_args)
flag.CommandLine.SetOutput(cli.errStream)
args := flag.Args()
if *version {
fmt.Fprintln(cli.outStream, Version)
return 0
}
if len(args) < 2 {
fmt.Fprintf(cli.errStream, "Usage git gsub [options] FROM TO [PATHS]\n")
fmt.Fprintf(cli.errStream, "\nOptions:\n")
fmt.Fprintf(cli.errStream, flag.CommandLine.FlagUsages())
return 1
}
rawFrom := args[0]
if *fgrep {
rawFrom = regexp.QuoteMeta(rawFrom)
}
to := args[1]
var targetPaths []string
if len(args) > 2 {
targetPaths = args[2:]
}
substitutions := map[string]Substitution{}
addSub(&substitutions, rawFrom, to, func(x string) string { return x })
if *snake || *all {
addSub(&substitutions, rawFrom, to, strcase.ToSnake)
}
if *kebab || *all {
addSub(&substitutions, rawFrom, to, strcase.ToKebab)
}
if *camel || *upperCamel || *all {
addSub(&substitutions, rawFrom, to, strcase.ToCamel)
}
if *lowerCamel || *all {
addSub(&substitutions, rawFrom, to, strcase.ToLowerCamel)
}
if *ruby {
addSub(&substitutions, rawFrom, to, ToRubyDirectory)
addSub(&substitutions, rawFrom, to, ToRubyModule)
}
files, err := getAllFiles(targetPaths)
if err != nil {
fmt.Fprint(cli.errStream, err)
return 1
}
maxProcs, err := getMaxProcs()
if err != nil {
fmt.Fprint(cli.errStream, err)
return 1
}
cn := make(chan bool, maxProcs)
errCn := make(chan error, maxProcs)
var wg sync.WaitGroup
for _, path := range files {
wg.Add(1)
go func(path_ string) {
cn <- true
err := runSubstitionsAndRenames(substitutions, *rename, path_)
if err != nil {
errCn <- err
}
<-cn
wg.Done()
}(path)
}
wg.Wait()
close(errCn)
failed := false
for err := range errCn {
fmt.Fprint(cli.errStream, err)
failed = true
}
if failed {
return 1
} else {
return 0
}
}
func main() {
cli := &CLI{outStream: os.Stdout, errStream: os.Stderr}
exitcode := cli.Run(os.Args[1:])
os.Exit(exitcode)
}