basstler-notes 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.
@@ -0,0 +1,400 @@
1
+ """
2
+ Deletes the progress notes of branches whose pull requests have all merged or closed.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import sys
9
+ from abc import ABC, abstractmethod
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from pathlib import Path
13
+
14
+ from basstler.environment import GitHubCredentialVariable
15
+ from basstler.exceptions import DataclassException
16
+ from basstler.git.commands import GitCommandRunner
17
+ from basstler.github.client import GitHubRestClient
18
+ from basstler.github.pull_request_record import (
19
+ PullRequestField,
20
+ PullRequestHeadKey,
21
+ PullRequestRecord,
22
+ )
23
+ from basstler.github.pull_request_state import PullRequestState
24
+ from basstler.github.repository import Repository
25
+ from basstler.github.repository_access import GitHubRepository
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 command prints through.
31
+ """
32
+
33
+
34
+ class ProgressNotesFile(StrEnum):
35
+ """
36
+ How a branch's progress notes are named within their directory.
37
+ """
38
+
39
+ SUFFIX = ".md"
40
+ """
41
+ The extension every progress-notes file carries.
42
+ """
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class BranchPullRequests:
47
+ """
48
+ Which of a repository's own branches have an open pull request, and which have only
49
+ finished ones.
50
+ """
51
+
52
+ open_branches: frozenset[str]
53
+ """
54
+ Branches with at least one open pull request.
55
+ """
56
+
57
+ finished_branches: frozenset[str]
58
+ """
59
+ Branches every pull request of which has merged or closed.
60
+ """
61
+
62
+ @classmethod
63
+ def from_pull_requests(
64
+ cls, pull_requests: list[PullRequestRecord], repository: Repository
65
+ ) -> BranchPullRequests:
66
+ """
67
+ :param pull_requests: Every pull request of the repository, in any state.
68
+ :param repository: The repository whose own branches count; a pull request from
69
+ a fork's branch of the same name says nothing about this one.
70
+ :return: The branches, grouped by whether any of their pull requests is open.
71
+ """
72
+ open_branches: set[str] = set()
73
+ branches_with_pull_requests: set[str] = set()
74
+ for pull_request in pull_requests:
75
+ head = pull_request[PullRequestField.HEAD.key]
76
+ head_repository = head[PullRequestHeadKey.HEAD_REPOSITORY]
77
+ if (
78
+ head_repository is None
79
+ or head_repository[PullRequestHeadKey.FULL_NAME] != repository.full_name
80
+ ):
81
+ continue
82
+ branch = head[PullRequestHeadKey.REFERENCE]
83
+ branches_with_pull_requests.add(branch)
84
+ if pull_request[PullRequestField.STATE.key] == PullRequestState.OPEN:
85
+ open_branches.add(branch)
86
+ return cls(
87
+ open_branches=frozenset(open_branches),
88
+ finished_branches=frozenset(branches_with_pull_requests - open_branches),
89
+ )
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class ProgressNotesDirectory:
94
+ """
95
+ The directory holding one progress-notes file per branch, named after the branch.
96
+ """
97
+
98
+ path: Path
99
+ """
100
+ The directory itself.
101
+ """
102
+
103
+ def branches(self) -> list[str]:
104
+ """
105
+ :return: The branch every progress-notes file in the directory belongs to.
106
+ """
107
+ return sorted(
108
+ file.relative_to(self.path).as_posix()[: -len(ProgressNotesFile.SUFFIX)]
109
+ for file in self.path.rglob(f"*{ProgressNotesFile.SUFFIX}")
110
+ )
111
+
112
+ def remove_finished(
113
+ self,
114
+ pull_requests: BranchPullRequests,
115
+ remote_branches: frozenset[str],
116
+ kept_branch: str,
117
+ ) -> list[str]:
118
+ """
119
+ Delete the progress notes no session will read again: those of a branch that is
120
+ gone from the remote, or whose pull requests have all merged or closed.
121
+
122
+ :param pull_requests: The repository's branches, grouped by pull request state.
123
+ :param remote_branches: Every branch the remote still has.
124
+ :param kept_branch: A branch whose notes stay whatever its state, because they are
125
+ being saved.
126
+ :raises EmptyRemoteBranchListError: If *remote_branches* is empty, which would
127
+ read every branch as gone.
128
+ :return: The branches whose notes were deleted.
129
+ """
130
+ if not remote_branches:
131
+ raise EmptyRemoteBranchListError(directory=self.path)
132
+ removed = [
133
+ branch
134
+ for branch in self.branches()
135
+ if branch != kept_branch
136
+ and (
137
+ branch not in remote_branches
138
+ or branch in pull_requests.finished_branches
139
+ )
140
+ ]
141
+ for branch in removed:
142
+ (self.path / f"{branch}{ProgressNotesFile.SUFFIX}").unlink()
143
+ return removed
144
+
145
+
146
+ @dataclass
147
+ class EmptyRemoteBranchListError(DataclassException, ValueError):
148
+ """
149
+ Raised when pruning is asked to judge branches against a remote that lists none.
150
+ """
151
+
152
+ directory: Path
153
+ """
154
+ The progress-notes directory that was to be pruned.
155
+ """
156
+
157
+ def error_message(self) -> str:
158
+ return (
159
+ f"no remote branches were listed, so every note in {self.directory} would "
160
+ "read as belonging to a deleted branch; nothing was pruned"
161
+ )
162
+
163
+ def suggest_correction(self) -> str:
164
+ return ""
165
+
166
+
167
+ # %% pruning against the remote
168
+
169
+
170
+ @dataclass
171
+ class PruningSkipped(DataclassException, ABC):
172
+ """
173
+ Raised when a prune cannot judge any branch, so it removes nothing.
174
+ """
175
+
176
+ def error_message(self) -> str:
177
+ return (
178
+ "Finished branches' progress notes were not pruned and stay on the "
179
+ f"personal-notes branch: {self.reason()}."
180
+ )
181
+
182
+ @abstractmethod
183
+ def reason(self) -> str:
184
+ """
185
+ :return: Why no branch could be judged.
186
+ """
187
+
188
+
189
+ @dataclass
190
+ class NoGitHubCredentialError(PruningSkipped):
191
+ """
192
+ Raised when no GitHub token is set, so the branches' pull requests cannot be listed.
193
+ """
194
+
195
+ def reason(self) -> str:
196
+ return (
197
+ f"no {' or '.join(GitHubCredentialVariable)} is set, so the branches' pull "
198
+ "requests cannot be listed"
199
+ )
200
+
201
+ def suggest_correction(self) -> str:
202
+ return (
203
+ f"Set {' or '.join(GitHubCredentialVariable)} to a token that can read this "
204
+ "repository's pull requests, then save again."
205
+ )
206
+
207
+
208
+ @dataclass
209
+ class UnreadableRemoteError(PruningSkipped):
210
+ """
211
+ Raised when the remote's URL or branches cannot be read, so which branches still
212
+ exist is unknown.
213
+ """
214
+
215
+ remote: str
216
+ """
217
+ The remote that could not be read.
218
+ """
219
+
220
+ def reason(self) -> str:
221
+ return (
222
+ f"the URL or branches of remote {self.remote!r} could not be read, so which "
223
+ "branches still exist is unknown"
224
+ )
225
+
226
+ def suggest_correction(self) -> str:
227
+ return (
228
+ f"Make sure remote {self.remote!r} names a GitHub repository and can be "
229
+ "reached, then save again."
230
+ )
231
+
232
+
233
+ @dataclass(frozen=True)
234
+ class ProgressNotesPruning:
235
+ """
236
+ One prune of a progress-notes directory against a checkout's remote.
237
+ """
238
+
239
+ directory: ProgressNotesDirectory
240
+ """
241
+ The notes to prune.
242
+ """
243
+
244
+ git: GitCommandRunner
245
+ """
246
+ The checkout whose remote the branches live on.
247
+ """
248
+
249
+ remote: str
250
+ """
251
+ The remote the branches and pull requests belong to.
252
+ """
253
+
254
+ kept_branch: str
255
+ """
256
+ The branch whose notes are being saved.
257
+ """
258
+
259
+ def run(self) -> list[str]:
260
+ """
261
+ :raises NoGitHubCredentialError: If no GitHub token is set.
262
+ :raises UnreadableRemoteError: If the remote's URL or branches cannot be read.
263
+ :return: The branches whose notes were deleted.
264
+ """
265
+ token = GitHubCredentialVariable.first_token()
266
+ if token is None:
267
+ raise NoGitHubCredentialError()
268
+ url = self.git.attempt("remote", "get-url", self.remote)
269
+ heads = self.git.attempt("ls-remote", "--heads", self.remote)
270
+ if not (
271
+ url.succeeded
272
+ and Repository.names_a_repository(url.output)
273
+ and heads.succeeded
274
+ and heads.output
275
+ ):
276
+ raise UnreadableRemoteError(remote=self.remote)
277
+ repository = Repository.from_remote_url(url.output)
278
+ pull_requests = BranchPullRequests.from_pull_requests(
279
+ GitHubRepository(repository, GitHubRestClient(token)).all_pull_requests(),
280
+ repository,
281
+ )
282
+ remote_branches = frozenset(
283
+ line.split("refs/heads/", 1)[1] for line in heads.output.splitlines()
284
+ )
285
+ return self.directory.remove_finished(
286
+ pull_requests, remote_branches, self.kept_branch
287
+ )
288
+
289
+
290
+ # %% command line
291
+
292
+
293
+ class ProgressNotesCommand(StrEnum):
294
+ """
295
+ The subcommands this module's command line runs.
296
+ """
297
+
298
+ PRUNE = "prune"
299
+ """
300
+ Delete the progress notes of finished pull requests.
301
+ """
302
+
303
+
304
+ class ProgressNotesOption(StrEnum):
305
+ """
306
+ The options this module's command line takes.
307
+ """
308
+
309
+ DIRECTORY = "--directory"
310
+ """
311
+ The progress-notes directory to prune.
312
+ """
313
+
314
+ REMOTE = "--remote"
315
+ """
316
+ The remote the branches and pull requests belong to.
317
+ """
318
+
319
+ KEEP = "--keep"
320
+ """
321
+ The branch whose notes are being saved, and so are never removed.
322
+ """
323
+
324
+
325
+ class ProgressNotesArgument(StrEnum):
326
+ """
327
+ The names this module's command line parses its subcommand and arguments under.
328
+ """
329
+
330
+ SUBCOMMAND = "subcommand"
331
+ """
332
+ The subcommand to run, a :class:`ProgressNotesCommand`.
333
+ """
334
+
335
+ DIRECTORY = "directory"
336
+ """
337
+ The value of :attr:`ProgressNotesOption.DIRECTORY`.
338
+ """
339
+
340
+ REMOTE = "remote"
341
+ """
342
+ The value of :attr:`ProgressNotesOption.REMOTE`.
343
+ """
344
+
345
+ KEEP = "keep"
346
+ """
347
+ The value of :attr:`ProgressNotesOption.KEEP`.
348
+ """
349
+
350
+
351
+ def main() -> int:
352
+ """
353
+ Prune a progress-notes directory and report which branches' notes were removed,
354
+ or why none were judged.
355
+ """
356
+ parser = argparse.ArgumentParser(
357
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
358
+ )
359
+ subcommands = parser.add_subparsers(
360
+ dest=ProgressNotesArgument.SUBCOMMAND, required=True
361
+ )
362
+ prune = subcommands.add_parser(
363
+ ProgressNotesCommand.PRUNE,
364
+ help="Delete the progress notes of finished pull requests",
365
+ )
366
+ prune.add_argument(
367
+ ProgressNotesOption.DIRECTORY,
368
+ dest=ProgressNotesArgument.DIRECTORY,
369
+ required=True,
370
+ type=Path,
371
+ )
372
+ prune.add_argument(
373
+ ProgressNotesOption.REMOTE, dest=ProgressNotesArgument.REMOTE, required=True
374
+ )
375
+ prune.add_argument(
376
+ ProgressNotesOption.KEEP, dest=ProgressNotesArgument.KEEP, required=True
377
+ )
378
+ arguments = vars(parser.parse_args())
379
+
380
+ try:
381
+ removed = ProgressNotesPruning(
382
+ directory=ProgressNotesDirectory(
383
+ arguments[ProgressNotesArgument.DIRECTORY]
384
+ ),
385
+ git=GitCommandRunner(Path.cwd()),
386
+ remote=arguments[ProgressNotesArgument.REMOTE],
387
+ kept_branch=arguments[ProgressNotesArgument.KEEP],
388
+ ).run()
389
+ except PruningSkipped as skipped:
390
+ logger.warning(str(skipped))
391
+ return 0
392
+ if removed:
393
+ logger.info(
394
+ "Removed the progress notes of finished branches:\n" + "\n".join(removed)
395
+ )
396
+ return 0
397
+
398
+
399
+ if __name__ == "__main__":
400
+ sys.exit(main())
File without changes