Skip to content

fix(gitea): resolve last_commit from PR commits, not repo commits - #2569

Merged
naorpeled merged 2 commits into
The-PR-Agent:mainfrom
vaibzde:fix/gitea-pr-commits
Aug 1, 2026
Merged

naorpeled merged 2 commits into
The-PR-Agent:mainfrom
vaibzde:fix/gitea-pr-commits

Conversation

@vaibzde

@vaibzde vaibzde commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

GiteaProvider.__init__ populated self.pr_commits with list_all_commits(owner, repo), which calls GET /repos/{owner}/{repo}/commits — the commits of the repository's default branch, not of the PR. It then took [-1] of that list; since Gitea returns commits newest-first, last_commit ended up being the oldest commit on the default branch.

Everything that reads last_commit was therefore pointing at a commit unrelated to the PR:

  • get_latest_commit_url() returned a default-branch commit URL.
  • publish_inline_comments() posted with a wrong commit_id.
  • _get_file_content_from_latest_commit() read file content from the wrong commit.
  • Because that SHA never changed between pushes, persistent review/suggestion headers kept reporting the same stale commit and did not register new work on the PR.

Fix

Fetch the PR's own commits through the get_pr_commits() wrapper that already exists in RepoApi (GET /repos/{owner}/{repo}/pulls/{pr_number}/commits).

  • Gitea returns PR commits newest-first, so they are reversed into the oldest-first order the GitHub and Azure DevOps providers use.
  • last_commit is matched against the PR head SHA (pr.head.sha), so it does not silently depend on the ordering.
  • get_pr_commits() returns raw JSON dicts, while the rest of the codebase expects attribute access on commit objects (for example pr_description.py uses git_provider.last_commit_id.sha). The payload is wrapped in a small _GiteaCommitAdapter exposing .sha / .html_url, mirroring _AzureCommitAdapter in azuredevops_provider.py.
  • An empty commit list previously raised IndexError from __init__; now last_commit stays None and the getters degrade to the head SHA or an empty string.

list_all_commits() is left in place — it is a plain endpoint wrapper and removing it would widen the surface of a behaviour fix.

Tests

Added TestGiteaProviderPRCommits in tests/unittest/test_gitea_provider.py, following the existing pattern in that file of building the provider with __new__ and wiring only the attributes under test:

  • the PR commits endpoint is called with pr_number, and list_all_commits is not called (this is the assertion that pins the regression);
  • with a newest-first payload, last_commit is the PR head and pr_commits is stored oldest-first;
  • with an unknown head SHA, last_commit falls back to the newest commit;
  • an empty payload leaves last_commit is None and get_latest_commit_url() returns "" instead of raising;
  • _get_file_content_from_latest_commit() reads from the PR head SHA.

Run locally in a clean venv built from this repo:

PYTHONPATH=. pytest tests/unittest -q
1550 passed, 1 skipped, 1 xfailed

ruff check on both touched files reports the same pre-existing findings as on main, and none from this change.

Notes

  • I do not have a Gitea instance, so the fix is verified by unit tests and by reasoning about the Gitea API, not against a live server. The one assumption I could not verify end-to-end is that /pulls/{index}/commits returns commits newest-first; the head-SHA match means last_commit is correct either way, and only the order of pr_commits depends on it.
  • Open PR Add pagination handling for Gitea provider API endpoints #2147 also touches this file, but at a different layer — it rewrites the RepoApi wrappers for pagination, while this change is in the provider that consumes them. No functional overlap.

Closes #2206

GiteaProvider.__init__ called list_all_commits(owner, repo), which hits
GET /repos/{owner}/{repo}/commits and returns commits of the default
branch. Taking [-1] of that newest-first list left last_commit pointing
at the oldest commit of the default branch, so the latest-commit URL,
inline comment commit_id and the file content read from "the latest
commit" all referenced a commit unrelated to the PR. Because that SHA
never changed between pushes, persistent reviews also stopped detecting
new commits.

Fetch the PR's own commits instead, via the existing get_pr_commits()
wrapper. Gitea returns them newest-first, so they are reversed to the
oldest-first order the other providers use, and last_commit is matched
against the PR head SHA. The raw payload is wrapped in a small adapter
so callers keep the .sha/.html_url attribute access they already relied
on, mirroring _AzureCommitAdapter in the Azure DevOps provider.

An empty commit list no longer raises IndexError; last_commit stays
None and the affected getters degrade to the head SHA or an empty
string.
@github-actions github-actions Bot added the bug label Jul 27, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fix GiteaProvider to derive last_commit from PR commits (not default-branch commits)

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Fetch PR commit list via the PR commits endpoint, not the repo default-branch commits.
• Resolve last_commit by matching PR head SHA, and handle empty commit lists safely.
• Add regression tests ensuring correct endpoint usage, ordering, and fallback behavior.
Diagram

graph TD
  A["GiteaProvider.__init__"] --> B["_set_pr_commits"] --> C["RepoApi.get_pr_commits"] --> D["_GiteaCommitAdapter"] --> E["last_commit/last_commit_id"] --> F["get_latest_commit_url"]
  E --> G["_get_file_content_from_latest_commit"]

  subgraph Legend
    direction LR
    _cls["Provider method"] ~~~ _api[["API wrapper"]] ~~~ _data[("Commit data")]
  end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use raw dict payloads end-to-end (no adapter)
  • ➕ Less indirection and fewer small classes
  • ➕ Avoids maintaining a commit shape abstraction
  • ➖ Requires widespread refactors where attribute access is assumed (.sha/.html_url)
  • ➖ Increases coupling to provider-specific JSON shapes
2. Derive commit SHA from PR head only; skip commit list for last_commit
  • ➕ Avoids dependency on commits endpoint ordering/availability for selecting SHA
  • ➕ Simplifies last_commit selection logic
  • ➖ Still needs commit metadata (e.g., html_url) for get_latest_commit_url()
  • ➖ Does not provide a normalized pr_commits list for other code paths

Recommendation: Keep the current approach: fetch PR commits via get_pr_commits(), normalize ordering, and adapt payloads to a consistent commit interface. This is the smallest change that fixes incorrect default-branch behavior while preserving existing attribute-based expectations across the codebase, and it adds safe fallbacks for empty commit lists.

Files changed (2) +113 / -8

Bug fix (1) +29 / -8
gitea_provider.pyResolve last_commit from PR commits and add safe fallbacks +29/-8

Resolve last_commit from PR commits and add safe fallbacks

• Stops using the repository default-branch commits to compute pr_commits/last_commit and instead fetches PR commits via RepoApi.get_pr_commits(). Adds a small adapter to expose .sha/.html_url over raw Gitea JSON, matches last_commit against the PR head SHA, and hardens helpers to handle empty commit lists without raising.

pr_agent/git_providers/gitea_provider.py

Tests (1) +84 / -0
test_gitea_provider.pyAdd regression tests for PR commit resolution (#2206) +84/-0

Add regression tests for PR commit resolution (#2206)

• Introduces TestGiteaProviderPRCommits to assert the PR commits endpoint is used (and list_all_commits is not), ordering is normalized, last_commit selection matches head SHA with fallback behavior, empty commit lists are handled safely, and file-content reads use the PR head SHA.

tests/unittest/test_gitea_provider.py

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

qodo-free-for-open-source-projects Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. None last_commit_id deref ✓ Resolved 🐞 Bug ≡ Correctness
Description
GiteaProvider._set_pr_commits() can now set last_commit/last_commit_id to None when the PR
commits endpoint returns an empty list, but downstream paths assume a valid commit object and either
dereference last_commit_id.sha (crashing with AttributeError) or submit commit_id="" to
Gitea’s reviews endpoint (causing inline review creation to fail or be unanchored despite self.sha
being available).
Code

pr_agent/git_providers/gitea_provider.py[R120-126]

+        if not self.pr_commits:
+            self.logger.error("Failed to get PR commits")
+        self.last_commit = next(
+            (commit for commit in self.pr_commits if commit.sha and commit.sha == self.sha),
+            self.pr_commits[-1] if self.pr_commits else None
+        )
+        self.last_commit_id = self.last_commit
Evidence
The updated logic in _set_pr_commits() explicitly permits an empty commits response and assigns
last_commit/last_commit_id from that result, meaning these fields can remain None (as
observed/tested). Existing consumers are not written for that state: the PR description header path
uses last_commit_id.sha without a None guard, which will raise AttributeError, and
publish_inline_comments() builds commit_id as `self.last_commit.sha if self.last_commit else
"", producing requests with a non-SHA empty commit_id when last_commit` is unset.

pr_agent/git_providers/gitea_provider.py[111-127]
tests/unittest/test_gitea_provider.py[423-431]
pr_agent/tools/pr_description.py[518-522]
pr_agent/git_providers/gitea_provider.py[336-344]

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

## Issue description
`GiteaProvider._set_pr_commits()` can leave `last_commit`/`last_commit_id` as `None` when the PR commits endpoint returns an empty list. Downstream code paths assume a commit object exists: some dereference `last_commit_id.sha` (triggering `AttributeError`), and `publish_inline_comments()` may submit `commit_id=""` to Gitea’s reviews endpoint, causing inline reviews to fail or be unanchored even though the PR head SHA is available in `self.sha`.
## Issue Context
This PR intentionally changes behavior from raising an `IndexError` during initialization to allowing an empty commit list; the provider must remain compatible with existing consumers that expect `.sha` to exist. The provider already has the PR head SHA in `self.sha`, and at least one other method (e.g. `_get_file_content_from_latest_commit`) correctly falls back to `self.sha` when `last_commit` is missing, suggesting a consistent fallback strategy should be applied.
## Fix Focus Areas
- pr_agent/git_providers/gitea_provider.py[111-127]
- pr_agent/git_providers/gitea_provider.py[336-344]

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



Remediation recommended

2. Head SHA missing fallback 🐞 Bug ≡ Correctness
Description
In GiteaProvider._set_pr_commits(), if the PR head SHA (self.sha) is not present in the returned
commits list, last_commit falls back to self.pr_commits[-1] (the oldest commit in the returned
subset), producing an incorrect last_commit SHA. This can mis-anchor persistent description headers
and inline comment creation which rely on last_commit_id.sha / last_commit.sha.
Code

pr_agent/git_providers/gitea_provider.py[R130-133]

+        self.last_commit = next(
+            (commit for commit in self.pr_commits if commit.sha and commit.sha == self.sha),
+            self.pr_commits[-1] if self.pr_commits else _GiteaCommitAdapter({"sha": self.sha})
+        )
Evidence
get_pr_commits() fetches commits via a single call and returns the decoded JSON without pagination
handling, so it may return only a subset of PR commits. _set_pr_commits() then sets last_commit
to the matching head SHA if present, otherwise it uses self.pr_commits[-1], which can be incorrect
when the head SHA is missing from that subset. Downstream, PR description headers and inline review
creation use last_commit_id.sha / last_commit.sha, so an incorrect last_commit propagates to
user-visible and API-affecting behavior.

pr_agent/git_providers/gitea_provider.py[111-135]
pr_agent/git_providers/gitea_provider.py[1094-1118]
pr_agent/tools/pr_description.py[518-521]
pr_agent/git_providers/gitea_provider.py[344-352]

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

## Issue description
`_set_pr_commits()` intends to set `last_commit` to the PR head commit, but if the returned commit list does not contain `self.sha` (e.g., only a single page of commits is returned), it falls back to `self.pr_commits[-1]`, which is just the last element of the returned subset.
### Issue Context
`RepoApi.get_pr_commits()` performs a single request and returns the JSON payload as-is. If that payload is incomplete, `last_commit` can become unrelated to the PR head even though `self.sha` is known.
### Fix Focus Areas
- pr_agent/git_providers/gitea_provider.py[111-135]
### Suggested fix
- Change the fallback logic so that when `self.sha` is known but not found in `self.pr_commits`, `last_commit` becomes an adapter wrapping `self.sha` (optionally with a computed html_url if available), instead of selecting `self.pr_commits[-1]`.
- Add a regression unit test where `get_pr_commits()` returns a non-empty list that does **not** include `head_sha`, and assert `last_commit.sha == head_sha` (not the last element of the list).

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


3. Single quotes in new tests ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
New test code introduces single-quoted strings, which deviates from the repo’s Python style
preference for double quotes. This creates inconsistent formatting and may trigger Ruff/formatting
churn across the file.
Code

tests/unittest/test_gitea_provider.py[R373-383]

+    def _provider(pr_commits, head_sha='head-sha'):
+        from pr_agent.git_providers.gitea_provider import GiteaProvider
+
+        provider = GiteaProvider.__new__(GiteaProvider)
+        provider.logger = MagicMock()
+        provider.owner = 'owner'
+        provider.repo = 'repo'
+        provider.pr_number = 123
+        provider.sha = head_sha
+        provider.repo_api = MagicMock()
+        provider.repo_api.get_pr_commits.return_value = pr_commits
Evidence
PR Compliance ID 15 requires new/changed Python code to follow the repo style including double
quotes. The added helper _provider() and related assertions introduce several single-quoted
literals (e.g., head_sha='head-sha', provider.owner = 'owner').

AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes: AGENTS.md: Follow Repository Python Style: Ruff (line length 120), isort Import Grouping, Double Quotes
tests/unittest/test_gitea_provider.py[373-383]

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

## Issue description
The newly added tests use single quotes for string literals, but the repository style requires double quotes.
## Issue Context
Rule requires aligning new/changed Python code with Ruff/style conventions, including preferring double quotes.
## Fix Focus Areas
- tests/unittest/test_gitea_provider.py[373-383]

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



Informational

4. Unvalidated commits payload ✓ Resolved 🐞 Bug ☼ Reliability
Description
_set_pr_commits() assumes RepoApi.get_pr_commits() returns a list of dicts, but
get_pr_commits() returns raw json.loads() output without validating type; if a non-list/non-dict
shape is returned, reversed(raw_commits) and _GiteaCommitAdapter(raw).get(...) can raise at
runtime.
Code

pr_agent/git_providers/gitea_provider.py[R113-120]

+        raw_commits = self.repo_api.get_pr_commits(
+            owner=self.owner,
+            repo=self.repo,
+            pr_number=self.pr_number
+        ) or []
+        # Gitea returns PR commits newest-first; oldest-first matches GitHub iteration order.
+        self.pr_commits = [_GiteaCommitAdapter(commit) for commit in reversed(raw_commits)]
+        if not self.pr_commits:
Evidence
get_pr_commits() returns whatever json.loads() produces and _set_pr_commits() immediately
reverses/iterates it and assumes dict-like .get() in the adapter, which will fail for unexpected
shapes.

pr_agent/git_providers/gitea_provider.py[111-120]
pr_agent/git_providers/gitea_provider.py[1086-1109]

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

## Issue description
`_set_pr_commits()` iterates `reversed(raw_commits)` and passes each element to `_GiteaCommitAdapter` which calls `.get()`. `RepoApi.get_pr_commits()` returns `json.loads()` output directly with no validation.
## Issue Context
While the endpoint is expected to return a list, defensive validation prevents hard crashes if the response is an object, an error payload, or contains unexpected elements.
## Fix Focus Areas
- pr_agent/git_providers/gitea_provider.py[111-120]
- pr_agent/git_providers/gitea_provider.py[1086-1110]
### Suggested fix
- In `_set_pr_commits()`: if `raw_commits` is not a `list`, log error and treat as empty.
- Filter/skip any non-mapping elements before adapting.
- Optionally harden `_GiteaCommitAdapter` to accept only mappings (else treat as `{}`).

ⓘ 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.

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

@naorpeled

Copy link
Copy Markdown
Member

Hey @vaibzde,
can you please address Qodo's feedback?

…s nothing

_set_pr_commits() could leave last_commit/last_commit_id as None when the PR
commits endpoint returned an empty list, but downstream code (the description
header, publish_inline_comments) dereferences .sha unconditionally. Fall back
to a commit wrapping self.sha instead of None, so those paths always get a
real SHA. Also guard against a non-list commits payload instead of assuming
list/dict shape, and switch the new test file's string literals to double
quotes to match repo style.
@vaibzde

vaibzde commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor Author

@naorpeled pushed a fix addressing all three Qodo findings:

  1. None last_commit_id deref (action required) — _set_pr_commits() now falls back to a commit wrapping self.sha (the PR head) instead of None when the commits endpoint returns nothing, so publish_inline_comments() and the description header always get a real SHA instead of an empty string or an AttributeError.
  2. Single quotes in new tests (style) — switched the new test class to double quotes.
  3. Unvalidated commits payload (optional) — _set_pr_commits() now checks the payload is actually a list before iterating, and filters non-dict elements, instead of assuming the shape.

Updated test_no_commits_leaves_last_commit_unset_without_raising to reflect the new fallback behavior (renamed to test_no_commits_falls_back_to_a_commit_wrapping_the_head_sha) and added a test for the non-list payload guard.

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

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit e0bdea9

@naorpeled
naorpeled merged commit 4a26c38 into The-PR-Agent:main Aug 1, 2026
5 checks passed
developerdesigner18 pushed a commit to developerdesigner18/DDS-PR-AGENT that referenced this pull request Aug 17, 2026
developerdesigner18 pushed a commit to developerdesigner18/DDS-PR-AGENT that referenced this pull request Sep 3, 2026
developerdesigner18 pushed a commit to developerdesigner18/DDS-PR-AGENT that referenced this pull request Sep 9, 2026
developerdesigner18 pushed a commit to developerdesigner18/DDS-PR-AGENT that referenced this pull request Sep 14, 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