Skip to content

Commit 3565acb

Browse files
tarunchaudharydevgithub-issue-actionsclaude
authored
fix(change-detector): compare full push range (#44833)
Co-authored-by: github-issue-actions <github-issue-actions@users.noreply.github.com> Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent f58eb5d commit 3565acb

2 files changed

Lines changed: 199 additions & 10 deletions

File tree

‎scripts/change_detector.py‎

Lines changed: 43 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import re
2222
import subprocess
2323
import time
24-
from typing import List, Optional
24+
from typing import Any, List, Optional
2525
from urllib.error import HTTPError, URLError
2626
from urllib.request import Request, urlopen
2727

@@ -31,6 +31,7 @@
3131
MAX_RETRIES: int = 4
3232
RETRY_BACKOFF_SECONDS: int = 2
3333
REQUEST_TIMEOUT_SECONDS: int = 30
34+
ZERO_SHA = "0" * 40
3435
# GitHub returns 429 when throttling, which is transient and worth retrying
3536
# alongside 5xx server errors. It also returns 403 for two very different
3637
# reasons — a secondary rate limit, and a token missing the required scope —
@@ -223,17 +224,27 @@ def fetch_changed_files_pr(repo: str, pr_number: str) -> List[str]:
223224
return [file_info["filename"] for file_info in files]
224225

225226

226-
def fetch_changed_files_push(repo: str, sha: str) -> List[str]:
227-
"""Fetches files changed in the last commit for push events using GitHub API."""
228-
# Fetch commit details to get the parent SHA
227+
def fetch_changed_files_push(
228+
repo: str, sha: str, before_sha: Optional[str] = None
229+
) -> List[str]:
230+
"""Fetches files changed in a push event using GitHub API."""
231+
if before_sha:
232+
compare_url = (
233+
f"https://api.github.com/repos/{repo}/compare/{before_sha}...{sha}"
234+
)
235+
comparison_data = fetch_files_github_api(compare_url)
236+
return [file["filename"] for file in comparison_data["files"]]
237+
229238
commit_url = f"https://api.github.com/repos/{repo}/commits/{sha}"
230239
commit_data = fetch_files_github_api(commit_url)
240+
231241
if "parents" not in commit_data or len(commit_data["parents"]) < 1:
232242
raise RuntimeError("No parent commit found for comparison.")
243+
233244
parent_sha = commit_data["parents"][0]["sha"]
234-
# Compare the current commit against its parent
235245
compare_url = f"https://api.github.com/repos/{repo}/compare/{parent_sha}...{sha}"
236246
comparison_data = fetch_files_github_api(compare_url)
247+
237248
return [file["filename"] for file in comparison_data["files"]]
238249

239250

@@ -254,6 +265,20 @@ def is_int(s: str) -> bool:
254265
return bool(re.match(r"^-?\d+$", s))
255266

256267

268+
def get_push_event() -> dict[str, Any]:
269+
"""Reads the webhook payload GitHub writes for the triggering event.
270+
271+
Returns an empty dict when `GITHUB_EVENT_PATH` is unset (local runs).
272+
"""
273+
event_path = os.getenv("GITHUB_EVENT_PATH")
274+
275+
if not event_path:
276+
return {}
277+
278+
with open(event_path, encoding="utf-8") as event_file:
279+
return json.load(event_file)
280+
281+
257282
def main(event_type: str, sha: str, repo: str) -> None:
258283
"""Main function to check for file changes based on event context."""
259284
print("SHA:", sha)
@@ -267,9 +292,19 @@ def main(event_type: str, sha: str, repo: str) -> None:
267292
print_files(files)
268293

269294
elif event_type == "push":
270-
files = fetch_changed_files_push(repo, sha)
271-
print("Files touched since previous commit:")
272-
print_files(files)
295+
event = get_push_event()
296+
before_sha = event.get("before")
297+
if event.get("forced") or before_sha == ZERO_SHA:
298+
# A force push rewrites history, so `before...after` diffs against
299+
# the merge base and can miss changes. A zero `before` (a new
300+
# branch's first push) has no base to compare against. Treat both
301+
# like workflow_dispatch/schedule: every group is changed.
302+
print("forced or new-branch push, assuming all changed")
303+
files = None
304+
else:
305+
files = fetch_changed_files_push(repo, sha, before_sha)
306+
print("Files touched by push:")
307+
print_files(files)
273308

274309
elif event_type in ("workflow_dispatch", "schedule"):
275310
# Manual or cron-triggered runs aren't tied to a specific diff, so

‎tests/unit_tests/scripts/change_detector_test.py‎

Lines changed: 156 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515
# specific language governing permissions and limitations
1616
# under the License.
1717
import io
18+
from pathlib import Path
1819
from unittest import mock
1920
from urllib.error import HTTPError, URLError
2021

2122
import pytest
2223

2324
from scripts import change_detector
25+
from superset.utils import json
2426

2527

2628
def _make_response(body: bytes) -> mock.MagicMock:
@@ -188,6 +190,155 @@ def test_grype_config_changes_trigger_docker_build() -> None:
188190
)
189191

190192

193+
def test_fetch_changed_files_push_uses_full_push_range() -> None:
194+
changed_files = [
195+
{"filename": "superset/foo.py"},
196+
{"filename": "superset-frontend/src/foo.tsx"},
197+
]
198+
199+
with mock.patch.object(
200+
change_detector,
201+
"fetch_files_github_api",
202+
return_value={"files": changed_files},
203+
) as fetch_mock:
204+
result = change_detector.fetch_changed_files_push(
205+
"apache/superset",
206+
"after-sha",
207+
"before-sha",
208+
)
209+
210+
assert result == [
211+
"superset/foo.py",
212+
"superset-frontend/src/foo.tsx",
213+
]
214+
215+
fetch_mock.assert_called_once_with(
216+
"https://api.github.com/repos/apache/superset/compare/before-sha...after-sha"
217+
)
218+
219+
220+
def test_get_push_event_returns_empty_without_event_path(
221+
monkeypatch: pytest.MonkeyPatch,
222+
) -> None:
223+
"""Local runs have no event file, so there is no `before` to compare from."""
224+
monkeypatch.delenv("GITHUB_EVENT_PATH", raising=False)
225+
226+
assert change_detector.get_push_event() == {}
227+
228+
229+
def test_get_push_event_reads_event_file(
230+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
231+
) -> None:
232+
"""The webhook payload GitHub writes to GITHUB_EVENT_PATH is returned as-is."""
233+
event = {"before": "before-sha", "after": "after-sha", "forced": False}
234+
event_file = tmp_path / "github-event.json"
235+
event_file.write_text(json.dumps(event))
236+
monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_file))
237+
238+
assert change_detector.get_push_event() == event
239+
240+
241+
def test_main_push_detects_changes_from_multiple_commits(
242+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
243+
) -> None:
244+
"""The push range is `before...after`: the final commit only touches the
245+
frontend, yet python must be detected from the earlier commit. A revert to
246+
the parent-only compare fails the python assertion."""
247+
event_file = tmp_path / "github-event.json"
248+
event_file.write_text(json.dumps({"before": "before-sha", "after": "after-sha"}))
249+
output_file = tmp_path / "github-output"
250+
monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_file))
251+
monkeypatch.setenv("GITHUB_OUTPUT", str(output_file))
252+
253+
responses = {
254+
"https://api.github.com/repos/apache/superset/compare/before-sha...after-sha": {
255+
"files": [
256+
{"filename": "superset/foo.py"},
257+
{"filename": "superset-frontend/src/foo.tsx"},
258+
]
259+
},
260+
"https://api.github.com/repos/apache/superset/commits/after-sha": {
261+
"parents": [{"sha": "parent-sha"}]
262+
},
263+
"https://api.github.com/repos/apache/superset/compare/parent-sha...after-sha": {
264+
"files": [{"filename": "superset-frontend/src/foo.tsx"}]
265+
},
266+
}
267+
with mock.patch.object(
268+
change_detector,
269+
"fetch_files_github_api",
270+
side_effect=lambda url: responses[url],
271+
):
272+
change_detector.main("push", "after-sha", "apache/superset")
273+
274+
output = output_file.read_text()
275+
assert "python=true" in output
276+
assert "frontend=true" in output
277+
278+
279+
def test_main_push_without_event_file_compares_against_parent(
280+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
281+
) -> None:
282+
"""Local runs have no event file, so the parent-only compare is kept."""
283+
output_file = tmp_path / "github-output"
284+
monkeypatch.delenv("GITHUB_EVENT_PATH", raising=False)
285+
monkeypatch.setenv("GITHUB_OUTPUT", str(output_file))
286+
287+
responses = {
288+
"https://api.github.com/repos/apache/superset/commits/after-sha": {
289+
"parents": [{"sha": "parent-sha"}]
290+
},
291+
"https://api.github.com/repos/apache/superset/compare/parent-sha...after-sha": {
292+
"files": [{"filename": "superset-frontend/src/foo.tsx"}]
293+
},
294+
}
295+
with mock.patch.object(
296+
change_detector,
297+
"fetch_files_github_api",
298+
side_effect=lambda url: responses[url],
299+
):
300+
change_detector.main("push", "after-sha", "apache/superset")
301+
302+
output = output_file.read_text()
303+
assert "frontend=true" in output
304+
assert "python=true" not in output
305+
306+
307+
@pytest.mark.parametrize(
308+
"event",
309+
[
310+
pytest.param(
311+
{"before": "a" * 40, "after": "b" * 40, "forced": True},
312+
id="forced-push",
313+
),
314+
pytest.param(
315+
{"before": change_detector.ZERO_SHA, "after": "b" * 40, "forced": False},
316+
id="new-branch-first-push",
317+
),
318+
],
319+
)
320+
def test_main_push_assumes_all_changed_for_forced_or_new_branch_push(
321+
event: dict[str, object], tmp_path: Path, monkeypatch: pytest.MonkeyPatch
322+
) -> None:
323+
"""A force push rewrites history, so `before...after` can skip real changes,
324+
and a zero `before` has no base to compare against. Both must run every
325+
group and every language without calling the GitHub API."""
326+
event_file = tmp_path / "github-event.json"
327+
event_file.write_text(json.dumps(event))
328+
output_file = tmp_path / "github-output"
329+
monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_file))
330+
monkeypatch.setenv("GITHUB_OUTPUT", str(output_file))
331+
332+
with mock.patch.object(change_detector, "fetch_files_github_api") as fetch_mock:
333+
change_detector.main("push", "b" * 40, "apache/superset")
334+
335+
fetch_mock.assert_not_called()
336+
output = output_file.read_text().splitlines()
337+
for group in change_detector.PATTERNS:
338+
assert f"{group}=true" in output
339+
assert 'languages=["javascript", "python"]' in output
340+
341+
191342
@pytest.mark.parametrize(
192343
"path",
193344
[
@@ -252,7 +403,10 @@ def test_main_writes_languages_to_github_output(tmp_path, monkeypatch) -> None:
252403
monkeypatch.setattr(
253404
change_detector,
254405
"fetch_changed_files_push",
255-
lambda repo, sha: ["superset/foo.py", "superset-frontend/src/bar.tsx"],
406+
lambda repo, sha, before_sha=None: [
407+
"superset/foo.py",
408+
"superset-frontend/src/bar.tsx",
409+
],
256410
)
257411

258412
change_detector.main("push", "deadbeef", "apache/superset")
@@ -272,7 +426,7 @@ def test_main_languages_respects_the_99_file_cap(tmp_path, monkeypatch) -> None:
272426
monkeypatch.setattr(
273427
change_detector,
274428
"fetch_changed_files_push",
275-
lambda repo, sha: [f"docs/page{i}.md" for i in range(99)],
429+
lambda repo, sha, before_sha=None: [f"docs/page{i}.md" for i in range(99)],
276430
)
277431

278432
change_detector.main("push", "deadbeef", "apache/superset")

0 commit comments

Comments
 (0)