fix: off-by-one errors in code comment patches (#39887)

Code comments next to a diff hunk could show one line too high in the
conversation view vs. in the code view that showed them on the correct
line.

- Treat the hunk end in `CutDiffAroundLine` as exclusive, so the line
after a hunk falls back to the unchanged-line context
- Don't count `\ No newline at end of file` markers as lines when
cutting the hunk
- Share the unchanged-line fallback with migrated review comments
This commit is contained in:
silverwind authored and GitHub committed 2026-10-20 22:10:04 +00:00
1 parent c52e7c0cd2
commit 82536a3ede
5 files changed
+41 -37

No files matched your search

+1 -15
View File
@@ -17,7 +17,6 @@ import (
"gitea.dev/modules/git/gitcmd"
"gitea.dev/modules/log"
"gitea.dev/modules/optional"
"gitea.dev/modules/setting"
"gitea.dev/modules/util"
"gitea.dev/services/gitdiff"
notify_service "gitea.dev/services/notify"
@@ -258,23 +257,10 @@ func createCodeComment(ctx context.Context, doer *user_model.User, repo *repo_mo
commitID = headCommitID
}
patch, err = git.GetFileDiffCutAroundLine(ctx,
gitRepo, pr.MergeBase, headCommitID, treePath,
int64((&issues_model.Comment{Line: line}).UnsignedLine()), line < 0, setting.UI.CodeCommentLines,
)
patch, err = gitdiff.GetCodeCommentPatch(ctx, gitRepo, pr.MergeBase, headCommitID, treePath, line)
if err != nil {
return nil, err
}
// If patch is still empty (unchanged line), generate code context
contextCommitID := util.Iif(line < 0, pr.MergeBase, headCommitID) // the line number is relative to the diff sides, not to the blamed commitID
if patch == "" && contextCommitID != "" {
patch, err = gitdiff.GeneratePatchForUnchangedLine(ctx, gitRepo, contextCommitID, treePath, line, setting.UI.CodeCommentLines)
if err != nil {
// Log the error but don't fail comment creation
log.Debug("Unable to generate patch for unchanged line (file=%s, line=%d, commit=%s): %v", treePath, line, contextCommitID, err)
}
}
}
return issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{
Type: issues_model.CommentTypeCode,