basstler-github 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 (60) hide show
  1. basstler/github/__init__.py +0 -0
  2. basstler/github/actions_budget.py +428 -0
  3. basstler/github/actions_secret.py +25 -0
  4. basstler/github/actions_settings.py +162 -0
  5. basstler/github/actions_usage.py +297 -0
  6. basstler/github/basstler_project.py +75 -0
  7. basstler/github/branch_pull_request.py +24 -0
  8. basstler/github/client.py +452 -0
  9. basstler/github/comparison.py +60 -0
  10. basstler/github/constants.py +197 -0
  11. basstler/github/credential.py +85 -0
  12. basstler/github/exceptions.py +264 -0
  13. basstler/github/file_proposal.py +440 -0
  14. basstler/github/fork_sync.py +44 -0
  15. basstler/github/git_objects.py +57 -0
  16. basstler/github/graphql.py +101 -0
  17. basstler/github/issue.py +221 -0
  18. basstler/github/label.py +78 -0
  19. basstler/github/login_lending.py +46 -0
  20. basstler/github/main_failure.py +289 -0
  21. basstler/github/permission_level.py +33 -0
  22. basstler/github/pull_request.py +74 -0
  23. basstler/github/pull_request_changes.py +141 -0
  24. basstler/github/pull_request_description.py +145 -0
  25. basstler/github/pull_request_ends.py +58 -0
  26. basstler/github/pull_request_form.py +136 -0
  27. basstler/github/pull_request_models.py +321 -0
  28. basstler/github/pull_request_record.py +369 -0
  29. basstler/github/pull_request_source.py +395 -0
  30. basstler/github/pull_request_state.py +437 -0
  31. basstler/github/queries/pull_request_for_branch.graphql +17 -0
  32. basstler/github/queries/review_threads_page.graphql +72 -0
  33. basstler/github/query_documents.py +37 -0
  34. basstler/github/release_version.py +565 -0
  35. basstler/github/remote.py +36 -0
  36. basstler/github/repository.py +532 -0
  37. basstler/github/repository_access.py +459 -0
  38. basstler/github/repository_attachment.py +95 -0
  39. basstler/github/repository_details.py +98 -0
  40. basstler/github/repository_option.py +43 -0
  41. basstler/github/repository_resources.py +133 -0
  42. basstler/github/rest_models.py +353 -0
  43. basstler/github/review_models.py +223 -0
  44. basstler/github/run_listing.py +148 -0
  45. basstler/github/stack_configuration.py +178 -0
  46. basstler/github/states.py +257 -0
  47. basstler/github/token_form.py +360 -0
  48. basstler/github/tooling_labels.py +83 -0
  49. basstler/github/user_steps.py +170 -0
  50. basstler/github/web_form.py +56 -0
  51. basstler/github/web_page.py +33 -0
  52. basstler/github/wire_form.py +159 -0
  53. basstler/github/workflow_run.py +126 -0
  54. basstler/github/workflows.py +561 -0
  55. basstler/templates/actions_budget.py.jinja +26 -0
  56. basstler_github-4.2.0.dist-info/METADATA +16 -0
  57. basstler_github-4.2.0.dist-info/RECORD +60 -0
  58. basstler_github-4.2.0.dist-info/WHEEL +4 -0
  59. basstler_github-4.2.0.dist-info/licenses/LICENSE +202 -0
  60. basstler_github-4.2.0.dist-info/licenses/NOTICE +13 -0
@@ -0,0 +1,565 @@
1
+ """
2
+ Releases: every change merged to ``main`` is one once its tests pass, tagged on the
3
+ merge commit itself as the latest release with its patch, or the part a merged pull
4
+ request's ``release:minor`` or ``release:major`` label names, incremented.
5
+
6
+ Only the released plugin's manifest names the version.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import importlib.metadata
13
+ import json
14
+ import sys
15
+ from dataclasses import dataclass
16
+ from enum import StrEnum
17
+ from pathlib import Path
18
+
19
+ from basstler.class_property import classproperty
20
+ from basstler.exceptions import DataclassException
21
+ from basstler.exit_codes import CommandFailure, ExitCode
22
+ from basstler.git.commands import GitCommandRunner
23
+ from basstler.github.basstler_project import BasstlerProject
24
+ from basstler.json_model import ValidatedJSONModel
25
+ from basstler.locations import BasstlerRepositoryLocation
26
+ from basstler.standard_streams import StandardStreamHandler
27
+ from basstler.text_file import TextFile
28
+
29
+ logger = StandardStreamHandler.logger_for(__name__)
30
+ """
31
+ This module's logger, which is also what its command prints through.
32
+ """
33
+
34
+
35
+ class ReleaseVersionExitCode(ExitCode):
36
+ """
37
+ How a subcommand ended, as its caller reads it.
38
+ """
39
+
40
+ SUCCESS = 0
41
+ """
42
+ The subcommand did what it was asked.
43
+ """
44
+
45
+ MALFORMED_VERSION = 1
46
+ """
47
+ A version is not ``<major>.<minor>.<patch>``.
48
+ """
49
+
50
+
51
+ class ReleaseCommand(StrEnum):
52
+ """
53
+ The subcommands this module answers.
54
+ """
55
+
56
+ UNRELEASED = "unreleased"
57
+ """
58
+ Print the commits since the latest release, whose pull requests choose its part.
59
+ """
60
+
61
+ RELEASE = "release"
62
+ """
63
+ Decide the release of everything since the latest one, for the workflow to tag.
64
+ """
65
+
66
+ PLUGIN = "plugin"
67
+ """
68
+ Print the commit the plugin release branch moves to for a release.
69
+ """
70
+
71
+
72
+ class VersionPart(StrEnum):
73
+ """
74
+ The part of a version a release increments, ordered from least to most significant.
75
+ """
76
+
77
+ PATCH = "patch"
78
+ """
79
+ A fix, or any other change; what a release increments unless a label says otherwise.
80
+ """
81
+
82
+ MINOR = "minor"
83
+ """
84
+ A new capability.
85
+ """
86
+
87
+ MAJOR = "major"
88
+ """
89
+ An incompatible change.
90
+ """
91
+
92
+ @classproperty
93
+ def label_prefix(cls) -> str:
94
+ """:return: What a part's pull request label puts before its name."""
95
+ return "release:"
96
+
97
+ @property
98
+ def significance(self) -> int:
99
+ """:return: Its rank: a release of several parts increments the highest."""
100
+ return list(VersionPart).index(self)
101
+
102
+ @property
103
+ def label(self) -> str:
104
+ """:return: The pull request label that asks a release to increment it."""
105
+ return f"{self.label_prefix}{self}"
106
+
107
+ @classmethod
108
+ def labelled(cls, label: str) -> VersionPart:
109
+ """
110
+ :param label: A pull request label's name.
111
+ :return: The part it is the label of, else the patch.
112
+ """
113
+ return next((part for part in cls if part.label == label), cls.PATCH)
114
+
115
+
116
+ class ReleaseOutputKey(StrEnum):
117
+ """
118
+ The ``<key>=<value>`` lines ``release`` prints, in the form a workflow step appends
119
+ to ``$GITHUB_OUTPUT``.
120
+ """
121
+
122
+ TAG = "tag"
123
+ """
124
+ The tag to create, or empty when there is nothing to release.
125
+ """
126
+
127
+
128
+ class PullRequestLabel(ValidatedJSONModel):
129
+ """
130
+ One label on a merged pull request.
131
+ """
132
+
133
+ name: str
134
+ """
135
+ The label's name.
136
+ """
137
+
138
+ @property
139
+ def part(self) -> VersionPart:
140
+ """:return: The part it asks a release to increment."""
141
+ return VersionPart.labelled(self.name)
142
+
143
+
144
+ class MergedPullRequest(ValidatedJSONModel):
145
+ """
146
+ A pull request merged since the latest release, and the labels it carries.
147
+ """
148
+
149
+ number: int
150
+ """
151
+ Its number.
152
+ """
153
+
154
+ labels: tuple[PullRequestLabel, ...]
155
+ """
156
+ Its labels.
157
+ """
158
+
159
+ @classmethod
160
+ def read_all(cls, path: Path) -> tuple[MergedPullRequest, ...]:
161
+ """
162
+ :param path: A JSON array of pull request objects, one per entry GitHub returned;
163
+ a pull request reached by several commits appears more than once.
164
+ :return: Each pull request once.
165
+ """
166
+ parsed = (cls.from_json(entry) for entry in json.loads(TextFile(path).read()))
167
+ return tuple({pull.number: pull for pull in parsed}.values())
168
+
169
+ @property
170
+ def part(self) -> VersionPart:
171
+ """:return: The most significant part its labels ask for."""
172
+ return max(
173
+ (label.part for label in self.labels),
174
+ key=lambda part: part.significance,
175
+ default=VersionPart.PATCH,
176
+ )
177
+
178
+
179
+ @dataclass
180
+ class MalformedVersion(CommandFailure, DataclassException, ValueError):
181
+ """
182
+ Raised when a version is not ``<major>.<minor>.<patch>``.
183
+ """
184
+
185
+ text: str
186
+ """
187
+ The version as written.
188
+ """
189
+
190
+ @classproperty
191
+ def exit_code(cls) -> ReleaseVersionExitCode:
192
+ """:return: The status this kind of error ends a command with."""
193
+ return ReleaseVersionExitCode.MALFORMED_VERSION
194
+
195
+ def error_message(self) -> str:
196
+ return f"{self.text!r} is not a <major>.<minor>.<patch> version."
197
+
198
+ def suggest_correction(self) -> str:
199
+ return (
200
+ "Write three dot-separated numbers, e.g. 0.1.1, with no "
201
+ f"{ReleaseVersion.tag_prefix!r} prefix; that belongs to the tag."
202
+ )
203
+
204
+
205
+ @dataclass(frozen=True, order=True)
206
+ class ReleaseVersion:
207
+ """
208
+ A ``<major>.<minor>.<patch>`` version, ordered as releases are.
209
+ """
210
+
211
+ major: int
212
+ """
213
+ Incremented by an incompatible change.
214
+ """
215
+
216
+ minor: int
217
+ """
218
+ Incremented by a new capability.
219
+ """
220
+
221
+ patch: int
222
+ """
223
+ Incremented by any other change.
224
+ """
225
+
226
+ @classproperty
227
+ def tag_prefix(cls) -> str:
228
+ """:return: What a release's tag puts before its version."""
229
+ return "v"
230
+
231
+ @classmethod
232
+ def parse(cls, text: str) -> ReleaseVersion:
233
+ """
234
+ :param text: A version as written, e.g. ``"0.1.1"``.
235
+ :raises MalformedVersion: If it is not three dot-separated numbers.
236
+ :return: The version.
237
+ """
238
+ parts = text.split(".")
239
+ if len(parts) != 3 or not all(part.isdigit() for part in parts):
240
+ raise MalformedVersion(text)
241
+ return cls(*(int(part) for part in parts))
242
+
243
+ @classmethod
244
+ def from_tag(cls, tag: str) -> ReleaseVersion | None:
245
+ """
246
+ :param tag: A git tag.
247
+ :return: The version it releases, or ``None`` if it is not a release tag.
248
+ """
249
+ if not tag.startswith(cls.tag_prefix):
250
+ return None
251
+ try:
252
+ return cls.parse(tag.removeprefix(cls.tag_prefix))
253
+ except MalformedVersion:
254
+ return None
255
+
256
+ @classmethod
257
+ def installed(cls) -> ReleaseVersion | None:
258
+ """
259
+ :return: The release of the installed package, ``None`` for a build that is no
260
+ release, such as a source checkout past one.
261
+ """
262
+ return cls.from_tag(
263
+ f"{cls.tag_prefix}{importlib.metadata.version(BasstlerProject.name)}"
264
+ )
265
+
266
+ def bumped(self, part: VersionPart) -> ReleaseVersion:
267
+ """
268
+ :param part: The part to increment; every part after it resets to zero.
269
+ :return: The next version.
270
+ """
271
+ if part is VersionPart.MAJOR:
272
+ return ReleaseVersion(self.major + 1, 0, 0)
273
+ if part is VersionPart.MINOR:
274
+ return ReleaseVersion(self.major, self.minor + 1, 0)
275
+ return ReleaseVersion(self.major, self.minor, self.patch + 1)
276
+
277
+ @property
278
+ def tag(self) -> str:
279
+ """:return: The tag the release of this version carries."""
280
+ return f"{self.tag_prefix}{self}"
281
+
282
+ def __str__(self) -> str:
283
+ return f"{self.major}.{self.minor}.{self.patch}"
284
+
285
+
286
+ @dataclass(frozen=True)
287
+ class PublishedReleases:
288
+ """
289
+ The releases a remote repository has tagged.
290
+ """
291
+
292
+ git: GitCommandRunner
293
+ """
294
+ A checkout, whose git lists the remote's tags.
295
+ """
296
+
297
+ remote: str
298
+ """
299
+ The remote's name or URL.
300
+ """
301
+
302
+ def latest(self) -> ReleaseVersion | None:
303
+ """
304
+ :return: The highest released version, ``None`` before the first release.
305
+ """
306
+ listed = self.git.run("ls-remote", "--tags", "--refs", self.remote)
307
+ tags = "\n".join(
308
+ line.rpartition("refs/tags/")[2] for line in listed.splitlines()
309
+ )
310
+ return max(Release.released(tags), default=None)
311
+
312
+ def is_ahead_of(self, installed: ReleaseVersion | None) -> bool:
313
+ """
314
+ :param installed: The release a session runs, ``None`` when it runs none.
315
+ :return: Whether a release newer than it is published.
316
+ """
317
+ latest = self.latest()
318
+ return installed is not None and latest is not None and installed < latest
319
+
320
+
321
+ @dataclass(frozen=True)
322
+ class PlannedRelease:
323
+ """
324
+ What ``release`` decided to release.
325
+ """
326
+
327
+ version: ReleaseVersion
328
+ """
329
+ The version to tag.
330
+ """
331
+
332
+ def output_lines(self) -> str:
333
+ """:return: The release as ``<key>=<value>`` lines for ``$GITHUB_OUTPUT``."""
334
+ return f"{ReleaseOutputKey.TAG}={self.version.tag}"
335
+
336
+
337
+ @dataclass(frozen=True)
338
+ class Release:
339
+ """
340
+ One checkout, the commit checked out in it, and the releases before it.
341
+ """
342
+
343
+ checkout: Path
344
+ """
345
+ The root of the checkout.
346
+ """
347
+
348
+ @classproperty
349
+ def first(cls) -> ReleaseVersion:
350
+ """:return: The version a repository with no release yet releases."""
351
+ return ReleaseVersion(0, 1, 0)
352
+
353
+ @property
354
+ def git(self) -> GitCommandRunner:
355
+ """:return: A runner for git in the checkout."""
356
+ return GitCommandRunner(working_directory=self.checkout)
357
+
358
+ @staticmethod
359
+ def released(tags: str) -> list[ReleaseVersion]:
360
+ """
361
+ :param tags: Tag names, one per line.
362
+ :return: The versions those that are release tags release.
363
+ """
364
+ versions = (ReleaseVersion.from_tag(tag) for tag in tags.splitlines())
365
+ return [version for version in versions if version]
366
+
367
+ def latest_release(self) -> ReleaseVersion | None:
368
+ """
369
+ :return: The highest version whose tag the checked-out commit contains, or
370
+ ``None`` before the first release.
371
+ """
372
+ tags = self.git.run("tag", "--merged", "HEAD", "--list")
373
+ return max(self.released(tags), default=None)
374
+
375
+ def is_released(self) -> bool:
376
+ """
377
+ :return: Whether a release tag already contains the checked-out commit, as when
378
+ a later merge's run has released it, or this run is run again.
379
+ """
380
+ return bool(self.released(self.git.run("tag", "--contains", "HEAD", "--list")))
381
+
382
+ def changed_since(self, release: ReleaseVersion) -> bool:
383
+ """
384
+ :param release: A released version.
385
+ :return: Whether the checked-out commit differs from that release.
386
+ """
387
+ return not self.git.attempt("diff", "--quiet", release.tag, "HEAD").succeeded
388
+
389
+ def unreleased_commits(self) -> tuple[str, ...]:
390
+ """
391
+ :return: The commits on the first-parent line since the latest release, oldest
392
+ first: one merge commit per merged pull request, plus any direct push.
393
+ """
394
+ latest = self.latest_release()
395
+ revisions = f"{latest.tag}..HEAD" if latest else "HEAD"
396
+ listed = self.git.run("rev-list", "--first-parent", "--reverse", revisions)
397
+ return tuple(listed.splitlines())
398
+
399
+ def plan(self, merged: tuple[MergedPullRequest, ...]) -> PlannedRelease | None:
400
+ """
401
+ Decide the release of everything since the latest one: the latest release with
402
+ the most significant part any merged pull request's labels ask for, else its
403
+ patch, incremented.
404
+
405
+ :param merged: The pull requests merged since the latest release.
406
+ :return: The release, or ``None`` when nothing changed since the latest one.
407
+ """
408
+ if self.is_released():
409
+ return None
410
+ latest = self.latest_release()
411
+ if latest is None:
412
+ return PlannedRelease(self.first)
413
+ if not self.changed_since(latest):
414
+ return None
415
+ part = max(
416
+ (pull.part for pull in merged),
417
+ key=lambda part: part.significance,
418
+ default=VersionPart.PATCH,
419
+ )
420
+ return PlannedRelease(latest.bumped(part))
421
+
422
+
423
+ @dataclass(frozen=True)
424
+ class PluginRelease:
425
+ """
426
+ The checked-out commit's plugin, alone at the root of a commit whose manifest names
427
+ the release's version.
428
+ """
429
+
430
+ release: Release
431
+ """
432
+ The checkout whose plugin is released.
433
+ """
434
+
435
+ version: ReleaseVersion
436
+ """
437
+ The version the release tags.
438
+ """
439
+
440
+ previous: str
441
+ """
442
+ The plugin release branch, which the commit descends from so the branch only moves
443
+ forward; it need not exist yet.
444
+ """
445
+
446
+ def commit(self) -> str:
447
+ """
448
+ :return: The new commit, its first parent the plugin's own history.
449
+ """
450
+ git = self.release.git
451
+ plugin = git.run(
452
+ "subtree",
453
+ "split",
454
+ "--quiet",
455
+ f"--prefix={BasstlerRepositoryLocation.PLUGIN}",
456
+ "HEAD",
457
+ )
458
+ manifest_path = BasstlerRepositoryLocation.PLUGIN_MANIFEST.path_in_plugin
459
+ manifest = json.loads(git.file_at(plugin, manifest_path))
460
+ manifest["version"] = str(self.version)
461
+ previous = git.commit_or_none(self.previous)
462
+ return git.commit_files(
463
+ plugin,
464
+ {manifest_path.as_posix(): json.dumps(manifest, indent=2)},
465
+ f"Release the plugin at {self.version.tag}",
466
+ merged_parents=(previous,) if previous else (),
467
+ )
468
+
469
+
470
+ class ReleaseCommandLine:
471
+ """
472
+ The command line: its arguments, and the subcommand they name.
473
+ """
474
+
475
+ @classmethod
476
+ def parser(cls) -> argparse.ArgumentParser:
477
+ """
478
+ :return: The parser for every subcommand and its arguments.
479
+ """
480
+ parser = argparse.ArgumentParser(
481
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
482
+ )
483
+ subcommands = parser.add_subparsers(dest="subcommand", required=True)
484
+ unreleased_parser = subcommands.add_parser(
485
+ ReleaseCommand.UNRELEASED,
486
+ help="Print the commits since the latest release, oldest first",
487
+ )
488
+ release_parser = subcommands.add_parser(
489
+ ReleaseCommand.RELEASE,
490
+ help="Decide the release of everything since the latest one",
491
+ )
492
+ release_parser.add_argument(
493
+ "--pull-requests",
494
+ type=Path,
495
+ help="A JSON array of the pull requests GitHub associates with the "
496
+ "unreleased commits (default: none, so a patch release)",
497
+ )
498
+ plugin_parser = subcommands.add_parser(
499
+ ReleaseCommand.PLUGIN,
500
+ help="Print the commit the plugin release branch moves to for a release",
501
+ )
502
+ plugin_parser.add_argument(
503
+ "--tag", required=True, help="The tag the release carries, e.g. v1.2.3"
504
+ )
505
+ plugin_parser.add_argument(
506
+ "--previous",
507
+ required=True,
508
+ help="The plugin release branch as the checkout names it, which need not "
509
+ "exist yet",
510
+ )
511
+ for subcommand_parser in (unreleased_parser, release_parser, plugin_parser):
512
+ subcommand_parser.add_argument(
513
+ "--checkout",
514
+ type=Path,
515
+ default=Path.cwd(),
516
+ help="The checkout's root (default: the current directory)",
517
+ )
518
+ return parser
519
+
520
+ @classmethod
521
+ def run(cls, arguments: argparse.Namespace) -> ReleaseVersionExitCode:
522
+ """
523
+ Carry out the subcommand *arguments* name.
524
+
525
+ :param arguments: The parsed command line.
526
+ :return: How the subcommand ended.
527
+ """
528
+ release = Release(arguments.checkout)
529
+ try:
530
+ match arguments.subcommand:
531
+ case ReleaseCommand.UNRELEASED:
532
+ for commit in release.unreleased_commits():
533
+ logger.info(commit)
534
+ case ReleaseCommand.RELEASE:
535
+ merged = (
536
+ MergedPullRequest.read_all(arguments.pull_requests)
537
+ if arguments.pull_requests
538
+ else ()
539
+ )
540
+ planned = release.plan(merged)
541
+ if planned is None:
542
+ logger.warning("Nothing changed since the latest release.")
543
+ else:
544
+ logger.info(planned.output_lines())
545
+ case ReleaseCommand.PLUGIN:
546
+ released = ReleaseVersion.parse(
547
+ arguments.tag.removeprefix(ReleaseVersion.tag_prefix)
548
+ )
549
+ plugin = PluginRelease(release, released, arguments.previous)
550
+ logger.info(plugin.commit())
551
+ except MalformedVersion as error:
552
+ logger.error(str(error))
553
+ return error.exit_code
554
+ return ReleaseVersionExitCode.SUCCESS
555
+
556
+
557
+ def main() -> ReleaseVersionExitCode:
558
+ """
559
+ Parse arguments and dispatch to the requested subcommand.
560
+ """
561
+ return ReleaseCommandLine.run(ReleaseCommandLine.parser().parse_args())
562
+
563
+
564
+ if __name__ == "__main__":
565
+ sys.exit(main())
@@ -0,0 +1,36 @@
1
+ """
2
+ A remote of a clone, named by the GitHub repository it points at.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass
8
+
9
+ from basstler.git.remote import Remote
10
+ from basstler.github.repository import Repository
11
+
12
+ # %% the remote
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class GitHubRemote(Remote):
17
+ """
18
+ A :class:`Remote` that knows the GitHub repository it points at.
19
+ """
20
+
21
+ @property
22
+ def github_repository(self) -> Repository | None:
23
+ """
24
+ :return: The repository the remote points at, ``None`` when it names none - a
25
+ remote given as a local path.
26
+ """
27
+ url = self.url
28
+ if not Repository.names_a_repository(url):
29
+ return None
30
+ return Repository.from_remote_url(url)
31
+
32
+ @property
33
+ def description(self) -> str:
34
+ """:return: The repository's name, or the remote's where it names none."""
35
+ repository = self.github_repository
36
+ return repository.full_name if repository else self.location