-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreplace_diffs_in_files.go
More file actions
279 lines (265 loc) · 7.25 KB
/
Copy pathreplace_diffs_in_files.go
File metadata and controls
279 lines (265 loc) · 7.25 KB
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
// -----------------------------------------------------------------------------
// CMDX Utilities Suite cmdx/[replace_diffs_in_files.go]
// (c) balarabe@protonmail.com License: GPLv3
// -----------------------------------------------------------------------------
package main
import (
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"github.com/balacode/zr"
)
// DebugReplaceDiffsInFiles
//
// # Command Handler
// replaceDiffsInFiles(cmd Command, args []string)
//
// # Subfunctions
// replaceDiffsInFilesM struct
// (M replaceDiffsInFilesM) getFindRepls(
// configLines []string,
// ) (ret []FindReplLines)
// (M replaceDiffsInFilesM) replaceFileAsync(
// task *sync.WaitGroup,
// changesAtomic *int32,
// filename string,
// lines []string,
// findRepls []FindReplLines,
// )
// (M replaceDiffsInFilesM) trimBlankLines(lines []string) []string
// DebugReplaceDiffsInFiles displays arguments and the
// return value to the console, when set to true
const DebugReplaceDiffsInFiles = false
// replaceDiffsInFilesM joins all subfunctions used by
// replaceDiffsInFiles(), so that their names don't
// clutter the project's namespace.
type replaceDiffsInFilesM struct{}
// -----------------------------------------------------------------------------
// # Command Handler
// replaceDiffsInFiles _ _
func replaceDiffsInFiles(cmd Command, args []string) {
if len(args) != 1 {
env.Println("requires <command-file> parameter")
return
}
var (
divider = strings.Repeat("-", 80)
configFile = args[0]
pathExtsMap = map[string][]FindReplLines{}
M replaceDiffsInFilesM
findRepls = M.getFindRepls(env.ReadFileLines(configFile))
err error
)
configFile, err = filepath.Abs(configFile)
env.Println(divider)
if err != nil {
env.Println("Failed getting path of", configFile, "due to:", err)
return
}
// group batches of items by their path and extensions (using a map)
for _, it := range findRepls {
// join path and extensions list to give a map key
key := it.Path + "\n" + strings.Join(it.Exts, "\n")
pathExtsMap[key] = append(pathExtsMap[key], it)
}
env.Println(divider)
//
// for each file in group, call replaceFileAsync() with applicable items
var task sync.WaitGroup
var changesAtomic int32
for key, items := range pathExtsMap {
var (
ar = strings.Split(key, "\n") // read details back from key
path = ar[0]
exts = ar[1:]
fileList = env.GetFilePaths(path, exts...)
)
for _, filename := range fileList {
if filename == configFile {
continue // must not overwrite the config file itself
}
data, done := env.ReadFile(filename)
if !done {
continue
}
lines := strings.Split(string(data), "\n")
task.Add(1)
go M.replaceFileAsync(&task, &changesAtomic,
filename, lines, items)
}
}
task.Wait()
//
// report total number of changes
n := atomic.LoadInt32(&changesAtomic)
if n == 0 {
env.Println("NO CHANGES")
} else {
env.Println(n, "TOTAL")
}
}
// -----------------------------------------------------------------------------
// # Subfunctions
// getFindRepls _ _
func (M replaceDiffsInFilesM) getFindRepls(
configLines []string,
) (ret []FindReplLines) {
var (
mark = DefaultMark
path = DefaultPath
exts = DefaultExts
undo = false
caseMode = zr.MatchCase
findGroup []string
replGroup []string
)
for _, line := range configLines {
// lines that begin with the marker are configuration or comments:
if strings.HasPrefix(line, mark) {
line = strings.TrimSpace(line[len(mark):])
switch {
case strings.HasPrefix(line, "path"):
path = strings.TrimSpace(line[5:])
env.Println("SET PATH:", path)
//
case strings.HasPrefix(line, "exts"):
exts = strings.Fields(line[5:])
env.Println("SET EXTS:", exts)
//
case strings.HasPrefix(line, "mark"):
mark = strings.TrimSpace(line[5:])
if mark == "" {
mark = DefaultMark
}
env.Println("SET MARK:", mark)
//
// booleans:
case hasConfigBool(line, "case"):
match, _ := getConfigBool(line, "case")
env.Println("SET CASE:", match)
if match {
caseMode = zr.MatchCase
} else {
caseMode = zr.IgnoreCase
}
//
case hasConfigBool(line, "undo"):
undo, _ = getConfigBool(line, "undo")
env.Println("SET UNDO:", undo)
//
}
continue
}
switch {
case strings.HasPrefix(line, "-"): // find lines
findGroup = append(findGroup, line[1:])
//
case strings.HasPrefix(line, "+"): // replace with lines
replGroup = append(replGroup, line[1:])
//
case len(findGroup) > 0:
it := FindReplLines{
Path: path,
Exts: exts,
FindLines: M.trimBlankLines(findGroup),
ReplLines: M.trimBlankLines(replGroup),
CaseMode: caseMode,
}
if undo {
it.FindLines, it.ReplLines = it.ReplLines, it.FindLines
}
ret = append(ret, it)
findGroup = []string{}
replGroup = []string{}
}
}
if DebugReplaceDiffsInFiles {
pl := env.Println
pl("REPLACED DIFFS:", len(ret), "ITEM(S):")
for i, it := range ret {
pl("ITEM", i)
zr.DV("Path:", it.Path)
zr.DV("Exts:", it.Exts)
zr.DV("CaseMode", it.CaseMode)
zr.DV("FindLines:", it.FindLines)
zr.DV("ReplLines:", it.ReplLines)
}
}
return ret
}
// replaceFileAsync _ _
func (M replaceDiffsInFilesM) replaceFileAsync(
task *sync.WaitGroup,
changesAtomic *int32,
filename string,
lines []string,
findRepls []FindReplLines,
) {
if task != nil {
defer task.Done()
}
changes := 0
for _, caseMode := range []zr.CaseMode{zr.MatchCase, zr.IgnoreCase} {
var finds, repls [][]string
for _, it := range findRepls {
if it.CaseMode != caseMode {
continue
}
finds = append(finds, it.FindLines)
repls = append(repls, it.ReplLines)
}
var n int
lines, n = replaceLines(lines, finds, repls, caseMode)
changes += n
}
if changes == 0 {
return
}
if !M.writeFileLines(filename, lines) {
return // auto-logs error
}
env.Println(changes, "replacement in", filename)
atomic.AddInt32(changesAtomic, int32(changes))
}
// trimBlankLines removes leading and trailing blank lines in a
// string slice. Does not remove blank lines between non-blank lines.
// Lines that only contain white spaces are treated as blank lines.
func (M replaceDiffsInFilesM) trimBlankLines(lines []string) []string {
// trim leading blank lines
for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" {
lines = lines[1:]
}
// trim trailing blank lines
for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" {
lines = lines[:len(lines)-1]
}
return lines
}
// writeFileLines writes lines to filename using UNIX (LF) line endings.
func (M replaceDiffsInFilesM) writeFileLines(
filename string,
lines []string,
) bool {
filename = strings.TrimSpace(filename)
if filename == "" {
env.Println("No file name specified")
return false
}
s := strings.Join(lines, "\n")
s = strings.ReplaceAll(s, "\r\n", "\n")
//
// terminate the last line with a newline
if !strings.HasSuffix(s, "\n") {
s += "\n"
}
// save the file
err := os.WriteFile(filename, []byte(s), 0644)
if err != nil {
env.Println("Failed writing", filename, "due to:", err)
return false
}
return true
}
// end