Skip to content

fix(gitea): use PR head commits for last_commit instead of default branch - #2555

Closed
Sanjays2402 wants to merge 1 commit into
The-PR-Agent:mainfrom
Sanjays2402:fix/gitea-last-commit-pr-head
Closed

Sanjays2402 wants to merge 1 commit into
The-PR-Agent:mainfrom
Sanjays2402:fix/gitea-last-commit-pr-head

Conversation

@Sanjays2402

Copy link
Copy Markdown

Closes #2206

GiteaProvider.__init__ called list_all_commits() with no ref, which hits GET /repos/{owner}/{repo}/commits and returns the default branch. Gitea returns commits newest-first, so self.pr_commits[-1] was the oldest default-branch commit — last_commit never pointed at the PR head, which then propagated to get_latest_commit_url(), the commit_id used by publish_inline_comments(), _get_file_content_from_latest_commit(), and incremental-review change detection.

The listing is now anchored at the PR head sha and the head commit selected from it, matching get_commit_messages(), which already uses the PR-scoped endpoint.

Regression test in tests/unittest/test_gitea_provider.py fails without the fix (last_commit.sha is None/default-branch) and passes with it; the gitea suite is 20 passed.

…anch

GiteaProvider.__init__ populated self.pr_commits via list_all_commits()
without a ref, which calls GET /repos/{owner}/{repo}/commits and returns
the repository default branch. Since Gitea returns commits newest-first,
self.pr_commits[-1] was the oldest default-branch commit, so last_commit
never pointed at the PR head.

That wrong SHA propagated to get_latest_commit_url(), the commit_id used
by publish_inline_comments(), _get_file_content_from_latest_commit(), and
the incremental-review change detection.

The listing is now anchored at the PR head sha and the head commit is
selected from it, matching get_commit_messages() which already uses the
PR-scoped endpoint.

Adds a regression test asserting the sha is passed and last_commit is the
PR head.
@github-actions github-actions Bot added the bug label Jul 25, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix Gitea last_commit to use PR head commit instead of default branch

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Anchor commit listing at the PR head SHA to avoid default-branch history.
• Select the PR head commit from Gitea’s newest-first commit ordering.
• Add regression test asserting sha scoping and last_commit correctness.
Diagram

graph TD
  A["GiteaProvider.__init__"] --> B["RepoApi.list_all_commits(sha=pr.head.sha)"] --> C{{"Gitea REST API"}} --> D["Commit listing (newest-first)"] --> E["__select_last_commit(head_sha)"] --> F["last_commit / last_commit_id"]
  F --> G["get_latest_commit_url()"]
  F --> H["publish_inline_comments()"]
  F --> I["_get_file_content_from_latest_commit()"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use PR-scoped commits endpoint only
  • ➕ Avoids ambiguity about branch/default-branch behavior
  • ➕ Matches other PR-specific operations semantically
  • ➖ May require additional client method/support in RepoApi if not already present
  • ➖ Could be a larger change than needed for a targeted fix
2. Derive last_commit directly from PR metadata
  • ➕ Avoids an extra commit-list API call during initialization
  • ➕ Guaranteed to match PR head SHA
  • ➖ May not provide full commit object fields currently expected downstream (e.g., html_url) without an additional fetch
  • ➖ Could require a second API call to hydrate commit details

Recommendation: Current approach (scoping list_all_commits by PR head SHA and selecting the head commit from the returned order) is a minimal, low-risk fix that keeps existing downstream expectations (full commit objects) while aligning behavior with PR-scoped commit usage elsewhere. The PR-scoped endpoint could be a future improvement if you want stricter semantic separation.

Files changed (2) +68 / -4

Bug fix (1) +27 / -4
gitea_provider.pyScope commit listing to PR head SHA and select correct last_commit +27/-4

Scope commit listing to PR head SHA and select correct last_commit

• Passes the PR head SHA to list_all_commits so commit history is taken from the PR branch rather than the default branch. Adds a helper to select the PR head commit from Gitea’s newest-first ordering (preferring an exact SHA match) and updates RepoApi.list_all_commits to accept an optional sha parameter.

pr_agent/git_providers/gitea_provider.py

Tests (1) +41 / -0
test_gitea_provider.pyAdd regression test for last_commit pointing at PR head +41/-0

Add regression test for last_commit pointing at PR head

• Adds a unit test that simulates default-branch vs PR-branch commit listings and asserts list_all_commits is called with the PR head SHA. Verifies provider.last_commit and last_commit_id resolve to the PR head commit.

tests/unittest/test_gitea_provider.py

@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0) 📜 Skill insights (0)

Context used

Grey Divider


Action required

1. __select_last_commit may return None 📘 Rule violation ☼ Reliability
Description
GiteaProvider.__select_last_commit() returns None when the commit list is empty, but later
methods dereference self.last_commit (e.g., get_latest_commit_url() and
_get_file_content_from_latest_commit()), which can raise runtime AttributeError. This unhandled
edge case creates a deferred failure mode where initialization may succeed but PR-head dependent
behavior can crash when the commits listing fails or is empty.
Code

pr_agent/git_providers/gitea_provider.py[R111-124]

+    @staticmethod
+    def __select_last_commit(commits, head_sha: str):
+        """Pick the PR head commit from a Gitea commit listing.
+
+        Gitea returns commits newest-first, so the head is the first entry;
+        prefer an exact ``head_sha`` match when it is present.
+        """
+        if not commits:
+            return None
+        if head_sha:
+            for commit in commits:
+                if getattr(commit, "sha", None) == head_sha:
+                    return commit
+        return commits[0]
Evidence
PR Compliance ID 3 requires edge cases to be handled gracefully, yet the updated commit-selection
helper explicitly returns None when commits is empty (if not commits: return None) and its
result is assigned to self.last_commit. Other methods still unconditionally access
self.last_commit.html_url and self.last_commit.sha, so if the commits API returns an empty
list/None, calling those methods will dereference None and trigger an AttributeError,
demonstrating the unhandled edge case.

Rule 3: Robust Error Handling
pr_agent/git_providers/gitea_provider.py[89-104]
pr_agent/git_providers/gitea_provider.py[111-124]
pr_agent/git_providers/gitea_provider.py[248-249]
pr_agent/git_providers/gitea_provider.py[458-463]
pr_agent/git_providers/gitea_provider.py[89-124]
pr_agent/git_providers/gitea_provider.py[458-464]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`__select_last_commit()` can return `None` when the commits listing is empty, but downstream code assumes `self.last_commit` is always present and dereferences `.html_url` / `.sha`, leading to `AttributeError` at runtime or invalid behavior. Fix this edge case so PR-head dependent features behave predictably even when the commits API returns empty results.

## Issue Context
The provider now selects `last_commit` via `__select_last_commit(self.pr_commits, self.sha)` during initialization, and `__select_last_commit()` explicitly allows returning `None` when `commits` is empty. Methods like `get_latest_commit_url()` and `_get_file_content_from_latest_commit()` still dereference `self.last_commit` unconditionally, so initialization can appear successful but later operations crash; the provider should either fail fast with a clear error message or provide a safe fallback (e.g., based on `self.sha`) to satisfy graceful edge-case handling expectations.

## Fix Focus Areas
- pr_agent/git_providers/gitea_provider.py[89-104]
- pr_agent/git_providers/gitea_provider.py[111-124]
- pr_agent/git_providers/gitea_provider.py[248-249]
- pr_agent/git_providers/gitea_provider.py[458-464]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Qodo Logo

Comment on lines +111 to +124
@staticmethod
def __select_last_commit(commits, head_sha: str):
"""Pick the PR head commit from a Gitea commit listing.

Gitea returns commits newest-first, so the head is the first entry;
prefer an exact ``head_sha`` match when it is present.
"""
if not commits:
return None
if head_sha:
for commit in commits:
if getattr(commit, "sha", None) == head_sha:
return commit
return commits[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

1. __select_last_commit may return none 📘 Rule violation ☼ Reliability

GiteaProvider.__select_last_commit() returns None when the commit list is empty, but later
methods dereference self.last_commit (e.g., get_latest_commit_url() and
_get_file_content_from_latest_commit()), which can raise runtime AttributeError. This unhandled
edge case creates a deferred failure mode where initialization may succeed but PR-head dependent
behavior can crash when the commits listing fails or is empty.
Agent Prompt
## Issue description
`__select_last_commit()` can return `None` when the commits listing is empty, but downstream code assumes `self.last_commit` is always present and dereferences `.html_url` / `.sha`, leading to `AttributeError` at runtime or invalid behavior. Fix this edge case so PR-head dependent features behave predictably even when the commits API returns empty results.

## Issue Context
The provider now selects `last_commit` via `__select_last_commit(self.pr_commits, self.sha)` during initialization, and `__select_last_commit()` explicitly allows returning `None` when `commits` is empty. Methods like `get_latest_commit_url()` and `_get_file_content_from_latest_commit()` still dereference `self.last_commit` unconditionally, so initialization can appear successful but later operations crash; the provider should either fail fast with a clear error message or provide a safe fallback (e.g., based on `self.sha`) to satisfy graceful edge-case handling expectations.

## Fix Focus Areas
- pr_agent/git_providers/gitea_provider.py[89-104]
- pr_agent/git_providers/gitea_provider.py[111-124]
- pr_agent/git_providers/gitea_provider.py[248-249]
- pr_agent/git_providers/gitea_provider.py[458-464]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@IsmaelMartinez

Copy link
Copy Markdown
Collaborator

This landed in main on 1 August via #2569 (commit 4a26c38d), and #2206 is now closed.

Your diagnosis matches what was merged exactly — the difference is only in approach: the merged version resolves last_commit through the PR-scoped get_pr_commits() rather than adding a sha parameter to list_all_commits, and it carries the same regression cases you wrote, at tests/unittest/test_gitea_provider.py:365-430.

So this is superseded and now conflicts; it can probably be closed. Worth flagging that yours was filed a few days earlier, in case the maintainers want to look at how the duplicate work happened.

@Sanjays2402

Copy link
Copy Markdown
Author

Confirmed - main now resolves last_commit from repo_api.get_pr_commits(...) and picks the head SHA out of that listing (gitea_provider.py:113-134), with get_latest_commit_url, publish_inline_comments and _get_file_content_from_latest_commit all guarded for the empty case. That covers the same bug this PR was after, and via the PR-scoped endpoint, which is the cleaner of the two options. #2206 is closed.

Closing this as superseded - no point carrying the conflict.

@Sanjays2402 Sanjays2402 closed this Aug 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gitea provider: list_all_commits fetches repo commits instead of PR commits

2 participants