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,315 @@
1
+ """
2
+ Finds text read or written in the locale encoding, which on Windows is a code page that
3
+ cannot encode most of Unicode, and fixes it to UTF-8.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Iterator
9
+ from dataclasses import dataclass
10
+ from enum import StrEnum
11
+ from typing import override
12
+
13
+ import libcst
14
+ from libcst import matchers
15
+
16
+ from basstler.class_property import classproperty
17
+ from basstler.code_modification.positions import PositionedModule
18
+ from basstler.code_modification.patterns import CodePattern
19
+ from basstler.code_modification.syntax import ConstantName, ExpressionSyntax
20
+ from basstler.code_rules.fixes import (
21
+ BehaviourDeclaration,
22
+ BehaviourEffect,
23
+ CallLackingKeywordArgument,
24
+ CodeFix,
25
+ FixableChecker,
26
+ KeywordArgumentFix,
27
+ )
28
+ from basstler.code_rules.subprocess_function import SubprocessFunction
29
+ from basstler.text_file import UTF_8
30
+
31
+ # %% what reads and writes text
32
+
33
+
34
+ class TextFunction(StrEnum):
35
+ """
36
+ The functions and methods that read or write text in the locale encoding unless
37
+ given one.
38
+ """
39
+
40
+ READ_TEXT = "read_text"
41
+ """
42
+ :meth:`pathlib.Path.read_text`.
43
+ """
44
+
45
+ WRITE_TEXT = "write_text"
46
+ """
47
+ :meth:`pathlib.Path.write_text`.
48
+ """
49
+
50
+ OPEN = "open"
51
+ """
52
+ :func:`open` and :meth:`pathlib.Path.open`, unless they open the file in binary
53
+ mode.
54
+ """
55
+
56
+
57
+ class TextKeyword(StrEnum):
58
+ """
59
+ The keyword arguments that decide how a call reads and writes text.
60
+ """
61
+
62
+ ENCODING = "encoding"
63
+ """
64
+ The encoding text is read and written in.
65
+ """
66
+
67
+ MODE = "mode"
68
+ """
69
+ The mode :data:`TextFunction.OPEN` opens a file in.
70
+ """
71
+
72
+ TEXT = "text"
73
+ """
74
+ The :mod:`subprocess` switch decoding output in the locale encoding.
75
+ """
76
+
77
+
78
+ BINARY_MODE = "b"
79
+ """
80
+ The letter in a file mode that opens the file for bytes rather than text.
81
+ """
82
+
83
+
84
+ # %% the fix
85
+
86
+
87
+ class UTF8EncodingFix(KeywordArgumentFix):
88
+ """
89
+ Names UTF-8 as the encoding, in place of the :mod:`subprocess` text switch where the
90
+ call has one.
91
+ """
92
+
93
+ @classproperty
94
+ def behaviour(cls) -> BehaviourDeclaration:
95
+ return BehaviourDeclaration(
96
+ BehaviourEffect.CHANGED,
97
+ "Text is read and written as UTF-8 instead of in the locale encoding; "
98
+ "nothing changes where the locale encoding is UTF-8.",
99
+ )
100
+
101
+ @classproperty
102
+ def keyword(cls) -> str:
103
+ return TextKeyword.ENCODING
104
+
105
+ @classproperty
106
+ def value(cls) -> libcst.BaseExpression:
107
+ return libcst.SimpleString(f'"{UTF_8}"')
108
+
109
+
110
+ # %% the patterns
111
+
112
+
113
+ class NonEncodingArgument(CodePattern):
114
+ """
115
+ An argument that is not the encoding.
116
+ """
117
+
118
+ @classproperty
119
+ def matcher(cls) -> matchers.Arg:
120
+ return matchers.Arg(
121
+ keyword=matchers.DoesNotMatch(matchers.Name(TextKeyword.ENCODING))
122
+ )
123
+
124
+
125
+ class ConstantPositionalArgument(CodePattern):
126
+ """
127
+ A positional argument given a constant, as :meth:`pathlib.Path.open` is.
128
+ """
129
+
130
+ @classproperty
131
+ def matcher(cls) -> matchers.Arg:
132
+ return matchers.Arg(
133
+ keyword=None,
134
+ star="",
135
+ value=matchers.MatchIfTrue(
136
+ lambda value: ExpressionSyntax(value).is_constant
137
+ ),
138
+ )
139
+
140
+
141
+ class SubprocessTextSwitch(CodePattern):
142
+ """
143
+ A call of a :mod:`subprocess` function that decodes its output in the locale
144
+ encoding; the ``text=True`` argument is saved as :attr:`saved_switch_name`.
145
+ """
146
+
147
+ @classproperty
148
+ def saved_switch_name(cls) -> str:
149
+ """
150
+ The name the ``text=True`` argument is saved under when the pattern matches.
151
+ """
152
+ return "switch"
153
+
154
+ @classproperty
155
+ def matcher(cls) -> matchers.Call:
156
+ others = matchers.ZeroOrMore(NonEncodingArgument.matcher)
157
+ switch = matchers.Arg(
158
+ keyword=matchers.Name(TextKeyword.TEXT),
159
+ value=matchers.Name(ConstantName.TRUE),
160
+ )
161
+ return matchers.Call(
162
+ func=SubprocessFunction.matcher,
163
+ args=[
164
+ others,
165
+ matchers.SaveMatchedNode(switch, cls.saved_switch_name),
166
+ others,
167
+ ],
168
+ )
169
+
170
+
171
+ class BinaryModeArgument(CodePattern):
172
+ """
173
+ An argument that names a binary mode.
174
+ """
175
+
176
+ @classproperty
177
+ def matcher(cls) -> matchers.Arg:
178
+ return matchers.Arg(
179
+ value=matchers.MatchIfTrue(
180
+ lambda value: (
181
+ BINARY_MODE in (ExpressionSyntax(value).literal_text or "")
182
+ )
183
+ )
184
+ )
185
+
186
+
187
+ class BinaryOpen(CodePattern):
188
+ """
189
+ A call of :func:`open` or :meth:`pathlib.Path.open` that names a binary mode: by
190
+ keyword, as the second argument of the function or the first of the method.
191
+ """
192
+
193
+ @classproperty
194
+ def matcher(cls) -> matchers.OneOf:
195
+ binary = BinaryModeArgument.matcher
196
+ by_keyword = matchers.Arg(
197
+ keyword=matchers.Name(TextKeyword.MODE), value=binary.value
198
+ )
199
+ function = matchers.Name(TextFunction.OPEN)
200
+ method = matchers.Attribute(attr=matchers.Name(TextFunction.OPEN))
201
+ return matchers.OneOf(
202
+ matchers.Call(
203
+ func=matchers.OneOf(function, method),
204
+ args=[matchers.ZeroOrMore(), by_keyword, matchers.ZeroOrMore()],
205
+ ),
206
+ matchers.Call(
207
+ func=function,
208
+ args=[matchers.Arg(keyword=None), binary, matchers.ZeroOrMore()],
209
+ ),
210
+ matchers.Call(func=method, args=[binary, matchers.ZeroOrMore()]),
211
+ )
212
+
213
+
214
+ class FileOpen(CodePattern):
215
+ """
216
+ A call of :func:`open`, or of a method named so that is given nothing but constants
217
+ as :meth:`pathlib.Path.open` is, unlike an opener handed a request; unless it names
218
+ its encoding.
219
+ """
220
+
221
+ @classproperty
222
+ def matcher(cls) -> matchers.OneOf:
223
+ keyword = matchers.Arg(
224
+ keyword=matchers.AllOf(
225
+ matchers.Name(),
226
+ matchers.DoesNotMatch(matchers.Name(TextKeyword.ENCODING)),
227
+ )
228
+ )
229
+ unpacked_keywords = matchers.Arg(keyword=None, star="**")
230
+ return matchers.OneOf(
231
+ matchers.Call(
232
+ func=matchers.Name(TextFunction.OPEN),
233
+ args=[matchers.ZeroOrMore(NonEncodingArgument.matcher)],
234
+ ),
235
+ matchers.Call(
236
+ func=matchers.Attribute(attr=matchers.Name(TextFunction.OPEN)),
237
+ args=[
238
+ matchers.ZeroOrMore(
239
+ matchers.OneOf(
240
+ keyword,
241
+ ConstantPositionalArgument.matcher,
242
+ unpacked_keywords,
243
+ )
244
+ )
245
+ ],
246
+ ),
247
+ )
248
+
249
+
250
+ class PathReadOrWrite(CodePattern):
251
+ """
252
+ A call of ``read_text`` or ``write_text`` that names no encoding.
253
+ """
254
+
255
+ @classproperty
256
+ def matcher(cls) -> matchers.Call:
257
+ text_function = matchers.OneOf(
258
+ matchers.Name(TextFunction.READ_TEXT),
259
+ matchers.Name(TextFunction.WRITE_TEXT),
260
+ )
261
+ return matchers.Call(
262
+ func=matchers.OneOf(text_function, matchers.Attribute(attr=text_function)),
263
+ args=[matchers.ZeroOrMore(NonEncodingArgument.matcher)],
264
+ )
265
+
266
+
267
+ class LocaleTextCall(CodePattern):
268
+ """
269
+ A call that reads or writes text without naming its encoding.
270
+ """
271
+
272
+ @classproperty
273
+ def matcher(cls) -> matchers.OneOf:
274
+ return matchers.OneOf(
275
+ SubprocessTextSwitch.matcher,
276
+ FileOpen.matcher,
277
+ PathReadOrWrite.matcher,
278
+ )
279
+
280
+
281
+ # %% the check
282
+
283
+
284
+ @dataclass(frozen=True)
285
+ class LocaleEncodingChecker(FixableChecker[CallLackingKeywordArgument]):
286
+ """
287
+ Finds calls reading or writing text without naming its encoding: file reads and
288
+ writes, files opened in text mode, and :mod:`subprocess` calls decoding their output.
289
+ """
290
+
291
+ @classproperty
292
+ def fix(cls) -> CodeFix[CallLackingKeywordArgument]:
293
+ return UTF8EncodingFix()
294
+
295
+ @classproperty
296
+ def violation_description(cls) -> str:
297
+ return (
298
+ "reads or writes text in the locale encoding, which on Windows cannot "
299
+ f'encode most of Unicode; pass {TextKeyword.ENCODING}="{UTF_8}"'
300
+ )
301
+
302
+ @override
303
+ def specifications_of_module(
304
+ self, module: PositionedModule
305
+ ) -> Iterator[CallLackingKeywordArgument]:
306
+ for occurrence in LocaleTextCall.found_in(module):
307
+ call = libcst.ensure_type(occurrence.node, libcst.Call)
308
+ if BinaryOpen.matches(call, module.metadata):
309
+ continue
310
+ captured = LocaleTextCall.captures(call, module.metadata)
311
+ yield CallLackingKeywordArgument(
312
+ occurrence.location,
313
+ call,
314
+ captured.get(SubprocessTextSwitch.saved_switch_name),
315
+ )
@@ -0,0 +1,344 @@
1
+ """
2
+ Finds imports that cross from one distribution into another it does not list.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import tempfile
8
+ from collections.abc import Iterator, Mapping
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from types import TracebackType
12
+
13
+ import libcst
14
+ from libcst.helpers import get_full_name_for_node
15
+ from libcst.metadata import CodeRange
16
+
17
+ from basstler.code_modification.positions import PositionedModule
18
+ from basstler.code_modification.source_file import PythonSourceFile
19
+ from basstler.code_rules.checker import CodeRuleChecker, CodeRuleViolation
20
+ from basstler.directory_tree import DirectoryTree
21
+ from basstler.git.commands import GitCommandRunner
22
+ from basstler.locations import PackageLocation, WorkspaceLocation
23
+ from basstler.package_map import Workspace
24
+
25
+ # %% imports
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ModuleImport:
30
+ """
31
+ One module of the package that an import statement imports, with the statement.
32
+ """
33
+
34
+ imported_module: str
35
+ """
36
+ The dotted name, within ``basstler``, of the module imported.
37
+ """
38
+
39
+ location: CodeRange
40
+ """
41
+ Where the import statement lies in the source.
42
+ """
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class BoundaryCrossing:
47
+ """
48
+ A module importing a module of a distribution its own distribution does not list.
49
+ """
50
+
51
+ importing_module: str
52
+ """
53
+ The dotted name, within ``basstler``, of the module holding the import.
54
+ """
55
+
56
+ imported_module: str
57
+ """
58
+ The dotted name, within ``basstler``, of the module it imports.
59
+ """
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class ModuleRenames:
64
+ """
65
+ The modules of the package a change moved.
66
+ """
67
+
68
+ new_name_by_old_name: Mapping[str, str]
69
+ """
70
+ Each moved module's dotted name within ``basstler`` before the change, and its name
71
+ after.
72
+ """
73
+
74
+ def current_name(self, module: str) -> str:
75
+ """
76
+ :param module: A module's dotted name within ``basstler`` before the change.
77
+ :return: Its name after the change; *module* itself when it did not move.
78
+ """
79
+ return self.new_name_by_old_name.get(module, module)
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class PackageCrossings:
84
+ """
85
+ Every boundary crossing of one checkout of the package.
86
+ """
87
+
88
+ crossings: tuple[BoundaryCrossing, ...]
89
+ """
90
+ The crossings, each once, ordered by importing and then imported module.
91
+ """
92
+
93
+ def added_since(self, base: PackageCrossings) -> tuple[BoundaryCrossing, ...]:
94
+ """
95
+ :param base: The crossings of the checkout this one is compared with.
96
+ :return: The crossings this checkout has and *base* does not.
97
+ """
98
+ return tuple(
99
+ crossing for crossing in self.crossings if crossing not in base.crossings
100
+ )
101
+
102
+ def renamed(self, renames: ModuleRenames) -> PackageCrossings:
103
+ """
104
+ :param renames: The modules a change moved.
105
+ :return: These crossings, with each module named as it is after the change.
106
+ """
107
+ return PackageCrossings(
108
+ crossings=tuple(
109
+ BoundaryCrossing(
110
+ importing_module=renames.current_name(crossing.importing_module),
111
+ imported_module=renames.current_name(crossing.imported_module),
112
+ )
113
+ for crossing in self.crossings
114
+ )
115
+ )
116
+
117
+
118
+ # %% the checker
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class PackageBoundaryChecker(CodeRuleChecker):
123
+ """
124
+ Reports an import of a distribution the importing module's distribution does not
125
+ list.
126
+ """
127
+
128
+ workspace: Workspace = field(
129
+ default_factory=lambda: Workspace(PackageLocation.SOURCE_TREE.value)
130
+ )
131
+ """
132
+ The distributions checked; files outside their parts of ``basstler`` are not.
133
+ """
134
+
135
+ def violations(self, path: Path) -> Iterator[CodeRuleViolation]:
136
+ module = self.module_name(path)
137
+ if not module:
138
+ return
139
+ importing = self.workspace.package_map.claiming(module)
140
+ for crossing in self.crossings(path):
141
+ imported = self.workspace.package_map.claiming(crossing.imported_module)
142
+ yield CodeRuleViolation(
143
+ path,
144
+ crossing.location.start.line,
145
+ crossing.location.end.line,
146
+ f"{importing.distribution} imports basstler.{crossing.imported_module} "
147
+ f"from {imported.distribution}, which its pyproject.toml does not list; "
148
+ "move the code or the import",
149
+ )
150
+
151
+ def package_crossings(self) -> PackageCrossings:
152
+ """
153
+ :return: The crossings of every module of :attr:`workspace`.
154
+ """
155
+ crossings = {
156
+ BoundaryCrossing(
157
+ importing_module=module, imported_module=crossing.imported_module
158
+ )
159
+ for directory in self.workspace.namespace_package.directories
160
+ for path in directory.rglob("*.py")
161
+ if (module := self.module_name(path))
162
+ for crossing in self.crossings(path)
163
+ }
164
+ return PackageCrossings(
165
+ crossings=tuple(
166
+ sorted(
167
+ crossings,
168
+ key=lambda crossing: (
169
+ crossing.importing_module,
170
+ crossing.imported_module,
171
+ ),
172
+ )
173
+ )
174
+ )
175
+
176
+ def module_renames(self, git: GitCommandRunner, base_commit: str) -> ModuleRenames:
177
+ """
178
+ :param git: The checkout of the package.
179
+ :param base_commit: The commit the checked out package is compared with.
180
+ :return: The modules of :attr:`workspace` git detects as moved since
181
+ *base_commit*.
182
+ """
183
+ listing = git.run(
184
+ "diff",
185
+ "--name-status",
186
+ "--find-renames",
187
+ "--diff-filter=R",
188
+ "--relative",
189
+ base_commit,
190
+ "HEAD",
191
+ "--",
192
+ str(self.workspace.root / WorkspaceLocation.PACKAGES),
193
+ )
194
+ new_name_by_old_name = {}
195
+ for line in listing.splitlines():
196
+ _, old_path, new_path = line.split("\t")
197
+ old_module = self.module_name(git.working_directory / old_path)
198
+ new_module = self.module_name(git.working_directory / new_path)
199
+ if old_path.endswith(".py") and old_module and new_module:
200
+ new_name_by_old_name[old_module] = new_module
201
+ return ModuleRenames(new_name_by_old_name)
202
+
203
+ def module_name(self, path: Path) -> str | None:
204
+ """
205
+ :param path: A Python source file.
206
+ :return: Its dotted name within ``basstler``; none for a file outside every
207
+ distribution's part of it.
208
+ """
209
+ source = path.resolve()
210
+ directory = next(
211
+ (
212
+ directory.resolve()
213
+ for directory in self.workspace.namespace_package.directories
214
+ if source.is_relative_to(directory.resolve())
215
+ ),
216
+ None,
217
+ )
218
+ if directory is None:
219
+ return None
220
+ parts = source.relative_to(directory).with_suffix("").parts
221
+ return ".".join(parts[:-1] if parts[-1] == "__init__" else parts)
222
+
223
+ def crossings(self, path: Path) -> Iterator[ModuleImport]:
224
+ """
225
+ :param path: A source file of a module some distribution claims.
226
+ :return: Every import in it of a module of a distribution the module's own
227
+ distribution does not list.
228
+ """
229
+ importing = self.workspace.package_map.claiming(self.module_name(path))
230
+ allowed = {importing.distribution, *importing.dependencies}
231
+ for module_import in self.module_imports(path):
232
+ imported = self.workspace.package_map.claiming(
233
+ module_import.imported_module
234
+ )
235
+ if imported is None or imported.distribution in allowed:
236
+ continue
237
+ yield module_import
238
+
239
+ def module_imports(self, path: Path) -> Iterator[ModuleImport]:
240
+ """
241
+ :param path: A Python source file.
242
+ :return: Every import in it of a module of the package.
243
+ """
244
+ module = PositionedModule(PythonSourceFile(path).parse())
245
+ for statement, location in module.positions.items():
246
+ if isinstance(statement, libcst.Import):
247
+ for alias in statement.names:
248
+ root, _, imported = self.dotted_name(alias.name).partition(".")
249
+ if root == PackageLocation.DIRECTORY.name and imported:
250
+ yield ModuleImport(imported, location)
251
+ if isinstance(statement, libcst.ImportFrom) and not statement.relative:
252
+ root, _, package = self.dotted_name(statement.module).partition(".")
253
+ if root != PackageLocation.DIRECTORY.name:
254
+ continue
255
+ names = (
256
+ ["*"]
257
+ if isinstance(statement.names, libcst.ImportStar)
258
+ else [self.dotted_name(alias.name) for alias in statement.names]
259
+ )
260
+ for name in names:
261
+ yield ModuleImport(self.imported_name(package, name), location)
262
+
263
+ @staticmethod
264
+ def dotted_name(name: libcst.Attribute | libcst.Name | None) -> str:
265
+ """
266
+ :return: The dotted name *name* spells; empty where there is none.
267
+ """
268
+ return get_full_name_for_node(name) or "" if name is not None else ""
269
+
270
+ def imported_name(self, package: str, name: str) -> str:
271
+ """
272
+ :param package: The dotted name within ``basstler`` a ``from`` import reads from.
273
+ :param name: A name it imports.
274
+ :return: The module *name* is, when it is one, else *package*.
275
+ """
276
+ candidate = ".".join(part for part in (package, name) if part)
277
+ location = Path(*candidate.split("."))
278
+ namespace_package = self.workspace.namespace_package
279
+ if namespace_package.every(location) or namespace_package.every(
280
+ location.with_suffix(".py")
281
+ ):
282
+ return candidate
283
+ return package
284
+
285
+
286
+ # %% the package at another commit
287
+
288
+
289
+ @dataclass
290
+ class PackageAtCommit:
291
+ """
292
+ The workspace as one commit holds it, in a detached worktree removed on exit.
293
+ """
294
+
295
+ git: GitCommandRunner
296
+ """
297
+ The checkout the worktree is added to.
298
+ """
299
+
300
+ commit: str
301
+ """
302
+ The commit checked out.
303
+ """
304
+
305
+ workspace_root: Path
306
+ """
307
+ The workspace's root in :attr:`git`'s checkout.
308
+ """
309
+
310
+ directory: Path = field(init=False)
311
+ """
312
+ The worktree's root, once entered.
313
+ """
314
+
315
+ def __enter__(self) -> PackageBoundaryChecker | None:
316
+ """
317
+ :return: A checker of the workspace at :attr:`commit`, under the package map
318
+ its distributions declare there; none when it holds no distributions.
319
+ """
320
+ self.directory = Path(tempfile.mkdtemp())
321
+ self.git.run(
322
+ "worktree", "add", "--detach", "--quiet", str(self.directory), self.commit
323
+ )
324
+ workspace = Workspace(
325
+ self.directory
326
+ / self.workspace_root.resolve().relative_to(
327
+ self.git.working_directory.resolve()
328
+ )
329
+ )
330
+ if not workspace.package_directories:
331
+ return None
332
+ return PackageBoundaryChecker(workspace)
333
+
334
+ def __exit__(
335
+ self,
336
+ exception_type: type[BaseException] | None,
337
+ exception: BaseException | None,
338
+ traceback: TracebackType | None,
339
+ ) -> None:
340
+ """
341
+ Remove the worktree, whether or not the workspace was read.
342
+ """
343
+ self.git.attempt("worktree", "remove", "--force", str(self.directory))
344
+ DirectoryTree(self.directory).remove()