-
Notifications
You must be signed in to change notification settings - Fork 2
Give FormatsConf.FORMATS AST parsing a strategy layer
#162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
wpak-ai
merged 4 commits into
cppalliance:develop
from
whisper67265:fix/ast-strategy-layer
Jul 7, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| # SPDX-FileCopyrightText: 2026 Andrew Zhang <whisper67265@outlook.com> | ||
| # | ||
| # SPDX-License-Identifier: BSL-1.0 | ||
|
|
||
| """Upstream Weblate core format path resolution for ``WEBLATE_FORMATS``.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| import importlib.metadata | ||
| from pathlib import Path | ||
| from typing import Protocol | ||
|
|
||
| import weblate.formats | ||
|
|
||
|
|
||
| class FormatsSourceResolutionError(Exception): | ||
| """Raised when a :class:`FormatsSource` cannot resolve core format paths.""" | ||
|
|
||
| def __init__(self, *, source: str, detail: str) -> None: | ||
| self.source = source | ||
| self.detail = detail | ||
| super().__init__(detail) | ||
|
|
||
|
|
||
| class FormatsSource(Protocol): | ||
| """Strategy for resolving upstream Weblate core ``WEBLATE_FORMATS`` paths.""" | ||
|
|
||
| def core_format_paths(self) -> tuple[str, ...]: | ||
| """Return dotted import paths for stock Weblate format handlers.""" | ||
| raise NotImplementedError | ||
|
|
||
|
|
||
| def _weblate_version() -> str: | ||
| try: | ||
| return importlib.metadata.version("Weblate") | ||
| except importlib.metadata.PackageNotFoundError: | ||
| return "unknown" | ||
|
|
||
|
|
||
| def _formats_models_path() -> Path: | ||
| return Path(weblate.formats.__file__).resolve().parent / "models.py" | ||
|
|
||
|
|
||
| def _parse_formatsconf_formats_ast(models_text: str) -> list[str]: | ||
| """AST-parse ``FormatsConf.FORMATS`` from upstream ``models.py`` source text.""" | ||
| tree = ast.parse(models_text) | ||
| for node in tree.body: | ||
| if isinstance(node, ast.ClassDef) and node.name == "FormatsConf": | ||
| return _formats_assignment_to_strings(node.body) | ||
| msg = "Class FormatsConf not found in weblate formats models source" | ||
| raise RuntimeError(msg) | ||
|
|
||
|
|
||
| def _formats_assignment_to_strings(class_body: list[ast.stmt]) -> list[str]: | ||
| for node in class_body: | ||
| if not isinstance(node, ast.Assign): | ||
| continue | ||
| for target in node.targets: | ||
| if isinstance(target, ast.Name) and target.id == "FORMATS": | ||
| return _string_tuple_or_list(node.value) | ||
| msg = "FORMATS assignment not found on FormatsConf" | ||
| raise RuntimeError(msg) | ||
|
|
||
|
|
||
| def _string_tuple_or_list(node: ast.expr) -> list[str]: | ||
| if isinstance(node, (ast.Tuple, ast.List)): | ||
| out: list[str] = [] | ||
| for elt in node.elts: | ||
| if isinstance(elt, ast.Constant) and isinstance(elt.value, str): | ||
| out.append(elt.value) | ||
| else: | ||
| msg = f"Unexpected literal in FormatsConf.FORMATS: {ast.dump(elt)}" | ||
| raise RuntimeError(msg) | ||
| return out | ||
| msg = f"Unexpected FormatsConf.FORMATS value: {ast.dump(node)}" | ||
| raise RuntimeError(msg) | ||
|
|
||
|
|
||
| class AstFormatsConfSource: | ||
| """Resolve core paths by AST-parsing ``FormatsConf.FORMATS`` in ``models.py``. | ||
|
|
||
| Avoids ``import weblate.formats.models`` during settings import, which can | ||
| raise ``AppRegistryNotReady``. | ||
| """ | ||
|
|
||
| def core_format_paths(self) -> tuple[str, ...]: | ||
| models_py = _formats_models_path() | ||
| try: | ||
| src = models_py.read_text(encoding="utf-8") | ||
| except OSError as exc: | ||
| raise FormatsSourceResolutionError( | ||
| source=str(models_py), | ||
| detail=f"could not read weblate formats models source: {exc}", | ||
| ) from exc | ||
| try: | ||
| core = tuple(_parse_formatsconf_formats_ast(src)) | ||
| except RuntimeError as exc: | ||
| raise FormatsSourceResolutionError( | ||
| source=str(models_py), | ||
| detail=str(exc), | ||
| ) from exc | ||
| except (SyntaxError, ValueError) as exc: | ||
| raise FormatsSourceResolutionError( | ||
| source=str(models_py), | ||
| detail=f"could not parse FormatsConf.FORMATS from {models_py}", | ||
| ) from exc | ||
| if not core: | ||
| raise FormatsSourceResolutionError( | ||
| source=str(models_py), | ||
| detail=f"no format paths parsed from {models_py}", | ||
| ) | ||
| return core | ||
|
|
||
|
|
||
| def resolve_core_weblate_formats( | ||
| *, | ||
| source: FormatsSource | None = None, | ||
| ) -> tuple[str, ...]: | ||
| """Return upstream core format paths via *source* (default: AST parse).""" | ||
| resolved = AstFormatsConfSource() if source is None else source | ||
| try: | ||
| return resolved.core_format_paths() | ||
| except FormatsSourceResolutionError as exc: | ||
| version = _weblate_version() | ||
| msg = ( | ||
| f"boost_weblate: could not resolve core WEBLATE_FORMATS " | ||
| f"(Weblate {version}): {exc.detail} " | ||
| f"(source: {exc.source})" | ||
| ) | ||
| raise RuntimeError(msg) from exc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| # SPDX-FileCopyrightText: 2026 Andrew Zhang <whisper67265@outlook.com> | ||
| # | ||
| # SPDX-License-Identifier: BSL-1.0 | ||
|
|
||
| """Tests for upstream Weblate core format path resolution.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import importlib.metadata | ||
| import importlib.util | ||
| import re | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from boost_weblate.formats.formats_source import ( | ||
| AstFormatsConfSource, | ||
| FormatsSourceResolutionError, | ||
| _parse_formatsconf_formats_ast, | ||
| resolve_core_weblate_formats, | ||
| ) | ||
|
|
||
| _CONTRACT_PREFIX_FORMATSCONF = "Weblate contract broken [FormatsConf.FORMATS AST]:" | ||
|
|
||
|
|
||
| def _load_weblate_formats_models_source() -> str: | ||
| spec = importlib.util.find_spec("weblate") | ||
| if spec is None or not spec.submodule_search_locations: | ||
| msg = f"{_CONTRACT_PREFIX_FORMATSCONF} Weblate is not installed" | ||
| raise AssertionError(msg) | ||
| path = Path(spec.submodule_search_locations[0]) / "formats" / "models.py" | ||
| return path.read_text(encoding="utf-8") | ||
|
|
||
|
|
||
| def test_ast_formats_source_matches_direct_parse() -> None: | ||
| upstream = _load_weblate_formats_models_source() | ||
| expected = tuple(_parse_formatsconf_formats_ast(upstream)) | ||
| got = AstFormatsConfSource().core_format_paths() | ||
| assert got == expected | ||
| assert got | ||
|
|
||
|
|
||
| @pytest.mark.weblate_contract | ||
| def test_weblate_contract_formatsconf_ast() -> None: | ||
| try: | ||
| parsed = _parse_formatsconf_formats_ast(_load_weblate_formats_models_source()) | ||
| except (RuntimeError, SyntaxError, ValueError) as exc: | ||
| msg = f"{_CONTRACT_PREFIX_FORMATSCONF} {exc}" | ||
| raise AssertionError(msg) from exc | ||
| if not parsed: | ||
| msg = ( | ||
| f"{_CONTRACT_PREFIX_FORMATSCONF} " | ||
| "FormatsConf.FORMATS parsed to an empty sequence" | ||
| ) | ||
| raise AssertionError(msg) | ||
|
|
||
|
|
||
| def test_resolve_core_weblate_formats_error_includes_version( | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| ) -> None: | ||
| detail = "FORMATS assignment not found on FormatsConf" | ||
| source_path = "/tmp/models.py" | ||
|
|
||
| def _fail(self: AstFormatsConfSource) -> tuple[str, ...]: | ||
| raise FormatsSourceResolutionError(source=source_path, detail=detail) | ||
|
|
||
| monkeypatch.setattr(AstFormatsConfSource, "core_format_paths", _fail) | ||
|
|
||
| weblate_version = importlib.metadata.version("Weblate") | ||
| with pytest.raises(RuntimeError, match=re.escape(weblate_version)) as exc_info: | ||
| resolve_core_weblate_formats() | ||
| assert detail in str(exc_info.value) | ||
| assert source_path in str(exc_info.value) | ||
|
|
||
|
|
||
| class _FalsyFormatsSource: | ||
| """Strategy that is falsy via ``__bool__`` but still callable.""" | ||
|
|
||
| def __bool__(self) -> bool: | ||
| return False | ||
|
|
||
| def core_format_paths(self) -> tuple[str, ...]: | ||
| return ("custom.formats.FakeFormat",) | ||
|
|
||
|
|
||
| def test_resolve_core_weblate_formats_honors_explicit_falsy_source() -> None: | ||
| assert resolve_core_weblate_formats(source=_FalsyFormatsSource()) == ( | ||
| "custom.formats.FakeFormat", | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.