π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
ci: check for module-level names dropped by a refactor (#4029)
Shlok Vaishnavab8552871b3f
diff --git a/.github/scripts/check_import_surface.py b/.github/scripts/check_import_surface.pynew file mode 100644index 000000000..add9d504f--- /dev/null+++ b/.github/scripts/check_import_surface.py@@ -0,0 +1,356 @@+#!/usr/bin/env python3++# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Flag module-level names that a change removes from a ``kornia/`` module.++Refactors sometimes drop a name that used to be bound at module scope --+either a documented export (listed in ``__all__``) or a name that was merely+importable because of how the module happened to be written (e.g. ``from+kornia.core import ..., pad, ...`` made ``pad`` importable from that module+too, even though it was never in ``__all__``). Either kind of removal can+silently break third-party code. See #3986.++This script statically compares the set of module-level names bound in each+changed ``kornia/**/*.py`` file between a base revision and the working tree,+using ``ast`` only -- it never imports kornia, so it works even when the+environment can't build/run the package.++Usage::++ python3 .github/scripts/check_import_surface.py --base-ref origin/main++Exit status is 1 only when a name is removed from ``__all__`` (a break of+documented public API, per the stability policy). Names that disappear from+module scope but were never in ``__all__`` are reported for visibility but do+not fail the check -- hard-failing on those would make every incidental+third-party re-export permanent API. Two exemptions from the hard-fail path:++- A module with a module-level ``__getattr__`` in the new revision is+ presumed to be using it as a deprecation shim (the pattern+ ``kornia.utils`` uses) -- its removals are reported, not fatal.+- ``kornia.contrib`` is the Experimental tier per+ ``docs/source/get-started/stability.rst`` ("No stability promise") --+ its removals are reported, not fatal.+"""++from __future__ import annotations++import argparse+import ast+import subprocess+import sys+from dataclasses import dataclass, field+++def _is_type_checking(test: ast.expr) -> bool:+ """Whether an `if` test is (a reference to) `typing.TYPE_CHECKING`."""+ if isinstance(test, ast.Name):+ return test.id == "TYPE_CHECKING"+ if isinstance(test, ast.Attribute):+ return test.attr == "TYPE_CHECKING"+ return False+++@dataclass+class ModuleSurface:+ """Names bound at module scope, split into documented and undocumented."""++ all_names: set[str] = field(default_factory=set)+ """Names listed in this module's ``__all__``, if it defines one."""++ other_names: set[str] = field(default_factory=set)+ """Other names bound at module scope (defs, assignments, imports)."""++ has_all: bool = False+ """Whether the module defines ``__all__`` at all."""++ has_getattr: bool = False+ """Whether the module defines a module-level ``__getattr__`` (deprecation shim)."""+++def _string_literals(node: ast.AST) -> list[str]:+ """Extract string literals from a list/tuple/set literal AST node."""+ if not isinstance(node, (ast.List, ast.Tuple, ast.Set)):+ return []+ return [elt.value for elt in node.elts if isinstance(elt, ast.Constant) and isinstance(elt.value, str)]+++def parse_module_surface(source: str | bytes) -> ModuleSurface:+ """Parse a module's source and collect the names it binds at module scope.++ Accepts bytes as well as text, and hands them to `ast.parse` undecoded so+ that a PEP 263 coding cookie is honored exactly as the interpreter honors+ it -- the same source Python can import is the source this can parse.++ Recurses into ``try``/``except``/``else``/``finally`` and plain ``if``+ bodies, since names bound there (e.g. a version-conditional import) are+ still real module-scope bindings. The one deliberate exception is an+ ``if TYPE_CHECKING:`` body: those names are never bound at runtime, so+ they are neither surface nor regression.+ """+ surface = ModuleSurface()++ def walk(body: list[ast.stmt]) -> None:+ for node in body:+ if isinstance(node, ast.If):+ walk(node.orelse if _is_type_checking(node.test) else node.body + node.orelse)+ elif isinstance(node, ast.Try):+ walk(node.body + node.orelse + node.finalbody)+ for handler in node.handlers:+ walk(handler.body)+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ if node.name == "__getattr__":+ surface.has_getattr = True+ surface.other_names.add(node.name)+ elif isinstance(node, ast.Import):+ for alias in node.names:+ surface.other_names.add(alias.asname or alias.name.split(".")[0])+ elif isinstance(node, ast.ImportFrom):+ for alias in node.names:+ if alias.name == "*":+ continue+ surface.other_names.add(alias.asname or alias.name)+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]+ is_all_assignment = any(isinstance(t, ast.Name) and t.id == "__all__" for t in targets)+ if is_all_assignment:+ surface.has_all = True+ value = node.value+ if isinstance(value, ast.BinOp):+ # Tolerate `__all__ = [...] + [...]`.+ for side in (value.left, value.right):+ surface.all_names.update(_string_literals(side))+ elif value is not None:+ surface.all_names.update(_string_literals(value))+ continue+ for t in targets:+ if isinstance(t, ast.Name):+ surface.other_names.add(t.id)++ walk(ast.parse(source).body)++ # Anything in __all__ is, by definition, also bound at module scope --+ # keep other_names as "everything else" so the two sets are disjoint.+ surface.other_names -= surface.all_names+ return surface+++def _git_show(ref: str, path: str) -> bytes | None:+ """Return the file's bytes at `ref`, or None if it didn't exist there.++ Bytes, not text: decoding is `ast.parse`'s job (see `parse_module_surface`),+ and decoding here with the platform locale (e.g. cp1252 on Windows) would+ raise on non-ASCII source bytes that Python itself reads fine.+ """+ result = subprocess.run( # noqa: S603+ ["git", "show", f"{ref}:{path}"], # noqa: S607+ capture_output=True,+ check=False,+ )+ if result.returncode != 0:+ return None+ return result.stdout+++def _changed_kornia_files(base_ref: str) -> list[str]:+ """Paths under `kornia/` that differ between `base_ref` and the working tree."""+ # Git's "**" glob pathspec only matches when there's at least one directory+ # between "kornia/" and the filename, so "kornia/foo.py" itself wouldn't+ # match "kornia/**/*.py". Scope to the "kornia/" pathspec instead and+ # filter for ".py" ourselves.+ #+ # --no-renames: with rename detection on (the default), a moved module+ # (`git mv old.py new.py`) shows up as only `new.py` -- the old path never+ # reaches check_file, so a module deleted by being renamed away is never+ # diffed against its old __all__. check_file's own FileNotFoundError+ # fallback (_alternate_path) still tolerates the one legitimate rename+ # shape, `x.py` <-> `x/__init__.py` packageification, so this doesn't+ # trade the rename blind spot for a packageification false positive.+ #+ # No `...HEAD`: check_file reads the *working tree*, so the file list has+ # to be the working tree's diff against base too. Committed-range diffing+ # would silently skip a removal that is edited but not yet committed --+ # invisible for the local runs this script documents, identical to+ # `base...HEAD` on CI's clean checkout (base is already the merge-base).+ #+ # -z: without it, git quotes (and octal-escapes) any path holding+ # non-ASCII or special bytes, so the name arrives wrapped in double+ # quotes, fails the ".py" filter below, and drops out of the check+ # entirely. -z also removes the need to un-escape such a name.+ result = subprocess.run( # noqa: S603+ ["git", "diff", "--no-renames", "--name-only", "-z", base_ref, "--", "kornia/"], # noqa: S607+ capture_output=True,+ encoding="utf-8",+ errors="surrogateescape",+ check=True,+ )+ return [name for name in result.stdout.split("\0") if name.endswith(".py")]+++# docs/source/get-started/stability.rst puts kornia.contrib in the Experimental+# tier: "No stability promise." Removals there are reported, never fatal.+EXPERIMENTAL = ("kornia.contrib",)+++def _module_name(path: str) -> str:+ stem = path[: -len(".py")]+ if stem.endswith("/__init__"):+ stem = stem[: -len("/__init__")]+ return stem.replace("/", ".")+++def _is_experimental(module: str) -> bool:+ return any(module == e or module.startswith(e + ".") for e in EXPERIMENTAL)+++def _read_source(path: str) -> bytes:+ """Read a working-tree file as bytes, the way `_git_show` reads the base revision.++ Both ends of the comparison must handle the same bytes. Decoding as UTF-8 text+ here would raise on a module Python imports happily under a PEP 263 cookie, and+ abort the whole check with a traceback rather than reporting that one file.+ """+ with open(path, "rb") as f:+ return f.read()+++def _alternate_path(path: str) -> str:+ """The other file spelling of the same module name (`x.py` <-> `x/__init__.py`)."""+ stem = path[: -len(".py")]+ if stem.endswith("/__init__"):+ return stem[: -len("/__init__")] + ".py"+ return stem + "/__init__.py"+++@dataclass+class FileReport:+ path: str+ removed_from_all: set[str]+ removed_undocumented: set[str]+ fatal: bool+ """Whether removed_from_all should actually fail the check for this file."""+++def diff_surfaces(old: ModuleSurface, new: ModuleSurface) -> tuple[set[str], set[str]]:+ """Return (removed_from_all, removed_undocumented) between two surfaces."""+ removed_from_all = old.all_names - new.all_names+ removed_undocumented = old.other_names - new.other_names - new.all_names+ return removed_from_all, removed_undocumented+++def check_file(base_ref: str, path: str) -> FileReport | None:+ """Compare `path`'s module surface between `base_ref` and the working tree.++ A deleted file is diffed against an empty surface, so removing a whole+ module is reported (and can be fatal) just like emptying its `__all__`.++ Returns None if there's nothing to report (new file, unparsable source,+ or no names removed).+ """+ old_source = _git_show(base_ref, path)+ if old_source is None:+ return None # new file, nothing to compare against++ try:+ new_source: bytes | None = _read_source(path)+ except FileNotFoundError:+ # The path is gone, but the *module* may not be: x.py <-> x/__init__.py is the same+ # importable name (packageification), not a removal. Only try the one alternate+ # spelling -- anything else missing here is a real deletion.+ try:+ new_source = _read_source(_alternate_path(path))+ except (FileNotFoundError, NotADirectoryError, IsADirectoryError):+ new_source = None # module genuinely gone -- diff against an empty surface++ try:+ old_surface = parse_module_surface(old_source)+ new_surface = parse_module_surface(new_source) if new_source is not None else ModuleSurface()+ except (SyntaxError, ValueError):+ # SyntaxError: not valid Python at one end of the diff (a template file, or+ # bytes that don't decode under the module's declared encoding).+ # ValueError: source ast.parse rejects outright, e.g. embedded null bytes.+ return None++ removed_from_all, removed_undocumented = diff_surfaces(old_surface, new_surface)++ if not removed_from_all and not removed_undocumented:+ return None++ # A module-level __getattr__ in the new revision is presumed to be+ # serving these names as a deprecation shim (kornia.utils's pattern) --+ # don't punish the one thing done right.+ fatal = bool(removed_from_all) and not new_surface.has_getattr and not _is_experimental(_module_name(path))+ return FileReport(+ path=path,+ removed_from_all=removed_from_all,+ removed_undocumented=removed_undocumented,+ fatal=fatal,+ )+++def main(argv: list[str] | None = None) -> int:+ """CLI entry point; returns the process exit status."""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--base-ref", default="origin/main", help="Git ref to diff against (default: origin/main)")+ args = parser.parse_args(argv)++ # _changed_kornia_files diffs against the merge-base (triple-dot); check_file must read old+ # content from that same commit, not the tip of base_ref, or the two can disagree whenever+ # base_ref has moved since the branch point (see review discussion on #4029).+ merge_base = subprocess.run( # noqa: S603+ ["git", "merge-base", args.base_ref, "HEAD"], # noqa: S607+ capture_output=True,+ text=True,+ check=False,+ )+ if merge_base.returncode != 0:+ print(f"::error::could not resolve merge-base of {args.base_ref!r} and HEAD")+ return 1+ base = merge_base.stdout.strip()++ try:+ files = _changed_kornia_files(base)+ except subprocess.CalledProcessError as exc:+ # `base` came from merge-base, so this is close to unreachable -- but a check that+ # can't list its files must fail loudly and closed, not traceback (or pass empty).+ print(f"::error::could not list changed files against {base}: {exc.stderr.strip() or exc}")+ return 1++ reports = [r for r in (check_file(base, path) for path in files) if r is not None]++ hard_fail = False+ for report in reports:+ if report.removed_from_all:+ names = sorted(report.removed_from_all)+ if report.fatal:+ hard_fail = True+ print(f"::error file={report.path}::Removed from __all__: {names}")+ else:+ print(f"::notice file={report.path}::Removed from __all__ (exempt, see comment above): {names}")+ if report.removed_undocumented:+ names = sorted(report.removed_undocumented)+ print(+ f"::notice file={report.path}::No longer bound at module scope (was never in "+ f"__all__, so this is informational): {names}"+ )++ return 1 if hard_fail else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/workflows/import-surface.yml b/.github/workflows/import-surface.ymlnew file mode 100644index 000000000..cbf2fc667--- /dev/null+++ b/.github/workflows/import-surface.yml@@ -0,0 +1,30 @@+name: Import Surface++on:+ pull_request:+ branches:+ - main+ paths:+ - 'kornia/**/*.py'+ - '.github/scripts/check_import_surface.py'+ - '.github/workflows/import-surface.yml'++permissions:+ contents: read++jobs:+ check:+ name: Check for dropped module-level names+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ with:+ # Need the PR's merge-base commit to diff against, not just the tip.+ fetch-depth: 0++ - uses: actions/setup-python@v7+ with:+ python-version: '3.12'++ - name: Check import surface+ run: python3 .github/scripts/check_import_surface.py --base-ref "origin/${{ github.base_ref }}"diff --git a/tests/scripts/test_check_import_surface.py b/tests/scripts/test_check_import_surface.pynew file mode 100644index 000000000..6937b0942--- /dev/null+++ b/tests/scripts/test_check_import_surface.py@@ -0,0 +1,540 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+import os+import subprocess+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).parent.parent.parent / ".github" / "scripts"))+from check_import_surface import (+ _changed_kornia_files,+ _is_experimental,+ _module_name,+ check_file,+ diff_surfaces,+ main,+ parse_module_surface,+)+++def test_parse_module_surface_collects_defs_imports_and_assignments():+ source = """+import math+from torch import nn as torch_nn++CONST = 1++def foo():+ pass++class Bar:+ pass+"""+ surface = parse_module_surface(source)+ assert surface.other_names == {"math", "torch_nn", "CONST", "foo", "Bar"}+ assert surface.all_names == set()+ assert surface.has_all is False+++def test_parse_module_surface_reads_all_list():+ source = """+def foo():+ pass++def _private():+ pass++__all__ = ["foo"]+"""+ surface = parse_module_surface(source)+ assert surface.has_all is True+ assert surface.all_names == {"foo"}+ # Anything in __all__ is excluded from other_names, so the two sets stay disjoint.+ assert surface.other_names == {"_private"}+++def test_parse_module_surface_handles_concatenated_all():+ source = """+__all__ = ["a"] + ["b"]+a = 1+b = 2+"""+ surface = parse_module_surface(source)+ assert surface.all_names == {"a", "b"}+++def test_diff_surfaces_flags_all_removal():+ old = parse_module_surface("def foo():\n pass\n\n__all__ = ['foo']\n")+ new = parse_module_surface("__all__ = []\n")+ removed_from_all, removed_undocumented = diff_surfaces(old, new)+ assert removed_from_all == {"foo"}+ assert removed_undocumented == set()+++def test_diff_surfaces_flags_undocumented_removal_separately():+ # This is the pyramid.py/#3986 case: `pad` leaked out via an import that+ # was never in __all__, and a later refactor dropped that import.+ old = parse_module_surface("from torch.nn.functional import pad\n\n__all__ = []\n")+ new = parse_module_surface("__all__ = []\n")+ removed_from_all, removed_undocumented = diff_surfaces(old, new)+ assert removed_from_all == set()+ assert removed_undocumented == {"pad"}+++def test_diff_surfaces_no_change_reports_nothing():+ old = parse_module_surface("def foo():\n pass\n")+ new = parse_module_surface("def foo():\n pass\n\ndef bar():\n pass\n")+ removed_from_all, removed_undocumented = diff_surfaces(old, new)+ assert removed_from_all == set()+ assert removed_undocumented == set()+++def test_parse_module_surface_recurses_into_try_and_if():+ source = """+try:+ import ujson as jsonlib+except ImportError:+ import json as jsonlib++if True:+ def conditional_fn():+ pass+"""+ surface = parse_module_surface(source)+ assert surface.other_names == {"jsonlib", "conditional_fn"}+++def test_parse_module_surface_excludes_type_checking_block():+ source = """+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from torch import Tensor+"""+ surface = parse_module_surface(source)+ # TYPE_CHECKING is bound (a real runtime import); Tensor is not (never runs).+ assert surface.other_names == {"TYPE_CHECKING"}+++def test_parse_module_surface_detects_module_level_getattr():+ source = """+def __getattr__(name):+ raise AttributeError(name)+"""+ surface = parse_module_surface(source)+ assert surface.has_getattr is True+++def test_module_name_from_path():+ assert _module_name("kornia/geometry/transform/pyramid.py") == "kornia.geometry.transform.pyramid"+ assert _module_name("kornia/core/__init__.py") == "kornia.core"+++def test_is_experimental_matches_contrib_and_submodules():+ assert _is_experimental("kornia.contrib") is True+ assert _is_experimental("kornia.contrib.foo") is True+ assert _is_experimental("kornia.core") is False+++def _git(*args, cwd):+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True) # noqa: S603, S607+++def test_check_file_end_to_end_against_a_real_git_repo(tmp_path):+ # Build a throwaway repo so this doesn't depend on kornia's own history.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "mymodule.py"+ mod.write_text("from torch.nn.functional import pad\n\n__all__ = ['foo']\n\ndef foo():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ # Refactor: drop both the undocumented `pad` import and the documented `foo` export.+ mod.write_text("__all__ = []\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "refactor", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ report = check_file("base", "kornia/mymodule.py")+ finally:+ os.chdir(original_cwd)++ assert report is not None+ assert report.removed_from_all == {"foo"}+ assert report.removed_undocumented == {"pad"}+ assert report.fatal is True+++def test_check_file_getattr_shim_is_not_fatal(tmp_path):+ # kornia.utils's own pattern: a name leaves __all__ but is still served+ # dynamically via a module-level __getattr__ deprecation shim.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "mymodule.py"+ mod.write_text("__all__ = ['old_name']\n\ndef old_name():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ mod.write_text("__all__ = []\n\ndef __getattr__(name):\n raise AttributeError(name)\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "shim", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ report = check_file("base", "kornia/mymodule.py")+ finally:+ os.chdir(original_cwd)++ assert report is not None+ assert report.removed_from_all == {"old_name"}+ assert report.fatal is False+++def test_check_file_contrib_removal_is_not_fatal(tmp_path):+ repo = tmp_path / "repo"+ (repo / "kornia" / "contrib").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "contrib" / "experimental.py"+ mod.write_text("__all__ = ['thing']\n\ndef thing():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ mod.write_text("__all__ = []\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "remove", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ report = check_file("base", "kornia/contrib/experimental.py")+ finally:+ os.chdir(original_cwd)++ assert report is not None+ assert report.removed_from_all == {"thing"}+ assert report.fatal is False+++def test_main_uses_merge_base_not_tip_of_base_ref(tmp_path, capsys):+ # Reproduces the review's repro on #4029: the PR branch never touches __all__, but+ # base_ref (main) moves forward *after* the branch point and adds a name to it. Diffing+ # check_file against the tip of base_ref (instead of the merge-base) would blame the PR for+ # a name it never removed. Non-linear on purpose -- the existing linear-history tests can't+ # exercise this, since merge-base and tip coincide when nothing has moved main forward.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)+ _git("checkout", "-q", "-b", "main", cwd=repo)++ mod = repo / "kornia" / "mod.py"+ mod.write_text("__all__ = ['a']\n\ndef a():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)++ _git("checkout", "-q", "-b", "pr", cwd=repo)+ mod.write_text("# a docstring, __all__ untouched\n__all__ = ['a']\n\ndef a():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "pr change", cwd=repo)++ _git("checkout", "-q", "main", cwd=repo)+ mod.write_text("__all__ = ['a', 'b']\n\ndef a():\n pass\n\ndef b():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "main moved on", cwd=repo)++ _git("checkout", "-q", "pr", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ exit_code = main(["--base-ref", "main"])+ finally:+ os.chdir(original_cwd)++ captured = capsys.readouterr()+ assert exit_code == 0+ assert captured.out == ""+++def test_main_flags_module_removed_via_rename(tmp_path, capsys):+ # Rename detection is on by default for `git diff`, so a renamed module shows up as only+ # its new path -- the old path (and its __all__) never reaches check_file unless the file+ # list is built with --no-renames. A module removed by being renamed away is exactly how+ # modules get removed in practice (packageification refactors), so this must still fail.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)+ _git("checkout", "-q", "-b", "main", cwd=repo)++ mod = repo / "kornia" / "oldname.py"+ mod.write_text("__all__ = ['a', 'b']\n\ndef a():\n pass\n\ndef b():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)++ _git("checkout", "-q", "-b", "pr", cwd=repo)+ _git("mv", "kornia/oldname.py", "kornia/newname.py", cwd=repo)+ _git("commit", "-q", "-m", "rename away, dropping the module", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ exit_code = main(["--base-ref", "main"])+ finally:+ os.chdir(original_cwd)++ captured = capsys.readouterr()+ assert exit_code == 1+ assert "kornia/oldname.py" in captured.out+ assert "'a'" in captured.out+ assert "'b'" in captured.out+++def test_main_ignores_packageification_that_keeps_all_intact(tmp_path, capsys):+ # x.py -> x/__init__.py is the same importable module name (kornia.mymodule either way);+ # check_file's alternate-path fallback must recognize that and not treat it as a deletion.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)+ _git("checkout", "-q", "-b", "main", cwd=repo)++ mod = repo / "kornia" / "mymodule.py"+ mod.write_text("__all__ = ['a']\n\ndef a():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)++ _git("checkout", "-q", "-b", "pr", cwd=repo)+ (repo / "kornia" / "mymodule").mkdir()+ _git("mv", "kornia/mymodule.py", "kornia/mymodule/__init__.py", cwd=repo)+ _git("commit", "-q", "-m", "packageify, __all__ untouched", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ exit_code = main(["--base-ref", "main"])+ finally:+ os.chdir(original_cwd)++ captured = capsys.readouterr()+ assert exit_code == 0+ assert captured.out == ""+++def test_check_file_reports_and_fails_whole_module_deletion(tmp_path):+ # Deleting an entire module is the largest version of the break this check exists to catch;+ # it must not pass silently.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "mymodule.py"+ mod.write_text("__all__ = ['a', 'b']\n\ndef a():\n pass\n\ndef b():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ _git("rm", "-q", "kornia/mymodule.py", cwd=repo)+ _git("commit", "-q", "-m", "delete module", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ report = check_file("base", "kornia/mymodule.py")+ finally:+ os.chdir(original_cwd)++ assert report is not None+ assert report.removed_from_all == {"a", "b"}+ assert report.fatal is True+++def test_check_file_contrib_module_deletion_is_not_fatal(tmp_path):+ repo = tmp_path / "repo"+ (repo / "kornia" / "contrib").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "contrib" / "experimental.py"+ mod.write_text("__all__ = ['thing']\n\ndef thing():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ _git("rm", "-q", "kornia/contrib/experimental.py", cwd=repo)+ _git("commit", "-q", "-m", "delete module", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ report = check_file("base", "kornia/contrib/experimental.py")+ finally:+ os.chdir(original_cwd)++ assert report is not None+ assert report.removed_from_all == {"thing"}+ assert report.fatal is False+++def test_changed_kornia_files_lists_only_python_files_under_kornia(tmp_path):+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ (repo / "docs").mkdir()+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ (repo / "kornia" / "a.py").write_text("x = 1\n")+ (repo / "docs" / "b.py").write_text("x = 1\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ (repo / "kornia" / "a.py").write_text("x = 2\n")+ (repo / "docs" / "b.py").write_text("x = 2\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "change", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ files = _changed_kornia_files("base")+ finally:+ os.chdir(original_cwd)++ assert files == ["kornia/a.py"]+++def test_main_flags_removal_in_a_path_git_would_quote(tmp_path, capsys):+ # git quotes paths containing non-ASCII bytes ("kornia/f\303\266o.py") unless the diff is+ # asked for -z output. A quoted name doesn't end in ".py", so the file dropped out of the+ # file list and its __all__ removal passed silently -- the check's one job, skipped for a+ # reason invisible in the log.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "f\u00f6o.py" # escaped to keep this test file pure ASCII+ mod.write_text("__all__ = ['a']\n\ndef a():\n pass\n", encoding="utf-8")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ mod.write_text("__all__ = []\n", encoding="utf-8")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "drop the export", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ exit_code = main(["--base-ref", "base"])+ finally:+ os.chdir(original_cwd)++ captured = capsys.readouterr()+ assert exit_code == 1+ assert "'a'" in captured.out+++def test_main_flags_removal_that_is_not_committed_yet(tmp_path, capsys):+ # check_file reads the *working tree*, so the file list has to be the working tree's diff+ # against base. Listing a committed range instead (base...HEAD) skips an edit that isn't+ # committed yet -- silently reporting "clean" for the local `--base-ref origin/main` run+ # the module docstring tells contributors to make before pushing.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "mymodule.py"+ mod.write_text("__all__ = ['a']\n\ndef a():\n pass\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ mod.write_text("__all__ = []\n") # edited, deliberately not committed++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ exit_code = main(["--base-ref", "base"])+ finally:+ os.chdir(original_cwd)++ captured = capsys.readouterr()+ assert exit_code == 1+ assert "kornia/mymodule.py" in captured.out+ assert "'a'" in captured.out+++def test_check_file_honors_a_declared_source_encoding(tmp_path):+ # PEP 263: a module carrying a coding cookie is valid Python whose bytes aren't UTF-8.+ # Reading either side of the comparison as UTF-8 *text* raised UnicodeDecodeError out of+ # check_file and killed the whole run with a traceback; handing ast.parse the bytes lets+ # it apply the cookie exactly as the interpreter does when importing the same file.+ repo = tmp_path / "repo"+ (repo / "kornia").mkdir(parents=True)+ _git("init", "-q", cwd=repo)+ _git("config", "user.email", "[email protected]", cwd=repo)+ _git("config", "user.name", "Test", cwd=repo)++ mod = repo / "kornia" / "mymodule.py"+ mod.write_bytes(b"# -*- coding: latin-1 -*-\n__all__ = ['a']\n\ndef a():\n pass\n# a latin-1 byte: \xe9\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "base", cwd=repo)+ _git("branch", "base", cwd=repo)++ mod.write_bytes(b"# -*- coding: latin-1 -*-\n__all__ = []\n# a latin-1 byte: \xe9\n")+ _git("add", "-A", cwd=repo)+ _git("commit", "-q", "-m", "drop the export", cwd=repo)++ original_cwd = Path.cwd()+ try:+ os.chdir(repo)+ report = check_file("base", "kornia/mymodule.py")+ finally:+ os.chdir(original_cwd)++ assert report is not None+ assert report.removed_from_all == {"a"}+ assert report.fatal is True