lint-utils 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.

Potentially problematic release.


This version of lint-utils might be problematic. Click here for more details.

lint_utils/__init__.py ADDED
File without changes
lint_utils/__main__.py ADDED
@@ -0,0 +1,58 @@
1
+ from collections.abc import Sequence
2
+ from pathlib import Path
3
+ import click
4
+
5
+ from lint_utils._cli_commands.check import CheckCommand
6
+ from lint_utils.config import PyProject
7
+ from lint_utils.std import report_info
8
+ from lint_utils.text_styling import pluralize, to_bold, to_green, to_red
9
+ from lint_utils.timer import Timer
10
+
11
+
12
+ @click.group()
13
+ def cli() -> None:
14
+ pass
15
+
16
+
17
+ @cli.command("check")
18
+ @click.argument("args", nargs=-1)
19
+ def check(args: Sequence[str]) -> None:
20
+ pyproject = PyProject.from_toml(Path("pyproject.toml"))
21
+ lint_utils_config = (
22
+ pyproject.tool.lint_utils if pyproject and pyproject.tool else None
23
+ )
24
+
25
+ files_count = 0
26
+ errors_files_count = 0
27
+ not_processed_files: list[str] = []
28
+
29
+ if not args:
30
+ report_info(to_red("Please provide the file or directory name"))
31
+ return
32
+
33
+ with Timer() as timer:
34
+ for arg in args:
35
+ root_path = Path(arg)
36
+ paths = root_path.rglob("*.py") if root_path.is_dir() else (root_path,)
37
+ command = CheckCommand(paths=paths, config=lint_utils_config)
38
+ result = command.execute()
39
+
40
+ not_processed_files.extend(result.not_processed_files)
41
+ files_count += result.files_count
42
+ errors_files_count += result.errors_files_count
43
+
44
+ if errors_files_count > 0:
45
+ files_part = pluralize(errors_files_count, "file")
46
+ msg = to_bold(
47
+ to_red(f"Errors found in {errors_files_count} {files_part} 😱")
48
+ )
49
+ report_info(msg)
50
+ else:
51
+ report_info(to_bold(to_green("No errors found. All is well 🤗")))
52
+
53
+ total_info = f"Processed {files_count} {pluralize(files_count, 'file')} at {timer.total_seconds}"
54
+ report_info(to_bold((total_info)))
55
+
56
+
57
+ if __name__ == "__main__":
58
+ cli()
File without changes
@@ -0,0 +1,52 @@
1
+ from collections.abc import Iterable
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+
5
+ from lint_utils.config import LintUtilsConfig
6
+ from lint_utils.tree_info import get_tree_info
7
+ from lint_utils.visitors.useless_fields import check_useless_field
8
+
9
+
10
+ @dataclass(frozen=True, slots=True, kw_only=True)
11
+ class CheckResult:
12
+ files_count: int
13
+ errors_files_count: int
14
+ not_processed_files: list[str]
15
+
16
+
17
+ class CheckCommand:
18
+ def __init__(
19
+ self,
20
+ paths: Iterable[Path],
21
+ config: LintUtilsConfig | None,
22
+ ) -> None:
23
+ self._paths = paths
24
+ self._config = config
25
+
26
+ def execute(self) -> CheckResult:
27
+ files_count = 0
28
+ errors_files_count = 0
29
+ not_processed_files: list[str] = []
30
+
31
+ for path in self._paths:
32
+ info = get_tree_info(path)
33
+ if info is None:
34
+ not_processed_files.append(path.as_posix())
35
+ continue
36
+
37
+ has_errors = check_useless_field(
38
+ info,
39
+ file_path=path,
40
+ config=self._config,
41
+ )
42
+
43
+ if has_errors:
44
+ errors_files_count += 1
45
+
46
+ files_count += 1
47
+
48
+ return CheckResult(
49
+ files_count=files_count,
50
+ errors_files_count=errors_files_count,
51
+ not_processed_files=not_processed_files,
52
+ )
lint_utils/config.py ADDED
@@ -0,0 +1,44 @@
1
+ from pathlib import Path
2
+ from typing import Self
3
+ import msgspec
4
+
5
+ from lint_utils.std import report_error
6
+
7
+
8
+ class Base(
9
+ msgspec.Struct,
10
+ omit_defaults=True,
11
+ forbid_unknown_fields=False,
12
+ ):
13
+ pass
14
+
15
+
16
+ class LintConfig(Base):
17
+ ignore: list[str] = msgspec.field(default_factory=list)
18
+ exclude_classes: list[str] = msgspec.field(default_factory=list)
19
+ exclude_base_classes: list[str] = msgspec.field(default_factory=list)
20
+
21
+
22
+ class LintUtilsConfig(Base):
23
+ lint: LintConfig = msgspec.field(default_factory=LintConfig)
24
+ exclude: list[str] = msgspec.field(default_factory=list)
25
+
26
+
27
+ class Tool(Base):
28
+ lint_utils: LintUtilsConfig | None = None
29
+
30
+
31
+ class PyProject(Base):
32
+ tool: Tool | None = None
33
+
34
+ @classmethod
35
+ def from_toml(cls, path: Path) -> Self | None:
36
+ try:
37
+ with path.open("r", encoding="UTF-8") as file:
38
+ return msgspec.toml.decode(file.read(), type=PyProject)
39
+ except OSError as exc:
40
+ if isinstance(exc, FileNotFoundError):
41
+ return None
42
+
43
+ msg = f"There was a problem parsing the file pyproject.toml. Error: {repr(exc)}"
44
+ report_error(msg)
lint_utils/py.typed ADDED
File without changes
lint_utils/rules.py ADDED
@@ -0,0 +1,9 @@
1
+ from types import SimpleNamespace
2
+
3
+
4
+ class Rule(SimpleNamespace):
5
+ useless_field = "USL001"
6
+
7
+
8
+ def can_ignore_rule(code_lines: list[str], line: int, rule: str) -> bool:
9
+ return rule in code_lines[line]
lint_utils/std.py ADDED
@@ -0,0 +1,9 @@
1
+ import sys
2
+
3
+
4
+ def report_error(message: str) -> None:
5
+ sys.stderr.write(f"{message}\n")
6
+
7
+
8
+ def report_info(message: str) -> None:
9
+ sys.stdout.write(f"{message}\n")
@@ -0,0 +1,21 @@
1
+ def to_red(text: str) -> str:
2
+ return f"\033[31m{text}\033[0m"
3
+
4
+
5
+ def to_cyan(text: str) -> str:
6
+ return f"\033[36m{text}\033[0m"
7
+
8
+
9
+ def to_green(text: str) -> str:
10
+ return f"\033[32m{text}\033[0m"
11
+
12
+
13
+ def to_bold(text: str) -> str:
14
+ return f"\033[1m{text}\033[0m"
15
+
16
+
17
+ def pluralize(count: int, singular: str, *, plural: str | None = None):
18
+ if count == 1:
19
+ return singular
20
+
21
+ return f"{plural or singular + 's'}"
lint_utils/timer.py ADDED
@@ -0,0 +1,41 @@
1
+ import time
2
+ from types import TracebackType
3
+ from typing import Self
4
+
5
+
6
+ class Timer:
7
+ def __init__(self) -> None:
8
+ self._start_time: float | None = None
9
+ self._finish_time: float | None = None
10
+
11
+ @property
12
+ def elapsed_seconds(self) -> float:
13
+ if self._start_time is None:
14
+ msg = "Timer not started. Call `with Timer() as timer: ...`"
15
+ raise ValueError(msg)
16
+
17
+ if self._finish_time is None:
18
+ msg = "The timer has not finished its work yet"
19
+ raise ValueError(msg)
20
+
21
+ return self._finish_time - self._start_time
22
+
23
+ @property
24
+ def total_seconds(self) -> str:
25
+ elapsed = self.elapsed_seconds
26
+ minutes = int(elapsed // 60)
27
+ seconds = int(elapsed % 60)
28
+ milliseconds = int((elapsed - int(elapsed)) * 10000)
29
+ return f"{minutes}:{seconds:02}:{milliseconds:04}"
30
+
31
+ def __enter__(self) -> Self:
32
+ self._start_time = time.perf_counter()
33
+ return self
34
+
35
+ def __exit__(
36
+ self,
37
+ exc_type: type[BaseException] | None,
38
+ exc_val: BaseException | None,
39
+ exc_tb: TracebackType | None,
40
+ ) -> None:
41
+ self._finish_time = time.perf_counter()
@@ -0,0 +1,17 @@
1
+ from contextlib import suppress
2
+ from pathlib import Path
3
+
4
+ import ast
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True, slots=True, kw_only=True)
9
+ class TreeInfo:
10
+ tree: ast.Module
11
+ raw: str
12
+
13
+
14
+ def get_tree_info(file_path: Path) -> TreeInfo | None:
15
+ with suppress(SyntaxError, OSError, UnicodeDecodeError), file_path.open("r", encoding="UTF-8") as file:
16
+ source = file.read()
17
+ return TreeInfo(tree=ast.parse(source), raw=source)
@@ -0,0 +1,6 @@
1
+ from .useless_fields import UselessFieldVisitor, check_useless_field
2
+
3
+ __all__ = [
4
+ "UselessFieldVisitor",
5
+ "check_useless_field",
6
+ ]
@@ -0,0 +1,21 @@
1
+ import ast
2
+ from typing import Protocol
3
+
4
+ from lint_utils.config import LintUtilsConfig
5
+ from lint_utils.visitors.dto import FileInfoDTO
6
+
7
+
8
+ class HasRuleProtocol(Protocol):
9
+ rule: str
10
+ _config: LintUtilsConfig | None
11
+ _file_info: FileInfoDTO
12
+
13
+
14
+ class BaseVisitor(HasRuleProtocol, ast.NodeVisitor):
15
+ @property
16
+ def can_skip_visitor(self) -> bool:
17
+ if self._config is None:
18
+ return False
19
+
20
+ can_skip = self.rule in self._config.lint.ignore
21
+ return can_skip or self._file_info.path.as_posix() in self._config.exclude
@@ -0,0 +1,8 @@
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+
4
+
5
+ @dataclass(frozen=True, slots=True, kw_only=True)
6
+ class FileInfoDTO:
7
+ source_code_lines: list[str]
8
+ path: Path
@@ -0,0 +1,208 @@
1
+ import ast
2
+ from dataclasses import dataclass
3
+ import itertools
4
+ from pathlib import Path
5
+ from typing import Any, Final, Mapping, TypeAlias
6
+
7
+ from lint_utils.config import LintUtilsConfig
8
+ from lint_utils.rules import Rule, can_ignore_rule
9
+ from lint_utils.std import report_info
10
+ from lint_utils.text_styling import to_bold, to_cyan, to_red
11
+ from lint_utils.tree_info import TreeInfo
12
+ from lint_utils.visitors.base import BaseVisitor
13
+ from lint_utils.visitors.dto import FileInfoDTO
14
+
15
+ FuncDef: TypeAlias = ast.FunctionDef | ast.AsyncFunctionDef
16
+
17
+
18
+ @dataclass(frozen=True, slots=True, kw_only=True)
19
+ class FieldInfo:
20
+ class_name: str
21
+ name: str
22
+ line: int
23
+ col_offset: int
24
+ assigned_to: str | None = None
25
+
26
+
27
+ class UselessFieldVisitor(BaseVisitor):
28
+ rule: Final[str] = Rule.useless_field
29
+
30
+ def __init__(
31
+ self,
32
+ file_info: FileInfoDTO,
33
+ config: LintUtilsConfig | None = None,
34
+ ) -> None:
35
+ super().__init__()
36
+
37
+ self._file_info = file_info
38
+ self._class_name: str | None = None
39
+ self._base_class_names: list[str] | None = None
40
+ self._field_definitions: dict[str, FieldInfo] = {}
41
+ self._config = config
42
+
43
+ @property
44
+ def useless_fields(self) -> Mapping[str, FieldInfo]:
45
+ return self._field_definitions
46
+
47
+ @property
48
+ def class_name(self) -> str:
49
+ if self._class_name:
50
+ return self._class_name
51
+
52
+ raise ValueError
53
+
54
+ def _clear(self) -> None:
55
+ self._class_name = None
56
+ self._base_class_names = None
57
+ self._field_definitions = {}
58
+
59
+ def visit_ClassDef(self, node: ast.ClassDef) -> Any:
60
+ if self.can_skip_visitor:
61
+ return
62
+
63
+ self._class_name = node.name
64
+ self._base_class_names = self._get_parent_class_names(node)
65
+
66
+ if self._is_class_excluded:
67
+ return
68
+
69
+ for item in node.body:
70
+ if not isinstance(item, FuncDef):
71
+ continue
72
+
73
+ if item.name == "__init__":
74
+ self._process_init_assignment(item)
75
+
76
+ self.generic_visit(node)
77
+
78
+ def visit_Attribute(self, node: ast.Attribute) -> Any:
79
+ if isinstance(node.ctx, ast.Load):
80
+ root_node = _find_root_node(node)
81
+ self._field_definitions.pop(self._build_field_key(root_node.attr), None)
82
+
83
+ return self.generic_visit(node)
84
+
85
+ @property
86
+ def _is_class_excluded(self) -> bool:
87
+ if self._config is None or self._config.lint is None:
88
+ return False
89
+
90
+ excluded_classes = self._config.lint.exclude_classes or ()
91
+ excluded_base_classes = self._config.lint.exclude_base_classes or ()
92
+ all_excluded_classes = list(
93
+ itertools.chain(excluded_classes, excluded_base_classes)
94
+ )
95
+
96
+ is_excluded = False
97
+ if self._base_class_names:
98
+ is_excluded = any(
99
+ cls in all_excluded_classes for cls in self._base_class_names
100
+ )
101
+
102
+ return is_excluded or self.class_name in all_excluded_classes
103
+
104
+ def _get_parent_class_names(self, node: ast.ClassDef) -> list[str] | None:
105
+ base_names = []
106
+ for base in node.bases:
107
+ if isinstance(base, ast.Name):
108
+ base_names.append(base.id)
109
+
110
+ return base_names
111
+
112
+ def _process_init_assignment(self, method: FuncDef):
113
+ for item in method.body:
114
+ match item:
115
+ case ast.Assign():
116
+ target = item.targets[0]
117
+ if not isinstance(target, ast.Attribute):
118
+ continue
119
+
120
+ field_info = FieldInfo(
121
+ class_name=self._class_name,
122
+ name=target.attr,
123
+ line=target.lineno,
124
+ col_offset=target.col_offset,
125
+ assigned_to=_get_assigned_to(item),
126
+ )
127
+
128
+ case ast.AnnAssign():
129
+ target = item.target
130
+ if not isinstance(target, ast.Attribute):
131
+ continue
132
+
133
+ field_info = FieldInfo(
134
+ class_name=self._class_name,
135
+ name=target.attr,
136
+ line=target.lineno,
137
+ col_offset=target.col_offset,
138
+ assigned_to=_get_assigned_to(item),
139
+ )
140
+
141
+ case _:
142
+ continue
143
+
144
+ if can_ignore_rule(
145
+ self._file_info.source_code_lines,
146
+ line=field_info.line - 1,
147
+ rule=self.rule,
148
+ ):
149
+ continue
150
+
151
+ self._field_definitions[self._build_field_key(field_info.name)] = field_info
152
+
153
+ def _build_field_key(self, field_name: str) -> str:
154
+ return f"{self._class_name}_{field_name}"
155
+
156
+
157
+ def _get_assigned_to(attr: ast.Assign | ast.AnnAssign) -> str | None:
158
+ if not isinstance(attr.value, ast.Name):
159
+ return
160
+
161
+ return attr.value.id
162
+
163
+
164
+ def _find_root_node(node: ast.Attribute) -> ast.Attribute:
165
+ if isinstance(node.value, ast.Attribute):
166
+ return _find_root_node(node.value)
167
+
168
+ return node
169
+
170
+
171
+ def check_useless_field(
172
+ info: TreeInfo,
173
+ *,
174
+ file_path: Path,
175
+ config: LintUtilsConfig | None = None,
176
+ ) -> bool:
177
+ has_errors = []
178
+ for module in ast.walk(info.tree):
179
+ if isinstance(module, ast.Module):
180
+ for item in module.body:
181
+ if not isinstance(item, ast.ClassDef):
182
+ continue
183
+
184
+ visitor = UselessFieldVisitor(
185
+ file_info=FileInfoDTO(
186
+ source_code_lines=info.raw.split("\n"),
187
+ path=file_path,
188
+ ),
189
+ config=config,
190
+ )
191
+ visitor.visit(item)
192
+
193
+ if visitor.useless_fields:
194
+ msg = f"{to_bold(to_cyan(visitor.rule))} Unused object class fields found in class {to_bold(visitor.class_name)}"
195
+ report_info(msg)
196
+ for field_info in visitor.useless_fields.values():
197
+ full_path = f"{file_path.as_posix()}:{field_info.line}:{field_info.col_offset + 1}"
198
+ line_msg = (
199
+ f"{full_path} {to_bold(to_red(f'self.{field_info.name}'))}"
200
+ )
201
+ report_info(line_msg)
202
+ report_info("")
203
+
204
+ has_errors.append(True)
205
+
206
+ has_errors.append(False)
207
+
208
+ return any(has_errors)
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: lint-utils
3
+ Version: 0.1.0
4
+ License-File: LICENSE
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: click>=8.1.8
7
+ Requires-Dist: msgspec>=0.19.0
8
+ Requires-Dist: toml>=0.10.2
@@ -0,0 +1,20 @@
1
+ lint_utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ lint_utils/__main__.py,sha256=wMql3MQ_UvefoaT007NV2emhggQa_tmh5UH6F5_5Zgk,1834
3
+ lint_utils/config.py,sha256=3TTGXSEwMG3yHsA4fwCkbBHsWF15haYZs9-wrjY0fmM,1205
4
+ lint_utils/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ lint_utils/rules.py,sha256=0aX6aW0MDh63LrF-3KNMbT_ercrZHgq9pSRfxXF0ZfM,215
6
+ lint_utils/std.py,sha256=VQfxV4kJY0DW09ARo5XzcMrqAxsaSNmC_hlOVS_woyA,177
7
+ lint_utils/text_styling.py,sha256=wcs5gfty9DGxyLzTLt_gjl7gSgTuedivdrDZ0o4KcKM,453
8
+ lint_utils/timer.py,sha256=-msf_XgeGuKqeGQNboYG0K7hc8k6I9Img5hRfEumILA,1237
9
+ lint_utils/tree_info.py,sha256=8mykv7OsWkTvp1z2FqBRbqfJcr2etvryzDOCqqYdz6o,476
10
+ lint_utils/_cli_commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ lint_utils/_cli_commands/check.py,sha256=x2fkC3l_3LopVmTmyTAAlCvnxHdYkl-ks1li7iPPw10,1417
12
+ lint_utils/visitors/__init__.py,sha256=RY4Q3kDs0m7yj49suRVBwOjt6ZNheeDDc7cl2_o9MEQ,144
13
+ lint_utils/visitors/base.py,sha256=c4UxH9g8xNjulLQiqflH-yMnYuCZZtvEo_A6GwmFMs4,576
14
+ lint_utils/visitors/dto.py,sha256=2RpqWxQ5F8tusLTPOzf7gX2kc1eHh8OVikCgtjH5CDg,186
15
+ lint_utils/visitors/useless_fields.py,sha256=NGaXxiL8JuWxZBkxbCxg2OLSld_x86CLcHRZJj91rg8,6737
16
+ lint_utils-0.1.0.dist-info/METADATA,sha256=0JaGAEcZ_T-F_c5BHskCNob-8yUxIVhCvGv160obEPk,187
17
+ lint_utils-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
18
+ lint_utils-0.1.0.dist-info/entry_points.txt,sha256=YF7POdaUpTvidBRTm7VwI7VNgCIsNvl0EfdqFE8l1wM,55
19
+ lint_utils-0.1.0.dist-info/licenses/LICENSE,sha256=GJhW6T2ocUlP45LFYs3gbnzxlLs0ialnwbceFPjva1E,1089
20
+ lint_utils-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ lint-utils = lint_utils.__main__:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 barbarrista
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.