Skip to content
This repository has been archived by the owner on May 19, 2024. It is now read-only.

Commit

Permalink
Fix the regex again
Browse files Browse the repository at this point in the history
  • Loading branch information
owenrumney committed Jan 24, 2022
1 parent 0c8dbb5 commit 8aed495
Showing 1 changed file with 26 additions and 19 deletions.
45 changes: 26 additions & 19 deletions commenter/commenter.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type Commenter struct {
}

var (
patchRegex = regexp.MustCompile(`^@@.*[\+\-](\d+)(?>\s[\+\-](\d)|,(\d+)).+?@@`)
patchRegex = regexp.MustCompile(`^@@.*\d [\+\-](\d+),?(\d+)?.+?@@`)
commitRefRegex = regexp.MustCompile(".+ref=(.+)")
)

Expand Down Expand Up @@ -193,19 +193,39 @@ func buildComment(file, comment string, line int, info commitFileInfo) *github.P
}

func getCommitInfo(file *github.CommitFile) (cfi *commitFileInfo, err error) {
var hunkStart, hunkEnd int
var isBinary bool
patch := file.GetPatch()
hunkStart, hunkEnd, err := parseHunkPositions(patch, *file.Filename)
if err != nil {
return nil, err
}

shaGroups := commitRefRegex.FindAllStringSubmatch(file.GetContentsURL(), -1)
if len(shaGroups) < 1 {
return nil, fmt.Errorf("the sha details for [%s] could not be resolved", *file.Filename)
}
sha := shaGroups[0][1]

return &commitFileInfo{
FileName: *file.Filename,
hunkStart: hunkStart,
hunkEnd: hunkStart + (hunkEnd - 1),
sha: sha,
likelyBinary: isBinary,
}, nil
}

func parseHunkPositions(patch, filename string) (hunkStart int, hunkEnd int, err error) {
if patch != "" {
groups := patchRegex.FindAllStringSubmatch(patch, -1)
if len(groups) < 1 {
return nil, fmt.Errorf("the patch details for [%s] could not be resolved", *file.Filename)
return 0, 0, fmt.Errorf("the patch details for [%s] could not be resolved", filename)
}

patchGroup := groups[0]
endPos := 2
if len(patchGroup) > 2 {
endPos = 3
if len(patchGroup) > 2 && patchGroup[2] == "" {
endPos = 1
}

hunkStart, err = strconv.Atoi(patchGroup[1])
Expand All @@ -217,18 +237,5 @@ func getCommitInfo(file *github.CommitFile) (cfi *commitFileInfo, err error) {
hunkEnd = -1
}
}

shaGroups := commitRefRegex.FindAllStringSubmatch(file.GetContentsURL(), -1)
if len(shaGroups) < 1 {
return nil, fmt.Errorf("the sha details for [%s] could not be resolved", *file.Filename)
}
sha := shaGroups[0][1]

return &commitFileInfo{
FileName: *file.Filename,
hunkStart: hunkStart,
hunkEnd: hunkStart + (hunkEnd - 1),
sha: sha,
likelyBinary: isBinary,
}, nil
return hunkStart, hunkEnd, nil
}

0 comments on commit 8aed495

Please sign in to comment.