fix: move scanner.Err() check after loop and fix matches bounds check

Two bugs in ExtractMeta:

1. scanner.Err() was checked inside the Scan() loop. According to the
   bufio.Scanner docs, Err() returns nil during a successful scan; it
   only reflects an error after Scan() returns false. Moving the check
   after the loop ensures real I/O errors are surfaced instead of
   silently ignored.

2. The len(matches) guard was 'len(matches) > 1' but the code
   accessed matches[2] (requires len >= 3). reHeaderPatternV2 always
   produces a 3-element slice when it matches, but the condition was
   misleading and could panic if the regex were ever changed to make
   the second capture group optional. Changed to 'len(matches) > 2'.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Manuel Rüger 2026-03-13 02:01:45 +01:00
parent cf0699c088
commit d714bc9d2b

View File

@ -63,10 +63,6 @@ func ExtractMeta(data []byte, spaceFromCli string, titleFromH1 bool, titleFromFi
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
if err := scanner.Err(); err != nil {
return nil, nil, err
}
offset += len(line) + 1 offset += len(line) + 1
matches := reHeaderPatternV2.FindStringSubmatch(line) matches := reHeaderPatternV2.FindStringSubmatch(line)
@ -88,7 +84,7 @@ func ExtractMeta(data []byte, spaceFromCli string, titleFromH1 bool, titleFromFi
header := cases.Title(language.English).String(matches[1]) header := cases.Title(language.English).String(matches[1])
var value string var value string
if len(matches) > 1 { if len(matches) > 2 {
value = strings.TrimSpace(matches[2]) value = strings.TrimSpace(matches[2])
} }
@ -147,6 +143,10 @@ func ExtractMeta(data []byte, spaceFromCli string, titleFromH1 bool, titleFromFi
} }
} }
if err := scanner.Err(); err != nil {
return nil, nil, err
}
if titleFromH1 || titleFromFilename || spaceFromCli != "" { if titleFromH1 || titleFromFilename || spaceFromCli != "" {
if meta == nil { if meta == nil {
meta = &Meta{} meta = &Meta{}