pydebt 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.
pydebt/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
pydebt/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from pydebt.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
pydebt/baseline.py ADDED
@@ -0,0 +1,64 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import TypedDict
7
+
8
+ from pydebt.scanner import FileScan
9
+
10
+ BASELINE_FILE = ".pydebt.json"
11
+
12
+
13
+ class FileEntry(TypedDict):
14
+ lines: int
15
+ counts: dict[str, int]
16
+
17
+
18
+ class Baseline(TypedDict):
19
+ version: int
20
+ files: dict[str, FileEntry]
21
+
22
+
23
+ @dataclass
24
+ class Delta:
25
+ added: dict[str, int]
26
+ removed: dict[str, int]
27
+ changed_files: list[str]
28
+
29
+ @property
30
+ def net(self) -> int:
31
+ return sum(self.added.values()) - sum(self.removed.values())
32
+
33
+ @property
34
+ def worse(self) -> bool:
35
+ return self.net > 0
36
+
37
+
38
+ def build_baseline(scans: list[FileScan]) -> Baseline:
39
+ files: dict[str, FileEntry] = {}
40
+ for scan in scans:
41
+ counts: dict[str, int] = {}
42
+ for f in scan.findings:
43
+ counts[f.kind] = counts.get(f.kind, 0) + 1
44
+ files[scan.path] = FileEntry(lines=scan.lines, counts=counts)
45
+ return Baseline(version=1, files=files)
46
+
47
+
48
+ def write_baseline(root: Path, data: Baseline) -> Path:
49
+ path = root / BASELINE_FILE
50
+ path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
51
+ return path
52
+
53
+
54
+ def read_baseline(root: Path) -> Baseline | None:
55
+ path = root / BASELINE_FILE
56
+ if not path.exists():
57
+ return None
58
+ raw = path.read_text(encoding="utf-8")
59
+ data: Baseline = json.loads(raw)
60
+ return data
61
+
62
+
63
+ def totals(counts: dict[str, int]) -> int:
64
+ return sum(counts.values())
pydebt/cli.py ADDED
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import cast
8
+
9
+ from pydebt import __version__
10
+ from pydebt.baseline import (
11
+ Baseline,
12
+ Delta,
13
+ FileEntry,
14
+ build_baseline,
15
+ read_baseline,
16
+ totals,
17
+ write_baseline,
18
+ )
19
+ from pydebt.report import render_text, summary
20
+ from pydebt.scanner import scan_tree
21
+
22
+ DEFAULT_EXCLUDE = ["tests", "test", ".venv", "venv", "build", "dist", "node_modules"]
23
+
24
+
25
+ def cmd_scan(args: argparse.Namespace) -> int:
26
+ root = Path(args.root).resolve()
27
+ scans = scan_tree(root, exclude=args.exclude)
28
+ data = summary(scans)
29
+ if args.json:
30
+ print(json.dumps(data, indent=2))
31
+ else:
32
+ print(render_text(data, top=args.top))
33
+ return 0
34
+
35
+
36
+ def cmd_baseline(args: argparse.Namespace) -> int:
37
+ root = Path(args.root).resolve()
38
+ scans = scan_tree(root, exclude=args.exclude)
39
+ data = build_baseline(scans)
40
+ path = write_baseline(root, data)
41
+ total = sum(totals(f["counts"]) for f in data["files"].values())
42
+ print(f"baseline: {total} findings across {len(data['files'])} files -> {path.name}")
43
+ return 0
44
+
45
+
46
+ def _compute_delta(current: Baseline, baseline: Baseline) -> Delta:
47
+ cur_files = current["files"]
48
+ base_files = baseline["files"]
49
+ added: dict[str, int] = {}
50
+ removed: dict[str, int] = {}
51
+ changed: list[str] = []
52
+ empty = FileEntry(lines=0, counts={})
53
+
54
+ for path in sorted(set(cur_files) | set(base_files)):
55
+ cur_counts = cur_files.get(path, empty)["counts"]
56
+ base_counts = base_files.get(path, empty)["counts"]
57
+ for kind in set(cur_counts) | set(base_counts):
58
+ diff = cur_counts.get(kind, 0) - base_counts.get(kind, 0)
59
+ if diff > 0:
60
+ added[kind] = added.get(kind, 0) + diff
61
+ elif diff < 0:
62
+ removed[kind] = removed.get(kind, 0) - diff
63
+ if cur_counts != base_counts:
64
+ changed.append(path)
65
+
66
+ return Delta(added=added, removed=removed, changed_files=changed)
67
+
68
+
69
+ def cmd_check(args: argparse.Namespace) -> int:
70
+ root = Path(args.root).resolve()
71
+ baseline = read_baseline(root)
72
+ if baseline is None:
73
+ print("pydebt: no baseline found. run `pydebt baseline` first.", file=sys.stderr)
74
+ return 1
75
+
76
+ scans = scan_tree(root, exclude=args.exclude)
77
+ current = build_baseline(scans)
78
+ delta = _compute_delta(current, baseline)
79
+
80
+ if not delta.changed_files:
81
+ print("pydebt: no changes vs baseline.")
82
+ return 0
83
+
84
+ print(f"changed files: {len(delta.changed_files)}")
85
+ for kind, n in sorted(delta.added.items()):
86
+ print(f" +{n} {kind}")
87
+ for kind, n in sorted(delta.removed.items()):
88
+ print(f" -{n} {kind}")
89
+ print(f"net: {delta.net:+d}")
90
+
91
+ if delta.worse and not args.allow_growth:
92
+ print("pydebt: debt increased. failing.")
93
+ return 1
94
+ return 0
95
+
96
+
97
+ def cmd_report(args: argparse.Namespace) -> int:
98
+ root = Path(args.root).resolve()
99
+ scans = scan_tree(root, exclude=args.exclude)
100
+ data = summary(scans)
101
+ if args.json:
102
+ print(json.dumps(data, indent=2))
103
+ else:
104
+ print(render_text(data, top=args.top))
105
+ return 0
106
+
107
+
108
+ def build_parser() -> argparse.ArgumentParser:
109
+ parser = argparse.ArgumentParser(
110
+ prog="pydebt",
111
+ description="Measurable technical debt for Python projects.",
112
+ )
113
+ parser.add_argument("--version", action="version", version=f"pydebt {__version__}")
114
+
115
+ sub = parser.add_subparsers(dest="command", required=True)
116
+
117
+ def add_common(p: argparse.ArgumentParser) -> None:
118
+ p.add_argument("root", nargs="?", default=".", help="project root (default: .)")
119
+ p.add_argument(
120
+ "--exclude",
121
+ nargs="*",
122
+ default=DEFAULT_EXCLUDE,
123
+ help="directory names to skip",
124
+ )
125
+
126
+ p_scan = sub.add_parser("scan", help="scan and summarize")
127
+ add_common(p_scan)
128
+ p_scan.add_argument("--json", action="store_true", help="emit JSON")
129
+ p_scan.add_argument("--top", type=int, default=10, help="top N files/dirs")
130
+ p_scan.set_defaults(func=cmd_scan)
131
+
132
+ p_base = sub.add_parser("baseline", help="write .pydebt.json from current state")
133
+ add_common(p_base)
134
+ p_base.set_defaults(func=cmd_baseline)
135
+
136
+ p_check = sub.add_parser("check", help="compare current state to baseline")
137
+ add_common(p_check)
138
+ p_check.add_argument(
139
+ "--allow-growth", action="store_true", help="exit 0 even if debt increased"
140
+ )
141
+ p_check.set_defaults(func=cmd_check)
142
+
143
+ p_report = sub.add_parser("report", help="summary report")
144
+ add_common(p_report)
145
+ p_report.add_argument("--json", action="store_true", help="emit JSON")
146
+ p_report.add_argument("--top", type=int, default=10, help="top N files/dirs")
147
+ p_report.set_defaults(func=cmd_report)
148
+
149
+ return parser
150
+
151
+
152
+ def main(argv: list[str] | None = None) -> int:
153
+ parser = build_parser()
154
+ args = parser.parse_args(argv)
155
+ return cast(int, args.func(args))
pydebt/py.typed ADDED
File without changes
pydebt/report.py ADDED
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import Counter
4
+ from typing import TypedDict
5
+
6
+ from pydebt.scanner import FileScan
7
+
8
+
9
+ class Summary(TypedDict):
10
+ total: int
11
+ by_kind: dict[str, int]
12
+ by_dir: dict[str, int]
13
+ by_file: list[tuple[str, int]]
14
+
15
+
16
+ def summary(scans: list[FileScan]) -> Summary:
17
+ by_kind: Counter[str] = Counter()
18
+ by_dir: Counter[str] = Counter()
19
+ by_file: list[tuple[str, int]] = []
20
+ total = 0
21
+
22
+ for scan in scans:
23
+ if scan.findings:
24
+ by_file.append((scan.path, len(scan.findings)))
25
+ total += len(scan.findings)
26
+ dirname = scan.path.rsplit("/", 1)[0] if "/" in scan.path else "."
27
+ for f in scan.findings:
28
+ by_kind[f.kind] += 1
29
+ by_dir[dirname] += 1
30
+
31
+ by_file.sort(key=lambda x: (-x[1], x[0]))
32
+ return Summary(
33
+ total=total,
34
+ by_kind=dict(by_kind.most_common()),
35
+ by_dir=dict(by_dir.most_common()),
36
+ by_file=by_file,
37
+ )
38
+
39
+
40
+ def render_text(data: Summary, top: int = 10) -> str:
41
+ lines = [f"total findings: {data['total']}", ""]
42
+
43
+ if data["by_kind"]:
44
+ lines.append("by kind:")
45
+ kind_width = max(len(k) for k in data["by_kind"])
46
+ for kind, n in data["by_kind"].items():
47
+ lines.append(f" {kind:<{kind_width}} {n}")
48
+ lines.append("")
49
+
50
+ if data["by_dir"]:
51
+ lines.append("by directory:")
52
+ dir_width = max(len(d) for d in data["by_dir"])
53
+ for d, n in list(data["by_dir"].items())[:top]:
54
+ lines.append(f" {d:<{dir_width}} {n}")
55
+ lines.append("")
56
+
57
+ if data["by_file"]:
58
+ lines.append(f"top {top} files:")
59
+ for path, n in data["by_file"][:top]:
60
+ lines.append(f" {n:>4} {path}")
61
+
62
+ return "\n".join(lines)
pydebt/scanner.py ADDED
@@ -0,0 +1,127 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import io
5
+ import re
6
+ import tokenize
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+
10
+ FUNCTION_LINE_THRESHOLD = 50
11
+ FILE_LINE_THRESHOLD = 500
12
+
13
+ WORD_MARKERS = ("TODO", "FIXME", "HACK", "XXX")
14
+ PRAGMA_MARKERS = {
15
+ "TYPE_IGNORE": "type: ignore",
16
+ "NOQA": "noqa",
17
+ "NO_COVER": "pragma: no cover",
18
+ }
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Finding:
23
+ kind: str
24
+ path: str
25
+ line: int
26
+ detail: str = ""
27
+
28
+
29
+ @dataclass
30
+ class FileScan:
31
+ path: str
32
+ lines: int
33
+ findings: list[Finding] = field(default_factory=list)
34
+
35
+
36
+ def _scan_comments(source: str) -> list[tuple[int, str]]:
37
+ comments: list[tuple[int, str]] = []
38
+ try:
39
+ for tok in tokenize.generate_tokens(io.StringIO(source).readline):
40
+ if tok.type == tokenize.COMMENT:
41
+ comments.append((tok.start[0], tok.string))
42
+ except (tokenize.TokenError, IndentationError):
43
+ return comments
44
+ return comments
45
+
46
+
47
+ def _match_kind(comment: str) -> str | None:
48
+ for kind in WORD_MARKERS:
49
+ if re.search(rf"\b{kind}\b", comment):
50
+ return kind
51
+ lower = comment.lower()
52
+ for kind, needle in PRAGMA_MARKERS.items():
53
+ if needle in lower:
54
+ return kind
55
+ return None
56
+
57
+
58
+ def _scan_ast(source: str, path: str) -> list[Finding]:
59
+ findings: list[Finding] = []
60
+ try:
61
+ tree = ast.parse(source)
62
+ except SyntaxError:
63
+ return findings
64
+
65
+ for node in ast.walk(tree):
66
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
67
+ end = node.end_lineno if node.end_lineno is not None else node.lineno
68
+ length = end - node.lineno + 1
69
+ if length > FUNCTION_LINE_THRESHOLD:
70
+ findings.append(
71
+ Finding(
72
+ kind="LONG_FUNCTION",
73
+ path=path,
74
+ line=node.lineno,
75
+ detail=f"{node.name} ({length} lines)",
76
+ )
77
+ )
78
+ if (
79
+ isinstance(node, ast.ExceptHandler)
80
+ and len(node.body) == 1
81
+ and isinstance(node.body[0], ast.Pass)
82
+ ):
83
+ findings.append(
84
+ Finding(
85
+ kind="EXCEPT_PASS",
86
+ path=path,
87
+ line=node.lineno,
88
+ detail="silent except",
89
+ )
90
+ )
91
+ return findings
92
+
93
+
94
+ def scan_file(path: Path, root: Path) -> FileScan | None:
95
+ try:
96
+ source = path.read_text(encoding="utf-8")
97
+ except (UnicodeDecodeError, OSError):
98
+ return None
99
+
100
+ rel = str(path.relative_to(root)).replace("\\", "/")
101
+ lines = source.count("\n") + (1 if source and not source.endswith("\n") else 0)
102
+ result = FileScan(path=rel, lines=lines)
103
+
104
+ if lines > FILE_LINE_THRESHOLD:
105
+ result.findings.append(Finding(kind="LONG_FILE", path=rel, line=1, detail=f"{lines} lines"))
106
+
107
+ for lineno, text in _scan_comments(source):
108
+ kind = _match_kind(text)
109
+ if kind:
110
+ result.findings.append(Finding(kind=kind, path=rel, line=lineno))
111
+
112
+ result.findings.extend(_scan_ast(source, rel))
113
+ return result
114
+
115
+
116
+ def scan_tree(root: Path, exclude: list[str] | None = None) -> list[FileScan]:
117
+ exclude_set = set(exclude or [])
118
+ results: list[FileScan] = []
119
+ for path in sorted(root.rglob("*.py")):
120
+ if "__pycache__" in path.parts:
121
+ continue
122
+ if set(path.relative_to(root).parts) & exclude_set:
123
+ continue
124
+ scanned = scan_file(path, root)
125
+ if scanned is not None:
126
+ results.append(scanned)
127
+ return results
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: pydebt
3
+ Version: 0.1.0
4
+ Summary: Measurable technical debt for Python projects
5
+ Author-email: your name <you@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/eduardowebdev/pydebt
8
+ Project-URL: Repository, https://github.com/eduardowebdev/pydebt
9
+ Project-URL: Issues, https://github.com/eduardowebdev/pydebt/issues
10
+ Project-URL: Changelog, https://github.com/eduardowebdev/pydebt/blob/main/CHANGELOG.md
11
+ Keywords: technical-debt,linter,static-analysis,quality
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Quality Assurance
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8; extra == "dev"
26
+ Requires-Dist: ruff>=0.6; extra == "dev"
27
+ Requires-Dist: mypy>=1.11; extra == "dev"
28
+ Requires-Dist: build>=1.2; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # pydebt
32
+
33
+ [![ci](https://github.com/eduardowebdev/pydebt/actions/workflows/ci.yml/badge.svg)](https://github.com/eduardowebdev/pydebt/actions/workflows/ci.yml)
34
+ [![pypi](https://img.shields.io/pypi/v/pydebt.svg)](https://pypi.org/project/pydebt/)
35
+ [![python](https://img.shields.io/pypi/pyversions/pydebt.svg)](https://pypi.org/project/pydebt/)
36
+ [![license](https://img.shields.io/pypi/l/pydebt.svg)](https://pypi.org/project/pydebt/)
37
+
38
+ Measurable technical debt for Python. Counts markers, complexity signals, and
39
+ compares against a committed baseline so CI fails when debt grows.
40
+
41
+ ## Install
42
+
43
+ ~~~
44
+ pip install pydebt
45
+ ~~~
46
+
47
+ ## Usage
48
+
49
+ ~~~
50
+ # snapshot current state
51
+ pydebt baseline
52
+
53
+ # summarize
54
+ pydebt scan
55
+ pydebt scan --json --top 20
56
+
57
+ # compare to baseline (exit 1 if worse)
58
+ pydebt check
59
+
60
+ # allow growth, just report
61
+ pydebt check --allow-growth
62
+
63
+ # full report
64
+ pydebt report
65
+ ~~~
66
+
67
+ ## What it counts
68
+
69
+ | Kind | Source |
70
+ |---|---|
71
+ | `TODO` `FIXME` `HACK` `XXX` | comments (uppercase convention) |
72
+ | `TYPE_IGNORE` | `# type: ignore` in comments |
73
+ | `NOQA` | `# noqa` in comments |
74
+ | `NO_COVER` | `# pragma: no cover` in comments |
75
+ | `EXCEPT_PASS` | `except:` with only `pass` |
76
+ | `LONG_FUNCTION` | function > 50 lines |
77
+ | `LONG_FILE` | file > 500 lines |
78
+
79
+ ## CI
80
+
81
+ ~~~
82
+ - run: pip install pydebt
83
+ - run: pydebt check
84
+ ~~~
85
+
86
+ ## Baseline
87
+
88
+ `.pydebt.json` is committed. It stores per-file line count and per-kind marker
89
+ counts. `check` diffs current against it and fails on net growth.
90
+
91
+ ## Development
92
+
93
+ ~~~
94
+ pip install -e ".[dev]"
95
+ pytest
96
+ ruff check src tests
97
+ mypy src
98
+ ~~~
99
+
100
+ ## License
101
+
102
+ MIT
@@ -0,0 +1,13 @@
1
+ pydebt/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ pydebt/__main__.py,sha256=j3U-DOMfz0uVXLX8fQ1mhwsjeRp0L2XTS7MFWqZ6Pm8,85
3
+ pydebt/baseline.py,sha256=Gy9q_uc2BYUgDfyQZPHsf8WMh_bNHbwk03aTBJDyla8,1498
4
+ pydebt/cli.py,sha256=riPzYYjz7x74s_EOkMxMgJxPZg0dyNfv1AVppjQQgZY,4992
5
+ pydebt/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ pydebt/report.py,sha256=OorjV2AFfOVwhCgvK1xcGoVNd1BYjthfNuT9TMd6NMI,1770
7
+ pydebt/scanner.py,sha256=MXbI7n0TIeObns4YfQfjAtKpUqDImAFiaqk4OsPqc7k,3645
8
+ pydebt-0.1.0.dist-info/licenses/LICENSE,sha256=unCqpibCvd_QzWR4zmO6pkNvTghXSnbh-nVKQawYpfQ,1076
9
+ pydebt-0.1.0.dist-info/METADATA,sha256=iMPv8MNVU4i6h1zeq38JUmGp08-73pxxyEtJ4inWauI,2802
10
+ pydebt-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ pydebt-0.1.0.dist-info/entry_points.txt,sha256=6zoJkbzDJCeyJFkwumF_UjRluh9c2sF-2qAxT1Ji2EU,43
12
+ pydebt-0.1.0.dist-info/top_level.txt,sha256=tiKslpP9YVhXfXuZ4LePDYFkHVU2CtXeecLwWIsMCpI,7
13
+ pydebt-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pydebt = pydebt.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pydebt contributors
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 @@
1
+ pydebt