dlen 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.
- dlen/__init__.py +13 -0
- dlen/cli.py +89 -0
- dlen/core.py +130 -0
- dlen/py.typed +0 -0
- dlen-0.1.0.dist-info/METADATA +122 -0
- dlen-0.1.0.dist-info/RECORD +9 -0
- dlen-0.1.0.dist-info/WHEEL +4 -0
- dlen-0.1.0.dist-info/entry_points.txt +2 -0
- dlen-0.1.0.dist-info/licenses/LICENSE +21 -0
dlen/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""dlen — check how long your functions and classes are."""
|
|
2
|
+
|
|
3
|
+
from .core import Code, Finding, Level, Limits, check_file, check_paths, check_source
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"Code",
|
|
7
|
+
"Finding",
|
|
8
|
+
"Level",
|
|
9
|
+
"Limits",
|
|
10
|
+
"check_file",
|
|
11
|
+
"check_paths",
|
|
12
|
+
"check_source",
|
|
13
|
+
]
|
dlen/cli.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""The command line: parses arguments, renders findings, picks the exit code.
|
|
2
|
+
|
|
3
|
+
This is the only module that prints or reads argv. The core stays a pure function
|
|
4
|
+
of its inputs, which is what makes it usable from another program.
|
|
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 .core import Finding, Level, Limits, check_paths
|
|
16
|
+
|
|
17
|
+
DEFAULTS = Limits()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def format_full(findings: Sequence[Finding]) -> str:
|
|
21
|
+
"""One line per finding, the shape editors and CI logs already know how to parse."""
|
|
22
|
+
return "\n".join(f"{f.path}:{f.line}:{f.column}: {f.code.value} {f.message}" for f in findings)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def format_github(findings: Sequence[Finding]) -> str:
|
|
26
|
+
"""Workflow commands, so the findings land on the PR diff instead of in a log."""
|
|
27
|
+
return "\n".join(
|
|
28
|
+
f"::{f.level.value} file={f.path},line={f.line},col={f.column},"
|
|
29
|
+
f"title={f.code.value}::{f.message}"
|
|
30
|
+
for f in findings
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _as_dict(finding: Finding) -> dict[str, str | int]:
|
|
35
|
+
return {
|
|
36
|
+
"path": str(finding.path),
|
|
37
|
+
"line": finding.line,
|
|
38
|
+
"column": finding.column,
|
|
39
|
+
"code": finding.code.value,
|
|
40
|
+
"level": finding.level.value,
|
|
41
|
+
"message": finding.message,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def format_json(findings: Sequence[Finding]) -> str:
|
|
46
|
+
return json.dumps([_as_dict(f) for f in findings], indent=2)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
FORMATTERS = {"full": format_full, "github": format_github, "json": format_json}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _add_limit(parser: argparse.ArgumentParser, flag: str, default: int, verb: str) -> None:
|
|
53
|
+
parser.add_argument(
|
|
54
|
+
flag,
|
|
55
|
+
type=int,
|
|
56
|
+
default=default,
|
|
57
|
+
metavar="N",
|
|
58
|
+
help=f"{verb} above N lines (default: {default})",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
63
|
+
parser = argparse.ArgumentParser(
|
|
64
|
+
prog="dlen", description="Check how long your functions and classes are."
|
|
65
|
+
)
|
|
66
|
+
parser.add_argument("paths", nargs="+", type=Path, metavar="PATH", help="files or directories")
|
|
67
|
+
_add_limit(parser, "--warn-function", DEFAULTS.warn_function, "warn")
|
|
68
|
+
_add_limit(parser, "--max-function", DEFAULTS.max_function, "fail")
|
|
69
|
+
_add_limit(parser, "--max-class", DEFAULTS.max_class, "fail")
|
|
70
|
+
parser.add_argument(
|
|
71
|
+
"--output-format", choices=sorted(FORMATTERS), default="full", metavar="FORMAT"
|
|
72
|
+
)
|
|
73
|
+
return parser
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
77
|
+
"""Returns the exit code: 1 when anything is over a max, 0 otherwise."""
|
|
78
|
+
args = build_parser().parse_args(argv)
|
|
79
|
+
limits = Limits(args.warn_function, args.max_function, args.max_class)
|
|
80
|
+
|
|
81
|
+
findings = check_paths(args.paths, limits)
|
|
82
|
+
if findings:
|
|
83
|
+
print(FORMATTERS[args.output_format](findings))
|
|
84
|
+
|
|
85
|
+
return 1 if any(f.level is Level.ERROR for f in findings) else 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
if __name__ == "__main__": # pragma: no cover
|
|
89
|
+
sys.exit(main())
|
dlen/core.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Measuring how long a function or a class is, and deciding whether that is too long.
|
|
2
|
+
|
|
3
|
+
Everything here returns data. Nothing prints, nothing reads argv, nothing keeps state
|
|
4
|
+
between calls — so a second run can never inherit the first one's findings.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import ast
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from enum import Enum
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Level(str, Enum):
|
|
16
|
+
WARNING = "warning"
|
|
17
|
+
ERROR = "error"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Code(str, Enum):
|
|
21
|
+
FUNCTION_TOO_LONG = "DL001"
|
|
22
|
+
CLASS_TOO_LONG = "DL002"
|
|
23
|
+
SYNTAX_ERROR = "DL900"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class Limits:
|
|
28
|
+
"""The three thresholds, defaulting to the ones dlen has used since 2017."""
|
|
29
|
+
|
|
30
|
+
warn_function: int = 12
|
|
31
|
+
max_function: int = 20
|
|
32
|
+
max_class: int = 500
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class Finding:
|
|
37
|
+
path: Path
|
|
38
|
+
line: int
|
|
39
|
+
column: int
|
|
40
|
+
code: Code
|
|
41
|
+
level: Level
|
|
42
|
+
message: str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
Definition = ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef
|
|
46
|
+
Function = ast.FunctionDef | ast.AsyncFunctionDef
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _span(node: Definition) -> int:
|
|
50
|
+
"""Lines the node covers, decorators included — they are part of what you read."""
|
|
51
|
+
start = min([node.lineno, *(d.lineno for d in node.decorator_list)])
|
|
52
|
+
end = node.end_lineno if node.end_lineno is not None else node.lineno
|
|
53
|
+
return end - start + 1
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _finding(node: Definition, path: Path, code: Code, level: Level, text: str) -> Finding:
|
|
57
|
+
return Finding(path, node.lineno, node.col_offset + 1, code, level, text)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _describe(kind: str, name: str, length: int, limit: int, level: Level) -> str:
|
|
61
|
+
threshold = "max" if level is Level.ERROR else "warn"
|
|
62
|
+
return f"{kind} {name!r} is {length} lines ({threshold} {limit})"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _check_function(node: Function, path: Path, limits: Limits) -> Finding | None:
|
|
66
|
+
length = _span(node)
|
|
67
|
+
if length > limits.max_function:
|
|
68
|
+
level, limit = Level.ERROR, limits.max_function
|
|
69
|
+
elif length > limits.warn_function:
|
|
70
|
+
level, limit = Level.WARNING, limits.warn_function
|
|
71
|
+
else:
|
|
72
|
+
return None
|
|
73
|
+
text = _describe("function", node.name, length, limit, level)
|
|
74
|
+
return _finding(node, path, Code.FUNCTION_TOO_LONG, level, text)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _check_class(node: ast.ClassDef, path: Path, limits: Limits) -> Finding | None:
|
|
78
|
+
length = _span(node)
|
|
79
|
+
if length <= limits.max_class:
|
|
80
|
+
return None
|
|
81
|
+
text = _describe("class", node.name, length, limits.max_class, Level.ERROR)
|
|
82
|
+
return _finding(node, path, Code.CLASS_TOO_LONG, Level.ERROR, text)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _syntax_finding(exc: SyntaxError, path: Path) -> Finding:
|
|
86
|
+
line, column = exc.lineno or 1, exc.offset or 1
|
|
87
|
+
message = f"cannot parse: {exc.msg}"
|
|
88
|
+
return Finding(path, line, column, Code.SYNTAX_ERROR, Level.ERROR, message)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def check_source(source: str, path: Path, limits: Limits) -> list[Finding]:
|
|
92
|
+
"""Findings for one piece of source, in the order they appear in the file."""
|
|
93
|
+
try:
|
|
94
|
+
tree = ast.parse(source, filename=str(path))
|
|
95
|
+
except SyntaxError as exc:
|
|
96
|
+
return [_syntax_finding(exc, path)]
|
|
97
|
+
|
|
98
|
+
findings = []
|
|
99
|
+
for node in ast.walk(tree):
|
|
100
|
+
if isinstance(node, ast.ClassDef):
|
|
101
|
+
found = _check_class(node, path, limits)
|
|
102
|
+
elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
|
|
103
|
+
found = _check_function(node, path, limits)
|
|
104
|
+
else:
|
|
105
|
+
continue
|
|
106
|
+
if found is not None:
|
|
107
|
+
findings.append(found)
|
|
108
|
+
|
|
109
|
+
return sorted(findings, key=lambda f: (f.line, f.column))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def check_file(path: Path, limits: Limits) -> list[Finding]:
|
|
113
|
+
"""Findings for one file. An unreadable file is a finding, not a crash."""
|
|
114
|
+
try:
|
|
115
|
+
source = path.read_text(encoding="utf-8")
|
|
116
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
117
|
+
return [Finding(path, 1, 1, Code.SYNTAX_ERROR, Level.ERROR, f"cannot read: {exc}")]
|
|
118
|
+
return check_source(source, path, limits)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def iter_python_files(paths: list[Path]) -> list[Path]:
|
|
122
|
+
"""Every .py under the given paths, deduplicated and in a stable order."""
|
|
123
|
+
found: list[Path] = []
|
|
124
|
+
for path in paths:
|
|
125
|
+
found.extend(sorted(path.rglob("*.py")) if path.is_dir() else [path])
|
|
126
|
+
return list(dict.fromkeys(found))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def check_paths(paths: list[Path], limits: Limits) -> list[Finding]:
|
|
130
|
+
return [finding for path in iter_python_files(paths) for finding in check_file(path, limits)]
|
dlen/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: dlen
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Check how long your functions and classes are
|
|
5
|
+
Project-URL: Homepage, https://github.com/Endika/dlen
|
|
6
|
+
Project-URL: Repository, https://github.com/Endika/dlen
|
|
7
|
+
Project-URL: Issues, https://github.com/Endika/dlen/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/Endika/dlen/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Endika Iglesias <endika2@gmail.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: code-quality,complexity,linter,refactoring,static-analysis
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Environment :: Console
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# dlen
|
|
28
|
+
|
|
29
|
+
Check how long your functions and classes are.
|
|
30
|
+
|
|
31
|
+
A long function is the cheapest smell to detect and the most reliable one to act on.
|
|
32
|
+
`dlen` tells you which ones crossed the line, and where.
|
|
33
|
+
|
|
34
|
+
```console
|
|
35
|
+
$ dlen src/
|
|
36
|
+
src/importer.py:42:1: DL001 function 'process_batch' is 34 lines (max 20)
|
|
37
|
+
src/importer.py:88:5: DL001 function 'validate' is 14 lines (warn 12)
|
|
38
|
+
src/models.py:7:1: DL002 class 'LegacyRecord' is 812 lines (max 500)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```console
|
|
44
|
+
uv tool install dlen # or: pipx install dlen, pip install dlen
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Python 3.10 or newer. No dependencies.
|
|
48
|
+
|
|
49
|
+
## Use
|
|
50
|
+
|
|
51
|
+
```console
|
|
52
|
+
dlen src/ tests/ # files, directories, or both
|
|
53
|
+
dlen . --max-function 30 # your project, your thresholds
|
|
54
|
+
dlen . --output-format=json # for other tools
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
| Flag | Default | Meaning |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `--warn-function N` | 12 | report a function above N lines, without failing |
|
|
60
|
+
| `--max-function N` | 20 | fail on a function above N lines |
|
|
61
|
+
| `--max-class N` | 500 | fail on a class above N lines |
|
|
62
|
+
| `--output-format` | `full` | `full`, `github` or `json` |
|
|
63
|
+
|
|
64
|
+
A function's length includes its decorators — they are part of what you read before
|
|
65
|
+
you understand it.
|
|
66
|
+
|
|
67
|
+
### Exit codes
|
|
68
|
+
|
|
69
|
+
| Code | When |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `0` | nothing found, or only warnings |
|
|
72
|
+
| `1` | something was over a `max`, or a file could not be parsed |
|
|
73
|
+
| `2` | bad arguments |
|
|
74
|
+
|
|
75
|
+
Warnings never fail the build. That is the point of having two thresholds: one to
|
|
76
|
+
nudge, one to stop.
|
|
77
|
+
|
|
78
|
+
### Rules
|
|
79
|
+
|
|
80
|
+
| Code | Rule |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| `DL001` | function is too long |
|
|
83
|
+
| `DL002` | class is too long |
|
|
84
|
+
| `DL900` | file could not be read or parsed |
|
|
85
|
+
|
|
86
|
+
## In CI
|
|
87
|
+
|
|
88
|
+
`--output-format=github` puts each finding on the diff of the pull request instead
|
|
89
|
+
of burying it in a log:
|
|
90
|
+
|
|
91
|
+
```yaml
|
|
92
|
+
- run: uvx dlen src --output-format=github
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## As a library
|
|
96
|
+
|
|
97
|
+
The core returns data and prints nothing, so you can build your own reporting on it:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from pathlib import Path
|
|
101
|
+
from dlen import Limits, check_paths
|
|
102
|
+
|
|
103
|
+
findings = check_paths([Path("src")], Limits(max_function=30))
|
|
104
|
+
for finding in findings:
|
|
105
|
+
print(finding.code, finding.path, finding.line, finding.message)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Every call returns a fresh list. Two runs never see each other's findings.
|
|
109
|
+
|
|
110
|
+
## How it measures
|
|
111
|
+
|
|
112
|
+
`dlen` parses your code with Python's own `ast` module, so it agrees with Python
|
|
113
|
+
about what a function is. It sees `async def`, decorators, nested functions and
|
|
114
|
+
methods, and it is not fooled by the word `def` inside a string or a comment.
|
|
115
|
+
|
|
116
|
+
> Versions before 0.1.0 matched text with regular expressions and had been broken on
|
|
117
|
+
> Python 3 since 2017. 0.1.0 is a rewrite: the counts are now correct rather than
|
|
118
|
+
> compatible, and the output carries file, line and column.
|
|
119
|
+
|
|
120
|
+
## Licence
|
|
121
|
+
|
|
122
|
+
MIT.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
dlen/__init__.py,sha256=3RSReGaLufqvd_kqrOc_59eDXLTVk-O1uE5uHVLkVOc,275
|
|
2
|
+
dlen/cli.py,sha256=SpWR8lbrCO1SwhXTzn0wW-MT6DT49ZkkekeDuX0-6UE,2891
|
|
3
|
+
dlen/core.py,sha256=c4VQjt4zVpmDIKGiIUW-eOyWF0V1x4ZsDjv_K-THgj8,4350
|
|
4
|
+
dlen/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
dlen-0.1.0.dist-info/METADATA,sha256=Fp5YQxsg3kq5Y7SkKGzpLgybOiDIYiAM9XOqy22ZYcQ,3832
|
|
6
|
+
dlen-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
7
|
+
dlen-0.1.0.dist-info/entry_points.txt,sha256=nZ54_Po3rqunCEk8IwyJJdsl0sYzSOMg5inEQMYkFvI,39
|
|
8
|
+
dlen-0.1.0.dist-info/licenses/LICENSE,sha256=kDv_kGy0hM0TIgTJeWx0FzVESJ3AX2StwGMx6QW1hs4,1072
|
|
9
|
+
dlen-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 Endika Iglesias
|
|
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.
|