forked from webdevops/go-replace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuncs.go
100 lines (81 loc) · 2.23 KB
/
funcs.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
package main
import ()
import (
"bufio"
"bytes"
"regexp"
)
// check if string is contained in an array
func contains(slice []string, item string) bool {
set := make(map[string]struct{}, len(slice))
for _, s := range slice {
set[s] = struct{}{}
}
_, ok := set[item]
return ok
}
// Checks if there is a match in content, based on search options
func searchMatch(content string, changeset changeset) bool {
if changeset.Search.MatchString(content) {
return true
}
return false
}
// Replace text in whole content based on search options
func replaceText(content string, changeset changeset) string {
// --regex-backrefs
if opts.RegexBackref {
return changeset.Search.ReplaceAllString(content, changeset.Replace)
} else {
return changeset.Search.ReplaceAllLiteralString(content, changeset.Replace)
}
}
func handleLineInFile(changesets []changeset, buffer bytes.Buffer) (*bytes.Buffer, bool) {
var (
line string
writeBufferToFile bool
)
for _, changeset := range changesets {
if !changeset.MatchFound {
// just add line to file
line = changeset.Replace + "\n"
// remove backrefs (no match)
if opts.RegexBackref {
line = regexp.MustCompile("\\$[0-9]+").ReplaceAllLiteralString(line, "")
}
// --lineinfile-before
// --lineinfile-after
if opts.LineinfileBefore != "" || opts.LineinfileAfter != "" {
var matchFinder *regexp.Regexp
if opts.LineinfileBefore != "" {
matchFinder = regexp.MustCompile(opts.LineinfileBefore)
} else {
matchFinder = regexp.MustCompile(opts.LineinfileAfter)
}
var bufferCopy bytes.Buffer
scanner := bufio.NewScanner(&buffer)
for scanner.Scan() {
originalLine := scanner.Text()
if matchFinder.MatchString(originalLine) {
writeBufferToFile = true
if opts.LineinfileBefore != "" {
bufferCopy.WriteString(line)
}
bufferCopy.WriteString(originalLine + "\n")
if opts.LineinfileAfter != "" {
bufferCopy.WriteString(line)
}
} else {
bufferCopy.WriteString(originalLine + "\n")
}
}
buffer.Reset()
buffer.WriteString(bufferCopy.String())
} else {
buffer.WriteString(line)
writeBufferToFile = true
}
}
}
return &buffer, writeBufferToFile
}