-
Notifications
You must be signed in to change notification settings - Fork 18
/
search-replace.go
200 lines (163 loc) Β· 3.88 KB
/
search-replace.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
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"os"
"regexp"
"strconv"
"sync"
"unsafe"
)
const (
searchRe = `s:\d+:\\\".*?\\\";`
replaceRe = `s:\d+:\\\"(.*?)\\\";`
badInputRe = `\w:\d+:`
inputRe = `^[A-Za-z0-9_\-\.:/]+$`
minInLength = 4
minOutLength = 2
version = "0.0.6-dev"
)
var (
search = regexp.MustCompile(searchRe)
replace = regexp.MustCompile(replaceRe)
input = regexp.MustCompile(inputRe)
bad = regexp.MustCompile(badInputRe)
)
// Replacement has two fields (both byte slices): "From" & "To"
type Replacement struct {
From []byte
To []byte
}
func main() {
versionFlag := flag.Bool("version", false, "Show version information")
flag.Parse()
if *versionFlag {
fmt.Printf("go-search-replace version %s\n", version)
os.Exit(0)
return
}
if len(os.Args) < 3 {
fmt.Fprintln(os.Stderr, "Usage: search-replace <from> <to>")
os.Exit(1)
return
}
var replacements []*Replacement
args := os.Args[1:]
if len(args)%2 > 0 {
fmt.Fprintln(os.Stderr, "All replacements must have a <from> and <to> value")
os.Exit(1)
return
}
var from, to string
for i := 0; i < len(args)/2; i++ {
from = args[i*2]
if !validInput(from, minInLength) {
fmt.Fprintln(os.Stderr, "Invalid <from> URL, minimum length is 4")
os.Exit(2)
return
}
to = args[(i*2)+1]
if !validInput(to, minOutLength) {
fmt.Fprintln(os.Stderr, "Invalid <to>, minimum length is 2")
os.Exit(3)
return
}
replacements = append(replacements, &Replacement{
From: []byte(from),
To: []byte(to),
})
}
var wg sync.WaitGroup
lines := make(chan chan []byte, 10)
wg.Add(1)
go func() {
defer wg.Done()
r := bufio.NewReaderSize(os.Stdin, 2*1024*1024)
for {
line, err := r.ReadBytes('\n')
if err != nil {
if err == io.EOF {
if 0 == len(line) {
break
}
} else {
fmt.Fprintln(os.Stderr, err.Error())
break
}
}
wg.Add(1)
ch := make(chan []byte)
lines <- ch
go func(line *[]byte) {
defer wg.Done()
line = replaceAndFix(line, replacements)
ch <- *line
}(&line)
}
}()
go func() {
wg.Wait()
close(lines)
}()
for line := range lines {
fmt.Print(unsafeGetString(<-line))
}
}
func replaceAndFix(line *[]byte, replacements []*Replacement) *[]byte {
for _, replacement := range replacements {
if !bytes.Contains(*line, replacement.From) {
continue
}
// Find/replace from->to
*line = bytes.Replace(*line, replacement.From, replacement.To, -1)
// Fix serialized string lengths
*line = search.ReplaceAllFunc(*line, func(match []byte) []byte {
// Skip fixing if we didn't replace anything
if !bytes.Contains(match, replacement.To) {
return match
}
return fix(&match)
})
}
return line
}
func fix(match *[]byte) []byte {
parts := replace.FindSubmatch(*match)
if len(parts) != 2 {
// This looks wrong, don't touch anything
return *match
}
// Get string length - number of escaped characters and avoid double counting escaped \
length := strconv.Itoa(len(parts[1]) - (bytes.Count(parts[1], []byte(`\`)) - bytes.Count(parts[1], []byte(`\\`))))
// Allocate enough memory for the string so appending won't resize it
// length of the string +
// length of constant characters +
// number of digits in the "length" component
replaced := make([]byte, 0, len(parts[1])+8+len(length))
// Build the string
replaced = append(replaced, []byte("s:")...)
replaced = append(replaced, []byte(length)...)
replaced = append(replaced, ':')
replaced = append(replaced, []byte("\\\"")...)
replaced = append(replaced, parts[1]...)
replaced = append(replaced, []byte("\\\";")...)
return replaced
}
func validInput(in string, length int) bool {
if len(in) < length {
return false
}
if !input.MatchString(in) {
return false
}
if bad.MatchString(in) {
return false
}
return true
}
func unsafeGetString(bs []byte) string {
return *(*string)(unsafe.Pointer(&bs))
}