gz-mindload 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 g0
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.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: gz-mindload
3
+ Version: 0.1.0
4
+ Summary: Cognitive complexity scorer over CPython's ast: a Python API and a CLI
5
+ Author: g0
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Dist: pydantic>=2.14.1
9
+ Requires-Python: >=3.14, <3.15
10
+ Project-URL: Repository, https://github.com/tvproductions/gz-mindload
11
+ Description-Content-Type: text/markdown
12
+
13
+ # gz-mindload
14
+
15
+ A cognitive complexity scorer over CPython's `ast`, after G. Ann Campbell's
16
+ *Cognitive Complexity*. It never executes the code it scores.
17
+
18
+ ```python
19
+ from gz_mindload import score_cognitive
20
+
21
+ for record in score_cognitive(source, "module.py"):
22
+ print(record.name, record.line, record.score)
23
+ ```
24
+
25
+ ```bash
26
+ gz-mindload PATH...
27
+ ```
28
+
29
+ ## Provenance
30
+
31
+ Extracted as-is from [gzkit](https://github.com/tvproductions/gzkit) at commit
32
+ `a06a4f36a8e3fc538d8f20b61df91b9bf42d1ee7`: `src/gzkit/complexity/cognitive.py` and its tests. Only import paths
33
+ and the module named in the usage line changed.
34
+
35
+ ## Development
36
+
37
+ ```bash
38
+ uv sync --locked
39
+ uv run --locked python -m unittest discover -s tests -v
40
+ ```
@@ -0,0 +1,28 @@
1
+ # gz-mindload
2
+
3
+ A cognitive complexity scorer over CPython's `ast`, after G. Ann Campbell's
4
+ *Cognitive Complexity*. It never executes the code it scores.
5
+
6
+ ```python
7
+ from gz_mindload import score_cognitive
8
+
9
+ for record in score_cognitive(source, "module.py"):
10
+ print(record.name, record.line, record.score)
11
+ ```
12
+
13
+ ```bash
14
+ gz-mindload PATH...
15
+ ```
16
+
17
+ ## Provenance
18
+
19
+ Extracted as-is from [gzkit](https://github.com/tvproductions/gzkit) at commit
20
+ `a06a4f36a8e3fc538d8f20b61df91b9bf42d1ee7`: `src/gzkit/complexity/cognitive.py` and its tests. Only import paths
21
+ and the module named in the usage line changed.
22
+
23
+ ## Development
24
+
25
+ ```bash
26
+ uv sync --locked
27
+ uv run --locked python -m unittest discover -s tests -v
28
+ ```
@@ -0,0 +1,62 @@
1
+ [project]
2
+ name = "gz-mindload"
3
+ version = "0.1.0"
4
+ description = "Cognitive complexity scorer over CPython's ast: a Python API and a CLI"
5
+ readme = "README.md"
6
+ requires-python = ">=3.14,<3.15"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ dependencies = ["pydantic>=2.14.1"]
10
+
11
+ [[project.authors]]
12
+ name = "g0"
13
+
14
+ [project.scripts]
15
+ gz-mindload = "gz_mindload.cognitive:main"
16
+
17
+ [project.urls]
18
+ Repository = "https://github.com/tvproductions/gz-mindload"
19
+
20
+ [build-system]
21
+ requires = ["uv_build==0.13.9"]
22
+ build-backend = "uv_build"
23
+
24
+ [tool.uv]
25
+ required-version = ">=0.13.5"
26
+ python-preference = "only-managed"
27
+
28
+ [tool.uv.build-backend]
29
+ module-name = "gz_mindload"
30
+
31
+ [tool.ruff]
32
+ target-version = "py314"
33
+ line-length = 100
34
+
35
+ [tool.ruff.lint]
36
+ select = [
37
+ "E4",
38
+ "E7",
39
+ "E9",
40
+ "F",
41
+ "I",
42
+ "UP",
43
+ "B",
44
+ "SIM",
45
+ "RUF",
46
+ ]
47
+
48
+ [tool.ty.environment]
49
+ python-version = "3.14"
50
+
51
+ [tool.ty.src]
52
+ include = [
53
+ "src",
54
+ "tests",
55
+ ]
56
+
57
+ [dependency-groups]
58
+ dev = [
59
+ "ruff==0.17.6",
60
+ "ty==0.0.107",
61
+ "pre-commit==4.7.0",
62
+ ]
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "gz-mindload"
3
+ version = "0.1.0"
4
+ description = "Cognitive complexity scorer over CPython's ast: a Python API and a CLI"
5
+ readme = "README.md"
6
+ requires-python = ">=3.14,<3.15"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "g0" }]
10
+ dependencies = ["pydantic>=2.14.1"]
11
+
12
+ [project.scripts]
13
+ gz-mindload = "gz_mindload.cognitive:main"
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/tvproductions/gz-mindload"
17
+
18
+ [build-system]
19
+ requires = ["uv_build==0.13.9"]
20
+ build-backend = "uv_build"
21
+
22
+ [tool.uv]
23
+ required-version = ">=0.13.5"
24
+ python-preference = "only-managed"
25
+
26
+ [tool.uv.build-backend]
27
+ module-name = "gz_mindload"
28
+
29
+ [dependency-groups]
30
+ dev = [
31
+ "ruff==0.17.6",
32
+ "ty==0.0.107",
33
+ "pre-commit==4.7.0",
34
+ ]
35
+
36
+ [tool.ruff]
37
+ target-version = "py314"
38
+ line-length = 100
39
+
40
+ [tool.ruff.lint]
41
+ select = ["E4", "E7", "E9", "F", "I", "UP", "B", "SIM", "RUF"]
42
+
43
+ [tool.ty.environment]
44
+ python-version = "3.14"
45
+
46
+ [tool.ty.src]
47
+ include = ["src", "tests"]
@@ -0,0 +1,5 @@
1
+ """Cognitive complexity scorer over CPython's ast."""
2
+
3
+ from gz_mindload.cognitive import CognitiveScore, score_cognitive
4
+
5
+ __all__ = ["CognitiveScore", "score_cognitive"]
@@ -0,0 +1,276 @@
1
+ """Cognitive complexity over CPython's own ``ast`` (drydock RO-9 tranche 4).
2
+
3
+ The operator ruled complexipy a poor replacement and selected a gzkit-owned scorer
4
+ (2026-10-22, *"gzkit-owned, stdlib ast (Rec.)"*). This module implements G. Ann
5
+ Campbell, *Cognitive Complexity: A new way of measuring understandability*
6
+ (SonarSource, 2016-2023), for Python:
7
+
8
+ - **Structural** (+1, plus the nesting level): ``if``, a conditional expression,
9
+ ``for`` / ``async for`` / ``while``, each ``except`` clause, ``match``.
10
+ - **Hybrid** (+1, no nesting increment): ``elif``, ``else`` (on ``if``, a loop or
11
+ ``try``).
12
+ - **Fundamental** (+1): each sequence of like boolean operators (``a and b and c``
13
+ is one, ``a and b or c`` two); each comprehension ``if`` filter and each ``case``
14
+ guard; direct recursion, once per function.
15
+ - **Nesting** rises inside the bodies of the structural increments, ``elif`` and
16
+ ``else``, and inside a nested ``def``, ``lambda`` or class, whose complexity
17
+ counts toward the function that encloses it (the spec's lambda and nested-method
18
+ rule). ``try``, ``finally`` and ``with`` add nothing.
19
+
20
+ Python has no labelled ``break`` or ``continue`` and no ``goto``, so the spec's
21
+ jump increments never apply. Comprehension ``for`` clauses add nothing: the spec
22
+ ignores a structure that shorthands several statements readably into one.
23
+
24
+ Parsing is CPython's, so every syntax the running interpreter accepts is scored by
25
+ the grammar that defines it. The scored unit is a function with no enclosing
26
+ function: a module-level ``def`` or a method, named by its qualified name.
27
+
28
+ ``python -m gz_mindload.cognitive PATH...`` prints each function's score,
29
+ highest first, for a chore's worklist or its before-and-after evidence; the gate
30
+ that holds the ceiling is ``gz validate --complexity-ceiling``.
31
+ """
32
+
33
+ import argparse
34
+ import ast
35
+ import json
36
+ import sys
37
+ from collections.abc import Sequence
38
+ from pathlib import Path
39
+
40
+ from pydantic import BaseModel, ConfigDict, Field
41
+
42
+ __all__ = ["CognitiveScore", "score_cognitive"]
43
+
44
+ _FunctionNode = ast.FunctionDef | ast.AsyncFunctionDef
45
+ _LOOPS = (ast.For, ast.AsyncFor, ast.While)
46
+
47
+
48
+ class CognitiveScore(BaseModel):
49
+ """The cognitive complexity of one function with no enclosing function."""
50
+
51
+ model_config = ConfigDict(frozen=True, extra="forbid")
52
+
53
+ name: str = Field(..., description="Qualified name: `Class.method` or `function`")
54
+ line: int = Field(..., description="Line of the `def`")
55
+ score: int = Field(..., description="Cognitive complexity per the SonarSource spec")
56
+
57
+
58
+ class _Scorer:
59
+ """Score one function; reads the source to tell ``elif`` from ``else: if``."""
60
+
61
+ def __init__(self, lines: list[str], function: _FunctionNode) -> None:
62
+ self._lines = lines
63
+ self._function = function
64
+
65
+ def total(self) -> int:
66
+ body = self._block(self._function.body, 0)
67
+ return body + self._recursion() + self._signature(self._function, 0)
68
+
69
+ def _signature(self, node: _FunctionNode | ast.Lambda, nesting: int) -> int:
70
+ """Score default values, which are evaluated outside the body."""
71
+ return sum(self._node(d, nesting) for d in node.args.defaults + node.args.kw_defaults if d)
72
+
73
+ def _block(self, statements: list[ast.stmt], nesting: int) -> int:
74
+ return sum(self._node(statement, nesting) for statement in statements)
75
+
76
+ def _children(self, node: ast.AST, nesting: int) -> int:
77
+ return sum(self._node(child, nesting) for child in ast.iter_child_nodes(node))
78
+
79
+ def _node(self, node: ast.AST, nesting: int) -> int:
80
+ if isinstance(node, ast.If):
81
+ return 1 + nesting + self._if(node, nesting)
82
+ if isinstance(node, _LOOPS):
83
+ return self._loop(node, nesting)
84
+ if isinstance(node, ast.Try | ast.TryStar):
85
+ return self._try(node, nesting)
86
+ if isinstance(node, ast.Match):
87
+ return self._match(node, nesting)
88
+ if isinstance(node, ast.IfExp):
89
+ branches = self._node(node.body, nesting + 1) + self._node(node.orelse, nesting + 1)
90
+ return 1 + nesting + self._node(node.test, nesting) + branches
91
+ if isinstance(node, ast.BoolOp):
92
+ return self._bool_op(node, nesting)
93
+ if isinstance(node, ast.comprehension):
94
+ return len(node.ifs) + self._children(node, nesting)
95
+ if isinstance(node, _FunctionNode | ast.Lambda):
96
+ return self._nested_function(node, nesting)
97
+ if isinstance(node, ast.ClassDef):
98
+ return self._children(node, nesting + 1)
99
+ return self._children(node, nesting)
100
+
101
+ def _if(self, node: ast.If, nesting: int) -> int:
102
+ """Score an ``if`` after its own increment: test, body and the chain below it."""
103
+ score = self._node(node.test, nesting) + self._block(node.body, nesting + 1)
104
+ if not node.orelse:
105
+ return score
106
+ if (elif_node := self._elif(node.orelse)) is not None:
107
+ return score + 1 + self._if(elif_node, nesting)
108
+ return score + 1 + self._block(node.orelse, nesting + 1)
109
+
110
+ def _elif(self, orelse: list[ast.stmt]) -> ast.If | None:
111
+ """Return the ``elif`` an ``else`` branch spells, or None for a plain ``else``.
112
+
113
+ The AST spells ``elif`` and ``else: if`` alike, as a lone nested ``If``; only
114
+ the source at the node's position tells them apart.
115
+
116
+ Returns:
117
+ The nested ``If`` when the branch is spelled ``elif``; None otherwise.
118
+
119
+ """
120
+ node = orelse[0]
121
+ spelled = self._lines[node.lineno - 1].startswith("elif", node.col_offset)
122
+ return node if isinstance(node, ast.If) and spelled else None
123
+
124
+ def _loop(self, node: ast.For | ast.AsyncFor | ast.While, nesting: int) -> int:
125
+ head = (
126
+ self._node(node.test, nesting)
127
+ if isinstance(node, ast.While)
128
+ else self._node(node.target, nesting) + self._node(node.iter, nesting)
129
+ )
130
+ score = 1 + nesting + head + self._block(node.body, nesting + 1)
131
+ if node.orelse:
132
+ score += 1 + self._block(node.orelse, nesting + 1)
133
+ return score
134
+
135
+ def _try(self, node: ast.Try | ast.TryStar, nesting: int) -> int:
136
+ score = self._block(node.body, nesting) + self._block(node.finalbody, nesting)
137
+ for handler in node.handlers:
138
+ handled = self._node(handler.type, nesting) if handler.type else 0
139
+ score += 1 + nesting + handled + self._block(handler.body, nesting + 1)
140
+ if node.orelse:
141
+ score += 1 + self._block(node.orelse, nesting + 1)
142
+ return score
143
+
144
+ def _match(self, node: ast.Match, nesting: int) -> int:
145
+ score = 1 + nesting + self._node(node.subject, nesting)
146
+ for case in node.cases:
147
+ if case.guard is not None:
148
+ score += 1 + self._node(case.guard, nesting + 1)
149
+ score += self._block(case.body, nesting + 1)
150
+ return score
151
+
152
+ def _bool_op(self, node: ast.BoolOp, nesting: int) -> int:
153
+ """+1 for this sequence; an operand continuing the same operator adds nothing."""
154
+ score = 1
155
+ for value in node.values:
156
+ if isinstance(value, ast.BoolOp) and isinstance(value.op, type(node.op)):
157
+ score += self._bool_op(value, nesting) - 1
158
+ else:
159
+ score += self._node(value, nesting)
160
+ return score
161
+
162
+ def _nested_function(self, node: _FunctionNode | ast.Lambda, nesting: int) -> int:
163
+ decorators = (
164
+ 0
165
+ if isinstance(node, ast.Lambda)
166
+ else sum(self._node(d, nesting) for d in node.decorator_list)
167
+ )
168
+ body = (
169
+ self._node(node.body, nesting + 1)
170
+ if isinstance(node, ast.Lambda)
171
+ else self._block(node.body, nesting + 1)
172
+ )
173
+ return decorators + self._signature(node, nesting) + body
174
+
175
+ def _recursion(self) -> int:
176
+ """+1 when the function calls itself by name, or as ``self.``/``cls.`` for a method."""
177
+ name = self._function.name
178
+ for node in ast.walk(self._function):
179
+ if not isinstance(node, ast.Call):
180
+ continue
181
+ func = node.func
182
+ if isinstance(func, ast.Name) and func.id == name:
183
+ return 1
184
+ if (
185
+ isinstance(func, ast.Attribute)
186
+ and func.attr == name
187
+ and isinstance(func.value, ast.Name)
188
+ and func.value.id in {"self", "cls"}
189
+ ):
190
+ return 1
191
+ return 0
192
+
193
+
194
+ def _scored_functions(tree: ast.Module) -> list[tuple[str, _FunctionNode]]:
195
+ """Return (qualname, node) for each function with no enclosing function."""
196
+ found: list[tuple[str, _FunctionNode]] = []
197
+
198
+ def visit(body: list[ast.stmt], prefix: str) -> None:
199
+ for statement in body:
200
+ if isinstance(statement, _FunctionNode):
201
+ found.append((f"{prefix}{statement.name}", statement))
202
+ elif isinstance(statement, ast.ClassDef):
203
+ visit(statement.body, f"{prefix}{statement.name}.")
204
+ elif isinstance(statement, ast.If | ast.Try | ast.TryStar | ast.With | ast.AsyncWith):
205
+ # Conditional and guarded definitions at module or class level.
206
+ for field in ("body", "orelse", "finalbody"):
207
+ visit(getattr(statement, field, []), prefix)
208
+ for handler in getattr(statement, "handlers", []):
209
+ visit(handler.body, prefix)
210
+
211
+ visit(tree.body, "")
212
+ return found
213
+
214
+
215
+ def score_cognitive(source: str, filename: str = "<source>") -> list[CognitiveScore]:
216
+ """Score every function in *source* with no enclosing function.
217
+
218
+ Raises ``SyntaxError`` when *source* does not parse; the caller decides how a
219
+ module that cannot be measured is reported.
220
+
221
+ Returns:
222
+ One score per function with no enclosing function, in source order.
223
+
224
+ """
225
+ tree = ast.parse(source, filename=filename)
226
+ lines = source.splitlines()
227
+ return [
228
+ CognitiveScore(name=name, line=node.lineno, score=_Scorer(lines, node).total())
229
+ for name, node in _scored_functions(tree)
230
+ ]
231
+
232
+
233
+ def _python_files(paths: Sequence[str]) -> list[Path]:
234
+ files: list[Path] = []
235
+ for raw in paths:
236
+ path = Path(raw)
237
+ files.extend(sorted(path.rglob("*.py")) if path.is_dir() else [path])
238
+ return files
239
+
240
+
241
+ def main(argv: Sequence[str] | None = None) -> int:
242
+ """Print the cognitive score of every function under *argv*'s paths, highest first."""
243
+ parser = argparse.ArgumentParser(
244
+ prog="gz-mindload",
245
+ description="Print cognitive complexity per function, highest first.",
246
+ )
247
+ parser.add_argument("paths", nargs="+", help="Python files or directories to score")
248
+ parser.add_argument("--top", type=int, default=None, help="Print only the N highest")
249
+ parser.add_argument("--json", action="store_true", help="Print one JSON array")
250
+ args = parser.parse_args(argv)
251
+ rows: list[tuple[str, CognitiveScore]] = []
252
+ for path in _python_files(args.paths):
253
+ file = path.as_posix()
254
+ try:
255
+ scores = score_cognitive(path.read_text(encoding="utf-8"), file)
256
+ except SyntaxError as exc:
257
+ print(f"{file}: does not parse: {exc.msg}", file=sys.stderr)
258
+ return 1
259
+ rows.extend((file, score) for score in scores)
260
+ rows.sort(key=lambda row: (-row[1].score, row[0], row[1].line))
261
+ rows = rows[: args.top] if args.top is not None else rows
262
+ if args.json:
263
+ # The keys of data/cognitive_complexity_baseline.json, plus the line.
264
+ payload = [
265
+ {"file": file, "function": score.name, "line": score.line, "score": score.score}
266
+ for file, score in rows
267
+ ]
268
+ print(json.dumps(payload, indent=2))
269
+ else:
270
+ for file, score in rows:
271
+ print(f"{score.score:>4} {file}:{score.line} {score.name}")
272
+ return 0
273
+
274
+
275
+ if __name__ == "__main__":
276
+ raise SystemExit(main())