Skip to content

Commit 6403615

Browse files
committed
fix(apidocs): Handle renamed files and bad paths in --files
1 parent 165ce2b commit 6403615

3 files changed

Lines changed: 202 additions & 13 deletions

File tree

‎Makefile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,10 @@ api-owner-map:
8686
@mkdir -p .artifacts
8787
@sentry django api_endpoint_owners --output .artifacts/api-endpoint-owners.json
8888

89-
# Run once to write api_exceptions/exceptions.json. Needs the owner map from `make api-owner-map`.
89+
# Writes api_exceptions/exceptions.json or updates it with ARGS="--files example_file" (note this needs the owner map from `make api-owner-map`)
9090
api-baseline:
9191
@echo "--> Generating the API exceptions baseline"
92-
@python3 -m tools.api_guidelines.generate_baseline
92+
@python3 -m tools.api_guidelines.generate_baseline $(ARGS)
9393

9494
watch-api-docs:
9595
@cd api-docs/ && node ./watch.ts

‎tests/tools/api_guidelines/test_generate_baseline.py‎

Lines changed: 108 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ def test_files_leaves_unlisted_files_alone(fake_repo: Path) -> None:
450450
assert before is not None
451451

452452
# other.py's finding is fixed on disk but it isn't in `--files` so its entry stays
453-
(fake_repo / OTHER_PATH).unlink()
453+
(fake_repo / OTHER_PATH).write_text(OTHER_ENDPOINT.replace('request.GET.get("q")', "None"))
454454
assert _run_main(fake_repo, "--files", PATH) == 0
455455

456456
assert _find(_entries(output), "OtherEndpoint.get", "query:q") == before
@@ -466,12 +466,117 @@ def test_files_skips_paths_outside_src_and_non_python_files(
466466

467467
# PATH is deleted so if it were rescanned its entries would go away
468468
(fake_repo / PATH).unlink()
469+
bad = ["README.md", "tests/example.py", "src/sentry/foo.txt", "sentry/api/endpoints/example.py"]
470+
assert _run_main(fake_repo, "--files", *bad) == 1
471+
472+
assert output.read_text() == before
473+
err = capsys.readouterr().err
474+
for path in bad:
475+
assert f"Skipped {path}:" in err
476+
assert "None of the --files paths can be rescanned" in err
477+
478+
479+
def test_files_rescans_the_usable_paths_and_reports_the_rest(
480+
fake_repo: Path, capsys: pytest.CaptureFixture[str]
481+
) -> None:
482+
assert _run_main(fake_repo) == 0
483+
484+
_edit_endpoint(fake_repo, ' b = request.GET.get("id") # line 6\n', "")
485+
assert _run_main(fake_repo, "--files", "README.md", PATH) == 0
486+
487+
entry = _find(_entries(fake_repo / "out.json"), "ExampleEndpoint.get", "query:id")
488+
assert entry is not None
489+
assert entry["count"] == 1
490+
out, err = capsys.readouterr()
491+
assert "Rescanned 1 files" in out
492+
assert "Skipped README.md:" in err
493+
494+
495+
def test_files_takes_absolute_paths_inside_root(
496+
fake_repo: Path, tmp_path_factory: pytest.TempPathFactory, capsys: pytest.CaptureFixture[str]
497+
) -> None:
498+
# another checkout, i.e an older commit's worktree, where get reads id once
499+
other = tmp_path_factory.mktemp("other")
500+
endpoint = other / PATH
501+
endpoint.parent.mkdir(parents=True)
502+
endpoint.write_text(
503+
EXAMPLE_ENDPOINT.replace(' b = request.GET.get("id") # line 6\n', "")
504+
)
505+
assert _run_main(fake_repo) == 0
506+
507+
outside = fake_repo / "src" / "sentry" / "outside.py"
508+
assert _run_main(fake_repo, "--root", str(other), "--files", str(endpoint), str(outside)) == 0
509+
510+
entry = _find(_entries(fake_repo / "out.json"), "ExampleEndpoint.get", "query:id")
511+
assert entry is not None
512+
assert entry["count"] == 1
513+
# a path in another checkout is reported instead of crashing
514+
assert f"Skipped {outside}:" in capsys.readouterr().err
515+
516+
517+
RENAMED_PATH = "src/sentry/api/endpoints/renamed.py"
518+
519+
520+
def test_files_with_a_renamed_file_drops_the_old_entries_and_warns(
521+
fake_repo: Path, capsys: pytest.CaptureFixture[str]
522+
) -> None:
523+
assert _run_main(fake_repo) == 0
524+
output = fake_repo / "out.json"
525+
526+
# a plain `git diff --name-only` lists only the new path of a renamed file
527+
(fake_repo / PATH).rename(fake_repo / RENAMED_PATH)
528+
assert _run_main(fake_repo, "--files", RENAMED_PATH) == 0
529+
530+
paths = set()
531+
for entry in _entries(output):
532+
paths.add(entry["path"])
533+
assert paths == {RENAMED_PATH}
534+
assert _counted_findings(output) == 4
535+
536+
out, err = capsys.readouterr()
537+
assert "3 new, 3 fixed, 0 with a changed count" in out
469538
assert (
470-
_run_main(fake_repo, "--files", "README.md", "tests/example.py", "src/sentry/foo.txt") == 0
539+
f"Possibly moved: S026 {PATH} ExampleEndpoint.get query:id (issues-feed) -> {RENAMED_PATH}"
540+
in err
471541
)
542+
assert err.count("Possibly moved:") == 3
543+
# the move is already reported, so there's no second warning for the old path
544+
assert "Removed" not in err
545+
546+
547+
def test_files_warns_about_a_renamed_file_that_was_not_listed(
548+
fake_repo: Path, capsys: pytest.CaptureFixture[str]
549+
) -> None:
550+
(fake_repo / OTHER_PATH).write_text(OTHER_ENDPOINT)
551+
assert _run_main(fake_repo) == 0
552+
553+
# example.py is renamed but only other.py is listed, so the new path isn't scanned
554+
(fake_repo / PATH).rename(fake_repo / RENAMED_PATH)
555+
assert _run_main(fake_repo, "--files", OTHER_PATH) == 0
556+
557+
paths = set()
558+
for entry in _entries(fake_repo / "out.json"):
559+
paths.add(entry["path"])
560+
assert paths == {OTHER_PATH}
561+
out, err = capsys.readouterr()
562+
assert "0 new, 3 fixed, 0 with a changed count" in out
563+
assert f"Removed 3 entries for {PATH}: it's not in" in err
564+
565+
566+
def test_files_skips_a_missing_path_with_no_entries(
567+
fake_repo: Path, capsys: pytest.CaptureFixture[str]
568+
) -> None:
569+
assert _run_main(fake_repo) == 0
570+
output = fake_repo / "out.json"
571+
before = output.read_text()
572+
573+
typo = "src/sentry/api/endpoints/exampel.py"
574+
assert _run_main(fake_repo, "--files", typo) == 1
472575

473576
assert output.read_text() == before
474-
assert "Rescanned 0 files" in capsys.readouterr().out
577+
err = capsys.readouterr().err
578+
assert f"Skipped {typo}: it's not in" in err
579+
assert "None of the --files paths can be rescanned" in err
475580

476581

477582
def test_files_normalizes_dot_slash_paths(fake_repo: Path) -> None:

‎tools/api_guidelines/generate_baseline.py‎

Lines changed: 92 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from tools.api_guidelines.owners import owner_for
1111
from tools.api_guidelines.rules import BASELINED_RULES
1212
from tools.api_guidelines.scan import collect_findings
13-
from tools.api_guidelines.signature import BaselineSignature, normalize_path
13+
from tools.api_guidelines.signature import BaselineSignature
1414
from tools.flake8_plugin import ApiInputViolation
1515

1616
EXCEPTIONS_PATH = Path("api_exceptions/exceptions.json")
@@ -184,6 +184,46 @@ def diff_entries(
184184
return added, removed, changed
185185

186186

187+
def _possible_moves(
188+
removed: list[dict[str, object]], added: list[dict[str, object]]
189+
) -> list[tuple[dict[str, object], dict[str, object]]]:
190+
"""Finds entries that look like they moved to another file, i.e because the file was renamed
191+
`removed` the entries a run removed
192+
`added` the entries a run added
193+
Returns (removed, added) pairs with the same rule, scope and key in different files. A moved
194+
entry starts over with the defaults, so its old status and reason need copying by hand
195+
"""
196+
# {(rule, scope, key) -> [added entries]}
197+
added_by_finding: dict[tuple[object, object, object], list[dict[str, object]]] = {}
198+
for entry in added:
199+
added_by_finding.setdefault((entry["rule"], entry["scope"], entry["key"]), []).append(entry)
200+
201+
moves: list[tuple[dict[str, object], dict[str, object]]] = []
202+
for old in removed:
203+
for new in added_by_finding.get((old["rule"], old["scope"], old["key"]), []):
204+
moves.append((old, new))
205+
return moves
206+
207+
208+
def _rescan_path(path: str, root: Path) -> str | None:
209+
"""A `--files` path as a repo-relative path in `root`
210+
`path` the path as given, i.e "src/sentry/a.py", "./src/sentry/a.py" or an absolute path inside `root`
211+
`root` the checkout being scanned
212+
Returns the path like "src/sentry/a.py", or None when it isn't a Python file under root/src
213+
"""
214+
path = path.replace("\\", "/")
215+
if path.startswith("/"):
216+
try:
217+
path = Path(path).resolve().relative_to(root.resolve()).as_posix()
218+
except ValueError:
219+
return None
220+
221+
path = path.removeprefix("./")
222+
if not (path.startswith("src/") and path.endswith(".py")):
223+
return None
224+
return path
225+
226+
187227
def _describe(entry: dict[str, object]) -> str:
188228
"""One line naming an entry for the printed summary: rule, path, scope, key and owner"""
189229
return (
@@ -248,18 +288,46 @@ def main(argv: list[str] | None = None) -> int:
248288
old_entries: list[dict[str, object]] = []
249289
kept_entries: list[dict[str, object]] = []
250290

291+
# {path of a file that's gone but wasn't in --files -> how many entries it had}
292+
unlisted_gone: Counter[str] = Counter()
293+
251294
if args.files:
295+
old_entries = json.loads(args.output.read_text())["entries"]
296+
paths_with_entries: set[object] = set()
297+
for entry in old_entries:
298+
paths_with_entries.add(entry["path"])
299+
252300
rescan_paths = []
253-
for path in args.files:
254-
path = normalize_path(path)
255-
# skip repeats too i.e a.py and ./a.py, so the "Rescanned N files" count is right
256-
if path.startswith("src/") and path.endswith(".py") and path not in rescan_paths:
301+
for given in args.files:
302+
path = _rescan_path(given, args.root)
303+
if path is None:
304+
print(f"Skipped {given}: not a .py file under {args.root}/src", file=sys.stderr)
305+
# a missing file with entries was deleted so rescanning it removes them. Without
306+
# entries there's nothing to remove and it's often a typo like exampel.py
307+
elif not (args.root / path).exists() and path not in paths_with_entries:
308+
print(
309+
f"Skipped {given}: it's not in {args.root} and has no entries (a typo, or a deleted file with no findings)",
310+
file=sys.stderr,
311+
)
312+
# skip repeats too i.e file.py and ./file.py, so the "Rescanned N files" count is right
313+
elif path not in rescan_paths:
257314
rescan_paths.append(path)
258315

259-
old_entries = json.loads(args.output.read_text())["entries"]
316+
if not rescan_paths:
317+
print(
318+
"None of the --files paths can be rescanned. Nothing was changed.", file=sys.stderr
319+
)
320+
return 1
321+
260322
for entry in old_entries:
261-
if entry["path"] not in rescan_paths:
262-
kept_entries.append(entry)
323+
if entry["path"] in rescan_paths:
324+
continue
325+
# a file that's gone from the checkout has no findings left, i.e it was renamed and only
326+
# its new path was listed. Keeping its entries would leave them next to the new ones
327+
if not (args.root / str(entry["path"])).exists():
328+
unlisted_gone[str(entry["path"])] += 1
329+
continue
330+
kept_entries.append(entry)
263331

264332
# the scan returns every rule's findings, and only the rules with a baseline are kept. This
265333
# happens before build_entries so the count check below still adds up
@@ -304,6 +372,22 @@ def main(argv: list[str] | None = None) -> int:
304372
print(f" fixed {_describe(entry)}")
305373
for old, new in changed:
306374
print(f" count {_describe(new)}: {old['count']} -> {new['count']}")
375+
moved_from: set[object] = set()
376+
for old, new in _possible_moves(removed, added):
377+
moved_from.add(old["path"])
378+
print(
379+
f"Possibly moved: {_describe(old)} -> {new['path']}. Its status and reason were not "
380+
"carried over, so copy them by hand if they were reviewed.",
381+
file=sys.stderr,
382+
)
383+
# a renamed file whose new path wasn't listed: its findings show up as new on the next run
384+
for path in sorted(unlisted_gone):
385+
if path not in moved_from:
386+
print(
387+
f"Removed {unlisted_gone[path]} entries for {path}: it's not in {args.root} and wasn't "
388+
"in --files. If it was renamed, rescan its new path too.",
389+
file=sys.stderr,
390+
)
307391
else:
308392
print(f"Wrote {len(entries)} entries ({len(finding)} findings) to {args.output}")
309393

0 commit comments

Comments
 (0)