chore: refactor LineBlame (#8419)

- Refactor arguments of the function to make more sense.
  - `path` can be inferred from `repo` receiver.
  - `line` can be `uint64`.
- The two calls to this function check for specific errors, do this error checking in the function.
- The ID of a object format is not 40 in the case of SHA256, get the object format and use the correct length.
- Add test coverage for `LineBlame`, notably it checks for the errors that can legitimately happen.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/8419
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Co-authored-by: Gusted <postmaster@gusted.xyz>
Co-committed-by: Gusted <postmaster@gusted.xyz>
This commit is contained in:
Gusted 2025-07-05 16:31:53 +02:00 committed by Gusted
parent d8c5083c6f
commit 5f514a6e4d
3 changed files with 88 additions and 14 deletions

View file

@ -9,8 +9,6 @@ import (
"errors"
"fmt"
"io"
"regexp"
"strings"
"forgejo.org/models/db"
issues_model "forgejo.org/models/issues"
@ -25,8 +23,6 @@ import (
notify_service "forgejo.org/services/notify"
)
var notEnoughLines = regexp.MustCompile(`fatal: file .* has only \d+ lines?`)
// ErrDismissRequestOnClosedPR represents an error when an user tries to dismiss a review associated to a closed or merged PR.
type ErrDismissRequestOnClosedPR struct{}
@ -48,8 +44,8 @@ func (err ErrDismissRequestOnClosedPR) Unwrap() error {
// If the line got changed the comment is going to be invalidated.
func checkInvalidation(ctx context.Context, c *issues_model.Comment, repo *git.Repository, branch string) error {
// FIXME differentiate between previous and proposed line
commit, err := repo.LineBlame(branch, repo.Path, c.TreePath, uint(c.UnsignedLine()))
if err != nil && (strings.Contains(err.Error(), "fatal: no such path") || notEnoughLines.MatchString(err.Error())) {
commit, err := repo.LineBlame(branch, c.TreePath, c.UnsignedLine())
if err != nil && (errors.Is(err, git.ErrBlameFileDoesNotExist) || errors.Is(err, git.ErrBlameFileNotEnoughLines)) {
c.Invalidated = true
return issues_model.UpdateCommentInvalidate(ctx, c)
}
@ -230,10 +226,10 @@ func CreateCodeCommentKnownReviewID(ctx context.Context, doer *user_model.User,
// FIXME validate treePath
// Get latest commit referencing the commented line
// No need for get commit for base branch changes
commit, err := gitRepo.LineBlame(head, gitRepo.Path, treePath, uint(line))
commit, err := gitRepo.LineBlame(head, treePath, uint64(line))
if err == nil {
commitID = commit.ID.String()
} else if !strings.Contains(err.Error(), "exit status 128 - fatal: no such path") && !notEnoughLines.MatchString(err.Error()) {
} else if !errors.Is(err, git.ErrBlameFileDoesNotExist) && !errors.Is(err, git.ErrBlameFileNotEnoughLines) {
return nil, fmt.Errorf("LineBlame[%s, %s, %s, %d]: %w", pr.GetGitRefName(), gitRepo.Path, treePath, line, err)
}
}