pyapi-checker 0.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyapi/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from ._version import __version__ as __version__
pyapi/__main__.py ADDED
@@ -0,0 +1,20 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ if __name__ == "__main__":
18
+ from pyapi.cli import app
19
+
20
+ app()
pyapi/_version.py ADDED
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.11.0'
32
+ __version_tuple__ = version_tuple = (0, 11, 0)
33
+
34
+ __commit_id__ = commit_id = None
@@ -0,0 +1,136 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import json
18
+ from pathlib import Path
19
+ from subprocess import CalledProcessError
20
+ from typing import Any
21
+
22
+ from aexpy.models.difference import BreakingRank
23
+
24
+ from .api_processor import APIProcessor, CannotFindAPIVersionError
25
+ from .constants import PYAPI_BUILD_DIR
26
+ from .utils import run
27
+
28
+
29
+ class AexpyAPIProcessor(APIProcessor):
30
+ def __init__(self, project_path: Path, project_name: str, python_index: str):
31
+ self._project_path = project_path
32
+ self._python_index = python_index
33
+ self._build_dir = self._project_path / PYAPI_BUILD_DIR
34
+ self._project_name = project_name
35
+
36
+ def check_api(self, previous_version: str) -> list[str]:
37
+ wheel = self._download_wheel(self._project_path.name, previous_version)
38
+ preprocessed_output = self._preprocess()
39
+ extracted1 = self._extract_from_wheel(wheel, previous_version)
40
+ extracted2 = self._extract_from_preprocessed(preprocessed_output)
41
+ diff_output = self._diff(extracted1, extracted2, previous_version)
42
+ return self._parse_diff(diff_output)
43
+
44
+ def _download_wheel(self, package_name: str, version: str) -> Path:
45
+ download_dir = self._build_dir / "downloads"
46
+ download_dir.mkdir(parents=True, exist_ok=True)
47
+ wheel_glob_pattern = f"{self._project_name.replace('-', '_')}-{version}*.whl"
48
+ present_wheels = list(download_dir.glob(wheel_glob_pattern))
49
+ if len(present_wheels) == 1:
50
+ return present_wheels[0]
51
+ elif len(present_wheels) > 1:
52
+ raise RuntimeError(f"Multiple wheels found before download for {package_name} {version} in {download_dir}.")
53
+ # If not found delete any previously downloaded wheels.
54
+ for dist in download_dir.glob("*"):
55
+ dist.unlink()
56
+ try:
57
+ self._run_python_module(
58
+ [
59
+ "pip",
60
+ "download",
61
+ f"{self._project_name}=={version}",
62
+ "--index-url",
63
+ self._python_index,
64
+ "--no-deps",
65
+ "--only-binary=:all:",
66
+ "-d",
67
+ str(download_dir),
68
+ ]
69
+ )
70
+ except CalledProcessError as e:
71
+ if "Could not find a version that satisfies the requirement" in e.stderr.decode("utf-8"):
72
+ raise CannotFindAPIVersionError(f"Cannot find {package_name} {version} in Python index.", e)
73
+ raise e
74
+ present_wheels = list(download_dir.glob(wheel_glob_pattern))
75
+ if len(present_wheels) == 1:
76
+ return present_wheels[0]
77
+ elif len(present_wheels) > 1:
78
+ raise RuntimeError(f"Multiple wheels found after download for {package_name} {version} in {download_dir}.")
79
+ raise CannotFindAPIVersionError(f"Failed to download {package_name} {version} from Python index.")
80
+
81
+ def _preprocess(self) -> Path:
82
+ preprocessed_output = self._build_dir / f"preprocessed-{self._project_path.name}-source.json"
83
+ self._run_aexpy(["preprocess", "-s", str(self._project_path), str(preprocessed_output)])
84
+ return preprocessed_output
85
+
86
+ def _extract_from_preprocessed(self, preprocessed_output: Path) -> Path:
87
+ extracted_output = self._build_dir / f"extracted-{self._project_path.name}-source.json"
88
+ self._run_aexpy(["extract", str(preprocessed_output), str(extracted_output)])
89
+ return extracted_output
90
+
91
+ def _extract_from_wheel(self, distribution: Path, version: str) -> Path:
92
+ extracted_output = self._build_dir / f"extracted-{self._project_path.name}-{version}.json"
93
+ if extracted_output.exists():
94
+ return extracted_output
95
+ # Remove previous extracted json files from wheels.
96
+ for file in self._build_dir.glob(f"extracted-{self._project_path.name}-*.*.*.json"):
97
+ file.unlink()
98
+ self._run_aexpy(["extract", "-w", str(distribution), str(extracted_output)])
99
+ return extracted_output
100
+
101
+ def _diff(self, extracted1: Path, extracted2: Path, version: str) -> Path:
102
+ diff_output = self._build_dir / f"diff-{self._project_path.name}-{version}.json"
103
+ # TODO(BenjaminLowry): hash source files so we can use old preprocessed and diff files for efficiency.
104
+ # Remove previous diff json files.
105
+ for file in self._build_dir.glob(f"diff-{self._project_path.name}-*.*.*.json"):
106
+ file.unlink()
107
+ self._run_aexpy(["diff", str(extracted1), str(extracted2), str(diff_output)])
108
+ return diff_output
109
+
110
+ def _parse_diff(self, diff_output: Path) -> list[str]:
111
+ diff_json: dict[str, Any] = json.loads(diff_output.read_text())
112
+ maybe_entries = diff_json.get("entries")
113
+ if maybe_entries is None:
114
+ raise RuntimeError(f"Failed to parse diff output: cannot find 'entries' field in {diff_output}")
115
+ api_breaks = []
116
+ for entry in maybe_entries.values():
117
+ maybe_rank = entry.get("rank")
118
+ if maybe_rank is None:
119
+ raise RuntimeError(f"Failed to parse diff output: cannot find 'rank' field in {diff_output}")
120
+ if maybe_rank != BreakingRank.High.value and maybe_rank != BreakingRank.Medium.value:
121
+ continue
122
+
123
+ maybe_kind = entry.get("kind")
124
+ if not maybe_kind:
125
+ raise RuntimeError(f"Failed to parse diff output: cannot find 'kind' field in {diff_output}")
126
+ maybe_message = entry.get("message")
127
+ if not maybe_message:
128
+ raise RuntimeError(f"Failed to parse diff output: cannot find 'message' field in {diff_output}")
129
+ api_breaks.append(f"{maybe_kind}: {maybe_message}")
130
+ return api_breaks
131
+
132
+ def _run_aexpy(self, args: list[str]) -> None:
133
+ self._run_python_module(["aexpy"] + args)
134
+
135
+ def _run_python_module(self, args: list[str]) -> None:
136
+ run(["python3", "-m"] + args)
pyapi/api_processor.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from abc import ABC, abstractmethod
18
+
19
+
20
+ class APIProcessor(ABC):
21
+ """
22
+ Checks the current API of the local code against the API of `previous_version`
23
+ and returns a list of API breaks as string "codes" each representing a single API break.
24
+ These "codes" are what users will have to accept if they choose to accept the break.
25
+ """
26
+
27
+ @abstractmethod
28
+ def check_api(self, previous_version: str) -> list[str]:
29
+ pass
30
+
31
+
32
+ class CannotFindAPIVersionError(Exception):
33
+ pass
pyapi/app.py ADDED
@@ -0,0 +1,180 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import math
18
+ import os
19
+ from dataclasses import asdict
20
+ from functools import cached_property
21
+ from pathlib import Path
22
+
23
+ import tomli
24
+ import yaml
25
+
26
+ from .aexpy_api_processor import AexpyAPIProcessor
27
+ from .api_processor import CannotFindAPIVersionError
28
+ from .color import ANSIColor
29
+ from .config import PyAPICheckerConfig
30
+ from .constants import (
31
+ DOT_PALANTIR_DIR,
32
+ PIP_INDEX_URL_ENV_VAR,
33
+ PYAPI_CHECKER_CONFIG_KEY,
34
+ PYAPI_YML_PATH,
35
+ PYPI_INDEX_URL,
36
+ PYPROJECT_TOML,
37
+ UV_DEFAULT_INDEX_ENV_VAR,
38
+ )
39
+ from .git import get_git_version, get_previous_git_tag_from_HEAD, get_repo_root
40
+ from .model import AcceptedAPIBreak, PyAPIYml
41
+ from .utils import maybe_get_nested_value, print_with_local_color
42
+
43
+
44
+ class PyAPIApplication:
45
+ def __init__(self, project_dir: Path) -> None:
46
+ self._project_dir = project_dir
47
+ self._pyproject_path = self._project_dir / PYPROJECT_TOML
48
+ self._pyproject_toml = tomli.loads((self._pyproject_path).read_text())
49
+
50
+ maybe_name = maybe_get_nested_value(["project", "name"], self._pyproject_toml)
51
+ if not maybe_name:
52
+ raise RuntimeError(f"Failed to find project.name in {self._pyproject_path}")
53
+ if not isinstance(maybe_name, str):
54
+ raise RuntimeError(f"project.name is not a string in {self._pyproject_path}")
55
+ self._project_name: str = maybe_name
56
+
57
+ self._config = PyAPICheckerConfig(**self._pyproject_toml.get("tool", {}).get(PYAPI_CHECKER_CONFIG_KEY, {}))
58
+ self._index = (
59
+ self._config.index
60
+ or os.getenv(PIP_INDEX_URL_ENV_VAR)
61
+ or os.getenv(UV_DEFAULT_INDEX_ENV_VAR)
62
+ or PYPI_INDEX_URL
63
+ )
64
+ self._processor = AexpyAPIProcessor(self._project_dir, self._project_name, self._index)
65
+ self._pyapi_yml_path = self._repo_root / PYAPI_YML_PATH
66
+
67
+ @cached_property
68
+ def _repo_root(self) -> Path:
69
+ return get_repo_root()
70
+
71
+ @cached_property
72
+ def _previous_version(self) -> str:
73
+ previous_git_version = get_previous_git_tag_from_HEAD()
74
+ return self._pyapi_yml_contents.versionOverrides.get(previous_git_version, previous_git_version)
75
+
76
+ @cached_property
77
+ def _pyapi_yml_contents(self) -> PyAPIYml:
78
+ if not self._pyapi_yml_path.exists():
79
+ return PyAPIYml({}, {})
80
+ pyapi_yml = yaml.safe_load(self._pyapi_yml_path.read_text())
81
+ if not isinstance(pyapi_yml, dict):
82
+ raise RuntimeError(f"{self._pyapi_yml_path} is not valid yaml, cannot read to dict.")
83
+ try:
84
+ return PyAPIYml(**pyapi_yml)
85
+ except Exception as e:
86
+ raise RuntimeError(
87
+ f"{self._pyapi_yml_path} does not have the valid structure for pyapi.yml files, cannot read to dict."
88
+ ) from e
89
+
90
+ @cached_property
91
+ def _accepted_breaks_codes(self) -> set[str]:
92
+ return set([b.code for b in self._get_accepted_breaks(self._previous_version)])
93
+
94
+ @cached_property
95
+ def _breaks(self) -> list[str]:
96
+ try:
97
+ return self._processor.check_api(self._previous_version)
98
+ except CannotFindAPIVersionError as e:
99
+ print(e)
100
+ print_with_local_color(
101
+ "If the above version was tagged but failed to publish, apply a version override via:", ANSIColor.RED
102
+ )
103
+ print_with_local_color(" pyapi versionOverride <last-published-version>", ANSIColor.CYAN)
104
+ exit(1)
105
+
106
+ def analyze(self) -> None:
107
+ if get_git_version() == self._previous_version:
108
+ print("Current version is the same as the previous version, this is a release version, skipping analysis.")
109
+ return
110
+
111
+ if not self._breaks:
112
+ print("No Python API breaks found.")
113
+ return
114
+
115
+ unaccepted_breaks = []
116
+ for api_break_code in self._breaks:
117
+ if api_break_code not in self._accepted_breaks_codes:
118
+ unaccepted_breaks.append(api_break_code)
119
+ if not unaccepted_breaks:
120
+ print("No unaccepted Python API breaks found.")
121
+ return
122
+
123
+ print_with_local_color(f"\nPython API breaks found in {self._project_name}:", ANSIColor.RED_UNDERLINED)
124
+ for api_break_code in unaccepted_breaks:
125
+ print_with_local_color(f"{api_break_code}", ANSIColor.RED_HIGH_INTENSITY)
126
+ print("You can accept an API break via:")
127
+ print_with_local_color(f' pyapi acceptBreak "{self._breaks[0]}" ":justification:"', ANSIColor.CYAN)
128
+ print("or all API breaks via:")
129
+ print_with_local_color(' pyapi acceptAllBreaks ":justification:"', ANSIColor.CYAN)
130
+ exit(1)
131
+
132
+ def accept_break(self, code: str, justification: str) -> None:
133
+ if code in self._accepted_breaks_codes:
134
+ print(f"Break '{code}' is already accepted")
135
+ return
136
+
137
+ if not self._breaks or code not in self._breaks:
138
+ print_with_local_color(
139
+ f"\nBreak '{code}' is not a valid Python API break and cannot be accepted", ANSIColor.RED
140
+ )
141
+ exit(1)
142
+
143
+ self._accept_breaks([AcceptedAPIBreak(code=code, justification=justification)])
144
+
145
+ def accept_all_breaks(self, justification: str) -> None:
146
+ if not self._breaks:
147
+ print("No Python API breaks found to accept.")
148
+ return
149
+
150
+ breaks_to_accept = []
151
+ for api_break_code in self._breaks:
152
+ if api_break_code not in self._accepted_breaks_codes:
153
+ breaks_to_accept.append(AcceptedAPIBreak(code=api_break_code, justification=justification))
154
+
155
+ self._accept_breaks(breaks_to_accept)
156
+
157
+ def version_override(self, replacement_version: str) -> None:
158
+ modified_pyapi_yml = self._pyapi_yml_contents.union(
159
+ PyAPIYml(acceptedBreaks={}, versionOverrides={self._previous_version: replacement_version})
160
+ )
161
+ self._write_modified_pyapi_yml(modified_pyapi_yml)
162
+
163
+ def _accept_breaks(self, breaks_to_accept: list[AcceptedAPIBreak]) -> None:
164
+ modified_pyapi_yml = self._pyapi_yml_contents.union(
165
+ PyAPIYml(
166
+ acceptedBreaks={self._previous_version: {self._project_name: breaks_to_accept}}, versionOverrides={}
167
+ )
168
+ )
169
+ self._write_modified_pyapi_yml(modified_pyapi_yml)
170
+
171
+ def _write_modified_pyapi_yml(self, modified_pyapi_yml: PyAPIYml) -> None:
172
+ (self._repo_root / DOT_PALANTIR_DIR).mkdir(exist_ok=True)
173
+ self._pyapi_yml_path.write_text(yaml.safe_dump(asdict(modified_pyapi_yml), width=math.inf))
174
+
175
+ def _get_accepted_breaks(self, version: str) -> list[AcceptedAPIBreak]:
176
+ return self._pyapi_yml_contents.enumerate_breaks(version, self._project_name)
177
+
178
+
179
+ class InvalidAPIBreakAcceptance(Exception):
180
+ pass
pyapi/cli.py ADDED
@@ -0,0 +1,51 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from pathlib import Path
18
+
19
+ import typer
20
+
21
+ from .app import PyAPIApplication
22
+
23
+ app = typer.Typer()
24
+ pyapi_app = PyAPIApplication(Path.cwd().absolute())
25
+
26
+
27
+ @app.command()
28
+ def analyze() -> None:
29
+ pyapi_app.analyze()
30
+
31
+
32
+ @app.command(name="acceptBreak")
33
+ def accept_break(
34
+ code: str,
35
+ justification: str,
36
+ ) -> None:
37
+ pyapi_app.accept_break(code, justification)
38
+
39
+
40
+ @app.command(name="acceptAllBreaks")
41
+ def accept_all_breaks(justification: str) -> None:
42
+ pyapi_app.accept_all_breaks(justification)
43
+
44
+
45
+ @app.command(name="versionOverride")
46
+ def version_override(replacement_version: str) -> None:
47
+ pyapi_app.version_override(replacement_version)
48
+
49
+
50
+ if __name__ == "__main__":
51
+ app()
pyapi/color.py ADDED
@@ -0,0 +1,25 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from enum import Enum
18
+
19
+
20
+ class ANSIColor(Enum):
21
+ NO_COLOR = "\033[0m"
22
+ CYAN = "\033[36m"
23
+ RED = "\033[31m"
24
+ RED_UNDERLINED = "\033[31;4m"
25
+ RED_HIGH_INTENSITY = "\033[91m"
pyapi/config.py ADDED
@@ -0,0 +1,23 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from pydantic import Field
18
+ from pydantic.dataclasses import dataclass
19
+
20
+
21
+ @dataclass
22
+ class PyAPICheckerConfig:
23
+ index: str | None = Field(default=None)
pyapi/constants.py ADDED
@@ -0,0 +1,25 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ DOT_PALANTIR_DIR = ".palantir"
18
+ PIP_INDEX_URL_ENV_VAR = "PIP_INDEX_URL"
19
+ PYAPI_BUILD_DIR = "build/pyapi"
20
+ PYAPI_CHECKER_CONFIG_KEY = "pyapi-checker"
21
+ PYAPI_YML_FILENAME = "pyapi.yml"
22
+ PYAPI_YML_PATH = f"{DOT_PALANTIR_DIR}/{PYAPI_YML_FILENAME}"
23
+ PYPI_INDEX_URL = "https://pypi.org/simple"
24
+ PYPROJECT_TOML = "pyproject.toml"
25
+ UV_DEFAULT_INDEX_ENV_VAR = "UV_DEFAULT_INDEX"
pyapi/git.py ADDED
@@ -0,0 +1,42 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from pathlib import Path
18
+
19
+ from .utils import run
20
+
21
+
22
+ def get_git_version() -> str:
23
+ git_version = run(
24
+ [
25
+ "git",
26
+ "describe",
27
+ "--tags",
28
+ "--always",
29
+ "--first-parent",
30
+ "--abbrev=7",
31
+ ]
32
+ ).strip()
33
+ git_status = run(["git", "status", "--porcelain"]).strip()
34
+ return git_version + (".dirty" if git_status else "")
35
+
36
+
37
+ def get_previous_git_tag_from_HEAD() -> str:
38
+ return run(["git", "describe", "--tags", "--abbrev=0", "HEAD"]).strip()
39
+
40
+
41
+ def get_repo_root() -> Path:
42
+ return Path(run(["git", "rev-parse", "--show-toplevel"]).strip())
pyapi/model.py ADDED
@@ -0,0 +1,40 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ from pydantic.dataclasses import dataclass
18
+
19
+ from .utils import merge_dicts
20
+
21
+
22
+ @dataclass
23
+ class AcceptedAPIBreak:
24
+ code: str
25
+ justification: str
26
+
27
+
28
+ @dataclass
29
+ class PyAPIYml:
30
+ acceptedBreaks: dict[str, dict[str, list[AcceptedAPIBreak]]]
31
+ versionOverrides: dict[str, str]
32
+
33
+ def union(self, other: "PyAPIYml") -> "PyAPIYml":
34
+ return PyAPIYml(
35
+ merge_dicts(self.acceptedBreaks, other.acceptedBreaks),
36
+ merge_dicts(self.versionOverrides, other.versionOverrides),
37
+ )
38
+
39
+ def enumerate_breaks(self, version: str, project_name: str) -> list[AcceptedAPIBreak]:
40
+ return self.acceptedBreaks.get(version, {}).get(project_name, [])
pyapi/py.typed ADDED
File without changes
pyapi/utils.py ADDED
@@ -0,0 +1,66 @@
1
+ """
2
+ Copyright 2025 Palantir Technologies, Inc.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+
17
+ import os
18
+ import subprocess
19
+ from typing import Any
20
+
21
+ from .color import ANSIColor
22
+
23
+
24
+ def maybe_get_nested_value(keys: list[str], d: dict[str, Any]) -> Any | None:
25
+ if len(keys) == 1:
26
+ return d.get(keys[0])
27
+ sub_dict = d.get(keys[0])
28
+ if sub_dict:
29
+ keys.pop(0)
30
+ return maybe_get_nested_value(keys, sub_dict)
31
+ return None
32
+
33
+
34
+ def run(args: list[str]) -> str:
35
+ try:
36
+ res = subprocess.run(args=args, capture_output=True, check=True)
37
+ except subprocess.CalledProcessError as e:
38
+ print(e.stdout.decode("utf-8"))
39
+ print(e.stderr.decode("utf-8"))
40
+ raise e
41
+ return res.stdout.decode("utf-8")
42
+
43
+
44
+ def merge_dicts(dict1: dict[Any, Any], dict2: dict[Any, Any], root_key: str | None = None) -> dict[Any, Any]:
45
+ """
46
+ Merges dictionaries together recursively where key, value pairs in dict2 override key, value
47
+ pairs in dict1 if the keys are the same unless 1) the values are dictionaries and then these
48
+ dictionaries are merged recursively with the same rules or 2) the values are lists in which
49
+ case the list from dict2 is appended to dict1. Returns merged dictionary.
50
+ """
51
+ for key, value in dict2.items():
52
+ full_key_name = root_key + "." + key if root_key else key
53
+ if key in dict1 and isinstance(dict1[key], dict) and isinstance(value, dict):
54
+ dict1[key] = merge_dicts(dict1[key], value, full_key_name)
55
+ elif key in dict1 and isinstance(dict1[key], list) and isinstance(value, list):
56
+ dict1[key] = dict1[key] + value
57
+ else:
58
+ dict1[key] = value
59
+ return dict1
60
+
61
+
62
+ def print_with_local_color(message: str, color: ANSIColor) -> None:
63
+ if os.getenv("CI"):
64
+ print(message)
65
+ return
66
+ print(f"{color.value}{message}{ANSIColor.NO_COLOR.value}")
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyapi-checker
3
+ Version: 0.11.0
4
+ Summary: Tool for checking for breaking changes in Python APIs
5
+ Project-URL: Source code, https://github.com/palantir/pyapi-checker
6
+ Author-email: Benjamin Lowry <benjaminpaullowry.appdev@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.12
16
+ Requires-Dist: aexpy
17
+ Requires-Dist: pip
18
+ Requires-Dist: pydantic
19
+ Requires-Dist: pyyaml
20
+ Requires-Dist: tomli
21
+ Requires-Dist: typer
22
+ Description-Content-Type: text/markdown
23
+
24
+ ## About pyapi-checker
25
+
26
+ Tool for checking for and acknowledging Python API breaking changes. Inspired by [gradle-revapi](https://github.com/revapi/gradle-revapi) and built with the [aexpy](https://github.com/StardustDL/aexpy) API explorer.
27
+
28
+ ## Usage
29
+
30
+ Once you've installed `pyapi-checker` in an environment in your project you can interface with the `pyapi` CLI.
31
+
32
+ `pyapi analyze` is the command for checking for API breaks in your project which will produce output like this if you have 2 API breaks for example, and also exit with exit code 1:
33
+
34
+ ```
35
+ Python API breaks found in my-lib:
36
+ AddRequiredParameter: Add PositionalOrKeyword parameter (functions.bin.parse.parse): new_param.
37
+ MoveParameter: Move parameter (functions.bin.parse.parse): handle_errors: 3 -> 4.
38
+ ```
39
+
40
+ So you would want to include `pyapi analyze` in your CI process to require developers to acknowledge API breaks when creating PRs on a library.
41
+
42
+ ### Accepting Breaks
43
+
44
+ You can accept a single break via:
45
+
46
+ ```bash
47
+ pyapi acceptBreak "{break code}" "{justification why this is ok}"
48
+ ```
49
+
50
+ Or accept all breaks via:
51
+
52
+ ```bash
53
+ pyapi acceptAllBreaks "{justification why this is ok}"
54
+ ```
55
+
56
+ Accepted breaks will populate in the `.palantir/pyapi.yml` file looking like this:
57
+
58
+ ```yaml
59
+ acceptedBreaks:
60
+ version:
61
+ projectName:
62
+ - code: 'break code'
63
+ justification: justification
64
+ ```
65
+
66
+ ### Version overrides
67
+
68
+ Sometimes the previous release will have a successfully applied git tag but a failed publish build. In this case pyapi-checker will fail as it cannot resolve the previous API to compare against. To resolve this, you can set a version override that will use a different version instead of the last git tag. To do so, use the
69
+
70
+ ```bash
71
+ pyapi versionOverride <last-published-version>
72
+ ```
73
+
74
+ command to use the last correctly published version instead. This will create an entry in `.palantir/pyapi.yml` of the following format:
75
+
76
+ ```yaml
77
+ versionOverrides:
78
+ version: <last-published-version>
79
+ ```
80
+
81
+ ## Configuration
82
+
83
+ ### Python Index
84
+
85
+ After identifying the last published version preceeding your current commit, pyapi-checker downloads the corresponding wheel for your package and version from a Python index. If you do not specify an index then pyapi-checker uses the following in order (if set):
86
+
87
+ 1. `PIP_INDEX_URL`
88
+ 2. `UV_DEFAULT_INDEX`
89
+ 3. `https://pypi.org/simple`
90
+
91
+ To manually set an index you can set the following configuration:
92
+
93
+ ```toml
94
+ [tool.pyapi-checker]
95
+ index = "<your-index-url>"
96
+ ```
97
+
98
+ ## Implementation
99
+
100
+ `pyapi-checker` uses [aexpy](https://github.com/StardustDL/aexpy) to power it's API breakage detection. You can check out the list of types of API breaks that `aexpy` detects [here](https://github.com/StardustDL/aexpy/blob/main/docs/change-spec/description.md).
101
+
102
+ _Note: `aexpy` does not consider any breaks to an __internal__ module, function, attribute, etc. a high priority breaking change and thus we will not flag these breaks to you._
@@ -0,0 +1,19 @@
1
+ pyapi/__init__.py,sha256=HEX1GXbaGYfqCwPvUnNhwbW4j-frpV7jB6lSRgtdG5Q,622
2
+ pyapi/__main__.py,sha256=hTYOcZoEGVf2GFOGFdAFDwfOF_Ag2n77f0xrKAIQ3Wk,641
3
+ pyapi/_version.py,sha256=9eKRDJ72C44i2IPiti-C7phzF429SwV2Nogzt0etpr0,706
4
+ pyapi/aexpy_api_processor.py,sha256=76o3CvH-GstBwPnCvJ5R-1JpmkCMi5un7Z-ZeWdbkVw,6471
5
+ pyapi/api_processor.py,sha256=s4GPyVhTZJ8o2rshVGqwxCiHAK-Csjuom5U9VFVKQFU,1067
6
+ pyapi/app.py,sha256=xBX9yv91f6p_Q_wkNY1y61rgkWrYwfpynEa1XVSVttg,7288
7
+ pyapi/cli.py,sha256=-XD_VoL24w3ubpv-sKfXhYs9e1Eo2sJnJlxpXKIRLQQ,1258
8
+ pyapi/color.py,sha256=qRXfR8WDGXHNizbO5JfAYBgSb5W_DNfe8nmmiT4nRf8,758
9
+ pyapi/config.py,sha256=k97BD816nw0He0Bi2gul37xVeq63f3mmxPpyFPco5V4,726
10
+ pyapi/constants.py,sha256=te33RRcdBRL-1RKwE5tAexjwXVIjHN5ojiHm3fYHGkM,935
11
+ pyapi/git.py,sha256=MsYDkx4jB46Y0-4ZSZxRDPL0EtDYviiRZhoeEhMK7n8,1201
12
+ pyapi/model.py,sha256=qiVJsKqNGrEtOcnJWT_1MDAA2soZ4UUrYTvvK-YVUCc,1249
13
+ pyapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ pyapi/utils.py,sha256=srwEdSgjI-IyfkmtkE_u65cx7VzJqPSwQmfaKBQhBwE,2367
15
+ pyapi_checker-0.11.0.dist-info/METADATA,sha256=ShXXf6BNICyfMAhb-c4KApp7hNMhoyGV-PyjtDqTWcQ,3695
16
+ pyapi_checker-0.11.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
17
+ pyapi_checker-0.11.0.dist-info/entry_points.txt,sha256=M2MEd2U1FjKnfsTcItzy5G3AdmkE8JTkIfVNK-A81lE,40
18
+ pyapi_checker-0.11.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
19
+ pyapi_checker-0.11.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyapi = pyapi.cli:app
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.