-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
221 lines (187 loc) · 4.61 KB
/
main.go
File metadata and controls
221 lines (187 loc) · 4.61 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
package main
import (
"flag"
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
)
type hunk struct {
preImage lineIndex
postImage lineIndex
// e.g.
// diff --git a/file.txt b/file.txt
// index abcdef1..1234567 100644
// --- a/file.txt
// +++ b/file.txt
header string
// e.g.
// @@ -1,4 +1,4 @@
// Line 1
// +Line 2
// -Line 3
content string
}
type lineIndex struct {
start int
linesIncluded int
}
func main() {
keepChanges := flag.Bool("k", false, "Only keep changes matching the regex")
flag.Parse()
flag.Parse()
// After flags, the first non-flag argument should be the regex pattern
if len(flag.Args()) < 1 {
fmt.Fprintln(os.Stderr, "Error: Nothing to match against. Usage: ./patchmatch [-k] <regex>")
os.Exit(1)
}
regexPattern := flag.Arg(0)
regex, err := regexp.Compile(regexPattern)
if err != nil {
fmt.Fprintln(os.Stderr, "Error compiling regex:", err)
os.Exit(1)
}
input, err := io.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, "Error reading stdin:", err)
os.Exit(1)
}
stdIn := strings.ReplaceAll(string(input), "\r\n", "\n")
hunks := SplitHunks(stdIn)
header := ""
for _, h := range hunks {
if h.header != "" {
header = h.header
}
h.header = header
converted := ConvertHunk(h, regex, *keepChanges)
if converted != nil {
fmt.Println(converted.Str())
}
}
}
func SplitHunks(content string) []hunk {
content = strings.Trim(content, "\n ")
idx := strings.Index(content, "@@")
if idx == -1 {
return []hunk{}
}
hunks := []hunk{}
currentHunkHeader := ""
inHunk := false
splitted := strings.Split(content, "\n")
for i, line := range splitted {
if i != len(splitted)-1 {
line += "\n"
}
newHunk := false
if strings.HasPrefix(line, "@@") {
newHunk = true
inHunk = true
re := regexp.MustCompile("[0-9]+")
digits := re.FindAllString(line, -1)
intSlice := make([]int, len(digits))
for i, digit := range digits {
intSlice[i], _ = strconv.Atoi(digit)
}
hunks = append(hunks, hunk{
header: strings.TrimSuffix(currentHunkHeader, "\n"),
preImage: lineIndex{
start: intSlice[0],
linesIncluded: intSlice[1],
},
postImage: lineIndex{
start: intSlice[2],
linesIncluded: intSlice[3],
},
content: "",
})
currentHunkHeader = ""
} else if !inHunk {
currentHunkHeader += line
}
if inHunk && !newHunk {
hunks[len(hunks)-1].content += line
}
}
return hunks
}
func ConvertHunk(h hunk, regex *regexp.Regexp, onlyKeepMatch bool) *hunk {
resultingLines := []string{}
lastDiffStart := -1
inRemovingDiff := false
for _, line := range strings.Split(h.content, "\n") {
inDiff := isChangeLine(line)
if inDiff {
if lastDiffStart == -1 {
lastDiffStart = len(resultingLines) - 1
}
if !inRemovingDiff {
foundOccurence := regex.FindString(line) != ""
shouldRemove := (!onlyKeepMatch && foundOccurence) || (onlyKeepMatch && !foundOccurence)
if shouldRemove {
// This is way too drastic and will remove too many
// lines :) - might fix
// especially for cases with lines like: + + - + - - etc
// we just remove all connected differences w/o space in between
for j := len(resultingLines) - 1; j >= lastDiffStart; j-- {
if resultingLines[j][0] == '-' {
h.postImage.linesIncluded += 1
resultingLines[j] = " " + resultingLines[j][1:]
} else if resultingLines[j][0] == '+' {
h.postImage.linesIncluded -= 1
resultingLines = resultingLines[:len(resultingLines)-1]
}
}
inRemovingDiff = true
}
}
if inRemovingDiff {
if line[0] == '-' {
// keep - lines to restore previous line
h.postImage.linesIncluded += 1
newLine := " " + line[1:]
resultingLines = append(resultingLines, newLine)
} else if line[0] == '+' {
// remove + lines
h.postImage.linesIncluded -= 1
}
} else {
resultingLines = append(resultingLines, line)
}
} else {
lastDiffStart = -1
inRemovingDiff = false
resultingLines = append(resultingLines, line)
}
}
h.content = strings.Join(resultingLines, "\n")
if h.empty() {
return nil
}
return &h
}
func (h hunk) Str() string {
hunk := fmt.Sprintf(
"@@ -%d,%d +%d,%d @@\n%s",
h.preImage.start, h.preImage.linesIncluded,
h.postImage.start, h.postImage.linesIncluded,
h.content)
if h.header != "" {
hunk = fmt.Sprintf("%s\n%s", h.header, hunk)
}
return hunk
}
func (h hunk) empty() bool {
for _, line := range strings.Split(h.content, "\n") {
if isChangeLine(line) {
return false
}
}
return true
}
func isChangeLine(s string) bool {
return len(s) > 0 && (s[0] == '-' || s[0] == '+')
}