basstler-rules 4.2.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.
Files changed (40) hide show
  1. basstler/code_modification/__init__.py +7 -0
  2. basstler/code_modification/actions.py +171 -0
  3. basstler/code_modification/exceptions.py +127 -0
  4. basstler/code_modification/file_actions.py +141 -0
  5. basstler/code_modification/module_relocation.py +256 -0
  6. basstler/code_modification/patterns.py +86 -0
  7. basstler/code_modification/positions.py +39 -0
  8. basstler/code_modification/references.py +45 -0
  9. basstler/code_modification/source_file.py +27 -0
  10. basstler/code_modification/source_tree.py +107 -0
  11. basstler/code_modification/specification.py +41 -0
  12. basstler/code_modification/syntax.py +209 -0
  13. basstler/code_rules/__init__.py +4 -0
  14. basstler/code_rules/address_building.py +94 -0
  15. basstler/code_rules/bash_by_name.py +103 -0
  16. basstler/code_rules/checker.py +163 -0
  17. basstler/code_rules/command_line.py +165 -0
  18. basstler/code_rules/commands.py +47 -0
  19. basstler/code_rules/docstring_presence.py +255 -0
  20. basstler/code_rules/exceptions.py +34 -0
  21. basstler/code_rules/fixes.py +307 -0
  22. basstler/code_rules/instructions.py +80 -0
  23. basstler/code_rules/locale_encoding.py +315 -0
  24. basstler/code_rules/package_boundaries.py +344 -0
  25. basstler/code_rules/prose_length.py +220 -0
  26. basstler/code_rules/rule.py +158 -0
  27. basstler/code_rules/rule_module.py +84 -0
  28. basstler/code_rules/rules/__init__.py +3 -0
  29. basstler/code_rules/rules/code_quality.py +848 -0
  30. basstler/code_rules/rules/project.py +171 -0
  31. basstler/code_rules/subprocess_function.py +26 -0
  32. basstler/code_rules/syntax_tree_checker.py +38 -0
  33. basstler/code_rules/text_file_usage.py +146 -0
  34. basstler/code_rules/tree_removal.py +64 -0
  35. basstler/templates/agents.md.jinja +16 -0
  36. basstler_rules-4.2.0.dist-info/METADATA +15 -0
  37. basstler_rules-4.2.0.dist-info/RECORD +40 -0
  38. basstler_rules-4.2.0.dist-info/WHEEL +4 -0
  39. basstler_rules-4.2.0.dist-info/licenses/LICENSE +202 -0
  40. basstler_rules-4.2.0.dist-info/licenses/NOTICE +13 -0
@@ -0,0 +1,103 @@
1
+ """
2
+ Finds commands that start bash by its name instead of through
3
+ :class:`basstler.bash.Bash`.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Iterator
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import override
12
+
13
+ import libcst
14
+ from libcst import matchers
15
+
16
+ from basstler.bash import Bash, LocatedProgram
17
+ from basstler.class_property import classproperty
18
+ from basstler.code_modification.patterns import CodePattern
19
+ from basstler.code_modification.positions import PositionedModule
20
+ from basstler.code_modification.syntax import ExpressionSyntax
21
+ from basstler.code_rules.checker import CodeRuleViolation
22
+ from basstler.code_rules.subprocess_function import SubprocessFunction
23
+ from basstler.code_rules.syntax_tree_checker import SyntaxTreeChecker
24
+
25
+ # %% the patterns
26
+
27
+
28
+ class BashCommandLine(CodePattern):
29
+ """
30
+ A list or tuple whose first element is the bare name of bash.
31
+ """
32
+
33
+ @classproperty
34
+ def matcher(cls) -> matchers.OneOf:
35
+ bash_first = [
36
+ matchers.Element(
37
+ value=matchers.MatchIfTrue(
38
+ lambda value: (
39
+ ExpressionSyntax(value).literal_text == LocatedProgram.BASH
40
+ )
41
+ )
42
+ ),
43
+ matchers.ZeroOrMore(),
44
+ ]
45
+ return matchers.OneOf(
46
+ matchers.List(elements=bash_first), matchers.Tuple(elements=bash_first)
47
+ )
48
+
49
+
50
+ class BashStarted(CodePattern):
51
+ """
52
+ A call to a :mod:`subprocess` function, or a return, that hands on a command line
53
+ starting bash by its name; the command line is saved as :attr:`saved_command_name`.
54
+ """
55
+
56
+ @classproperty
57
+ def saved_command_name(cls) -> str:
58
+ """
59
+ The name the command line is saved under when the pattern matches.
60
+ """
61
+ return "command"
62
+
63
+ @classproperty
64
+ def matcher(cls) -> matchers.OneOf:
65
+ command = matchers.SaveMatchedNode(
66
+ BashCommandLine.matcher, cls.saved_command_name
67
+ )
68
+ return matchers.OneOf(
69
+ matchers.Return(value=command),
70
+ matchers.Call(
71
+ func=SubprocessFunction.matcher,
72
+ args=[matchers.Arg(value=command), matchers.ZeroOrMore()],
73
+ ),
74
+ )
75
+
76
+
77
+ # %% the check
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class BashByNameChecker(SyntaxTreeChecker):
82
+ """
83
+ Finds command lines whose program is bash given by its name, which Windows resolves
84
+ to WSL's launcher: those passed to a :mod:`subprocess` function, and those returned.
85
+ """
86
+
87
+ @override
88
+ def violations_of_module(
89
+ self, path: Path, module: PositionedModule
90
+ ) -> Iterator[CodeRuleViolation]:
91
+ for occurrence in BashStarted.found_in(module):
92
+ command = BashStarted.captures(occurrence.node, module.metadata)[
93
+ BashStarted.saved_command_name
94
+ ]
95
+ location = module.positions[libcst.ensure_type(command, libcst.CSTNode)]
96
+ yield CodeRuleViolation(
97
+ path,
98
+ location.start.line,
99
+ location.end.line,
100
+ f"starts {LocatedProgram.BASH} by its name, which Windows resolves to "
101
+ f"WSL's launcher; build the command with {Bash.__name__}.locate(...)"
102
+ f".{Bash.command.__name__}(...)",
103
+ )
@@ -0,0 +1,163 @@
1
+ """
2
+ The base every code rule checker extends, and the violations checkers report.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from abc import ABC, abstractmethod
9
+ from collections.abc import Iterator, Sequence
10
+ from dataclasses import dataclass
11
+ from functools import cached_property
12
+ from pathlib import Path
13
+
14
+ from basstler.git.commands import GitCommandRunner
15
+
16
+ # %% violations
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class CodeRuleViolation:
21
+ """
22
+ One place in a source file that breaks a rule.
23
+ """
24
+
25
+ path: Path
26
+ """
27
+ The file breaking the rule.
28
+ """
29
+
30
+ first_line: int
31
+ """
32
+ The first line of the offending code, counting from one.
33
+ """
34
+
35
+ last_line: int
36
+ """
37
+ The last line of the offending code, counting from one.
38
+ """
39
+
40
+ description: str
41
+ """
42
+ What is wrong and how to fix it, as one sentence fragment.
43
+ """
44
+
45
+ def touches(self, lines: set[int]) -> bool:
46
+ """
47
+ :param lines: Line numbers in the file.
48
+ :return: Whether any of them falls within the offending code.
49
+ """
50
+ return any(self.first_line <= line <= self.last_line for line in lines)
51
+
52
+ def render(self) -> str:
53
+ """
54
+ :return: The violation as it is printed.
55
+ """
56
+ return f"{self.path}:{self.first_line}: {self.description}"
57
+
58
+
59
+ # %% checkers
60
+
61
+
62
+ class CodeRuleChecker(ABC):
63
+ """
64
+ Finds the code that breaks one agent rule, the rule that names this checker.
65
+ """
66
+
67
+ @abstractmethod
68
+ def violations(self, path: Path) -> Iterator[CodeRuleViolation]:
69
+ """
70
+ :param path: A Python source file.
71
+ :return: Every place in it that breaks the rule.
72
+ """
73
+
74
+
75
+ # %% the staged change
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class StagedLines:
80
+ """
81
+ The lines a commit being prepared adds or changes.
82
+ """
83
+
84
+ git: GitCommandRunner
85
+ """
86
+ The repository the commit is prepared in.
87
+ """
88
+
89
+ def of(self, path: Path) -> set[int]:
90
+ """
91
+ :param path: A file in the repository.
92
+ :return: The line numbers, in the staged file, that the staged change adds or
93
+ changes; none for a file the change only moves.
94
+ """
95
+ return self.lines_by_file.get(path.resolve(), set())
96
+
97
+ @cached_property
98
+ def lines_by_file(self) -> dict[Path, set[int]]:
99
+ """
100
+ :return: The lines the staged change adds or changes, by the staged file they
101
+ are in, with moves detected so a moved file keeps its committed lines.
102
+ """
103
+ diff = self.git.run(
104
+ "diff",
105
+ "--cached",
106
+ "--find-renames",
107
+ "--unified=0",
108
+ "--no-color",
109
+ "--relative",
110
+ )
111
+ lines_by_file: dict[Path, set[int]] = {}
112
+ lines: set[int] = set()
113
+ for match in re.finditer(
114
+ r"^diff --git a/.+ b/(.+)$|^@@ -\S+ \+(\d+)(?:,(\d+))? @@",
115
+ diff,
116
+ re.MULTILINE,
117
+ ):
118
+ if match[1] is not None:
119
+ lines = lines_by_file.setdefault(
120
+ (self.git.working_directory / match[1]).resolve(), set()
121
+ )
122
+ continue
123
+ start = int(match[2])
124
+ count = 1 if match[3] is None else int(match[3])
125
+ lines.update(range(start, start + count))
126
+ return lines_by_file
127
+
128
+
129
+ # %% checking files
130
+
131
+
132
+ @dataclass(frozen=True)
133
+ class CodeRulesCheck:
134
+ """
135
+ Runs a set of checkers over a set of files.
136
+ """
137
+
138
+ checkers: tuple[CodeRuleChecker, ...]
139
+ """
140
+ The checkers to run.
141
+ """
142
+
143
+ staged: StagedLines | None = None
144
+ """
145
+ The staged change whose code alone is checked, ``None`` to check all of it.
146
+ """
147
+
148
+ def violations(self, paths: Sequence[Path]) -> list[CodeRuleViolation]:
149
+ """
150
+ :param paths: The Python files to check.
151
+ :return: Their violations, file by file, top to bottom.
152
+ """
153
+ violations: list[CodeRuleViolation] = []
154
+ for path in paths:
155
+ changed = None if self.staged is None else self.staged.of(path)
156
+ found = [
157
+ violation
158
+ for checker in self.checkers
159
+ for violation in checker.violations(path)
160
+ if changed is None or violation.touches(changed)
161
+ ]
162
+ violations.extend(sorted(found, key=lambda violation: violation.first_line))
163
+ return violations
@@ -0,0 +1,165 @@
1
+ """
2
+ The ``basstler code-rules`` commands: checking code against the rules, fixing it, and
3
+ generating ``AGENTS.md`` from them.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ from cyclopts import App
11
+
12
+ from basstler.code_modification.source_file import PythonSourceFile
13
+ from basstler.code_rules import rules
14
+ from basstler.code_rules.checker import CodeRulesCheck, StagedLines
15
+ from basstler.code_rules.commands import CodeRulesCommand
16
+ from basstler.code_rules.fixes import SourceFixer
17
+ from basstler.code_rules.instructions import AgentsInstructions
18
+ from basstler.code_rules.package_boundaries import (
19
+ PackageAtCommit,
20
+ PackageBoundaryChecker,
21
+ )
22
+ from basstler.code_rules.rule_module import RuleModule
23
+ from basstler.exit_codes import ExitCode
24
+ from basstler.git.commands import GitCommandRunner
25
+ from basstler.locations import ProjectLocation
26
+ from basstler.standard_streams import StandardStreamHandler
27
+
28
+ logger = StandardStreamHandler.logger_for(__name__)
29
+ """
30
+ This module's logger, which is also what its commands print through.
31
+ """
32
+
33
+
34
+ class CodeRulesExitCode(ExitCode):
35
+ """
36
+ What a ``basstler code-rules`` command's exit status tells pre-commit.
37
+ """
38
+
39
+ SUCCESS = 0
40
+ """
41
+ Nothing had to change.
42
+ """
43
+
44
+ CHANGES_NEEDED = 1
45
+ """
46
+ Code breaks a rule, a boundary crossing is new, or ``AGENTS.md`` was rewritten or
47
+ is out of date.
48
+ """
49
+
50
+
51
+ code_rules_app = App(
52
+ name=CodeRulesCommand.GROUP,
53
+ help=(
54
+ "Check code against the repository's rules, fix it, and generate AGENTS.md "
55
+ "from them."
56
+ ),
57
+ )
58
+ """
59
+ The ``code-rules`` command group.
60
+ """
61
+
62
+
63
+ @code_rules_app.command(name=CodeRulesCommand.CHECK)
64
+ def check(
65
+ paths: list[Path] | None = None, *, all_lines: bool = False
66
+ ) -> CodeRulesExitCode:
67
+ """
68
+ Report the code in *paths* that breaks a rule a checker enforces.
69
+
70
+ :param paths: The Python files to check.
71
+ :param all_lines: Check every line, not only those the staged change touches.
72
+ """
73
+ code_rules_check = CodeRulesCheck(
74
+ RuleModule(rules).checkers,
75
+ None if all_lines else StagedLines(GitCommandRunner(Path.cwd())),
76
+ )
77
+ violations = code_rules_check.violations(paths or [])
78
+ for violation in violations:
79
+ logger.error(violation.render())
80
+ if violations:
81
+ return CodeRulesExitCode.CHANGES_NEEDED
82
+ return CodeRulesExitCode.SUCCESS
83
+
84
+
85
+ @code_rules_app.command(name=CodeRulesCommand.FIX)
86
+ def fix(paths: list[Path] | None = None) -> CodeRulesExitCode:
87
+ """
88
+ Rewrite each file in *paths* that breaks a rule with a fix, applying the fix to
89
+ every place that breaks it; a file is written only once every file is fixed.
90
+
91
+ :param paths: The Python files to fix.
92
+ """
93
+ fixer = SourceFixer(RuleModule(rules).fixable_checkers)
94
+ fixed_sources = {
95
+ source_file: fixer.fix_module(source_file).result.code
96
+ for source_file in map(PythonSourceFile, paths or [])
97
+ }
98
+ changed = {
99
+ source_file: source
100
+ for source_file, source in fixed_sources.items()
101
+ if source != source_file.read()
102
+ }
103
+ for source_file, source in changed.items():
104
+ source_file.write(source)
105
+ logger.info("Fixed %s", source_file.path)
106
+ if changed:
107
+ return CodeRulesExitCode.CHANGES_NEEDED
108
+ return CodeRulesExitCode.SUCCESS
109
+
110
+
111
+ @code_rules_app.command(name=CodeRulesCommand.NEW_CROSSINGS)
112
+ def report_new_crossings(base_commit: str) -> CodeRulesExitCode:
113
+ """
114
+ Report each boundary crossing of the package that *base_commit* does not have.
115
+
116
+ The base is read under the package map its own distributions declare, so a
117
+ crossing only a change of a distribution's metadata creates is new as well; a module
118
+ moved since keeps the base's crossings.
119
+
120
+ :param base_commit: The commit the checked out package is compared with.
121
+ """
122
+ git = GitCommandRunner(Path.cwd())
123
+ checker = PackageBoundaryChecker()
124
+ with PackageAtCommit(git, base_commit, checker.workspace.root) as base_checker:
125
+ if base_checker is None:
126
+ logger.info(
127
+ "%s holds no workspace of distributions, so nothing is compared",
128
+ base_commit,
129
+ )
130
+ return CodeRulesExitCode.SUCCESS
131
+ base_crossings = base_checker.package_crossings()
132
+ renames = checker.module_renames(git, base_commit)
133
+ added = checker.package_crossings().added_since(base_crossings.renamed(renames))
134
+ for crossing in added:
135
+ logger.error(
136
+ "basstler.%s newly imports basstler.%s across a distribution boundary; "
137
+ "move the code or the import",
138
+ crossing.importing_module,
139
+ crossing.imported_module,
140
+ )
141
+ if added:
142
+ return CodeRulesExitCode.CHANGES_NEEDED
143
+ return CodeRulesExitCode.SUCCESS
144
+
145
+
146
+ @code_rules_app.command(name=CodeRulesCommand.AGENTS_MD)
147
+ def generate_agents_instructions(*, verify: bool = False) -> CodeRulesExitCode:
148
+ """
149
+ Write the current directory's ``AGENTS.md`` from the rules.
150
+
151
+ :param verify: Only report whether the file is current, writing nothing.
152
+ """
153
+ instructions = AgentsInstructions.of_repository(Path.cwd())
154
+ if instructions.is_current():
155
+ return CodeRulesExitCode.SUCCESS
156
+ if verify:
157
+ logger.error(
158
+ "%s is out of date; run `%s`.",
159
+ ProjectLocation.AGENTS_INSTRUCTIONS,
160
+ CodeRulesCommand.AGENTS_MD.invocation,
161
+ )
162
+ return CodeRulesExitCode.CHANGES_NEEDED
163
+ instructions.write()
164
+ logger.info("Wrote %s", ProjectLocation.AGENTS_INSTRUCTIONS)
165
+ return CodeRulesExitCode.CHANGES_NEEDED
@@ -0,0 +1,47 @@
1
+ """
2
+ The names of the ``basstler code-rules`` commands.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from enum import StrEnum
8
+
9
+ from basstler.locations import PackageLocation
10
+
11
+
12
+ class CodeRulesCommand(StrEnum):
13
+ """
14
+ The ``basstler code-rules`` command group and its commands, by name.
15
+ """
16
+
17
+ GROUP = "code-rules"
18
+ """
19
+ The command group itself.
20
+ """
21
+
22
+ CHECK = "check"
23
+ """
24
+ Report the code that breaks a rule a checker enforces.
25
+ """
26
+
27
+ FIX = "fix"
28
+ """
29
+ Apply the fix of every rule that has one.
30
+ """
31
+
32
+ NEW_CROSSINGS = "new-crossings"
33
+ """
34
+ Report the boundary crossings a base commit does not have.
35
+ """
36
+
37
+ AGENTS_MD = "agents-md"
38
+ """
39
+ Generate the repository's ``AGENTS.md`` from its rules.
40
+ """
41
+
42
+ @property
43
+ def invocation(self) -> str:
44
+ """
45
+ The command line running this command.
46
+ """
47
+ return f"{PackageLocation.DIRECTORY.name} {CodeRulesCommand.GROUP} {self}"