Skip to contentSkip to conversation

Harden local checks

PATCH Superseded Tamir Duberstein 1 participant 9 messages Apr 20 – Apr 27

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover Harden local checks

This series adds a local CI helper and raises patatt's local quality baseline incrementally while keeping the tree green after each step.

It starts with the checks that already pass, then adds Ruff import and format enforcement, strict pyright, and ty. The later patches make the small typing and cleanup changes needed for the stricter checkers, and remove stale optional-dependency handling for PyNaCl.

---
Tamir Duberstein (7):
Add local CI script
Add Ruff import checks
Add Ruff format check
Add pyright strict checks
Add ty checks
Reduce dictionary lookups
Import PyNaCl unconditionally

 ci.sh                               |  10 +
 conftest.py                         |   3 +-
 docs/conf.py                        |   5 +-
 pyproject.toml                      |  18 +-
 src/patatt/__init__.py              | 480 ++++++++++++++++++++++++------------
 tests/conftest.py                   |  21 +-
 tests/test_validation.py            |  25 +-
 tests/unit/test_byhash.py           |   4 +-
 tests/unit/test_devsig_header.py    |  26 +-
 tests/unit/test_get_algo_keydata.py |  22 +-
 tests/unit/test_patatt_message.py   |  27 +-
 11 files changed, 410 insertions(+), 231 deletions(-)

---
base-commit: f09b5a5681c2b7af33aa5b0fcea659f4534eed9b
change-id: 20260419-stronger-type-checking-3702559acba9

Best regards,

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

PATCH 1/7 Add local CI script

Add a small CI helper that runs the checks already passing in this tree:
Ruff linting, mypy, and pytest.

Remove asyncio_default_fixture_loop_scope which isn't used here since this project does not use async tests.

---
 ci.sh          | 7 +++++++
 pyproject.toml | 1 -
 2 files changed, 7 insertions(+), 1 deletion(-)
ci.sh new file +7 -0
new file mode 100755
index 0000000..3001db2
@@ -0,0 +1,7 @@
+#!/usr/bin/env sh
+
+set -eu
+
+uv run ruff check
+uv run mypy .
+uv run pytest --durations=0
pyproject.toml +0 -1
index 47f86a3..a541b01 100644
@@ -65,7 +65,6 @@ typeCheckingMode = "off"
 strict = true
 
 [tool.pytest.ini_options]
-asyncio_default_fixture_loop_scope = "function"
 testpaths = "tests"
 python_files = "test_*.py"
 python_classes = "Test*"
Signature · 1 line
2.53.0
#2 lore raw

PATCH 2/7 Add Ruff import checks

In reply to Tamir Duberstein

Run Ruff's default lint rules together with import sorting and the existing blanket-noqa check.

Sort imports and remove unused test imports so the expanded lint configuration is green under the local CI script.

---
 docs/conf.py                        |  5 +++--
 pyproject.toml                      |  3 ++-
 src/patatt/__init__.py              | 29 +++++++++++++----------------
 tests/conftest.py                   |  7 +++----
 tests/test_validation.py            |  7 ++++---
 tests/unit/test_byhash.py           |  2 +-
 tests/unit/test_devsig_header.py    |  6 +++---
 tests/unit/test_get_algo_keydata.py | 11 +++++------
 tests/unit/test_patatt_message.py   |  7 +++----
 9 files changed, 37 insertions(+), 40 deletions(-)
docs/conf.py +3 -2
index 042c753..cb0ca38 100644
@@ -9,13 +9,14 @@ import sys
 # Add the source directory to the path for autodoc
 sys.path.insert(0, os.path.abspath('../src'))
 
+# The version info
+from patatt import __VERSION__
+
 # -- Project information -----------------------------------------------------
 project = 'patatt'
 copyright = '2021-2026, Konstantin Ryabitsev'
 author = 'Konstantin Ryabitsev'
 
-# The version info
-from patatt import __VERSION__
 version = __VERSION__
 release = __VERSION__
 
pyproject.toml +2 -1
index a541b01..7583cd4 100644
@@ -52,7 +52,8 @@ version = {attr = "patatt.__VERSION__"}
 "share/man/man5" = ["man/patatt.5"]
 
 [tool.ruff.lint]
-select = [
+extend-select = [
+    "I",
     "PGH004", # https://docs.astral.sh/ruff/rules/blanket-noqa/
 ]
 flake8-quotes.inline-quotes = "single"
src/patatt/__init__.py +13 -16
index 499d820..935da55 100644
@@ -5,27 +5,24 @@
 #
 __author__ = 'Konstantin Ryabitsev <[email protected]>'
 
-import sys
-import os
-import re
-
 import argparse
-import hashlib
 import base64
-import subprocess
+import datetime
+import email.header
+import email.utils
+import hashlib
 import logging
+import os
+import re
+import subprocess
+import sys
 import tempfile
 import time
-import datetime
-import warnings
-
 import urllib.parse
-import email.utils
-import email.header
-
-from pathlib import Path
-from typing import Optional, List, Tuple, Dict, Union, Any
+import warnings
 from io import BytesIO
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple, Union
 
 GitConfigType = Dict[str, Union[str, List[str]]]
 
@@ -437,8 +434,8 @@ class DevsigHeader:
     def _sign_ed25519(payload: bytes, privkey: bytes) -> Tuple[bytes, bytes]:
         global KEYCACHE
         try:
-            from nacl.signing import SigningKey
             from nacl.encoding import Base64Encoder
+            from nacl.signing import SigningKey
         except ModuleNotFoundError:
             raise RuntimeError('This operation requires PyNaCl libraries')
 
@@ -456,9 +453,9 @@ class DevsigHeader:
     @staticmethod
     def _validate_ed25519(sigdata: bytes, pubkey: bytes) -> bytes:
         try:
-            from nacl.signing import VerifyKey
             from nacl.encoding import Base64Encoder
             from nacl.exceptions import BadSignatureError
+            from nacl.signing import VerifyKey
         except ModuleNotFoundError:
             raise RuntimeError('This operation requires PyNaCl libraries')
 
tests/conftest.py +3 -4
index a9c9157..8bb6064 100644
@@ -1,13 +1,12 @@
+import base64
+import tempfile
 from pathlib import Path
+from typing import Dict, Generator
 
-import os
-import tempfile
 import pytest
-import base64
 
 from patatt import DevsigHeader, PatattMessage
 
-from typing import Generator, Dict
 
 @pytest.fixture
 def sample_email_bytes() -> bytes:
tests/test_validation.py +4 -3
index 61c4ab6..d51be81 100644
@@ -1,9 +1,10 @@
-import pytest
 import os
-import tempfile
 from pathlib import Path
 
-from patatt import PatattMessage, sign_message, validate_message, RES_VALID
+import pytest
+
+from patatt import RES_VALID, validate_message
+
 
 @pytest.mark.parametrize("sample_file", [
     "ed25519-signed.txt",
tests/unit/test_byhash.py +1 -1
index a24d338..c3fe4d2 100644
@@ -4,7 +4,7 @@ from pathlib import Path
 
 import pytest
 
-from patatt import make_byhash_path, make_pkey_path, get_public_key
+from patatt import get_public_key, make_byhash_path, make_pkey_path
 
 
 class TestMakeByhashPath:
tests/unit/test_devsig_header.py +3 -3
index 5c5bb06..547593d 100644
@@ -1,11 +1,11 @@
-import pytest
 import base64
 import hashlib
 from io import BytesIO
 
-from typing import Dict
+import pytest
+
+from patatt import DevsigHeader
 
-from patatt import DevsigHeader, ValidationError, SigningError
 
 class TestDevsigHeader:
 
tests/unit/test_get_algo_keydata.py +5 -6
index 6f268eb..545f051 100644
@@ -1,14 +1,13 @@
-import pytest
+from typing import Callable
+from unittest.mock import MagicMock, patch
 
-from typing import Any, Callable
-from unittest.mock import patch, MagicMock
+import pytest
 
 from patatt import (
-    get_algo_keydata,
-    NoKeyError,
-    ConfigurationError,
     KEYCACHE,
     GitConfigType,
+    NoKeyError,
+    get_algo_keydata,
 )
 
 
tests/unit/test_patatt_message.py +3 -4
index 1422ee7..58338f4 100644
@@ -1,10 +1,9 @@
+from typing import Tuple
+
 import pytest
-import re
-from io import BytesIO
 
-from patatt import PatattMessage, ValidationError
+from patatt import PatattMessage
 
-from typing import Tuple
 
 class TestPatattMessage:
 
Signature · 1 line
2.53.0
#3 lore raw

PATCH 3/7 Add Ruff format check

In reply to Tamir Duberstein

Run Ruff's formatter as part of the local CI helper and configure it to preserve the project's single-quote style.

Apply the one-time formatting pass so the new check starts from a green baseline.

---
 ci.sh                               |   1 +
 conftest.py                         |   3 +-
 pyproject.toml                      |   3 +
 src/patatt/__init__.py              | 345 +++++++++++++++++++++++++++---------
 tests/conftest.py                   |  10 +-
 tests/test_validation.py            |  16 +-
 tests/unit/test_byhash.py           |   2 -
 tests/unit/test_devsig_header.py    |  17 +-
 tests/unit/test_get_algo_keydata.py |   9 +-
 tests/unit/test_patatt_message.py   |  20 ++-
 10 files changed, 307 insertions(+), 119 deletions(-)
ci.sh +1 -0
index 3001db2..ec0baf8 100755
@@ -2,6 +2,7 @@
 
 set -eu
 
+uv run ruff format --check
 uv run ruff check
 uv run mypy .
 uv run pytest --durations=0
conftest.py +1 -2
index c106f53..33276ab 100644
@@ -3,7 +3,6 @@ from pathlib import Path
 
 # Add the src directory to the Python path
 project_root = Path(__file__).parent
-src_path = str(project_root / "src")
+src_path = str(project_root / 'src')
 if src_path not in sys.path:
     sys.path.insert(0, src_path)
-
pyproject.toml +3 -0
index 7583cd4..d56d828 100644
@@ -58,6 +58,9 @@ extend-select = [
 ]
 flake8-quotes.inline-quotes = "single"
 
+[tool.ruff.format]
+quote-style = "single"
+
 [tool.pyright]
 typeCheckingMode = "off"
 
src/patatt/__init__.py +260 -85

642 lines not on this page · raw message

tests/conftest.py +7 -3
index 8bb6064..a2d2124 100644
@@ -18,6 +18,7 @@ Message-ID: <[email protected]>
 This is a test email body.
 """
 
+
 @pytest.fixture
 def temp_data_dir() -> Generator[str, None, None]:
     """Create a temporary data directory structure for patatt."""
@@ -32,23 +33,26 @@ def temp_data_dir() -> Generator[str, None, None]:
         # Return path to the temp directory
         yield tmpdirname
 
+
 @pytest.fixture
 def devsig_header() -> DevsigHeader:
     """Create a basic DevsigHeader instance."""
     return DevsigHeader()
 
+
 @pytest.fixture
 def patatt_message(sample_email_bytes: bytes) -> PatattMessage:
     """Create a PatattMessage from a sample email."""
     return PatattMessage(sample_email_bytes)
 
+
 @pytest.fixture
 def sample_ed25519_key_pair() -> Dict[str, bytes]:
     """Generate a sample ed25519 key pair for testing."""
     try:
         from nacl.signing import SigningKey
     except ImportError:
-        pytest.skip("PyNaCl not installed, skipping ed25519 tests")
+        pytest.skip('PyNaCl not installed, skipping ed25519 tests')
 
     # Generate a key pair
     private_key = SigningKey.generate()
@@ -57,5 +61,5 @@ def sample_ed25519_key_pair() -> Dict[str, bytes]:
     # Return base64 encoded keys
     return {
         'private': base64.b64encode(bytes(private_key)),
-        'public': base64.b64encode(public_key.encode())
-    }
\ No newline at end of file
+        'public': base64.b64encode(public_key.encode()),
+    }
tests/test_validation.py +7 -9
index d51be81..1477fbe 100644
@@ -6,11 +6,9 @@ import pytest
 from patatt import RES_VALID, validate_message
 
 
[email protected]("sample_file", [
-    "ed25519-signed.txt",
-    "pgp-signed.txt",
-    "openssh-signed.txt"
-])
[email protected](
+    'sample_file', ['ed25519-signed.txt', 'pgp-signed.txt', 'openssh-signed.txt']
+)
 def test_validate(sample_file: str) -> None:
     """Test validation of an ed25519 signed message from samples directory."""
     # Path to the sample file
@@ -29,14 +27,14 @@ def test_validate(sample_file: str) -> None:
     results = validate_message(signed_data, [sources_path])
 
     # Check validation results
-    assert results, "Validation should return results"
+    assert results, 'Validation should return results'
 
     # At least one valid signature should be found
     valid_signatures = [r for r in results if r[0] == RES_VALID]
-    assert valid_signatures, "Should find at least one valid signature"
+    assert valid_signatures, 'Should find at least one valid signature'
 
     # Print validation details for debugging
-    print(f"Found {len(valid_signatures)} valid signatures:")
+    print(f'Found {len(valid_signatures)} valid signatures:')
     for result in valid_signatures:
         status, algo, keytype, identity, selector, errors = result
-        print(f"  - {keytype} signature by {identity} ({selector})")
+        print(f'  - {keytype} signature by {identity} ({selector})')
tests/unit/test_byhash.py +0 -2
index c3fe4d2..e90ee82 100644
@@ -8,7 +8,6 @@ from patatt import get_public_key, make_byhash_path, make_pkey_path
 
 
 class TestMakeByhashPath:
-
     def test_basic_hash_computation(self) -> None:
         """Test that make_byhash_path computes the correct hash."""
         keytype = 'openssh'
@@ -42,7 +41,6 @@ class TestMakeByhashPath:
 
 
 class TestGetPublicKeyByHash:
-
     def test_filesystem_byhash_lookup(self) -> None:
         """Test that get_public_key finds a key via by-hash fallback."""
         with tempfile.TemporaryDirectory() as tmpdir:
tests/unit/test_devsig_header.py +9 -8
index 547593d..7b6e461 100644
@@ -8,7 +8,6 @@ from patatt import DevsigHeader
 
 
 class TestDevsigHeader:
-
     def test_initialization(self) -> None:
         """Test that DevsigHeader initializes correctly."""
         header = DevsigHeader()
@@ -17,7 +16,9 @@ class TestDevsigHeader:
 
     def test_from_bytes(self) -> None:
         """Test parsing a header from bytes."""
-        header_bytes = b'v=1; a=ed25519-sha256; t=1623456789; [email protected]; bh=abcd1234'
+        header_bytes = (
+            b'v=1; a=ed25519-sha256; t=1623456789; [email protected]; bh=abcd1234'
+        )
         header = DevsigHeader(header_bytes)
 
         assert header.get_field_as_str('v') == '1'
@@ -41,7 +42,7 @@ class TestDevsigHeader:
     def test_set_body(self) -> None:
         """Test setting the body and calculating the body hash."""
         header = DevsigHeader()
-        body = b"This is a test body"
+        body = b'This is a test body'
 
         header.set_body(body)
 
@@ -55,7 +56,7 @@ class TestDevsigHeader:
     def test_set_body_with_maxlen(self) -> None:
         """Test setting the body with a maxlen parameter."""
         header = DevsigHeader()
-        body = b"This is a test body"
+        body = b'This is a test body'
         maxlen = 10
 
         header.set_body(body, maxlen=maxlen)
@@ -95,17 +96,17 @@ class TestDevsigHeader:
         """Test that sanity_check fails if required fields are not set."""
         header = DevsigHeader()
 
-        with pytest.raises(RuntimeError, match="Must set \"a\" field first"):
+        with pytest.raises(RuntimeError, match='Must set "a" field first'):
             header.sanity_check()
 
         header.set_field('a', 'ed25519-sha256')
 
-        with pytest.raises(RuntimeError, match="Must use set_body first"):
+        with pytest.raises(RuntimeError, match='Must use set_body first'):
             header.sanity_check()
 
-        header.set_body(b"Test body")
+        header.set_body(b'Test body')
 
-        with pytest.raises(RuntimeError, match="Must use set_headers first"):
+        with pytest.raises(RuntimeError, match='Must use set_headers first'):
             header.sanity_check()
 
     # @pytest.mark.skipif(True, reason="Requires actual ed25519 keys")
tests/unit/test_get_algo_keydata.py +7 -2
index 545f051..c4ccc8d 100644
@@ -41,7 +41,10 @@ class TestGetAlgoKeydataSSHSigningKey:
     def test_ssh_format_uses_openssh(self, mock_gcfg: MagicMock) -> None:
         """When gpg.format=ssh, user.signingkey should get the openssh: prefix."""
         mock_gcfg.side_effect = _make_mock_get_config(
-            usercfg={'email': '[email protected]', 'signingkey': '/home/user/.ssh/id_ed25519.pub'},
+            usercfg={
+                'email': '[email protected]',
+                'signingkey': '/home/user/.ssh/id_ed25519.pub',
+            },
             gpgcfg={'format': 'ssh'},
         )
         config: GitConfigType = {'identity': '[email protected]'}
@@ -91,7 +94,9 @@ class TestGetAlgoKeydataSSHSigningKey:
             get_algo_keydata(config)
 
     @patch('patatt.get_config_from_git')
-    def test_patatt_signingkey_skips_user_signingkey(self, mock_gcfg: MagicMock) -> None:
+    def test_patatt_signingkey_skips_user_signingkey(
+        self, mock_gcfg: MagicMock
+    ) -> None:
         """When patatt.signingkey is already set, user.signingkey is not consulted."""
         mock_gcfg.side_effect = _make_mock_get_config(
             usercfg={'email': '[email protected]', 'signingkey': 'SHOULD_NOT_BE_USED'},
tests/unit/test_patatt_message.py +12 -8
index 58338f4..17d4a30 100644
@@ -6,7 +6,6 @@ from patatt import PatattMessage
 
 
 class TestPatattMessage:
-
     def test_initialization(self, sample_email_bytes: bytes) -> None:
         """Test initialization of PatattMessage with sample email."""
         message = PatattMessage(sample_email_bytes)
@@ -25,7 +24,7 @@ This is a test body.
         message = PatattMessage(email_bytes)
 
         assert len(message.headers) == 2
-        assert message.body == b"This is a test body.\n"
+        assert message.body == b'This is a test body.\n'
 
     def test_as_bytes(self, sample_email_bytes: bytes) -> None:
         """Test converting message back to bytes."""
@@ -44,17 +43,22 @@ This is a test body.
         assert isinstance(output, str)
         assert output == sample_email_bytes.decode()
 
-    def test_git_canonicalize(self, monkeypatch: pytest.MonkeyPatch, sample_email_bytes: bytes) -> None:
+    def test_git_canonicalize(
+        self, monkeypatch: pytest.MonkeyPatch, sample_email_bytes: bytes
+    ) -> None:
         """Test git canonicalization of message."""
+
         # Mock _get_git_mailinfo to avoid actual git command execution
         def mock_get_git_mailinfo(payload: bytes) -> Tuple[bytes, bytes, bytes]:
             # Return mock metadata, patch, and info
-            metadata = b"Author: Test User\nEmail: [email protected]\nSubject: Test email\n"
-            patch = b"This is a test body.\n"
-            info = b"email: [email protected]\nauthor: Test User\nsubject: Test email\n"
+            metadata = (
+                b'Author: Test User\nEmail: [email protected]\nSubject: Test email\n'
+            )
+            patch = b'This is a test body.\n'
+            info = b'email: [email protected]\nauthor: Test User\nsubject: Test email\n'
             return metadata, patch, info
 
-        monkeypatch.setattr(PatattMessage, "_get_git_mailinfo", mock_get_git_mailinfo)
+        monkeypatch.setattr(PatattMessage, '_get_git_mailinfo', mock_get_git_mailinfo)
 
         message = PatattMessage(sample_email_bytes)
         message.git_canonicalize()
@@ -62,7 +66,7 @@ This is a test body.
         # Check that the message was canonicalized
         assert message.canon_body is not None
         assert message.canon_headers is not None
-        assert message.canon_identity == "[email protected]"
+        assert message.canon_identity == '[email protected]'
 
     # @pytest.mark.skipif(True, reason="Requires actual signing setup")
     # def test_sign(self) -> None:
Signature · 1 line
2.53.0
#4 lore raw

PATCH 4/7 Add pyright strict checks

In reply to Tamir Duberstein

Configure pyright in strict mode and run it from the local CI helper.

Tighten ambiguous containers, cached binary paths, and result tuples so strict analysis has concrete types. Keep private-usage checks disabled only for tests because the existing tests assert internal state directly.

---
 ci.sh                               |   1 +
 pyproject.toml                      |   7 ++-
 src/patatt/__init__.py              | 105 ++++++++++++++++++------------------
 tests/test_validation.py            |   2 +-
 tests/unit/test_devsig_header.py    |   3 +-
 tests/unit/test_get_algo_keydata.py |   2 +-
 6 files changed, 62 insertions(+), 58 deletions(-)
ci.sh +1 -0
index ec0baf8..4b07fa2 100755
@@ -5,4 +5,5 @@ set -eu
 uv run ruff format --check
 uv run ruff check
 uv run mypy .
+uv run pyright
 uv run pytest --durations=0
pyproject.toml +6 -1
index d56d828..9615a41 100644
@@ -28,6 +28,7 @@ dependencies = [
 dev = [
     "mypy",
     "pip-tools",
+    "pyright",
     "pytest",
     "ruff",
 ]
@@ -62,7 +63,11 @@ flake8-quotes.inline-quotes = "single"
 quote-style = "single"
 
 [tool.pyright]
-typeCheckingMode = "off"
+typeCheckingMode = "strict"
+
+executionEnvironments = [
+    { root = "tests", reportPrivateUsage = false },
+]
 
 # Configure mypy in strict mode
 [tool.mypy]
src/patatt/__init__.py +51 -54

261 lines not on this page · raw message

tests/test_validation.py +1 -1
index 1477fbe..c399f14 100644
@@ -36,5 +36,5 @@ def test_validate(sample_file: str) -> None:
     # Print validation details for debugging
     print(f'Found {len(valid_signatures)} valid signatures:')
     for result in valid_signatures:
-        status, algo, keytype, identity, selector, errors = result
+        _status, _algo, keytype, identity, selector, _errors = result
         print(f'  - {keytype} signature by {identity} ({selector})')
tests/unit/test_devsig_header.py +2 -1
index 7b6e461..d94bdc9 100644
@@ -1,6 +1,7 @@
 import base64
 import hashlib
 from io import BytesIO
+from typing import List
 
 import pytest
 
@@ -76,7 +77,7 @@ class TestDevsigHeader:
         header = DevsigHeader()
 
         # Parse the sample email to get headers
-        headers = []
+        headers: List[bytes] = []
         with BytesIO(sample_email_bytes) as fh:
             while True:
                 line = fh.readline()
tests/unit/test_get_algo_keydata.py +1 -1
index c4ccc8d..4d9b7e6 100644
@@ -119,7 +119,7 @@ class TestGetAlgoKeydataSSHSigningKey:
             gpgcfg={'format': 'ssh'},
         )
         config: GitConfigType = {}
-        algo, keydata = get_algo_keydata(config)
+        algo, _keydata = get_algo_keydata(config)
 
         assert config['identity'] == '[email protected]'
         assert algo == 'openssh'
Signature · 1 line
2.53.0
#5 lore raw

PATCH 5/7 Add ty checks

In reply to Tamir Duberstein

Add ty to the development dependencies and enable all ty rules.

---
 ci.sh          | 1 +
 pyproject.toml | 4 ++++
 2 files changed, 5 insertions(+)
ci.sh +1 -0
index 4b07fa2..c97c853 100755
@@ -4,6 +4,7 @@ set -eu
 
 uv run ruff format --check
 uv run ruff check
+uv run ty check
 uv run mypy .
 uv run pyright
 uv run pytest --durations=0
pyproject.toml +4 -0
index 9615a41..34ff5ab 100644
@@ -31,6 +31,7 @@ dev = [
     "pyright",
     "pytest",
     "ruff",
+    "ty",
 ]
 
 [tool.setuptools.packages.find]
@@ -69,6 +70,9 @@ executionEnvironments = [
     { root = "tests", reportPrivateUsage = false },
 ]
 
+[tool.ty.rules]
+all = "error"
+
 # Configure mypy in strict mode
 [tool.mypy]
 strict = true
Signature · 1 line
2.53.0
#6 lore raw

PATCH 6/7 Reduce dictionary lookups

In reply to Tamir Duberstein

Use dict.get instead of separately in checks and lookups.

---
 src/patatt/__init__.py | 21 +++++++++------------
 1 file changed, 9 insertions(+), 12 deletions(-)
src/patatt/__init__.py +9 -12
index 7087479..b20074a 100644
@@ -1024,8 +1024,8 @@ def get_data_dir() -> Path:
     Returns:
         Path to $XDG_DATA_HOME/patatt or ~/.local/share/patatt.
     """
-    if 'XDG_DATA_HOME' in os.environ:
-        datahome = Path(os.environ['XDG_DATA_HOME'])
+    if (xdg_data_home := os.environ.get('XDG_DATA_HOME')) is not None:
+        datahome = Path(xdg_data_home)
     else:
         datahome = Path.home() / '.local' / 'share'
     datadir = datahome / 'patatt'
@@ -1100,16 +1100,13 @@ def get_config_from_git(
                 continue
 
             if cfgkey in multivals:
-                if cfgkey not in gitconfig:
-                    values: List[str] = list()
+                cfgvalue = gitconfig.setdefault(cfgkey, list())
+                if isinstance(cfgvalue, str):
+                    values = [cfgvalue]
+                    gitconfig[cfgkey] = values
                 else:
-                    cfgvalue = gitconfig[cfgkey]
-                    if isinstance(cfgvalue, str):
-                        values = [cfgvalue]
-                    else:
-                        values = cfgvalue
+                    values = cfgvalue
                 values.append(value)
-                gitconfig[cfgkey] = values
             else:
                 gitconfig[cfgkey] = value
         except ValueError:
@@ -1423,8 +1420,8 @@ def get_algo_keydata(config: GitConfigType) -> Tuple[str, str]:
             'Identity must be a string, got %s' % type(identity).__name__
         )
 
-    if identity in KEYCACHE:
-        algo, keydata = KEYCACHE[identity]
+    if (t := KEYCACHE.get(identity)) is not None:
+        algo, keydata = t
         return algo, keydata
 
     if not config.get('signingkey'):
Signature · 1 line
2.53.0
#7 lore raw

PATCH 7/7 Import PyNaCl unconditionally

In reply to Tamir Duberstein

PyNaCl became a non-optional runtime dependency in 7eb7dfaf4c9f6028519f5209041da1cb61302cd8, so importing it lazily and translating missing imports to RuntimeError only hides packaging problems.

Import the required PyNaCl symbols at module load time and remove the matching test skip for an unavailable dependency.

---
 src/patatt/__init__.py | 22 ++++------------------
 tests/conftest.py      |  6 +-----
 2 files changed, 5 insertions(+), 23 deletions(-)
src/patatt/__init__.py +4 -18
index b20074a..5c8a480 100644
@@ -24,6 +24,10 @@ from io import BytesIO
 from pathlib import Path
 from typing import Any, Dict, List, Optional, Set, Tuple, Union
 
+from nacl.encoding import Base64Encoder
+from nacl.exceptions import BadSignatureError
+from nacl.signing import SigningKey, VerifyKey
+
 GitConfigType = Dict[str, Union[str, List[str]]]
 AttestationResult = Tuple[
     int, Optional[str], Optional[str], Optional[str], Optional[str], List[str]
@@ -450,12 +454,6 @@ class DevsigHeader:
     @staticmethod
     def _sign_ed25519(payload: bytes, privkey: bytes) -> Tuple[bytes, bytes]:
         global KEYCACHE
-        try:
-            from nacl.encoding import Base64Encoder
-            from nacl.signing import SigningKey
-        except ModuleNotFoundError:
-            raise RuntimeError('This operation requires PyNaCl libraries')
-
         if privkey not in KEYCACHE:
             sk = SigningKey(privkey, encoder=Base64Encoder)
             vk = base64.b64encode(sk.verify_key.encode())
@@ -469,13 +467,6 @@ class DevsigHeader:
 
     @staticmethod
     def _validate_ed25519(sigdata: bytes, pubkey: bytes) -> bytes:
-        try:
-            from nacl.encoding import Base64Encoder
-            from nacl.exceptions import BadSignatureError
-            from nacl.signing import VerifyKey
-        except ModuleNotFoundError:
-            raise RuntimeError('This operation requires PyNaCl libraries')
-
         vk = VerifyKey(pubkey, encoder=Base64Encoder)
         try:
             return vk.verify(sigdata, encoder=Base64Encoder)
@@ -1734,11 +1725,6 @@ def cmd_validate(cmdargs: argparse.Namespace, config: GitConfigType) -> None:
 
 
 def cmd_genkey(cmdargs: argparse.Namespace, config: GitConfigType) -> None:
-    try:
-        from nacl.signing import SigningKey
-    except ModuleNotFoundError:
-        raise RuntimeError('This operation requires PyNaCl libraries')
-
     # Do we have the signingkey defined?
     usercfg = get_config_from_git(r'user\..*')
     if not config.get('identity'):
tests/conftest.py +1 -5
index a2d2124..2301d1b 100644
@@ -4,6 +4,7 @@ from pathlib import Path
 from typing import Dict, Generator
 
 import pytest
+from nacl.signing import SigningKey
 
 from patatt import DevsigHeader, PatattMessage
 
@@ -49,11 +50,6 @@ def patatt_message(sample_email_bytes: bytes) -> PatattMessage:
 @pytest.fixture
 def sample_ed25519_key_pair() -> Dict[str, bytes]:
     """Generate a sample ed25519 key pair for testing."""
-    try:
-        from nacl.signing import SigningKey
-    except ImportError:
-        pytest.skip('PyNaCl not installed, skipping ed25519 tests')
-
     # Generate a key pair
     private_key = SigningKey.generate()
     public_key = private_key.verify_key
Signature · 1 line
2.53.0
#8 lore raw
In reply to Tamir Duberstein
Quoted 10 lines · Tamir Duberstein

This series adds a local CI helper and raises patatt's local quality baseline incrementally while keeping the tree green after each step.

It starts with the checks that already pass, then adds Ruff import and format enforcement, strict pyright, and ty. The later patches make the small typing and cleanup changes needed for the stricter checkers, and remove stale optional-dependency handling for PyNaCl.

Hi Konstantin, any interest in this series? I'm happy to make changes if needed.

Cheers.
Tamir