Skip to content

Commit

Permalink
github: Use bufio.Scanner to scan for lines
Browse files Browse the repository at this point in the history
Using bufio.Scanner handles \r\n and \n ensuring we don't leave \r in
the JSON which results in invisible ^M characters in the output which is
particularly annoying when storing result into a file.

Signed-off-by: Chance Zibolski <[email protected]>
  • Loading branch information
chancez committed Sep 26, 2024
1 parent 374eb83 commit 898bb04
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
28 changes: 22 additions & 6 deletions pkg/github/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package github

import (
"bufio"
"fmt"
"sort"
"strconv"
Expand All @@ -29,27 +30,42 @@ const (
releaseNoteBlock = "```release-note"
upstreamPRsBlock = "```upstream-prs"
commentTag = "<!--"
endBlock = "```"
)

func textBlockBetween(body, str string) string {
lines := strings.Split(body, "\n")
// Get the text between startBlock and endBlock
func textBlockBetween(body, startBlock string) string {
// Use a bufio.Scanner to scan line by line because it handles both `\n` and `\r\n`.
scanner := bufio.NewScanner(strings.NewReader(body))
beginning, end := -1, -1
for idx, line := range lines {
idx := 0
gotBlock := false
var lines []string
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if line == str {
lines = append(lines, line)
if line == startBlock {
beginning = idx
}
if beginning != -1 && line == "```" {
if !gotBlock && beginning != -1 && line == endBlock {
end = idx
break
// Got the block, but continue scanning so we can accumulate all the lines
gotBlock = true
}
if scanner.Err() != nil {
return ""
}
idx++
}

if beginning == end {
return ""
}
if end == -1 {
end = len(lines)
}

return strings.TrimSpace(strings.Join(lines[beginning+1:end], " "))
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/github/labels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func Test_getReleaseNote(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getReleaseNote(tt.args.title, tt.args.body); got != tt.want {
t.Errorf("getReleaseNote() = %v, want %v", got, tt.want)
t.Errorf("getReleaseNote() = %q, want %q", got, tt.want)
}
})
}
Expand Down

0 comments on commit 898bb04

Please sign in to comment.