0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-12-26 11:44:39 +01:00

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

+ Named groups in reges for easier group parsing
This commit is contained in:
kolaente 2018-10-18 04:03:49 +02:00 committed by techknowlogick
parent c37d1a9e99
commit e79e9248fd

View file

@ -273,7 +273,7 @@ func (diff *Diff) NumFiles() int {
} }
// Example: @@ -1,8 +1,9 @@ => [..., 1, 8, 1, 9] // 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 { func isHeader(lof string) bool {
return strings.HasPrefix(lof, cmdDiffHead) || strings.HasPrefix(lof, "---") || strings.HasPrefix(lof, "+++") return strings.HasPrefix(lof, cmdDiffHead) || strings.HasPrefix(lof, "---") || strings.HasPrefix(lof, "+++")
@ -311,21 +311,28 @@ func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLi
if len(hunk) > headerLines { if len(hunk) > headerLines {
break 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 { if old {
begin = com.StrTo(groups[1]).MustInt64() begin = com.StrTo(groups["beginOld"]).MustInt64()
end = com.StrTo(groups[2]).MustInt64() end = com.StrTo(groups["endOld"]).MustInt64()
// init otherLine with begin of opposite side // init otherLine with begin of opposite side
otherLine = com.StrTo(groups[3]).MustInt64() otherLine = com.StrTo(groups["beginNew"]).MustInt64()
} else { } else {
begin = com.StrTo(groups[3]).MustInt64() begin = com.StrTo(groups["beginNew"]).MustInt64()
if groups[5] != "" { if groups["endNew"] != "" {
end = com.StrTo(groups[5]).MustInt64() end = com.StrTo(groups["endNew"]).MustInt64()
} else { } else {
end = 0 end = 0
} }
// init otherLine with begin of opposite side // 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 end += begin // end is for real only the number of lines in hunk
// lof is between begin and end // lof is between begin and end