Skip to content

Commit 9948814

Browse files
committed
Improved search and replace
- Fix correct way of handling case insensitve non-regex search - Added more verbose messages
1 parent a3b5274 commit 9948814

File tree

1 file changed

+22
-22
lines changed

1 file changed

+22
-22
lines changed

goreplace.go

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -98,14 +98,8 @@ func Readln(r *bufio.Reader) (string, error) {
9898

9999
// Checks if there is a match in content, based on search options
100100
func searchMatch(content string) (bool) {
101-
if opts.Regex {
102-
if opts.SearchRegex.MatchString(content) {
103-
return true
104-
}
105-
} else {
106-
if strings.Contains(content, opts.Search) {
107-
return true
108-
}
101+
if opts.SearchRegex.MatchString(content) {
102+
return true
109103
}
110104

111105
return false
@@ -117,12 +111,7 @@ func replaceText(content string) (string, bool) {
117111

118112
if searchMatch(content) {
119113
status = true
120-
121-
if opts.Regex {
122-
content = opts.SearchRegex.ReplaceAllString(content, opts.Replace)
123-
} else {
124-
content = strings.Replace(content, opts.Search, opts.Replace, -1)
125-
}
114+
content = opts.SearchRegex.ReplaceAllString(content, opts.Replace)
126115
}
127116

128117
return content, status
@@ -144,6 +133,8 @@ func writeContentToFile(filepath string, content string) {
144133
if err != nil {
145134
panic(err)
146135
}
136+
137+
logMessage(fmt.Sprintf("%s found and replaced match", filepath))
147138
}
148139
}
149140

@@ -159,18 +150,27 @@ func logError(err error) {
159150
fmt.Printf("Error: %s\n", err)
160151
}
161152

162-
// Process search option
153+
// Process search term
163154
// Compiles regexp if regexp is used
164-
func processSearch() {
155+
func processSearchTerm() {
156+
var regex string
157+
165158
if opts.Regex {
166-
regex := opts.Search
159+
regex = opts.Search
160+
} else {
161+
regex = regexp.QuoteMeta(opts.Search)
162+
}
167163

168-
if opts.IgnoreCase {
169-
regex = "(?i:" + regex + ")"
170-
}
171164

172-
opts.SearchRegex = regexp.MustCompile(regex)
165+
if opts.IgnoreCase {
166+
regex = "(?i:" + regex + ")"
173167
}
168+
169+
if opts.Verbose {
170+
logMessage(fmt.Sprintf("Using regular expression: %s", regex))
171+
}
172+
173+
opts.SearchRegex = regexp.MustCompile(regex)
174174
}
175175

176176
func handleSpecialOptions(argparser *flags.Parser, args []string) {
@@ -208,7 +208,7 @@ func main() {
208208

209209
handleSpecialOptions(argparser, args)
210210

211-
processSearch()
211+
processSearchTerm()
212212

213213
for i := range args {
214214
var file string

0 commit comments

Comments
 (0)