-
Notifications
You must be signed in to change notification settings - Fork 1
/
replace_strings_in_files.go
285 lines (271 loc) · 6.62 KB
/
replace_strings_in_files.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
// -----------------------------------------------------------------------------
// CMDX Utilities Suite cmdx/[replace_strings_in_files.go]
// (c) [email protected] License: GPLv3
// -----------------------------------------------------------------------------
package main
import (
"fmt"
"path/filepath"
"strings"
"sync"
"github.com/balacode/zr"
)
// # Command Handler
// replaceStringsInFiles(cmd Command, args []string)
//
// # Support (File Scope)
// replaceAsync(task *sync.WaitGroup, cmd ReplCmd)
// replaceFileAsync(
// task *sync.WaitGroup,
// filename string,
// content string,
// items []ReplItem,
// )
// -----------------------------------------------------------------------------
// # Command Handler
// replConfig _ _
type replConfig struct {
configFile string
path string
exts []string
mark string
undo bool
caseMode zr.CaseMode
wordMode zr.WordMode
}
// replaceStringsInFiles _ _
func replaceStringsInFiles(cmd Command, args []string) {
if len(args) != 1 {
env.Println("requires <command-file> parameter")
return
}
cfg := replConfig{
configFile: args[0],
path: DefaultPath,
exts: DefaultExts,
mark: DefaultMark,
undo: false,
caseMode: zr.MatchCase,
wordMode: zr.IgnoreWord,
}
var configLines []string
var err error
cfg.configFile, err = filepath.Abs(cfg.configFile)
if err != nil {
env.Println("command file path error: ", cfg.configFile)
return
}
env.Println("FILE:", cfg.configFile)
{
data, done := env.ReadFile(cfg.configFile)
if !done {
return
}
s := string(data)
s = strings.TrimSpace(s)
s = strings.ReplaceAll(s, "\r\n", "\n")
for strings.Contains(s, "\n\n") {
s = strings.ReplaceAll(s, "\n\n", "\n")
}
configLines = strings.Split(s, "\n")
//
// add a blank line to initiate replacement
configLines = append(configLines, "")
}
//
// each item:
items := []ReplItem{}
env.Println(strings.Repeat("-", 80))
for lineNo, s := range configLines {
s = strings.TrimSpace(s)
//
// blank lines initiate replacement:
if s == "" && len(items) > 0 {
env.Println(strings.Repeat("-", 80))
var task sync.WaitGroup
task.Add(1)
cmd := ReplCmd{
Path: cfg.path,
Exts: cfg.exts,
Mark: cfg.mark,
Items: items,
}
go replaceAsync(&task, cfg.configFile, cmd)
task.Wait()
items = []ReplItem{}
continue
}
// skip lines that don't contain marker:
if !strings.Contains(s, cfg.mark) {
continue
}
// lines that begin with the marker are configuration or comments:
if strings.HasPrefix(s, cfg.mark) {
setReplConfig(s, &cfg)
continue
}
// lines that contain but don't begin with the marker are replacements
i := strings.Index(s, cfg.mark)
if i > 0 {
item := ReplItem{
Find: strings.TrimSpace(s[:i]),
Repl: strings.TrimSpace(s[i+len(cfg.mark):]),
CaseMode: cfg.caseMode,
WordMode: cfg.wordMode,
}
if cfg.undo {
item.Find, item.Repl = item.Repl, item.Find
}
if lineNo < ShownResultsLimit {
env.Println(
"FIND:", item.Find,
"REPL:", item.Repl,
"CASE:", item.CaseMode,
"WORD:", item.WordMode,
)
} else if lineNo == ShownResultsLimit {
env.Println("+", len(configLines)-lineNo, "more")
}
items = append(items, item)
}
}
}
// -----------------------------------------------------------------------------
// # Support (File Scope)
// getBool _ _
func getBool(s, keyword string) (value, exists bool) {
s = strings.ToUpper(s)
keyword = strings.ToUpper(keyword)
for i, ar := range [][]string{
{"0", "FALSE", "OFF", "IGNORE"},
{"1", "TRUE", "ON", "MATCH"},
} {
for _, match := range ar {
if strings.HasPrefix(s, keyword+" "+match) {
return i == 1, true
}
}
}
return false, false
}
// hasBool _ _
func hasBool(s, keyword string) (ret bool) {
_, ret = getBool(s, keyword)
return ret
}
// replaceAsync _ _
func replaceAsync(task *sync.WaitGroup, configFile string, cmd ReplCmd) {
// TODO: you can remove configFile arg, and add an if condition in caller
if task == nil {
zr.Error("") // TODO: add error message (replaceAsync())
}
if task != nil {
defer task.Done()
}
for _, filename := range env.GetFilePaths(cmd.Path, cmd.Exts...) {
data, done := env.ReadFile(filename)
if !done {
continue
}
if task != nil {
task.Add(1)
}
go replaceFileAsync(task, configFile, filename, string(data), cmd.Items)
}
}
// replaceFileAsync _ _
func replaceFileAsync(
task *sync.WaitGroup,
configFile string,
filename string,
content string,
items []ReplItem,
) {
if task != nil {
defer task.Done()
}
if filename == configFile {
return
}
var (
oldContent = content
max = 100 / float64(len(items))
percent = ""
newContent = content
)
for _, cm := range []zr.CaseMode{zr.MatchCase, zr.IgnoreCase} {
for _, wm := range []zr.WordMode{zr.MatchWord, zr.IgnoreWord} {
var finds, repls []string
for i, it := range items {
if it.CaseMode != cm || it.WordMode != wm {
continue
}
finds = append(finds, it.Find)
repls = append(repls, it.Repl)
if ShowProgressIndicator {
pc := fmt.Sprintf("c:%v w:%v %1.1f%%",
cm, wm, float64(int(max*float64(i)*10))/10)
if percent != pc {
env.Print(strings.Repeat("\b", len(percent)), pc)
percent = pc
}
}
}
newContent = zr.ReplaceMany(newContent, finds, repls, -1, cm, wm)
}
content = newContent
}
if ShowProgressIndicator {
env.Print(strings.Repeat("\b", len(percent)))
}
if content == oldContent {
return
}
if !env.WriteFile(filename, []byte(content)) {
return
}
env.Println("changed ", filename)
}
// setReplConfig _ _
func setReplConfig(s string, cfg *replConfig) {
s = strings.TrimSpace(s[len(cfg.mark):])
switch {
case strings.HasPrefix(s, "path"):
cfg.path = strings.TrimSpace(s[5:])
env.Println("SET PATH:", cfg.path)
//
case strings.HasPrefix(s, "exts"):
cfg.exts = strings.Fields(s[5:])
env.Println("SET EXTS:", cfg.exts)
//
case strings.HasPrefix(s, "mark"):
cfg.mark = strings.TrimSpace(s[5:])
if cfg.mark == "" {
cfg.mark = DefaultMark
}
env.Println("SET MARK:", cfg.mark)
//
case hasBool(s, "case"):
match, _ := getBool(s, "case")
env.Println("SET CASE:", match)
if match {
cfg.caseMode = zr.MatchCase
} else {
cfg.caseMode = zr.IgnoreCase
}
//
case hasBool(s, "undo"):
cfg.undo, _ = getBool(s, "undo")
env.Println("SET UNDO:", cfg.undo)
//
case hasBool(s, "word"):
match, _ := getBool(s, "word")
env.Println("SET WORD:", match)
if match {
cfg.wordMode = zr.MatchWord
} else {
cfg.wordMode = zr.IgnoreWord
}
}
}
// end