Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 34 additions & 12 deletions pr_agent/git_providers/gitlab_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -1000,13 +1000,14 @@ def _get_own_user_id(self) -> Optional[int]:
self._own_user_id = None
return self._own_user_id

def get_pr_file_content(self, file_path: str, branch: str, propagate_errors: bool = False) -> str:
def get_pr_file_content(self, file_path: str, branch: str, propagate_errors: bool = False,
missing_is_error: bool = False) -> str:
try:
file_obj = self.gl.projects.get(self.id_project, lazy=True).files.get(file_path, branch)
content = file_obj.decode()
return decode_if_bytes(content)
except GitlabGetError as e:
if propagate_errors and getattr(e, "response_code", None) != 404:
if propagate_errors and (missing_is_error or getattr(e, "response_code", None) != 404):
raise
return ''
except (GitlabError, RequestException, ValueError, AttributeError) as e:
Expand Down Expand Up @@ -1159,17 +1160,37 @@ def get_diff_files(self) -> list[FilePatchInfo]:

# allow only a limited number of files to be fully loaded. We can manage the rest with diffs only
counter_valid += 1
content_fetch_failed = False
if counter_valid < MAX_FILES_ALLOWED_FULL or not diff['diff']:
original_file_content_str = (
''
if not incremental_active and diff['new_file']
else self.get_pr_file_content(diff['old_path'], base_sha_for_content)
# Missing GitLab patches require every applicable content read. Treat an
# unexpected 404 as a failed read, or an empty side would invent changes.
strict_options = {"propagate_errors": True, "missing_is_error": True} if not diff['diff'] else {}
old_options = (
{"propagate_errors": True}
if incremental_active and diff['new_file'] and not diff['diff'] else strict_options
)
new_file_content_str = (
''
if not incremental_active and diff['deleted_file']
else self.get_pr_file_content(diff['new_path'], head_sha_for_content)
new_options = (
{"propagate_errors": True}
if incremental_active and diff['deleted_file'] and not diff['diff'] else strict_options
)
try:
original_file_content_str = (
''
if not incremental_active and diff['new_file']
else self.get_pr_file_content(diff['old_path'], base_sha_for_content, **old_options)
)
new_file_content_str = (
''
if not incremental_active and diff['deleted_file']
else self.get_pr_file_content(diff['new_path'], head_sha_for_content, **new_options)
)
except Exception as e:
if diff['diff']:
raise
get_logger().warning(f"Cannot reconstruct missing GitLab patch for {diff['new_path']}: {e}")
original_file_content_str = ''
new_file_content_str = ''
content_fetch_failed = True
else:
if counter_valid == MAX_FILES_ALLOWED_FULL:
get_logger().info("Too many files in PR, will avoid loading full content for rest of files")
Expand All @@ -1190,7 +1211,7 @@ def get_diff_files(self) -> list[FilePatchInfo]:

filename = diff['new_path']
patch = diff['diff']
if not patch:
if not patch and not content_fetch_failed:
patch = load_large_diff(filename, new_file_content_str, original_file_content_str)


Expand All @@ -1205,7 +1226,8 @@ def get_diff_files(self) -> list[FilePatchInfo]:
edit_type=edit_type,
old_filename=None if diff['old_path'] == diff['new_path'] else diff['old_path'],
num_plus_lines=num_plus_lines,
num_minus_lines=num_minus_lines, ))
num_minus_lines=num_minus_lines,
content_fetch_failed=content_fetch_failed, ))
if invalid_files_names:
get_logger().info(f"Filtered out files with invalid extensions: {invalid_files_names}")

Expand Down
20 changes: 15 additions & 5 deletions tests/unittest/test_gitlab_diffs_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,9 @@ def make(responses, count="2", project_id="group/sub/repo", metadata_responses=N
provider.diff_files = None
provider.incremental = IncrementalPR(False)
provider._expand_submodule_changes = Mock(side_effect=lambda changes, diff_refs: changes)
provider.get_pr_file_content = Mock(side_effect=lambda path, ref: "old\n" if ref == "base" else "new\n")
provider.get_pr_file_content = Mock(
side_effect=lambda path, ref, **_kwargs: "old\n" if ref == "base" else "new\n"
)
return provider, transport

yield make
Expand Down Expand Up @@ -140,7 +142,10 @@ def test_pruned_patch_on_later_page_is_reconstructed_from_both_blobs(provider_fa

assert [file.filename for file in files] == ["visible.py", "pruned.py"]
assert "-old" in files[1].patch and "+new" in files[1].patch
provider.get_pr_file_content.assert_has_calls([call("pruned.py", "base"), call("pruned.py", "head")])
strict = {"propagate_errors": True, "missing_is_error": True}
provider.get_pr_file_content.assert_has_calls([
call("pruned.py", "base", **strict), call("pruned.py", "head", **strict)
])
assert len(transport.diff_requests) == 2


Expand Down Expand Up @@ -281,7 +286,7 @@ def test_fresh_metadata_supplies_count_and_blob_refs_without_mutating_cached_mr(
)
cached_mr = provider.mr
cached_refs = dict(cached_mr.diff_refs)
provider.get_pr_file_content.side_effect = lambda path, ref: "old\n" if ref == "fresh-base" else "new\n"
provider.get_pr_file_content.side_effect = lambda path, ref, **_kwargs: "old\n" if ref == "fresh-base" else "new\n"

files = provider.get_diff_files()

Expand All @@ -290,7 +295,10 @@ def test_fresh_metadata_supplies_count_and_blob_refs_without_mutating_cached_mr(
assert provider.mr is cached_mr
assert provider.mr.changes_count == "1000+"
assert provider.mr.diff_refs == cached_refs
assert provider.get_pr_file_content.call_args_list == [call("a.py", "fresh-base"), call("a.py", "fresh-head")]
strict = {"propagate_errors": True, "missing_is_error": True}
assert provider.get_pr_file_content.call_args_list == [
call("a.py", "fresh-base", **strict), call("a.py", "fresh-head", **strict)
]
assert provider._expand_submodule_changes.call_args.args[1] == fresh["diff_refs"]
assert len(transport.requests) == 3

Expand Down Expand Up @@ -402,8 +410,10 @@ def test_incremental_ref_movement_falls_back_to_fresh_full_collection(provider_f
assert provider.git_files is None and provider.diff_files is None
assert provider.unreviewed_files_map == {}
assert [file.filename for file in provider.get_diff_files()] == ["a.py", "b.py"]
strict = {"propagate_errors": True, "missing_is_error": True}
provider.get_pr_file_content.assert_has_calls([
call("a.py", fresh["diff_refs"]["base_sha"]), call("a.py", fresh["diff_refs"]["head_sha"]),
call("a.py", fresh["diff_refs"]["base_sha"], **strict),
call("a.py", fresh["diff_refs"]["head_sha"], **strict),
])
assert len(transport.diff_requests) == 2
assert len(transport.requests) == 6
65 changes: 65 additions & 0 deletions tests/unittest/test_gitlab_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,71 @@ def test_get_pr_file_content_strict_missing_file_is_empty(self, gitlab_provider,

assert content == ""

def test_get_pr_file_content_required_file_raises_on_404(self, gitlab_provider, mock_project):
mock_project.files.get.side_effect = GitlabGetError("404 Not Found", response_code=404)

with pytest.raises(GitlabGetError):
gitlab_provider.get_pr_file_content(
"CHANGELOG.md", "main", propagate_errors=True, missing_is_error=True
)

@pytest.mark.parametrize("failed_ref,status", [("base", 404), ("head", 500)])
def test_missing_patch_does_not_invent_changes_after_content_error(
self, gitlab_provider, mock_project, failed_ref, status
):
gitlab_provider._get_merge_request_changes = MagicMock(return_value={
"changes": [{
"old_path": "src/app.py", "new_path": "src/app.py", "diff": "",
"new_file": False, "deleted_file": False, "renamed_file": False,
}],
"diff_refs": {"base_sha": "base", "head_sha": "head"},
})

def get_file(_path, ref):
if ref == failed_ref:
raise GitlabGetError("File unavailable", response_code=status)
file_obj = MagicMock()
file_obj.decode.return_value = b"real content\n"
return file_obj

mock_project.files.get.side_effect = get_file
with patch.object(gitlab_provider, "_expand_submodule_changes", side_effect=lambda changes, refs: changes):
files = gitlab_provider.get_diff_files()

assert len(files) == 1
assert files[0].filename == "src/app.py"
assert files[0].patch == ""
assert files[0].content_fetch_failed is True

@pytest.mark.parametrize("new_file,expected_ref", [(True, "head"), (False, "base")])
def test_incremental_missing_patch_allows_absent_file_side(
self, gitlab_provider, mock_project, new_file, expected_ref
):
change = {
"old_path": "src/app.py", "new_path": "src/app.py", "diff": "",
"new_file": new_file, "deleted_file": not new_file, "renamed_file": False,
}
gitlab_provider.incremental = IncrementalPR(True)
gitlab_provider.incremental.last_seen_commit = MagicMock(sha="base")
gitlab_provider._incremental_head_sha = "head"
gitlab_provider.unreviewed_files_map = {"src/app.py": change}
file_obj = MagicMock()
file_obj.decode.return_value = b"real content\n"

def get_file(_path, ref):
if ref != expected_ref:
raise GitlabGetError("404 Not Found", response_code=404)
return file_obj

mock_project.files.get.side_effect = get_file

with patch.object(gitlab_provider, "_expand_submodule_changes", side_effect=lambda changes, refs: changes):
files = gitlab_provider.get_diff_files()

assert mock_project.files.get.call_count == 2
assert files[0].patch
assert files[0].content_fetch_failed is False

@pytest.mark.parametrize(
"error",
[
Expand Down
Loading