sigdrift 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sigdrift/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Find documented parameter names that the real callable rejects."""
2
+
3
+ __version__ = "0.1.0"
sigdrift/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
sigdrift/check.py ADDED
@@ -0,0 +1,304 @@
1
+ """Compare documented signatures with the callables they describe.
2
+
3
+ The test for each documented keyword is the one Python itself applies:
4
+ ``inspect.signature(obj).bind_partial(name=...)``. Nothing documented is
5
+ ever called; only the modules named in the docs are imported.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import difflib
11
+ import fnmatch
12
+ import importlib
13
+ import inspect
14
+ import types
15
+ import warnings
16
+ from collections.abc import Iterable
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ from .params import DocParam, Kind, ParseError, parse_params
21
+ from .rst import DocSignature
22
+
23
+ #: Modules whose import has visible side effects.
24
+ DEFAULT_SKIP_MODULES = ("antigravity", "this", "__main__", "__hello__", "__phello__")
25
+
26
+ #: Docs name a parameter that exists under another keyword-passable name.
27
+ RENAMED = "SD001"
28
+ #: Docs imply a keyword, but the real parameter is positional-only.
29
+ POSITIONAL_ONLY = "SD002"
30
+ #: Docs name a parameter the callable does not have at all.
31
+ UNKNOWN = "SD003"
32
+
33
+ ALL_CODES = (RENAMED, POSITIONAL_ONLY, UNKNOWN)
34
+ #: SD002 is opt-in: many C callables are positional-only and older docs
35
+ #: predate the '/' notation, so it is a different (and much larger) cleanup.
36
+ DEFAULT_CODES = (RENAMED, UNKNOWN)
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Finding:
41
+ path: Path
42
+ line: int
43
+ code: str
44
+ name: str
45
+ param: str
46
+ message: str
47
+ suggestion: str | None = None
48
+
49
+ def as_dict(self) -> dict[str, object]:
50
+ return {
51
+ "path": str(self.path),
52
+ "line": self.line,
53
+ "code": self.code,
54
+ "name": self.name,
55
+ "param": self.param,
56
+ "message": self.message,
57
+ "suggestion": self.suggestion,
58
+ }
59
+
60
+
61
+ @dataclass
62
+ class Report:
63
+ findings: list[Finding] = field(default_factory=list)
64
+ checked: int = 0
65
+ #: Documented name could not be imported (platform-only module, typo, ...).
66
+ unresolved: list[DocSignature] = field(default_factory=list)
67
+ #: Resolved, but inspect.signature() has nothing to offer (some C callables).
68
+ no_signature: list[DocSignature] = field(default_factory=list)
69
+ unparsable: list[DocSignature] = field(default_factory=list)
70
+
71
+
72
+ class _Unresolved(LookupError):
73
+ pass
74
+
75
+
76
+ class Resolver:
77
+ """Import dotted names once, caching both successes and failures."""
78
+
79
+ def __init__(
80
+ self,
81
+ skip_modules: Iterable[str] = DEFAULT_SKIP_MODULES,
82
+ aliases: dict[str, str] | None = None,
83
+ ) -> None:
84
+ self.skip_modules = tuple(skip_modules)
85
+ #: Doc-only names mapped to importable ones, e.g.
86
+ #: ``{"asyncio.loop": "asyncio.BaseEventLoop"}``.
87
+ self.aliases = dict(aliases or {})
88
+ self._modules: dict[str, types.ModuleType | None] = {}
89
+
90
+ def _alias(self, dotted: str) -> str:
91
+ for old, new in self.aliases.items():
92
+ if dotted == old or dotted.startswith(old + "."):
93
+ return new + dotted[len(old):]
94
+ return dotted
95
+
96
+ def _import(self, name: str) -> types.ModuleType | None:
97
+ if name in self._modules:
98
+ return self._modules[name]
99
+ module = None
100
+ if not any(name == s or name.startswith(s + ".") for s in self.skip_modules):
101
+ with warnings.catch_warnings():
102
+ warnings.simplefilter("ignore")
103
+ try:
104
+ module = importlib.import_module(name)
105
+ except BaseException: # noqa: BLE001 - SystemExit, platform errors, ...
106
+ module = None
107
+ self._modules[name] = module
108
+ return module
109
+
110
+ def _walk(self, dotted: str) -> tuple[object, object | None, str]:
111
+ parts = dotted.split(".")
112
+ for cut in range(len(parts) - 1, 0, -1):
113
+ module = self._import(".".join(parts[:cut]))
114
+ if module is None:
115
+ continue
116
+ obj: object = module
117
+ parent: object | None = None
118
+ try:
119
+ with warnings.catch_warnings():
120
+ warnings.simplefilter("ignore")
121
+ for attr in parts[cut:]:
122
+ parent, obj = obj, getattr(obj, attr)
123
+ except Exception: # noqa: BLE001 - properties may raise anything
124
+ continue
125
+ return obj, parent, parts[-1]
126
+ raise _Unresolved(dotted)
127
+
128
+ def resolve(self, sig: DocSignature) -> tuple[object, object | None, str]:
129
+ candidates = []
130
+ if sig.module:
131
+ # If the documented module itself will not import (platform-only,
132
+ # missing C extension), falling back to builtins would compare
133
+ # e.g. lzma.open with builtins.open.
134
+ if self._import(sig.module) is None:
135
+ raise _Unresolved(sig.fullname)
136
+ candidates.append(f"{sig.module}.{sig.qualname}")
137
+ candidates += [sig.qualname, f"builtins.{sig.qualname}"]
138
+ for dotted in candidates:
139
+ try:
140
+ return self._walk(self._alias(dotted))
141
+ except _Unresolved:
142
+ continue
143
+ raise _Unresolved(sig.fullname)
144
+
145
+
146
+ def _is_unbound_method(obj: object, parent: object | None, attr: str) -> bool:
147
+ """True when ``obj`` is looked up on a class and still expects ``self``."""
148
+ if not isinstance(parent, type):
149
+ return False
150
+ try:
151
+ raw = inspect.getattr_static(parent, attr)
152
+ except AttributeError:
153
+ return False
154
+ if isinstance(raw, (staticmethod, classmethod, types.ClassMethodDescriptorType)):
155
+ return False
156
+ return inspect.isfunction(obj) or isinstance(
157
+ obj, (types.MethodDescriptorType, types.WrapperDescriptorType)
158
+ )
159
+
160
+
161
+ def real_signature(obj: object, parent: object | None, attr: str) -> inspect.Signature | None:
162
+ try:
163
+ sig = inspect.signature(obj)
164
+ except (TypeError, ValueError):
165
+ return None
166
+ params = list(sig.parameters.values())
167
+ if (
168
+ params
169
+ and _is_unbound_method(obj, parent, attr)
170
+ and params[0].kind in (params[0].POSITIONAL_ONLY, params[0].POSITIONAL_OR_KEYWORD)
171
+ ):
172
+ sig = sig.replace(parameters=params[1:])
173
+ return sig
174
+
175
+
176
+ def _counterpart(
177
+ doc_params: list[DocParam], param: DocParam, real: inspect.Signature
178
+ ) -> inspect.Parameter | None:
179
+ """The real parameter the docs most likely mean: same position, else closest name."""
180
+ real_params = [
181
+ p for p in real.parameters.values() if p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
182
+ ]
183
+ plain = [p for p in doc_params if p.kind not in (Kind.VAR_POSITIONAL, Kind.VAR_KEYWORD)]
184
+ if param.kind is Kind.POSITIONAL_OR_KEYWORD and param in plain:
185
+ index = plain.index(param)
186
+ if index < len(real_params) and real_params[index].kind is not inspect.Parameter.KEYWORD_ONLY:
187
+ return real_params[index]
188
+ documented = {p.name for p in doc_params}
189
+ keywordable = {
190
+ p.name: p
191
+ for p in real_params
192
+ if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY) and p.name not in documented
193
+ }
194
+ close = difflib.get_close_matches(param.name, list(keywordable), n=1)
195
+ return keywordable[close[0]] if close else None
196
+
197
+
198
+ def _absorbed_by_var_positional(
199
+ doc_params: list[DocParam], param: DocParam, real: inspect.Signature
200
+ ) -> bool:
201
+ """``nlst(argument, ...)`` documenting ``def nlst(self, *args)``: docs describe positions."""
202
+ if param.kind is not Kind.POSITIONAL_OR_KEYWORD:
203
+ return False
204
+ real_list = list(real.parameters.values())
205
+ star = next((i for i, p in enumerate(real_list) if p.kind is p.VAR_POSITIONAL), None)
206
+ if star is None:
207
+ return False
208
+ plain = [p for p in doc_params if p.kind not in (Kind.VAR_POSITIONAL, Kind.VAR_KEYWORD)]
209
+ return param in plain and plain.index(param) >= star
210
+
211
+
212
+ def _classify(
213
+ doc_params: list[DocParam], param: DocParam, real: inspect.Signature
214
+ ) -> tuple[str, str, str | None] | None:
215
+ same = real.parameters.get(param.name)
216
+ if same is None and _absorbed_by_var_positional(doc_params, param, real):
217
+ return None
218
+ if same is not None and same.kind is same.POSITIONAL_ONLY:
219
+ return POSITIONAL_ONLY, f"'{param.name}' is positional-only, but the docs do not mark it with '/'", None
220
+ other = _counterpart(doc_params, param, real)
221
+ if other is None:
222
+ return UNKNOWN, f"no parameter named '{param.name}'", None
223
+ if other.kind is other.POSITIONAL_ONLY:
224
+ return (
225
+ POSITIONAL_ONLY,
226
+ f"'{param.name}' is positional-only (real name '{other.name}'), "
227
+ "but the docs do not mark it with '/'",
228
+ None,
229
+ )
230
+ return RENAMED, f"'{param.name}' is not accepted as a keyword; the real name is '{other.name}'", other.name
231
+
232
+
233
+ def _lists_base_classes(obj: object, doc_params: list[DocParam]) -> bool:
234
+ """``.. class:: Transport(ReadTransport, WriteTransport)`` names bases, not arguments."""
235
+ if not isinstance(obj, type):
236
+ return False
237
+ bases = {cls.__name__ for cls in obj.__mro__[1:]}
238
+ return any(p.name in bases for p in doc_params)
239
+
240
+
241
+ def ignored(patterns: Iterable[str], name: str, param: str | None = None) -> bool:
242
+ keys = [name] if param is None else [name, f"{name}:{param}"]
243
+ return any(fnmatch.fnmatchcase(key, pat) for pat in patterns for key in keys)
244
+
245
+
246
+ def check_signatures(
247
+ sigs: Iterable[DocSignature],
248
+ *,
249
+ ignore: Iterable[str] = (),
250
+ select: Iterable[str] = DEFAULT_CODES,
251
+ include_brackets: bool = False,
252
+ resolver: Resolver | None = None,
253
+ ) -> Report:
254
+ ignore = list(ignore)
255
+ select = set(select)
256
+ resolver = resolver or Resolver()
257
+ report = Report()
258
+ for sig in sigs:
259
+ if sig.params is None or ignored(ignore, sig.fullname):
260
+ continue
261
+ try:
262
+ doc_params = parse_params(sig.params)
263
+ except ParseError:
264
+ report.unparsable.append(sig)
265
+ continue
266
+ # Some docs spell out the receiver: ``.. method:: EnumType.__len__(cls)``.
267
+ if doc_params and doc_params[0].name in ("self", "cls"):
268
+ doc_params = doc_params[1:]
269
+ candidates = [
270
+ p for p in doc_params if p.keyword_passable and (include_brackets or not p.bracketed)
271
+ ]
272
+ if not candidates:
273
+ continue
274
+ try:
275
+ obj, parent, attr = resolver.resolve(sig)
276
+ except _Unresolved:
277
+ report.unresolved.append(sig)
278
+ continue
279
+ if _lists_base_classes(obj, doc_params):
280
+ continue
281
+ real = real_signature(obj, parent, attr)
282
+ if real is None:
283
+ report.no_signature.append(sig)
284
+ continue
285
+ report.checked += 1
286
+ for param in candidates:
287
+ if ignored(ignore, sig.fullname, param.name):
288
+ continue
289
+ try:
290
+ real.bind_partial(**{param.name: None})
291
+ except TypeError:
292
+ pass
293
+ else:
294
+ continue
295
+ classified = _classify(doc_params, param, real)
296
+ if classified is None:
297
+ continue
298
+ code, message, suggestion = classified
299
+ if code not in select:
300
+ continue
301
+ report.findings.append(
302
+ Finding(sig.path, sig.line, code, sig.fullname, param.name, message, suggestion)
303
+ )
304
+ return report
sigdrift/cli.py ADDED
@@ -0,0 +1,129 @@
1
+ """Command line entry point: ``sigdrift Doc/`` or ``python -m sigdrift Doc/``.
2
+
3
+ Run it with the interpreter whose packages the docs describe; sigdrift
4
+ imports them to read their real signatures.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+ from collections.abc import Sequence
13
+ from pathlib import Path
14
+
15
+ from . import __version__
16
+ from .check import ALL_CODES, Finding, Report, Resolver, check_signatures
17
+ from .config import ConfigError, load_config
18
+ from .rst import iter_rst_files, parse_rst
19
+
20
+
21
+ def _codes(text: str) -> list[str]:
22
+ codes = [c.strip().upper() for c in text.split(",") if c.strip()]
23
+ bad = [c for c in codes if c not in ALL_CODES]
24
+ if bad:
25
+ raise argparse.ArgumentTypeError(f"unknown code(s): {', '.join(bad)}")
26
+ return codes
27
+
28
+
29
+ def _alias(text: str) -> tuple[str, str]:
30
+ old, sep, new = text.partition("=")
31
+ if not sep or not old or not new:
32
+ raise argparse.ArgumentTypeError("expected OLD=NEW, e.g. asyncio.loop=asyncio.BaseEventLoop")
33
+ return old, new
34
+
35
+
36
+ def build_parser() -> argparse.ArgumentParser:
37
+ parser = argparse.ArgumentParser(
38
+ prog="sigdrift",
39
+ description="Find parameter names in Sphinx docs that the real callable rejects as keywords.",
40
+ )
41
+ parser.add_argument("paths", nargs="*", type=Path, help=".rst files or folders (default: config 'paths')")
42
+ parser.add_argument("--select", type=_codes, help=f"comma-separated codes to report ({', '.join(ALL_CODES)})")
43
+ parser.add_argument(
44
+ "--ignore", action="append", default=[], metavar="PATTERN",
45
+ help="skip 'module.name' or 'module.name:param' (fnmatch); repeatable",
46
+ )
47
+ parser.add_argument(
48
+ "--include-brackets", action="store_true", default=None,
49
+ help="also check parameters written in the old [optional] bracket notation",
50
+ )
51
+ parser.add_argument("--skip-module", action="append", default=[], metavar="MODULE", help="never import MODULE")
52
+ parser.add_argument(
53
+ "--alias", action="append", default=[], type=_alias, metavar="OLD=NEW",
54
+ help="resolve a doc-only name through an importable one; repeatable",
55
+ )
56
+ parser.add_argument("--format", choices=("text", "json", "github"), default="text")
57
+ parser.add_argument("--config", type=Path, help="pyproject.toml to read [tool.sigdrift] from")
58
+ parser.add_argument("--verbose", "-v", action="store_true", help="also list names that could not be checked")
59
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
60
+ return parser
61
+
62
+
63
+ def _format_text(finding: Finding) -> str:
64
+ return f"{finding.path}:{finding.line}: {finding.code} {finding.name}: {finding.message}"
65
+
66
+
67
+ def _format_github(finding: Finding) -> str:
68
+ message = f"{finding.name}: {finding.message}".replace("%", "%25").replace("\n", "%0A")
69
+ return f"::error file={finding.path},line={finding.line},title=sigdrift {finding.code}::{message}"
70
+
71
+
72
+ def _summary(report: Report) -> str:
73
+ return (
74
+ f"{len(report.findings)} finding(s) in {report.checked} checked signature(s); "
75
+ f"{len(report.unresolved)} unresolved, {len(report.no_signature)} without a signature"
76
+ )
77
+
78
+
79
+ def main(argv: Sequence[str] | None = None) -> int:
80
+ parser = build_parser()
81
+ args = parser.parse_args(argv)
82
+ try:
83
+ config = load_config(args.config)
84
+ except ConfigError as exc:
85
+ parser.error(str(exc))
86
+
87
+ paths = args.paths or [Path(p) for p in config.paths]
88
+ if not paths:
89
+ parser.error("no paths given (pass .rst files or folders, or set [tool.sigdrift] paths)")
90
+ missing = [str(p) for p in paths if not p.exists()]
91
+ if missing:
92
+ parser.error(f"no such file or folder: {', '.join(missing)}")
93
+
94
+ resolver = Resolver(
95
+ skip_modules=config.skip_modules + args.skip_module,
96
+ aliases={**config.aliases, **dict(args.alias)},
97
+ )
98
+ sigs = [sig for path in iter_rst_files(paths) for sig in parse_rst(path)]
99
+ report = check_signatures(
100
+ sigs,
101
+ ignore=config.ignore + args.ignore,
102
+ select=args.select or config.select,
103
+ include_brackets=config.include_brackets if args.include_brackets is None else True,
104
+ resolver=resolver,
105
+ )
106
+
107
+ if args.format == "json":
108
+ json.dump(
109
+ {
110
+ "findings": [f.as_dict() for f in report.findings],
111
+ "checked": report.checked,
112
+ "unresolved": [s.fullname for s in report.unresolved],
113
+ "no_signature": [s.fullname for s in report.no_signature],
114
+ },
115
+ sys.stdout,
116
+ indent=2,
117
+ )
118
+ print()
119
+ else:
120
+ fmt = _format_github if args.format == "github" else _format_text
121
+ for finding in report.findings:
122
+ print(fmt(finding))
123
+ if args.verbose:
124
+ for sig in report.unresolved:
125
+ print(f"{sig.path}:{sig.line}: unresolved {sig.fullname}", file=sys.stderr)
126
+ for sig in report.no_signature:
127
+ print(f"{sig.path}:{sig.line}: no signature {sig.fullname}", file=sys.stderr)
128
+ print(_summary(report), file=sys.stderr)
129
+ return 1 if report.findings else 0
sigdrift/config.py ADDED
@@ -0,0 +1,61 @@
1
+ """Read ``[tool.sigdrift]`` from pyproject.toml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from .check import ALL_CODES, DEFAULT_CODES, DEFAULT_SKIP_MODULES
10
+
11
+
12
+ class ConfigError(ValueError):
13
+ pass
14
+
15
+
16
+ @dataclass
17
+ class Config:
18
+ paths: list[str] = field(default_factory=list)
19
+ select: list[str] = field(default_factory=lambda: list(DEFAULT_CODES))
20
+ #: fnmatch patterns over ``module.name`` or ``module.name:param``.
21
+ ignore: list[str] = field(default_factory=list)
22
+ include_brackets: bool = False
23
+ skip_modules: list[str] = field(default_factory=lambda: list(DEFAULT_SKIP_MODULES))
24
+ aliases: dict[str, str] = field(default_factory=dict)
25
+
26
+
27
+ _KEYS = {
28
+ "paths": list,
29
+ "select": list,
30
+ "ignore": list,
31
+ "include-brackets": bool,
32
+ "skip-modules": list,
33
+ "aliases": dict,
34
+ }
35
+
36
+
37
+ def load_config(path: Path | None) -> Config:
38
+ """Load from ``path``, or from ./pyproject.toml when it exists."""
39
+ config = Config()
40
+ if path is None:
41
+ path = Path("pyproject.toml")
42
+ if not path.is_file():
43
+ return config
44
+ try:
45
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
46
+ except (OSError, tomllib.TOMLDecodeError) as exc:
47
+ raise ConfigError(f"{path}: {exc}") from exc
48
+ table = data.get("tool", {}).get("sigdrift", {})
49
+ for key, value in table.items():
50
+ expected = _KEYS.get(key)
51
+ if expected is None:
52
+ raise ConfigError(f"{path}: unknown [tool.sigdrift] key {key!r}")
53
+ if not isinstance(value, expected):
54
+ raise ConfigError(f"{path}: [tool.sigdrift] {key} must be a {expected.__name__}")
55
+ if key == "skip-modules":
56
+ value = config.skip_modules + list(value)
57
+ setattr(config, key.replace("-", "_"), value)
58
+ unknown = set(config.select) - set(ALL_CODES)
59
+ if unknown:
60
+ raise ConfigError(f"{path}: unknown codes in select: {', '.join(sorted(unknown))}")
61
+ return config
sigdrift/params.py ADDED
@@ -0,0 +1,135 @@
1
+ """Parse the parameter list of a documented signature.
2
+
3
+ Docs write signatures loosely: CPython still uses the old bracket notation
4
+ ``foo(a[, b[, c]])`` for optional arguments, defaults can contain commas
5
+ and brackets, and ``...`` stands for "more of the same". This module turns
6
+ that text into a list of :class:`DocParam` with the kind each parameter has
7
+ *as the reader sees it*.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import enum
13
+ from dataclasses import dataclass
14
+
15
+
16
+ class Kind(enum.Enum):
17
+ POSITIONAL_ONLY = "positional-only"
18
+ POSITIONAL_OR_KEYWORD = "positional-or-keyword"
19
+ VAR_POSITIONAL = "var-positional"
20
+ KEYWORD_ONLY = "keyword-only"
21
+ VAR_KEYWORD = "var-keyword"
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class DocParam:
26
+ name: str
27
+ kind: Kind
28
+ #: Written inside the old ``[...]`` optional-argument brackets.
29
+ bracketed: bool = False
30
+
31
+ @property
32
+ def keyword_passable(self) -> bool:
33
+ """Would a reader believe ``f(name=...)`` works?"""
34
+ return self.kind in (Kind.POSITIONAL_OR_KEYWORD, Kind.KEYWORD_ONLY)
35
+
36
+
37
+ class ParseError(ValueError):
38
+ pass
39
+
40
+
41
+ def _split_params(text: str) -> list[tuple[str, bool]]:
42
+ """Split on top-level commas; return (raw param, inside brackets) pairs.
43
+
44
+ A ``[`` is a bracket-notation marker unless it starts or sits inside a
45
+ default value (``x=[]``, ``x=[1, 2]``).
46
+ """
47
+ out: list[tuple[str, bool]] = []
48
+ cur: list[str] = []
49
+ cur_bracketed: bool | None = None # bracket level when the name began
50
+ level = 0 # bracket-notation nesting
51
+ depth = 0 # nesting inside a default value
52
+ quote: str | None = None
53
+ in_default = False
54
+ default_text: list[str] = []
55
+
56
+ def flush() -> None:
57
+ nonlocal cur, cur_bracketed, in_default, default_text
58
+ raw = "".join(cur).strip()
59
+ if raw:
60
+ out.append((raw, bool(cur_bracketed)))
61
+ cur, cur_bracketed, in_default, default_text = [], None, False, []
62
+
63
+ for i, ch in enumerate(text):
64
+ if quote:
65
+ cur.append(ch)
66
+ if in_default:
67
+ default_text.append(ch)
68
+ if ch == quote and text[i - 1] != "\\":
69
+ quote = None
70
+ continue
71
+ if ch in "'\"":
72
+ quote = ch
73
+ elif in_default and ch in "([{" and (depth or ch != "[" or not "".join(default_text).strip()):
74
+ depth += 1
75
+ elif in_default and ch in ")]}" and depth:
76
+ depth -= 1
77
+ elif ch == "[":
78
+ level += 1
79
+ continue
80
+ elif ch == "]":
81
+ level = max(level - 1, 0)
82
+ continue
83
+ elif ch == "," and not depth:
84
+ flush()
85
+ continue
86
+ elif ch == "=" and not depth and not in_default:
87
+ in_default = True
88
+ cur.append(ch)
89
+ continue
90
+
91
+ if cur_bracketed is None and not ch.isspace():
92
+ cur_bracketed = level > 0
93
+ cur.append(ch)
94
+ if in_default:
95
+ default_text.append(ch)
96
+ if quote or depth:
97
+ raise ParseError(f"unbalanced signature: {text!r}")
98
+ flush()
99
+ return out
100
+
101
+
102
+ def parse_params(text: str) -> list[DocParam]:
103
+ """Parse ``a, b=1, /, *args, c, **kw`` into DocParams.
104
+
105
+ Entries that are not plain parameters (``...``, prose) are skipped.
106
+ """
107
+ params: list[DocParam] = []
108
+ keyword_only = False
109
+ for raw, bracketed in _split_params(text):
110
+ if raw in ("...", "…"):
111
+ continue
112
+ if raw == "/":
113
+ params = [
114
+ DocParam(p.name, Kind.POSITIONAL_ONLY, p.bracketed)
115
+ if p.kind is Kind.POSITIONAL_OR_KEYWORD
116
+ else p
117
+ for p in params
118
+ ]
119
+ continue
120
+ if raw == "*":
121
+ keyword_only = True
122
+ continue
123
+ if raw.startswith("**"):
124
+ name, kind = raw[2:], Kind.VAR_KEYWORD
125
+ elif raw.startswith("*"):
126
+ name, kind = raw[1:], Kind.VAR_POSITIONAL
127
+ keyword_only = True
128
+ else:
129
+ name = raw
130
+ kind = Kind.KEYWORD_ONLY if keyword_only else Kind.POSITIONAL_OR_KEYWORD
131
+ name = name.split("=", 1)[0].split(":", 1)[0].strip()
132
+ if not name.isidentifier():
133
+ continue # prose such as "iterable1, iterable2, ..." variants
134
+ params.append(DocParam(name, kind, bracketed))
135
+ return params
sigdrift/rst.py ADDED
@@ -0,0 +1,161 @@
1
+ """Pull callable signatures out of hand-written Sphinx reStructuredText.
2
+
3
+ Only the Python domain directives that document something callable are read
4
+ (``function``, ``method``, ``class`` and friends). The parser tracks
5
+ ``module`` / ``currentmodule`` and the class a nested ``method`` belongs to,
6
+ so each signature comes back with the dotted name needed to import it.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ # Directives whose arguments are call signatures we can check.
16
+ CALLABLE_DIRECTIVES = frozenset(
17
+ {
18
+ "function",
19
+ "method",
20
+ "class",
21
+ "exception",
22
+ "classmethod",
23
+ "staticmethod",
24
+ "coroutinefunction",
25
+ "coroutinemethod",
26
+ "awaitablefunction",
27
+ "awaitablemethod",
28
+ "abstractmethod",
29
+ }
30
+ )
31
+ # Directives that open a scope for nested methods.
32
+ CLASS_DIRECTIVES = frozenset({"class", "exception"})
33
+
34
+ _DIRECTIVE = re.compile(r"^(?P<indent>\s*)\.\.\s+(?:py:)?(?P<name>[a-z]+)::\s*(?P<arg>.*)$")
35
+ _OPTION = re.compile(r"^\s*:[\w-]+:")
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class DocSignature:
40
+ """One documented signature, e.g. ``urlsplit(urlstring, scheme='')``."""
41
+
42
+ path: Path
43
+ line: int
44
+ directive: str
45
+ module: str | None
46
+ #: Dotted name relative to ``module``, e.g. ``Path.match``.
47
+ qualname: str
48
+ #: Text between the outer parentheses, or None when no parentheses were written.
49
+ params: str | None
50
+
51
+ @property
52
+ def fullname(self) -> str:
53
+ return f"{self.module}.{self.qualname}" if self.module else self.qualname
54
+
55
+
56
+ def _split_signature(text: str) -> tuple[str, str | None] | None:
57
+ """Split ``name(params) -> ret`` into ``(name, params)``."""
58
+ text = text.strip()
59
+ match = re.match(r"^(?P<name>[A-Za-z_][\w.]*)\s*(?P<rest>.*)$", text)
60
+ if not match:
61
+ return None
62
+ name, rest = match["name"], match["rest"].strip()
63
+ if not rest:
64
+ return name, None
65
+ if not rest.startswith("("):
66
+ return None
67
+ depth = 0
68
+ quote: str | None = None
69
+ for i, ch in enumerate(rest):
70
+ if quote:
71
+ if ch == quote and rest[i - 1] != "\\":
72
+ quote = None
73
+ elif ch in "'\"":
74
+ quote = ch
75
+ elif ch == "(":
76
+ depth += 1
77
+ elif ch == ")":
78
+ depth -= 1
79
+ if depth == 0:
80
+ return name, rest[1:i]
81
+ return None # unbalanced parentheses
82
+
83
+
84
+ def _directive_arguments(lines: list[str], start: int, first: str) -> list[tuple[int, str]]:
85
+ """Collect the signature lines of a directive starting at ``lines[start]``.
86
+
87
+ Sphinx treats each following indented, non-option line as another
88
+ signature, and a trailing backslash as a line continuation.
89
+ """
90
+ sigs: list[tuple[int, str]] = []
91
+ current, current_line = first, start + 1
92
+ i = start + 1
93
+ while True:
94
+ if current.rstrip().endswith("\\") and i < len(lines):
95
+ current = current.rstrip()[:-1] + " " + lines[i].strip()
96
+ i += 1
97
+ continue
98
+ if current.strip():
99
+ sigs.append((current_line, current.strip()))
100
+ if i >= len(lines):
101
+ break
102
+ nxt = lines[i]
103
+ if not nxt.strip() or _OPTION.match(nxt) or not nxt[:1].isspace():
104
+ break
105
+ current, current_line = nxt, i + 1
106
+ i += 1
107
+ return sigs
108
+
109
+
110
+ def parse_rst(path: Path, text: str | None = None) -> list[DocSignature]:
111
+ """Return every callable signature documented in one ``.rst`` file."""
112
+ if text is None:
113
+ text = path.read_text(encoding="utf-8")
114
+ lines = text.splitlines()
115
+ module: str | None = None
116
+ # Stack of (indent, class qualname) for nested method directives.
117
+ scopes: list[tuple[int, str]] = []
118
+ found: list[DocSignature] = []
119
+
120
+ for idx, line in enumerate(lines):
121
+ match = _DIRECTIVE.match(line)
122
+ if not match:
123
+ continue
124
+ indent = len(match["indent"].expandtabs())
125
+ name, arg = match["name"], match["arg"]
126
+ while scopes and scopes[-1][0] >= indent:
127
+ scopes.pop()
128
+
129
+ if name in ("module", "currentmodule"):
130
+ arg = arg.strip()
131
+ module = None if arg in ("", "None") else arg
132
+ scopes.clear()
133
+ continue
134
+ if name not in CALLABLE_DIRECTIVES:
135
+ continue
136
+
137
+ class_name = None
138
+ for lineno, sig in _directive_arguments(lines, idx, arg):
139
+ split = _split_signature(sig)
140
+ if split is None:
141
+ continue
142
+ qualname, params = split
143
+ if scopes and "." not in qualname:
144
+ qualname = f"{scopes[-1][1]}.{qualname}"
145
+ class_name = class_name or qualname
146
+ found.append(DocSignature(path, lineno, name, module, qualname, params))
147
+
148
+ if name in CLASS_DIRECTIVES and class_name:
149
+ scopes.append((indent, class_name))
150
+ return found
151
+
152
+
153
+ def iter_rst_files(paths: list[Path]) -> list[Path]:
154
+ """Expand directories into their ``.rst`` files, sorted for stable output."""
155
+ files: list[Path] = []
156
+ for path in paths:
157
+ if path.is_dir():
158
+ files.extend(sorted(path.rglob("*.rst")))
159
+ else:
160
+ files.append(path)
161
+ return files
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.5
2
+ Name: sigdrift
3
+ Version: 0.1.0
4
+ Summary: Find parameter names in hand-written Sphinx docs that the real function rejects as keywords.
5
+ Project-URL: Homepage, https://github.com/thejesh23/sigdrift
6
+ Project-URL: Issues, https://github.com/thejesh23/sigdrift/issues
7
+ Project-URL: Changelog, https://github.com/thejesh23/sigdrift/blob/main/CHANGELOG.md
8
+ Author: Thejesh
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: documentation,lint,rst,signature,sphinx
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Framework :: Sphinx
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Documentation :: Sphinx
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Requires-Python: >=3.11
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=8; extra == 'test'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # sigdrift
25
+
26
+ Find parameter names in hand-written Sphinx docs that the real function
27
+ rejects as keywords.
28
+
29
+ ```rst
30
+ .. function:: loads(data, *, fmt=None, dict_type=dict, aware_datetime=False)
31
+ ```
32
+
33
+ ```python
34
+ >>> plistlib.loads(data=b"...")
35
+ TypeError: loads() got an unexpected keyword argument 'data'
36
+ ```
37
+
38
+ The docs say `data`; the code says `value`. Anyone who copies the name from
39
+ the docs, including a code assistant, gets a `TypeError`. Docstring linters
40
+ such as docsig and pylint's `docparams` don't see this, because the signature
41
+ lives in an `.rst` file and not in a docstring. sigdrift reads those
42
+ directives, imports what they describe and asks Python whether each
43
+ documented keyword would bind.
44
+
45
+ ```console
46
+ $ python -m sigdrift Doc/library/plistlib.rst
47
+ Doc/library/plistlib.rst:85: SD001 plistlib.loads: 'data' is not accepted as a keyword; the real name is 'value'
48
+ 1 finding(s) in 5 checked signature(s); 0 unresolved, 0 without a signature
49
+ ```
50
+
51
+ ## Install
52
+
53
+ ```console
54
+ pip install sigdrift
55
+ ```
56
+
57
+ Python 3.11 or later, no dependencies. Install it into the same environment as
58
+ the package whose docs you are checking.
59
+
60
+ ## Usage
61
+
62
+ Run sigdrift **with the interpreter whose packages the docs describe**, since
63
+ it imports them to read their real signatures:
64
+
65
+ ```console
66
+ python -m sigdrift docs/ # folders are searched for *.rst
67
+ python -m sigdrift docs/api.rst --format json
68
+ python -m sigdrift docs/ --format github # annotations in GitHub Actions
69
+ ```
70
+
71
+ It exits 1 when there are findings, so it can gate CI. A
72
+ [pre-commit](https://pre-commit.com) hook is included (`id: sigdrift`).
73
+
74
+ | Code | Meaning | Default |
75
+ |---|---|---|
76
+ | SD001 | The docs name a parameter that exists under another, keyword-passable name | on |
77
+ | SD002 | The docs imply a keyword, but the real parameter is positional-only and the docs don't show `/` | off |
78
+ | SD003 | The docs name a parameter the callable does not have | on |
79
+
80
+ SD002 is opt-in (`--select SD001,SD002,SD003`): many C functions are
81
+ positional-only and their docs predate the `/` notation, so it is a much
82
+ larger, separate cleanup.
83
+
84
+ ### Options and configuration
85
+
86
+ ```toml
87
+ [tool.sigdrift]
88
+ paths = ["Doc"]
89
+ select = ["SD001", "SD003"]
90
+ # fnmatch patterns over "module.name" or "module.name:param"
91
+ ignore = [
92
+ "urllib.parse.urlsplit:urlstring", # name chosen on purpose
93
+ "decimal.*",
94
+ ]
95
+ include-brackets = false # also check old-style [optional] parameters
96
+ skip-modules = ["myapp.gui"] # never import these
97
+ aliases = { "asyncio.loop" = "asyncio.SelectorEventLoop" } # doc-only names
98
+ ```
99
+
100
+ Each setting has a command-line flag: `--select`, `--ignore`, `--include-brackets`,
101
+ `--skip-module`, `--alias OLD=NEW`, `--config`. Use `-v` to list what could not
102
+ be checked.
103
+
104
+ ## How it works
105
+
106
+ 1. Each `function`, `method`, `class`, `exception`, `classmethod`,
107
+ `staticmethod` and coroutine directive is read along with its signature
108
+ lines, tracking `module` / `currentmodule` and nested classes.
109
+ 2. The documented parameter list is parsed, including `/`, `*`, defaults that
110
+ contain commas, and the old `foo(a[, b])` bracket notation.
111
+ 3. The documented name is imported, and every parameter the docs present as
112
+ passable by keyword is tested with
113
+ `inspect.signature(obj).bind_partial(name=...)`. Nothing is called.
114
+
115
+ It stays quiet when the docs are describing positions rather than keywords:
116
+ parameters absorbed by a real `*args`, bracketed parameters (unless
117
+ `--include-brackets`), a leading `self`/`cls`, and `.. class:: Name(Base)`
118
+ directives that list base classes.
119
+
120
+ Limits:
121
+
122
+ - Importing a module runs its import-time code. Use `skip-modules` for anything
123
+ with side effects. `antigravity` and `this` are skipped by default.
124
+ - Names that don't import on this machine (platform-only modules, missing C
125
+ extensions) are reported as *unresolved* and never guessed. A missing `lzma`
126
+ is not silently replaced by `builtins.open`.
127
+ - Some C callables have no introspectable signature; those are counted, not
128
+ checked.
129
+ - Not every finding is a bug. Sometimes a descriptive name is chosen on purpose
130
+ (CPython's `urlsplit(urlstring)` signals "str or bytes"). Check the history,
131
+ then add an `ignore` entry.
132
+
133
+ ## Case study: CPython's documentation
134
+
135
+ Run against `Doc/` from a CPython main checkout of November 2026 (plus one
136
+ docs commit fixing the `email.utils` names), with the interpreter built from
137
+ the same commit:
138
+
139
+ | | |
140
+ |---|---|
141
+ | `.rst` files / callable signatures found | 576 / 7,862 |
142
+ | Signatures checked | 3,187 |
143
+ | Findings (SD001 + SD003) | 185 (181 + 4), in 162 callables across 63 files |
144
+ | Additional SD002 (positional-only without `/`) | 540 |
145
+ | Run time | about 1 second |
146
+
147
+ Examples, each confirmed to raise `TypeError` when called as documented:
148
+ `inspect.signature(callable=)`, `asyncio.run(coro=)`,
149
+ `plistlib.loads(data=)`, `logging.makeLogRecord(attrdict=)`,
150
+ `urllib.parse.urlunsplit(parts=)`, `unittest.TestCase.assertIs(first=, second=)`.
151
+
152
+ A few are deliberate, like `copy.copy(obj)` and `urlsplit(urlstring)`, and
153
+ belong in an `ignore` list rather than a docs change.
154
+
155
+ ## Roadmap
156
+
157
+ - A Sphinx extension that emits these as build warnings
158
+ - An inline ignore comment next to the directive
159
+ - MyST Markdown directives
160
+
161
+ ## License
162
+
163
+ MIT
@@ -0,0 +1,12 @@
1
+ sigdrift/__init__.py,sha256=v5GdnmtxosHGJHyOyjwnjIUUTYhTSmaT3Yqd932-TJI,93
2
+ sigdrift/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ sigdrift/check.py,sha256=8tvCNUh4AVQabozp0neuahCkCwK0etRL2Letq2qk3YQ,11273
4
+ sigdrift/cli.py,sha256=A475dDLjhu2fQz5KRaUTQjdcYEMTEa-khiQQQwe0pJc,5163
5
+ sigdrift/config.py,sha256=1mn1lG8R4D7f6EV0SUnXSXxeuiZLodT3r_SMQnue6fU,2009
6
+ sigdrift/params.py,sha256=lez0G49qT3-XrnXqoRSTW-inxXs0PFQa9MjozNDLEcM,4329
7
+ sigdrift/rst.py,sha256=6EEs3yxpRv8KBc_ESSNn97iC2O3cgKzJ6b0mhuiu-Kk,5252
8
+ sigdrift-0.1.0.dist-info/METADATA,sha256=4B54Pt7qSVpVNdQNtdF6NM5EU9AjzHpeC4JntjomJ4U,6134
9
+ sigdrift-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ sigdrift-0.1.0.dist-info/entry_points.txt,sha256=9XyQbkvA_iWAO_fh5dCowjKSUmbr8ML-L18W-iFqJ20,47
11
+ sigdrift-0.1.0.dist-info/licenses/LICENSE,sha256=y-JHtWVFtyFtRqDTzKUy62CVxxNjvCkhfBXDKN-8KKA,1064
12
+ sigdrift-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sigdrift = sigdrift.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thejesh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.