Skip to contentSkip to conversation

Tighten JSON and source type checks

PATCH Applied Tamir Duberstein 2 participants 5 messages Sep 18 – Oct 5

lore
Share & tools
lore
#0 lore raw

v2 cover Tighten JSON and source type checks

Upstream a047342a231d superseded the CI, formatting and checker setup from v1. These three remaining patches narrow JSON and git objects, replace the dynamic writer test double with a typed subclass, and enable strict Pyright checks for source code. They also align the contributor documentation with the uv-based CI workflow.

The Python 3.10 minimum was already part of v1; this revision also updates the interpreter matrix and installation documentation to match.

Assisted-by LLM

---
Changes in v2:
- Rebase onto 0.2.0 and drop the CI, formatting and checker setup
covered by a047342a231d.
- Centralize the mutually recursive JSON object/value aliases and
preserve null label and attachment arrays; model null labels in tests.
- Align the interpreter matrix and installation documentation with
the Python 3.10 minimum already introduced in v1.
- Declare typing-extensions for the test double's override decorator
and update uv.lock without upgrading the retained dependencies.
- Update CONTRIBUTING alongside the README development instructions.
- Link to v1: https://patch.msgid.link/[email protected]

---
Tamir Duberstein (3):
Narrow JSON types and type test doubles
Enable strict pyright source checks
Document local CI checks

 CONTRIBUTING.md           |  17 +--
 README.md                 |  15 ++-
 ci-matrix.sh              |   4 +-
 docs/installation.rst     |   2 +-
 pyproject.toml            |  16 +--
 src/ezgb/__init__.py      |  17 ++-
 src/ezgb/_models.py       |   4 +-
 src/ezgb/_reader.py       | 190 +++++++++++++++++++--------
 src/ezgb/_types.py        |  17 +++
 tests/conftest.py         |  89 ++++++-------
 tests/test_ezgb.py        |  42 ++++--
 tests/test_integration.py |  21 +--
 uv.lock                   | 328 ++++------------------------------------------
 13 files changed, 300 insertions(+), 462 deletions(-)

---
base-commit: b6f280f1dc99d57550e92798167c6a16d53ebf57
change-id: 20260419-stronger-type-checking-64a26f72e878

Best regards,

Signature · 1 line
Tamir Duberstein <[email protected]>
#1 lore raw

PATCH v2 1/3 Narrow JSON types and type test doubles

Describe decoded JSON with mutually recursive object and value aliases, and narrow operation values before using them. Replace the untyped reader handle with Repository and narrow git objects to their expected classes. This supplies the types needed to remove the blanket Pyright exemptions.

Use a typed BugWriter test double instead of attaching private state and replacing methods at runtime. Preserve nullable git-bug arrays and model null label arrays in the existing test fixtures.

Raise the Python minimum to 3.10 for TypeGuard and align the interpreter matrix and installation documentation. Declare typing-extensions for the test double's override decorator on Python 3.10 and 3.11, and update the lockfile for the supported interpreters.

Assisted-by LLM
---
 CONTRIBUTING.md           |   2 +-
 README.md                 |   2 +-
 ci-matrix.sh              |   4 +-
 docs/installation.rst     |   2 +-
 pyproject.toml            |   3 +-
 src/ezgb/__init__.py      |   9 +-
 src/ezgb/_reader.py       | 150 ++++++++++++++++-----
 src/ezgb/_types.py        |  17 +++
 tests/conftest.py         |  89 ++++++-------
 tests/test_ezgb.py        |  42 ++++--
 tests/test_integration.py |  21 +--
 uv.lock                   | 328 ++++------------------------------------------
 12 files changed, 257 insertions(+), 412 deletions(-)
CONTRIBUTING.md +1 -1
index fb21248..ac70676 100644
@@ -26,7 +26,7 @@ contributor guide has a good overview:
 
 ## Coding style
 
-- Python 3.9+, `from __future__ import annotations` in every module.
+- Python 3.10+, `from __future__ import annotations` in every module.
 - `%`-style string formatting to match the existing code.
 - Run `ruff check` and `mypy --strict` before submitting.
 
README.md +1 -1
index ce65d34..3ee811e 100644
@@ -35,7 +35,7 @@ repo.add_comment(bug.id, 'I can reproduce this on Firefox 130.')
 
 ## Requirements
 
-- Python 3.9 or later
+- Python 3.10 or later
 - pygit2 (libgit2 Python bindings)
 - `git-bug` v0.10+ on your `$PATH` (needed for write operations and
   fast cached listing)
ci-matrix.sh +2 -2
index f698b63..e004dc2 100755
@@ -11,9 +11,9 @@ set -eu
 # Missing interpreters are pulled automatically from uv's managed Python
 # cache (python-build-standalone), so no system packages or sudo are needed.
 #
-# Override the version list: PYTHONS="3.9 3.14" ./ci-matrix.sh
+# Override the version list: PYTHONS="3.10 3.14" ./ci-matrix.sh
 
-PYTHONS="${PYTHONS:-3.9 3.10 3.11 3.12 3.13 3.14}"
+PYTHONS="${PYTHONS:-3.10 3.11 3.12 3.13 3.14}"
 
 # Install any requested interpreters that are missing. This is an explicit
 # step because a dev may have set UV_PYTHON_DOWNLOADS=manual globally to
docs/installation.rst +1 -1
index e62bf40..55fa7b3 100644
@@ -11,7 +11,7 @@ Python library
 Requirements
 ^^^^^^^^^^^^
 
-- **Python 3.9** or later.
+- **Python 3.10** or later.
 - **pygit2** -- Python bindings for libgit2 (``pip install pygit2``).
 - **git-bug** (v0.10 or later) must be on your ``$PATH`` if you want to
   create or modify bugs, or to use the fast CLI-cache listing path.
pyproject.toml +2 -1
index 063e67a..3f2ddb9 100644
@@ -7,7 +7,7 @@ name = 'ezgb'
 version = '0.2.0'
 description = 'A standalone Python library for working with git-bug repositories'
 readme = 'README.md'
-requires-python = '>=3.9'
+requires-python = '>=3.10'
 dependencies = ['pygit2']
 license = 'GPL-2.0-or-later'
 license-files = ['COPYING']
@@ -30,6 +30,7 @@ dev = [
     "pytest",
     "ruff",
     "ty",
+    "typing-extensions>=4.4",
 ]
 
 [project.urls]
src/ezgb/__init__.py +7 -2
index 31867fd..eb65cfc 100644
@@ -24,6 +24,7 @@ from ezgb._models import (
     UnsupportedFormatError,
 )
 from ezgb._reader import BugReader
+from ezgb._types import JsonValue
 from ezgb._writer import BugWriter
 
 __all__ = [
@@ -179,11 +180,13 @@ class GitBugRepo:
         if ecode != 0 or not out.strip():
             return None
         try:
-            raw_bugs: list[dict[str, object]] = json.loads(out)
+            raw_bugs: JsonValue = json.loads(out)
         except json.JSONDecodeError:
             return None
+        assert isinstance(raw_bugs, list)
         results: list[BugSummary] = []
         for raw in raw_bugs:
+            assert isinstance(raw, dict)
             bid = str(raw.get('id', ''))
             if not bid:
                 continue
@@ -275,11 +278,13 @@ class GitBugRepo:
         if ecode != 0:
             return []
         try:
-            raw_bugs: list[dict[str, object]] = json.loads(out)
+            raw_bugs: JsonValue = json.loads(out)
         except json.JSONDecodeError:
             return []
+        assert isinstance(raw_bugs, list)
         results: list[Bug] = []
         for raw in raw_bugs:
+            assert isinstance(raw, dict)
             bid = str(raw.get('id', ''))
             if not bid:
                 continue
src/ezgb/_reader.py +115 -35

340 lines not on this page · raw message

src/ezgb/_types.py new file +17 -0
new file mode 100644
index 0000000..d36bfca
@@ -0,0 +1,17 @@
+"""Internal type aliases."""
+
+from __future__ import annotations
+
+from typing import Union
+
+JsonObject = dict[str, 'JsonValue']
+
+JsonValue = Union[
+    None,
+    bool,
+    int,
+    float,
+    str,
+    list['JsonValue'],
+    JsonObject,
+]
tests/conftest.py +41 -48

181 lines not on this page · raw message

tests/test_ezgb.py +33 -9

103 lines not on this page · raw message

tests/test_integration.py +12 -9
index d037423..77315ab 100644
@@ -10,13 +10,12 @@ from __future__ import annotations
 import json
 import shutil
 import subprocess
-from collections.abc import Iterator
 from pathlib import Path
-from typing import Any
 
 import pytest
 
 from ezgb import GitBugRepo, Status
+from ezgb._types import JsonValue
 
 pytestmark = pytest.mark.skipif(
     shutil.which('git-bug') is None,
@@ -25,19 +24,18 @@ pytestmark = pytest.mark.skipif(
 
 
 @pytest.fixture()
-def gb_repo(tmp_path: Path) -> Iterator[GitBugRepo]:
+def gb_repo(tmp_path: Path) -> GitBugRepo:
     """Spin up a temporary git repo with git-bug and a test identity."""
     repo_dir = tmp_path / 'repo'
     repo_dir.mkdir()
     repo_path = str(repo_dir)
 
-    def _run(args: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+    def _run(args: list[str]) -> subprocess.CompletedProcess[str]:
         return subprocess.run(
             args,
             capture_output=True,
             text=True,
             check=True,
-            **kwargs,
         )
 
     # Initialise the git repo
@@ -63,10 +61,15 @@ def gb_repo(tmp_path: Path) -> Iterator[GitBugRepo]:
         ]
     )
     result = _run(['git', '-C', repo_path, 'bug', 'user', '-f', 'json'])
-    users = json.loads(result.stdout)
-    _run(['git', '-C', repo_path, 'bug', 'user', 'adopt', users[0]['id']])
-
-    yield GitBugRepo(repo_path)
+    users: JsonValue = json.loads(result.stdout)
+    assert isinstance(users, list)
+    user = users[0]
+    assert isinstance(user, dict)
+    user_id = user['id']
+    assert isinstance(user_id, str)
+    _run(['git', '-C', repo_path, 'bug', 'user', 'adopt', user_id])
+
+    return GitBugRepo(repo_path)
 
 
 # ------------------------------------------------------------------
uv.lock +25 -303

431 lines not on this page · raw message

Signature · 1 line
2.56.0.rc0.692.g34fd115c35.frankengit
#2 lore raw

PATCH v2 2/3 Enable strict pyright source checks

In reply to Tamir Duberstein

Remove the blanket unknown-type and private-usage exemptions now that JSON and git objects are narrowed before use. Limit the private-usage exception to tests, which intentionally exercise internal helpers.

Move the shared date parser to module scope so GitBugRepo no longer calls a private BugReader method, and give dataclass factories explicit element types.

Assisted-by LLM
---
 pyproject.toml       | 13 +++----------
 src/ezgb/__init__.py |  8 +++-----
 src/ezgb/_models.py  |  4 ++--
 src/ezgb/_reader.py  | 40 ++++++++++++++++++++--------------------
 4 files changed, 28 insertions(+), 37 deletions(-)
pyproject.toml +3 -10
index 3f2ddb9..28289fe 100644
@@ -61,16 +61,9 @@ quote-style = "single"
 # pyright tries to type-check every package in each one).
 exclude = [".venv", ".venv-*"]
 typeCheckingMode = "strict"
-
-# pygit2 ships no type information, so member/variable/argument types coming
-# out of it resolve to Unknown. Relax the strict "unknown type" reports
-# rather than sprinkling casts across every git-object access site.
-reportUnknownArgumentType = false
-reportUnknownMemberType = false
-reportUnknownVariableType = false
-
-# False positives caused by underscore-prefixed helpers used across modules.
-reportPrivateUsage = false
+executionEnvironments = [
+    { root = "tests", reportPrivateUsage = false },
+]
 
 [tool.ty.rules]
 all = "error"
src/ezgb/__init__.py +3 -5
index eb65cfc..1f7d0ab 100644
@@ -23,7 +23,7 @@ from ezgb._models import (
     Status,
     UnsupportedFormatError,
 )
-from ezgb._reader import BugReader
+from ezgb._reader import BugReader, parse_since
 from ezgb._types import JsonValue
 from ezgb._writer import BugWriter
 
@@ -77,9 +77,7 @@ class GitBugRepo:
                 since = since.replace(tzinfo=timezone.utc)
             return int(since.timestamp())
         # str -- delegate to the reader's parser
-        from ezgb._reader import BugReader
-
-        return BugReader._parse_since(since)
+        return parse_since(since)
 
     def list_bugs(
         self,
@@ -207,7 +205,7 @@ class GitBugRepo:
             author_id = author.get('id', '') if isinstance(author, dict) else ''
             raw_labels = raw.get('labels') or []
             if isinstance(raw_labels, list):
-                labels = frozenset(str(lb) for lb in raw_labels)
+                labels: frozenset[str] = frozenset(str(lb) for lb in raw_labels)
             else:
                 labels = frozenset()
             comment_count = raw.get('comments', 0)
src/ezgb/_models.py +2 -2
index 72eb759..426895a 100644
@@ -96,7 +96,7 @@ class Comment:
     text: str
     created_at: datetime
     count: int
-    attachment_ids: list[str] = field(default_factory=list)
+    attachment_ids: list[str] = field(default_factory=list[str])
 
 
 @dataclass
@@ -110,7 +110,7 @@ class Bug:
     created_at: datetime
     labels: set[str]
     comments: list[Comment]
-    metadata: dict[str, str] = field(default_factory=dict)
+    metadata: dict[str, str] = field(default_factory=dict[str, str])
 
 
 @dataclass(frozen=True)
src/ezgb/_reader.py +20 -20
index fe918ec..769604d 100644
@@ -56,6 +56,26 @@ def _is_dict_values(value: dict[_K, _T], value_ty: type[_U]) -> TypeGuard[dict[_
     return all(isinstance(value, value_ty) for value in value.values())
 
 
+def parse_since(since: str) -> int:
+    """Parse a datetime string to a unix timestamp.
+
+    Accepts ISO-8601 variants and ``YYYYMMDDHHMMSS``.
+    """
+    since = since.strip()
+    for fmt in (
+        '%Y-%m-%d %H:%M:%S',
+        '%Y%m%d%H%M%S',
+        '%Y-%m-%dT%H:%M:%SZ',
+        '%Y-%m-%dT%H:%M:%S',
+    ):
+        try:
+            dt = datetime.strptime(since, fmt).replace(tzinfo=timezone.utc)
+            return int(dt.timestamp())
+        except ValueError:
+            continue
+    raise ValueError('cannot parse since=%s' % since)
+
+
 def _combine_ids(primary: str, secondary: str) -> str:
     """Interleave primary and secondary IDs into a CombinedId.
 
@@ -412,26 +432,6 @@ class BugReader:
         """Convert a unix timestamp to a timezone-aware datetime."""
         return datetime.fromtimestamp(unix_ts, tz=timezone.utc)
 
-    @staticmethod
-    def _parse_since(since: str) -> int:
-        """Parse a datetime string to a unix timestamp.
-
-        Accepts ISO-8601 variants and ``YYYYMMDDHHMMSS``.
-        """
-        since = since.strip()
-        for fmt in (
-            '%Y-%m-%d %H:%M:%S',
-            '%Y%m%d%H%M%S',
-            '%Y-%m-%dT%H:%M:%SZ',
-            '%Y-%m-%dT%H:%M:%S',
-        ):
-            try:
-                dt = datetime.strptime(since, fmt).replace(tzinfo=timezone.utc)
-                return int(dt.timestamp())
-            except ValueError:
-                continue
-        raise ValueError('cannot parse since=%s' % since)
-
     def build_bug(
         self,
         bid: str,
Signature · 1 line
2.56.0.rc0.692.g34fd115c35.frankengit
#3 lore raw

PATCH v2 3/3 Document local CI checks

In reply to Tamir Duberstein

Development dependencies are now a dependency group, so the documented .[dev] extra no longer installs them. Document uv sync and ci.sh in the README and contributor guide so local checks include all linters, type checkers and tests.

Assisted-by LLM
---
 CONTRIBUTING.md | 15 ++++++++-------
 README.md       | 13 +++++++------
 2 files changed, 15 insertions(+), 13 deletions(-)
CONTRIBUTING.md +8 -7
index ac70676..0a6a0b7 100644
@@ -28,16 +28,17 @@ contributor guide has a good overview:
 
 - Python 3.10+, `from __future__ import annotations` in every module.
 - `%`-style string formatting to match the existing code.
-- Run `ruff check` and `mypy --strict` before submitting.
+- Run `./ci.sh` before submitting.
 
-## Running tests
+## Development checks
 
-    pip install -e '.[dev]'
-    python -m pytest
+    uv sync --all-groups
+    ./ci.sh
 
-The test suite includes unit tests (using real git objects in temporary
-repos via pygit2) and integration tests that exercise the full stack
-including the `git-bug` binary.
+The CI script runs Ruff, ty, mypy, pyright, and pytest. The test suite
+includes unit tests (using real git objects in temporary repos via
+pygit2) and integration tests that exercise the full stack including the
+`git-bug` binary.
 
 ## Licensing
 
README.md +7 -6
index 3ee811e..4d9042d 100644
@@ -59,16 +59,17 @@ make -C docs html
 
 Then open `docs/_build/html/index.html` in your browser.
 
-## Running tests
+## Development checks
 
 ```bash
-pip install -e '.[dev]'
-python -m pytest
+uv sync --all-groups
+./ci.sh
 ```
 
-The test suite includes unit tests (using real git objects in temporary
-repos via pygit2) and integration tests that exercise the full stack
-including the `git-bug` binary.
+The CI script runs Ruff, ty, mypy, pyright, and pytest. The test suite
+includes unit tests (using real git objects in temporary repos via
+pygit2) and integration tests that exercise the full stack including the
+`git-bug` binary.
 
 ## Contributing
 
Signature · 1 line
2.56.0.rc0.692.g34fd115c35.frankengit
#4 lore raw
In reply to Tamir Duberstein
Quoted 9 lines · Tamir Duberstein

Tighten JSON and source type checks

Upstream a047342a231d superseded the CI, formatting and checker setup from v1. These three remaining patches narrow JSON and git objects, replace the dynamic writer test double with a typed subclass, and enable strict Pyright checks for source code. They also align the contributor documentation with the uv-based CI workflow.

[...]

Applied, thanks!

[1/3] Narrow JSON types and type test doubles

      commit: 5773698ed41ac4a92b541f83173f9dfb51660abd
[2/3] Enable strict pyright source checks
      commit: 03bd9e3106783f39e808227aa8270572e7106083
[3/3] Document local CI checks
      commit: 87b89abeb9465e1e8b406978cb7336d88d1ff315

Best regards,

Signature · 1 line
Konstantin Ryabitsev <[email protected]>