Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix regex to support optional end line of old section in diff hunk #5096

Merged
merged 3 commits into from
Oct 18, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix regex to support optional end line of old section in diff hunk
+ Named groups in reges for easier group parsing
  • Loading branch information
kolaente committed Oct 17, 2018
commit 6aa08d4bf9a5c4567a11aba3b1845f10d7f274ce
25 changes: 16 additions & 9 deletions models/git_diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ func (diff *Diff) NumFiles() int {
}

// Example: @@ -1,8 +1,9 @@ => [..., 1, 8, 1, 9]
var hunkRegex = regexp.MustCompile(`^@@ -([0-9]+),([0-9]+) \+([0-9]+)(,([0-9]+))? @@`)
var hunkRegex = regexp.MustCompile(`^@@ -(?P<beginOld>[0-9]+)(,(?P<endOld>[0-9]+))? \+(?P<beginNew>[0-9]+)(,(?P<endNew>[0-9]+))? @@`)

func isHeader(lof string) bool {
return strings.HasPrefix(lof, cmdDiffHead) || strings.HasPrefix(lof, "---") || strings.HasPrefix(lof, "+++")
Expand Down Expand Up @@ -311,21 +311,28 @@ func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLi
if len(hunk) > headerLines {
break
}
groups := hunkRegex.FindStringSubmatch(lof)
// A map with named groups of our regex to recognize them later more easily
submatches := hunkRegex.FindStringSubmatch(lof)
groups := make(map[string]string)
for i, name := range hunkRegex.SubexpNames() {
if i != 0 && name != "" {
groups[name] = submatches[i]
}
}
if old {
begin = com.StrTo(groups[1]).MustInt64()
end = com.StrTo(groups[2]).MustInt64()
begin = com.StrTo(groups["beginOld"]).MustInt64()
end = com.StrTo(groups["endOld"]).MustInt64()
// init otherLine with begin of opposite side
otherLine = com.StrTo(groups[3]).MustInt64()
otherLine = com.StrTo(groups["beginNew"]).MustInt64()
} else {
begin = com.StrTo(groups[3]).MustInt64()
if groups[5] != "" {
end = com.StrTo(groups[5]).MustInt64()
begin = com.StrTo(groups["beginNew"]).MustInt64()
if groups["endNew"] != "" {
end = com.StrTo(groups["endNew"]).MustInt64()
} else {
end = 0
}
// init otherLine with begin of opposite side
otherLine = com.StrTo(groups[1]).MustInt64()
otherLine = com.StrTo(groups["beginOld"]).MustInt64()
}
end += begin // end is for real only the number of lines in hunk
// lof is between begin and end
Expand Down