Harden local CI checks
cover Harden local CI checks
Add a local CI script for ezgb and grow it from the checks that already pass to stricter formatting and type checking.
The series removes stale pytest async configuration, adds Ruff formatting, mypy, pyright, and ty to local CI, and documents the uv-based development workflow.
---
Tamir Duberstein (6):
Add local CI script
Add mypy checks
Add Ruff format check
Add pyright checks
Add ty checks
Document local CI checks
README.md | 13 +- ci.sh | 10 ++ pyproject.toml | 18 ++- src/ezgb/__init__.py | 94 ++++++------ src/ezgb/_git.py | 6 +- src/ezgb/_models.py | 13 +- src/ezgb/_reader.py | 253 ++++++++++++++++++++++---------- src/ezgb/_types.py | 15 ++ src/ezgb/_writer.py | 41 +++--- tests/conftest.py | 207 ++++++++++++++++++-------- tests/test_ezgb.py | 363 +++++++++++++++++++++++++++++----------------- tests/test_integration.py | 89 ++++++++---- 12 files changed, 749 insertions(+), 373 deletions(-)
---
base-commit: a52cb871360374d3cc13fc941869bc1f0bd2c7c9
change-id: 20260419-stronger-type-checking-64a26f72e878
Best regards,
Signature · 1 line
Tamir Duberstein <[email protected]>
PATCH 1/6 Add local CI script
Add a local CI helper with the checks that already pass: Ruff linting and pytest.
Drop stale pytest async options at the same time. This project has no async tests, so those settings only produced warnings.
--- ci.sh | 6 ++++++ pyproject.toml | 2 -- 2 files changed, 6 insertions(+), 2 deletions(-)
ci.sh new file +6 -0
@@ -0,0 +1,6 @@ +#!/usr/bin/env sh + +set -eu + +uv run ruff check +uv run pytest --durations=0
pyproject.toml +0 -2
@@ -41,8 +41,6 @@ where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] addopts = "--tb=short" -asyncio_mode = "strict" -asyncio_default_fixture_loop_scope = "function" [tool.mypy] strict = true
Signature · 1 line
2.53.0
PATCH 2/6 Add mypy checks
In reply to Tamir DubersteinAdd mypy to the local CI script after typing the shared test helpers and fixtures.
Use a typed BugWriter test double instead of attaching ad-hoc private attributes to BugWriter instances.
Bump requires-python to 3.10 because the typed implementation uses TypeGuard.
--- ci.sh | 1 + pyproject.toml | 2 +- src/ezgb/__init__.py | 14 +++- src/ezgb/_reader.py | 162 +++++++++++++++++++++++++++---------- src/ezgb/_types.py | 14 ++++ tests/conftest.py | 147 ++++++++++++++++++++++++---------- tests/test_ezgb.py | 200 ++++++++++++++++++++++++++++------------------ tests/test_integration.py | 59 ++++++++------ 8 files changed, 406 insertions(+), 193 deletions(-)
ci.sh +1 -0
@@ -3,4 +3,5 @@ set -eu uv run ruff check +uv run mypy . uv run pytest --durations=0
pyproject.toml +1 -1
@@ -7,7 +7,7 @@ name = 'ezgb' version = '0.1.1' 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']
src/ezgb/__init__.py +12 -2
@@ -23,6 +23,7 @@ from ezgb._models import ( UnsupportedFormatError, ) from ezgb._reader import BugReader +from ezgb._types import JsonValue from ezgb._writer import BugWriter __all__ = [
@@ -171,11 +172,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
@@ -188,9 +191,14 @@ class GitBugRepo: if isinstance(create_time, dict) else 0) et = (edit_time.get('timestamp', 0) if isinstance(edit_time, dict) else 0) + if not isinstance(ct, (bool, int, float, str)): + ct = 0 + if not isinstance(et, (bool, int, float, str)): + et = 0 author = raw.get('author') or {} author_name = (author.get('name', '') if isinstance(author, dict) else '') + assert isinstance(author_name, str) author_id = (author.get('id', '') if isinstance(author, dict) else '') raw_labels = raw.get('labels') or []
@@ -265,11 +273,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 +119 -43
361 lines not on this page · raw message
src/ezgb/_types.py new file +14 -0
@@ -0,0 +1,14 @@ +"""Internal type aliases.""" +from __future__ import annotations + +from typing import Dict, List, Union + +JsonValue = Union[ + None, + bool, + int, + float, + str, + List['JsonValue'], + Dict[str, 'JsonValue'], +]
tests/conftest.py +103 -44
261 lines not on this page · raw message
tests/test_ezgb.py +123 -77
640 lines not on this page · raw message
tests/test_integration.py +33 -26
213 lines not on this page · raw message
Signature · 1 line
2.53.0
PATCH 3/6 Add Ruff format check
In reply to Tamir DubersteinConfigure Ruff formatting to preserve the repository's single-quote style and add the format check to local CI.
Apply the formatter once so the new check starts green.
--- ci.sh | 1 + pyproject.toml | 3 + src/ezgb/__init__.py | 74 ++++++++++---------- src/ezgb/_git.py | 4 +- src/ezgb/_models.py | 9 +++ src/ezgb/_reader.py | 55 ++++++++++----- src/ezgb/_types.py | 1 + src/ezgb/_writer.py | 27 +++++--- tests/conftest.py | 62 ++++++++++++----- tests/test_ezgb.py | 169 ++++++++++++++++++++++++++++++---------------- tests/test_integration.py | 32 +++++++-- 11 files changed, 290 insertions(+), 147 deletions(-)
ci.sh +1 -0
@@ -3,5 +3,6 @@ set -eu uv run ruff check +uv run ruff format --check uv run mypy . uv run pytest --durations=0
pyproject.toml +3 -0
@@ -47,3 +47,6 @@ strict = true [tool.ruff.lint] select = ["E", "F", "W", "I"] + +[tool.ruff.format] +quote-style = "single"
src/ezgb/__init__.py +39 -35
133 lines not on this page · raw message
src/ezgb/_git.py +3 -1
@@ -3,6 +3,7 @@ # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (C) 2024 by the Linux Foundation """Thin git subprocess helpers for ezgb.""" + from __future__ import annotations import os
@@ -51,7 +52,8 @@ def git_lines(repo_path: str, args: list[str]) -> list[str]: def git_bug_cli( - repo_path: str, args: list[str], + repo_path: str, + args: list[str], stdin: str | None = None, ) -> tuple[int, str, str]: """Run ``git -C REPO bug <args>`` for write operations.
src/ezgb/_models.py +9 -0
@@ -3,6 +3,7 @@ # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (C) 2024 by the Linux Foundation """Data models, enums, exceptions, and constants for ezgb.""" + from __future__ import annotations import enum
@@ -13,6 +14,7 @@ _EPOCH_UTC = datetime.min.replace(tzinfo=timezone.utc) # -- Exceptions -------------------------------------------------------------- + class EzgbError(Exception): """Base exception for all ezgb errors."""
@@ -43,8 +45,10 @@ class CliError(EzgbError): # -- Enums ------------------------------------------------------------------- + class Status(enum.Enum): """Bug status matching git-bug's common.Status values.""" + OPEN = 1 CLOSED = 2
@@ -72,9 +76,11 @@ STATUS_CLOSED: int = 2 # -- Dataclasses ------------------------------------------------------------- + @dataclass(frozen=True) class Identity: """A git-bug user identity.""" + id: str name: str email: str
@@ -84,6 +90,7 @@ class Identity: @dataclass class Comment: """A comment on a bug.""" + id: str author: Identity text: str
@@ -95,6 +102,7 @@ class Comment: @dataclass class Bug: """A git-bug bug snapshot reconstructed from operations.""" + id: str title: str status: Status
@@ -117,6 +125,7 @@ class BugSummary: *edited_at* are available. When built from native git objects, these may be empty/epoch if identity resolution was skipped. """ + id: str title: str status: Status
src/ezgb/_reader.py +37 -18
169 lines not on this page · raw message
src/ezgb/_types.py +1 -0
@@ -1,4 +1,5 @@ """Internal type aliases.""" + from __future__ import annotations from typing import Dict, List, Union
src/ezgb/_writer.py +17 -10
@@ -3,6 +3,7 @@ # SPDX-License-Identifier: GPL-2.0-or-later # Copyright (C) 2024 by the Linux Foundation """CLI wrappers for git-bug write operations.""" + from __future__ import annotations import logging
@@ -35,8 +36,7 @@ class BugWriter: self._repo = repo_path self._reader = reader - def _cli(self, args: list[str], - stdin: str | None = None) -> tuple[int, str, str]: + def _cli(self, args: list[str], stdin: str | None = None) -> tuple[int, str, str]: """Run a git-bug CLI command.""" return git_bug_cli(self._repo, args, stdin=stdin)
@@ -58,9 +58,7 @@ class BugWriter: # Parse human_id from output like "abc1234 created" match = _NEW_BUG_RE.match(out.strip()) if not match: - raise CliError( - 'could not parse bug ID from git bug new output: %s' % out - ) + raise CliError('could not parse bug ID from git bug new output: %s' % out) human_id = match.group(1) self._reader.invalidate()
@@ -71,8 +69,13 @@ class BugWriter: """Add a comment to a bug and return the new Comment.""" bid = self._reader.resolve_bug_id(bid) args = [ - 'bug', 'comment', 'new', bid, - '-F', '-', '--non-interactive', + 'bug', + 'comment', + 'new', + bid, + '-F', + '-', + '--non-interactive', ] ecode, out, err = self._cli(args, stdin=text) if ecode != 0:
@@ -89,8 +92,13 @@ class BugWriter: """ bid = self._reader.resolve_bug_id(bid) args = [ - 'bug', 'comment', 'edit', comment_id, - '-F', '-', '--non-interactive', + 'bug', + 'comment', + 'edit', + comment_id, + '-F', + '-', + '--non-interactive', ] ecode, out, err = self._cli(args, stdin=text) if ecode != 0:
@@ -166,4 +174,3 @@ class BugWriter: invalidate caches after a successful pull. """ return self._cli(['pull', remote]) -
tests/conftest.py +44 -18
129 lines not on this page · raw message
tests/test_ezgb.py +111 -58
416 lines not on this page · raw message
tests/test_integration.py +25 -7
@@ -4,6 +4,7 @@ These tests create ephemeral git repositories, initialize git-bug with a test identity, and exercise the full ezgb stack end-to-end. Skip automatically when ``git-bug`` is not installed. """ + import json import shutil import subprocess
@@ -29,20 +30,34 @@ def gb_repo(tmp_path: Path) -> GitBugRepo: def _run(args: list[str]) -> subprocess.CompletedProcess[str]: return subprocess.run( - args, capture_output=True, text=True, check=True, + args, + capture_output=True, + text=True, + check=True, ) # Initialise the git repo _run(['git', 'init', repo_path]) _run(['git', '-C', repo_path, 'config', 'user.name', 'Test User']) - _run(['git', '-C', repo_path, 'config', 'user.email', - '[email protected]']) + _run(['git', '-C', repo_path, 'config', 'user.email', '[email protected]']) _run(['git', '-C', repo_path, 'commit', '--allow-empty', '-m', 'init']) # Create and adopt a git-bug identity - _run(['git', '-C', repo_path, 'bug', 'user', 'new', - '-n', 'Test User', '-e', '[email protected]', - '--non-interactive']) + _run( + [ + 'git', + '-C', + repo_path, + 'bug', + 'user', + 'new', + '-n', + 'Test User', + '-e', + '[email protected]', + '--non-interactive', + ] + ) result = _run(['git', '-C', repo_path, 'bug', 'user', '-f', 'json']) users: JsonValue = json.loads(result.stdout) assert isinstance(users, list)
@@ -59,6 +74,7 @@ def gb_repo(tmp_path: Path) -> GitBugRepo: # Tests # ------------------------------------------------------------------ + class TestCreateAndRead: def test_round_trip(self, gb_repo: GitBugRepo) -> None: bug = gb_repo.create_bug('Test bug', 'Description text')
@@ -283,11 +299,13 @@ class TestAttachments: # blob. Use the ops blob itself as a stand-in. # Instead, test against an actual blob by writing one via git. import subprocess + repo_path = gb_repo._repo result = subprocess.run( ['git', '-C', repo_path, 'hash-object', '-w', '--stdin'], input=b'test file content', - capture_output=True, check=True, + capture_output=True, + check=True, ) blob_hash = result.stdout.decode().strip()
Signature · 1 line
2.53.0
PATCH 4/6 Add pyright checks
In reply to Tamir DubersteinAdd pyright to local CI with strict source checking.
--- ci.sh | 1 + pyproject.toml | 7 +++++++ src/ezgb/__init__.py | 8 +++----- src/ezgb/_git.py | 2 +- src/ezgb/_models.py | 4 ++-- src/ezgb/_reader.py | 38 +++++++++++++++++++++----------------- src/ezgb/_writer.py | 14 +++++++------- 7 files changed, 42 insertions(+), 32 deletions(-)
ci.sh +1 -0
@@ -5,4 +5,5 @@ set -eu uv run ruff check uv run ruff format --check uv run mypy . +uv run pyright uv run pytest --durations=0
pyproject.toml +7 -0
@@ -26,6 +26,7 @@ classifiers = [ [dependency-groups] dev = [ "mypy", + "pyright", "pytest", "ruff", ]
@@ -50,3 +51,9 @@ select = ["E", "F", "W", "I"] [tool.ruff.format] quote-style = "single" + +[tool.pyright] +typeCheckingMode = "strict" +executionEnvironments = [ + { root = "tests", reportPrivateUsage = false }, +]
src/ezgb/__init__.py +3 -5
@@ -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,
@@ -206,7 +204,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/_git.py +1 -1
@@ -45,7 +45,7 @@ def git_run( def git_lines(repo_path: str, args: list[str]) -> list[str]: """Run a git command and return non-empty output lines.""" - ecode, out = git_run(repo_path, args) + _ecode, out = git_run(repo_path, args) if not isinstance(out, str): out = out.decode(errors='replace') return [line for line in out.split('\n') if line]
src/ezgb/_models.py +2 -2
@@ -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 +21 -17
@@ -57,6 +57,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.
@@ -415,23 +435,7 @@ class BugReader: @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) + return parse_since(since) def build_bug( self,
src/ezgb/_writer.py +7 -7
@@ -77,7 +77,7 @@ class BugWriter: '-', '--non-interactive', ] - ecode, out, err = self._cli(args, stdin=text) + ecode, _out, err = self._cli(args, stdin=text) if ecode != 0: raise CliError('git bug comment new failed: %s' % err) self._reader.invalidate(bid)
@@ -100,7 +100,7 @@ class BugWriter: '-', '--non-interactive', ] - ecode, out, err = self._cli(args, stdin=text) + ecode, _out, err = self._cli(args, stdin=text) if ecode != 0: raise CliError('git bug comment edit failed: %s' % err) self._reader.invalidate(bid)
@@ -112,7 +112,7 @@ class BugWriter: subcmd = 'close' else: subcmd = 'open' - ecode, out, err = self._cli(['bug', 'status', subcmd, bid]) + ecode, _out, err = self._cli(['bug', 'status', subcmd, bid]) if ecode != 0: raise CliError('git bug status %s failed: %s' % (subcmd, err)) self._reader.invalidate(bid)
@@ -121,7 +121,7 @@ class BugWriter: """Edit a bug's title.""" bid = self._reader.resolve_bug_id(bid) args = ['bug', 'title', 'edit', bid, '-t', title] - ecode, out, err = self._cli(args) + ecode, _out, err = self._cli(args) if ecode != 0: raise CliError('git bug title edit failed: %s' % err) self._reader.invalidate(bid)
@@ -129,7 +129,7 @@ class BugWriter: def add_label(self, bid: str, label: str) -> None: """Add a label to a bug.""" bid = self._reader.resolve_bug_id(bid) - ecode, out, err = self._cli( + ecode, _out, err = self._cli( ['bug', 'label', 'new', bid, label], ) if ecode != 0:
@@ -139,7 +139,7 @@ class BugWriter: def remove_label(self, bid: str, label: str) -> None: """Remove a label from a bug.""" bid = self._reader.resolve_bug_id(bid) - ecode, out, err = self._cli( + ecode, _out, err = self._cli( ['bug', 'label', 'rm', bid, label], ) if ecode != 0:
@@ -153,7 +153,7 @@ class BugWriter: remote copies. This is irreversible. """ bid = self._reader.resolve_bug_id(bid) - ecode, out, err = self._cli(['bug', 'rm', bid]) + ecode, _out, err = self._cli(['bug', 'rm', bid]) if ecode != 0: raise CliError('git bug rm failed: %s' % err) # Invalidate everything — the refs list has changed
Signature · 1 line
2.53.0
PATCH 5/6 Add ty checks
In reply to Tamir DubersteinAdd ty to the local CI script with all rules set to errors.
--- ci.sh | 1 + pyproject.toml | 4 ++++ 2 files changed, 5 insertions(+)
ci.sh +1 -0
@@ -4,6 +4,7 @@ set -eu uv run ruff check uv run ruff format --check +uv run ty check uv run mypy . uv run pyright uv run pytest --durations=0
pyproject.toml +4 -0
@@ -29,6 +29,7 @@ dev = [ "pyright", "pytest", "ruff", + "ty", ] [project.urls]
@@ -57,3 +58,6 @@ typeCheckingMode = "strict" executionEnvironments = [ { root = "tests", reportPrivateUsage = false }, ] + +[tool.ty.rules] +all = "error"
Signature · 1 line
2.53.0
PATCH 6/6 Document local CI checks
In reply to Tamir DubersteinReplace the old pytest-only development instructions with the uv workflow and the local CI script.
This keeps contributor documentation aligned with the checks used by the branch.
--- README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-)
README.md +7 -6
@@ -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.53.0
Quoted 9 lines · Tamir Duberstein
Add a local CI script for ezgb and grow it from the checks that already pass to stricter formatting and type checking.
The series removes stale pytest async configuration, adds Ruff formatting, mypy, pyright, and ty to local CI, and documents the uv-based development workflow.
Signed-off-by Tamir Duberstein <[email protected]>
Hi Konstantin, any interest in this series? I'm happy to make changes if needed.
Cheers.
Tamir