Skip to content

Commit 4163358

Browse files
committed
core(refactor[typing]) Narrow dataclass, regex and Sphinx inputs
why: These callers rely on dataclasses, compatible regex operands and the Python documentation domain. The original annotations did not express those conditions. what: - Verify dataclass and documentation inputs before using their specialized APIs and preserve regex lookup outcomes for byte and text values. - Describe the generator-based locks, use the verified Git object type directly, and remove an unnecessary annotation suppression.
1 parent 71785ae commit 4163358

7 files changed

Lines changed: 40 additions & 23 deletions

File tree

‎docs/conf.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,9 @@
77
import typing as t
88

99
if t.TYPE_CHECKING:
10-
from docutils import nodes # type: ignore[import-untyped]
10+
from docutils import nodes
1111
from sphinx import addnodes
1212
from sphinx.application import Sphinx
13-
from sphinx.domains.python import PythonDomain
1413
from sphinx.environment import BuildEnvironment
1514

1615
from gp_sphinx.config import make_linkcode_resolve, merge_sphinx_config
@@ -78,11 +77,14 @@ def _on_missing_class_reference(
7877
) -> nodes.reference | None:
7978
if node.get("refdomain") != "py" or node.get("reftype") != "class":
8079
return None
80+
from sphinx.domains.python import PythonDomain
8181
from sphinx.util.nodes import make_refnode
8282

83-
py_domain: PythonDomain = env.get_domain("py") # type: ignore[assignment]
83+
py_domain = env.get_domain("py")
84+
if not isinstance(py_domain, PythonDomain):
85+
return None
8486
target = node.get("reftarget", "")
85-
matches = py_domain.find_obj(env, "", "", target, None, 1) # type: ignore[attr-defined,unused-ignore]
87+
matches = py_domain.find_obj(env, "", "", target, None, 1)
8688
if not matches:
8789
return None
8890
_name, obj_entry = matches[0]

‎src/libvcs/_internal/dataclasses.py‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,8 @@
88
from __future__ import annotations
99

1010
import dataclasses
11-
import typing as t
1211
from operator import attrgetter
1312

14-
if t.TYPE_CHECKING:
15-
from _typeshed import DataclassInstance
16-
else:
17-
DataclassInstance = object
18-
1913

2014
class SkipDefaultFieldsReprMixin:
2115
r"""Skip default fields in :func:`~dataclasses.dataclass` object representation.
@@ -82,8 +76,11 @@ class SkipDefaultFieldsReprMixin:
8276
ItemWithMixin(name=Test, unit_price=2.05)
8377
"""
8478

85-
def __repr__(self: DataclassInstance) -> str:
79+
def __repr__(self) -> str:
8680
"""Omit default fields in object representation."""
81+
if not dataclasses.is_dataclass(self):
82+
msg = "must be called with a dataclass type or instance"
83+
raise TypeError(msg)
8784
nodef_f_vals = (
8885
(f.name, attrgetter(f.name)(self))
8986
for f in dataclasses.fields(self)

‎src/libvcs/_internal/preservation.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import tempfile
1515
import typing as t
1616
import uuid
17-
from collections.abc import Iterator
17+
from collections.abc import Generator
1818

1919
from libvcs.sync.base import RecoveryToken, SyncConflict, SyncResult
2020

@@ -120,7 +120,7 @@ def __init__(
120120
)
121121

122122
@contextlib.contextmanager
123-
def lock(self) -> Iterator[None]:
123+
def lock(self) -> Generator[None, None, None]:
124124
"""Exclude concurrent library operations without waiting."""
125125
if os.name != "posix":
126126
msg = "recovery requires POSIX ownership locks"

‎src/libvcs/_internal/query_list.py‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -274,22 +274,40 @@ def lookup_nin(
274274
return False
275275

276276

277+
def _search_regex(
278+
data: str | bytes | re.Pattern[str] | list[str] | Mapping[str, str],
279+
rhs: str | bytes | list[str] | Mapping[str, str] | re.Pattern[str],
280+
flags: int,
281+
) -> bool:
282+
if isinstance(rhs, str) and isinstance(data, str):
283+
return bool(re.search(rhs, data, flags))
284+
if isinstance(rhs, bytes) and isinstance(data, bytes):
285+
return bool(re.search(rhs, data, flags))
286+
if isinstance(rhs, (str, bytes)) and isinstance(data, (str, bytes, re.Pattern)):
287+
# Compile first so invalid patterns retain their native regex error.
288+
re.compile(rhs, flags)
289+
if isinstance(data, re.Pattern):
290+
msg = "expected string or bytes-like object, got 're.Pattern'"
291+
elif isinstance(rhs, bytes):
292+
msg = "cannot use a bytes pattern on a string-like object"
293+
else:
294+
msg = "cannot use a string pattern on a bytes-like object"
295+
raise TypeError(msg)
296+
return False
297+
298+
277299
def lookup_regex(
278300
data: str | list[str] | Mapping[str, str],
279301
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
280302
) -> bool:
281-
if isinstance(data, (str, bytes, re.Pattern)) and isinstance(rhs, (str, bytes)):
282-
return bool(re.search(rhs, data))
283-
return False
303+
return _search_regex(data, rhs, 0)
284304

285305

286306
def lookup_iregex(
287307
data: str | list[str] | Mapping[str, str],
288308
rhs: str | list[str] | Mapping[str, str] | re.Pattern[str],
289309
) -> bool:
290-
if isinstance(data, (str, bytes, re.Pattern)) and isinstance(rhs, (str, bytes)):
291-
return bool(re.search(rhs, data, re.IGNORECASE))
292-
return False
310+
return _search_regex(data, rhs, re.IGNORECASE)
293311

294312

295313
LOOKUP_NAME_MAP: Mapping[str, LookupProtocol] = {

‎src/libvcs/_internal/svn_preservation.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import subprocess
1212
import tempfile
1313
import xml.etree.ElementTree as et
14-
from collections.abc import Iterator
14+
from collections.abc import Generator
1515

1616
from libvcs import exc
1717
from libvcs._internal import preservation
@@ -92,7 +92,7 @@ def check_administration(self) -> None:
9292
raise ValueError(msg)
9393

9494
@contextlib.contextmanager
95-
def reservation(self) -> Iterator[None]:
95+
def reservation(self) -> Generator[None, None, None]:
9696
"""Reserve a validated format-31 database without waiting for native writers."""
9797
if os.name != "posix":
9898
msg = "SVN preservation requires POSIX"

‎src/libvcs/cmd/git_filter.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,7 @@ def _parse_filter(spec: str, *, depth: int) -> GitFilter:
371371
if raw_type not in _OBJECT_TYPES:
372372
msg = "type must be blob, tree, commit, or tag"
373373
raise ValueError(msg)
374-
return ObjectType(t.cast(t.Literal["blob", "tree", "commit", "tag"], raw_type))
374+
return ObjectType(raw_type)
375375
if spec.startswith("sparse:oid="):
376376
return SparseOid(spec.removeprefix("sparse:oid="))
377377
if spec == "auto":

‎src/libvcs/sync/hg.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def _set_remotes(self, *, overwrite: bool) -> None:
243243
msg = "libvcs paths block must remain last in Mercurial config"
244244
raise ValueError(msg)
245245
parser = configparser.ConfigParser(interpolation=None, delimiters=("=",))
246-
parser.optionxform = lambda optionstr: optionstr # type: ignore[method-assign]
246+
parser.optionxform = lambda optionstr: optionstr
247247
parser.read_string(block.removesuffix(end).decode("utf-8"))
248248
managed = dict(parser["paths"])
249249
else:

0 commit comments

Comments
 (0)