basstler-stack 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 (38) hide show
  1. basstler/maintenance/__init__.py +0 -0
  2. basstler/maintenance/__main__.py +128 -0
  3. basstler/maintenance/board.py +113 -0
  4. basstler/maintenance/check_overview.py +80 -0
  5. basstler/maintenance/commands.py +595 -0
  6. basstler/maintenance/default_branch_sync.py +444 -0
  7. basstler/maintenance/exceptions.py +36 -0
  8. basstler/maintenance/fast_forward.py +223 -0
  9. basstler/maintenance/finish_summary.py +515 -0
  10. basstler/maintenance/fork_pull_request_action.py +38 -0
  11. basstler/maintenance/landed_closing.py +85 -0
  12. basstler/maintenance/landed_closing_follow_up.py +85 -0
  13. basstler/maintenance/promotion.py +248 -0
  14. basstler/maintenance/promotion_context.py +221 -0
  15. basstler/maintenance/report.py +304 -0
  16. basstler/maintenance/restack_procedure.py +279 -0
  17. basstler/maintenance/restack_steps.py +769 -0
  18. basstler/maintenance/upstream_pull_request_synchronization.py +189 -0
  19. basstler/maintenance/upstream_read_route.py +37 -0
  20. basstler/stack/__init__.py +0 -0
  21. basstler/stack/__main__.py +377 -0
  22. basstler/stack/branch_status.py +54 -0
  23. basstler/stack/checkout.py +416 -0
  24. basstler/stack/commit_move.py +218 -0
  25. basstler/stack/exceptions.py +233 -0
  26. basstler/stack/label_write.py +68 -0
  27. basstler/stack/merge_probe.py +195 -0
  28. basstler/stack/model.py +696 -0
  29. basstler/stack/promotability.py +103 -0
  30. basstler/stack/promotion_link.py +138 -0
  31. basstler/stack/report.py +304 -0
  32. basstler/stack/settings.py +453 -0
  33. basstler/stack/stack.toml +31 -0
  34. basstler_stack-4.2.0.dist-info/METADATA +16 -0
  35. basstler_stack-4.2.0.dist-info/RECORD +38 -0
  36. basstler_stack-4.2.0.dist-info/WHEEL +4 -0
  37. basstler_stack-4.2.0.dist-info/licenses/LICENSE +202 -0
  38. basstler_stack-4.2.0.dist-info/licenses/NOTICE +13 -0
@@ -0,0 +1,416 @@
1
+ """
2
+ The git checkout the stack commands run in, asked through plain ``git``.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import subprocess
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+ from enum import IntEnum, StrEnum
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING
13
+
14
+ from basstler.exceptions import UnresolvableReferenceError
15
+ from basstler.git.commands import GitCommandRunner
16
+
17
+ if TYPE_CHECKING:
18
+ from basstler.stack.settings import Configuration
19
+
20
+ # %% git vocabulary
21
+
22
+
23
+ class GitArgument(StrEnum):
24
+ """
25
+ The git executable, subcommands and flags the stack commands run.
26
+ """
27
+
28
+ GIT = "git"
29
+ """
30
+ The git executable itself.
31
+ """
32
+
33
+ REMOTE = "remote"
34
+ """
35
+ Lists the remotes, or with :attr:`GET_URL` reads one's URL.
36
+ """
37
+
38
+ GET_URL = "get-url"
39
+ """
40
+ The :attr:`REMOTE` subcommand reading a remote's fetch URL.
41
+ """
42
+
43
+ REVISION_LIST = "rev-list"
44
+ """
45
+ Lists the commits in a revision range.
46
+ """
47
+
48
+ COUNT = "--count"
49
+ """
50
+ Makes :attr:`REVISION_LIST` print how many commits there are instead of naming them.
51
+ """
52
+
53
+ FETCH = "fetch"
54
+ """
55
+ Updates references from a remote.
56
+ """
57
+
58
+ QUIET = "-q"
59
+ """
60
+ Silences a fetch's progress output.
61
+ """
62
+
63
+ NO_WRITE_FETCH_HEAD = "--no-write-fetch-head"
64
+ """
65
+ Makes :attr:`FETCH` leave ``FETCH_HEAD`` to whoever else fetches.
66
+ """
67
+
68
+ REVISION_PARSE = "rev-parse"
69
+ """
70
+ Resolves a name to the object it stands for.
71
+ """
72
+
73
+ VERIFY = "--verify"
74
+ """
75
+ Makes :attr:`REVISION_PARSE` fail unless the name resolves to exactly one object.
76
+ """
77
+
78
+ MERGE_BASE = "merge-base"
79
+ """
80
+ Answers questions about two commits' common history.
81
+ """
82
+
83
+ IS_ANCESTOR = "--is-ancestor"
84
+ """
85
+ Makes :attr:`MERGE_BASE` answer whether the first commit is contained in the second.
86
+ """
87
+
88
+ MERGE_TREE = "merge-tree"
89
+ """
90
+ Merges two commits without touching the work tree.
91
+ """
92
+
93
+ WRITE_TREE = "--write-tree"
94
+ """
95
+ Makes :attr:`MERGE_TREE` merge for real and report conflicts in its exit status.
96
+ """
97
+
98
+ CAT_FILE = "cat-file"
99
+ """
100
+ Reads an object out of the repository.
101
+ """
102
+
103
+ EXISTS = "-e"
104
+ """
105
+ Makes :attr:`CAT_FILE` answer only whether the object exists.
106
+ """
107
+
108
+ SHOW = "show"
109
+ """
110
+ Prints an object's content.
111
+ """
112
+
113
+ BRANCH = "branch"
114
+ """
115
+ Reports on local branches.
116
+ """
117
+
118
+ SHOW_CURRENT = "--show-current"
119
+ """
120
+ Makes :attr:`BRANCH` print the checked-out branch.
121
+ """
122
+
123
+ FOR_EACH_REFERENCE = "for-each-ref"
124
+ """
125
+ Lists references, optionally only those a commit contains.
126
+ """
127
+
128
+ MERGED = "--merged"
129
+ """
130
+ Makes :attr:`FOR_EACH_REFERENCE` list only the references the given commit contains.
131
+ """
132
+
133
+ REFERENCE_NAME_FORMAT = "--format=%(refname)"
134
+ """
135
+ Makes :attr:`FOR_EACH_REFERENCE` print each reference's full name and nothing else.
136
+ """
137
+
138
+ REMOTE_REFERENCES = "refs/remotes"
139
+ """
140
+ The namespace holding every remote's tracking references.
141
+ """
142
+
143
+ LIST_REMOTE = "ls-remote"
144
+ """
145
+ Lists the references a remote has, without fetching anything.
146
+ """
147
+
148
+ HEADS = "--heads"
149
+ """
150
+ Makes :attr:`LIST_REMOTE` list only branches.
151
+ """
152
+
153
+ BRANCH_REFERENCES = "refs/heads"
154
+ """
155
+ The namespace holding every branch's reference.
156
+ """
157
+
158
+
159
+ class MergeTreeStatus(IntEnum):
160
+ """
161
+ The exit statuses of ``git merge-tree --write-tree`` that answer the question asked.
162
+ """
163
+
164
+ CLEAN = 0
165
+ """
166
+ The two commits merge without a conflict.
167
+ """
168
+
169
+ CONFLICTED = 1
170
+ """
171
+ Merging them conflicts.
172
+ """
173
+
174
+
175
+ # %% what a refresh found
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class ForkRefresh:
180
+ """
181
+ What refreshing the fork's references left out.
182
+ """
183
+
184
+ missing_branches: tuple[str, ...] = ()
185
+ """
186
+ The branches the board names that the fork does not have, so their state is unknown.
187
+ """
188
+
189
+
190
+ # %% the checkout
191
+
192
+
193
+ @dataclass(frozen=True)
194
+ class CurrentCheckout:
195
+ """
196
+ The git checkout the command runs in.
197
+ """
198
+
199
+ @staticmethod
200
+ def run(*arguments: str) -> subprocess.CompletedProcess[str]:
201
+ """
202
+ Run a git command in the working directory, capturing its output.
203
+
204
+ :param arguments: The git subcommand and its arguments.
205
+ :return: The finished command.
206
+ """
207
+ return subprocess.run(
208
+ [GitArgument.GIT, *arguments],
209
+ capture_output=True,
210
+ encoding="utf-8",
211
+ cwd=Path.cwd(),
212
+ )
213
+
214
+ @classmethod
215
+ def output(cls, *arguments: str) -> str:
216
+ """
217
+ :param arguments: The git subcommand and its arguments.
218
+ :return: The command's stripped stdout, empty when it failed.
219
+ """
220
+ return cls.run(*arguments).stdout.strip()
221
+
222
+ @classmethod
223
+ def succeeds(cls, *arguments: str) -> bool:
224
+ """
225
+ :param arguments: The git subcommand and its arguments.
226
+ :return: Whether the command exited successfully.
227
+ """
228
+ return cls.run(*arguments).returncode == 0
229
+
230
+ @classmethod
231
+ def remote_urls(cls) -> dict[str, str]:
232
+ """
233
+ :return: Every remote in this checkout, mapped to its fetch URL.
234
+ """
235
+ listed = cls.output(GitArgument.REMOTE).splitlines()
236
+ return {
237
+ name: cls.output(GitArgument.REMOTE, GitArgument.GET_URL, name)
238
+ for name in listed
239
+ if name
240
+ }
241
+
242
+ @classmethod
243
+ def commit_count(cls, revision_range: str) -> int | None:
244
+ """
245
+ :param revision_range: A git revision-range expression.
246
+ :return: The number of commits in it, or ``None`` if a reference is missing.
247
+ """
248
+ counted = cls.output(
249
+ GitArgument.REVISION_LIST, GitArgument.COUNT, revision_range
250
+ )
251
+ return int(counted) if counted.isdigit() else None
252
+
253
+ @classmethod
254
+ def fetch(cls, configuration: Configuration, branches: list[str]) -> ForkRefresh:
255
+ """
256
+ Refresh the references the stack names, so drift and landed branches are current.
257
+
258
+ A branch the fork does not have is left out, so it cannot stop the others being
259
+ fetched.
260
+
261
+ :param configuration: The static configuration.
262
+ :param branches: The fork branch names to fetch.
263
+ :return: The branches the fork does not have, in the order given.
264
+ :raises GitCommandFailed: If a remote cannot be read or a fetch fails.
265
+ """
266
+ git = GitCommandRunner(working_directory=Path.cwd())
267
+ git.fetch_branch(
268
+ configuration.upstream_location,
269
+ configuration.upstream_base,
270
+ configuration.upstream_remote,
271
+ ).raise_if_failed()
272
+ published = cls.published_branches(
273
+ git=git, remote=configuration.fork_remote, branches=branches
274
+ )
275
+ if published:
276
+ git.fetch(configuration.fork_remote, *published)
277
+ return ForkRefresh(
278
+ missing_branches=tuple(
279
+ branch for branch in branches if branch not in published
280
+ )
281
+ )
282
+
283
+ @classmethod
284
+ def published_branches(
285
+ cls, *, git: GitCommandRunner, remote: str, branches: list[str]
286
+ ) -> list[str]:
287
+ """
288
+ :param git: The runner to ask through.
289
+ :param remote: The remote to ask.
290
+ :param branches: Branch names.
291
+ :return: The ones the remote has, in the order given.
292
+ :raises GitCommandFailed: If the remote cannot be read.
293
+ """
294
+ if not branches:
295
+ return []
296
+ listing = (
297
+ git.attempt(
298
+ GitArgument.LIST_REMOTE,
299
+ GitArgument.HEADS,
300
+ remote,
301
+ *(f"{GitArgument.BRANCH_REFERENCES}/{branch}" for branch in branches),
302
+ )
303
+ .raise_if_failed()
304
+ .output
305
+ )
306
+ published = {line.split("\t", maxsplit=1)[1] for line in listing.splitlines()}
307
+ return [
308
+ branch
309
+ for branch in branches
310
+ if f"{GitArgument.BRANCH_REFERENCES}/{branch}" in published
311
+ ]
312
+
313
+ @classmethod
314
+ def ancestry_predicate(
315
+ cls, configuration: Configuration
316
+ ) -> Callable[[str, str], bool]:
317
+ """
318
+ :param configuration: The resolved configuration naming the fork remote.
319
+ :return: A predicate testing whether a fork branch is contained in a local branch.
320
+ """
321
+
322
+ def is_ancestor(candidate: str, descendant: str) -> bool:
323
+ return cls.succeeds(
324
+ GitArgument.MERGE_BASE,
325
+ GitArgument.IS_ANCESTOR,
326
+ configuration.reference_on_fork(candidate),
327
+ descendant,
328
+ )
329
+
330
+ return is_ancestor
331
+
332
+ @classmethod
333
+ def containment_predicate(
334
+ cls, configuration: Configuration
335
+ ) -> Callable[[str, str], bool]:
336
+ """
337
+ :param configuration: The resolved configuration naming the fork remote.
338
+ :return: A predicate testing whether one fork branch's commits are contained in
339
+ another's, which refuses a branch whose reference does not resolve rather
340
+ than answering for it.
341
+ """
342
+
343
+ def is_contained_by(candidate: str, container: str) -> bool:
344
+ return cls.succeeds(
345
+ GitArgument.MERGE_BASE,
346
+ GitArgument.IS_ANCESTOR,
347
+ cls.resolved_on_fork(configuration, candidate),
348
+ cls.resolved_on_fork(configuration, container),
349
+ )
350
+
351
+ return is_contained_by
352
+
353
+ @classmethod
354
+ def resolved_on_fork(cls, configuration: Configuration, branch: str) -> str:
355
+ """
356
+ :param configuration: The resolved configuration naming the fork remote.
357
+ :param branch: A fork branch name.
358
+ :return: The reference to the fork's copy of it, once known to name a commit.
359
+ :raises UnresolvableReferenceError: If it names none here.
360
+ """
361
+ reference = configuration.reference_on_fork(branch)
362
+ if not cls.succeeds(
363
+ GitArgument.REVISION_PARSE,
364
+ GitArgument.VERIFY,
365
+ GitArgument.QUIET,
366
+ f"{reference}^{{commit}}",
367
+ ):
368
+ raise UnresolvableReferenceError(reference=reference)
369
+ return reference
370
+
371
+
372
+ # %% which fork branches have landed upstream
373
+
374
+
375
+ @dataclass(frozen=True)
376
+ class LandedBranches:
377
+ """
378
+ The fork branches the upstream base contained when this snapshot was taken.
379
+ """
380
+
381
+ configuration: Configuration
382
+ """
383
+ The resolved configuration naming the fork remote and the upstream base.
384
+ """
385
+
386
+ landed_references: frozenset[str]
387
+ """
388
+ The full names of the fork's tracking references the upstream base contained.
389
+ """
390
+
391
+ @classmethod
392
+ def from_checkout(cls, configuration: Configuration) -> LandedBranches:
393
+ """
394
+ :param configuration: The resolved configuration naming the fork remote and the
395
+ upstream base.
396
+ :return: The fork branches the current checkout's upstream base contains now.
397
+ :raises GitCommandFailed: If the question cannot be answered, such as when the
398
+ upstream base was never fetched, so it is never read as none having landed.
399
+ """
400
+ listed = GitCommandRunner(working_directory=Path.cwd()).run(
401
+ GitArgument.FOR_EACH_REFERENCE,
402
+ f"{GitArgument.MERGED}={configuration.upstream_remote}/{configuration.upstream_base}",
403
+ GitArgument.REFERENCE_NAME_FORMAT,
404
+ f"{GitArgument.REMOTE_REFERENCES}/{configuration.fork_remote}/",
405
+ )
406
+ return cls(configuration, frozenset(listed.splitlines()))
407
+
408
+ def contains(self, name: str) -> bool:
409
+ """
410
+ :param name: A fork branch name.
411
+ :return: Whether the upstream base contained the fork's copy of it.
412
+ """
413
+ return (
414
+ f"{GitArgument.REMOTE_REFERENCES}/{self.configuration.reference_on_fork(name)}"
415
+ in self.landed_references
416
+ )
@@ -0,0 +1,218 @@
1
+ """
2
+ Whether commits a caller proposes to move onto a branch may be moved there.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from enum import StrEnum
10
+
11
+ from basstler.exit_codes import StackExitCode
12
+ from basstler.git.commands import GitCommandRunner
13
+ from basstler.stack.checkout import CurrentCheckout, GitArgument
14
+ from basstler.stack.model import Stack
15
+ from basstler.stack.settings import Configuration
16
+ from basstler.standard_streams import StandardStreamHandler
17
+
18
+ logger = StandardStreamHandler.logger_for(__name__)
19
+ """
20
+ This module's logger, which is also what its command prints through.
21
+ """
22
+
23
+ # %% move check
24
+
25
+
26
+ class CommitMoveAction(StrEnum):
27
+ """What a proposed move would do to the destination branch."""
28
+
29
+ PUSH = "push"
30
+ """Publish one branch's commits to a remote branch."""
31
+
32
+ MERGE = "merge"
33
+ """Bring one branch's commits into another locally."""
34
+
35
+ RESTACK = "restack"
36
+ """Integrate a moved parent and publish the result - a merge and a push together."""
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ProposedCommitMove:
41
+ """Commits a caller proposes to move onto a branch, before anything is run."""
42
+
43
+ action: CommitMoveAction
44
+ """What the move would do."""
45
+
46
+ source: str
47
+ """The branch whose commits would move."""
48
+
49
+ destination: str
50
+ """The branch they would land on."""
51
+
52
+ destination_remote: str
53
+ """The remote holding the destination branch."""
54
+
55
+
56
+ class RefusalReason(StrEnum):
57
+ """Why a proposed move must not be made.
58
+
59
+ Each names a move that has gone wrong in practice, so a caller can act on which one
60
+ it hit without reading the sentence explaining it.
61
+ """
62
+
63
+ NOT_CHECKED_OUT = "not-checked-out"
64
+ """The source is not the branch whose content a push would actually move."""
65
+
66
+ MISMATCHED_BRANCH_NAMES = "mismatched-branch-names"
67
+ """The source and the destination of the push are different branches."""
68
+
69
+ NOT_THE_FORK = "not-the-fork"
70
+ """The destination remote is not the fork the stack lives on."""
71
+
72
+ FALSE_MERGE = "false-merge"
73
+ """A child would become an ancestor of its own parent, which GitHub reads as merged."""
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class CommitMoveRefusal:
78
+ """One reason a proposed move must not be made."""
79
+
80
+ reason: RefusalReason
81
+ """Which refusal this is, for a caller deciding what to do about it."""
82
+
83
+ explanation: str
84
+ """What is wrong, in terms of the branches the caller named."""
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class CommitMoveChecks:
89
+ """Checks a proposed move against the checkout it would run in.
90
+
91
+ Every refusal describes a move that has gone wrong in practice - see
92
+ :class:`RefusalReason`.
93
+ """
94
+
95
+ stack: Stack
96
+ """The stack the branches belong to."""
97
+
98
+ checked_out_branch: str
99
+ """The branch actually checked out, whose content a push would move."""
100
+
101
+ is_ancestor: Callable[[str, str], bool]
102
+ """Maps a candidate ancestor branch and a descendant branch to whether the first is
103
+ contained in the second; injected so the checks are testable without git."""
104
+
105
+ @classmethod
106
+ def of_checkout(cls, stack: Stack) -> CommitMoveChecks:
107
+ """:param stack: The stack the branches belong to.
108
+ :return: The checks against the branch this checkout has checked out."""
109
+ return cls(
110
+ stack=stack,
111
+ checked_out_branch=CurrentCheckout.output(
112
+ GitArgument.BRANCH, GitArgument.SHOW_CURRENT
113
+ ),
114
+ is_ancestor=CurrentCheckout.ancestry_predicate(stack.configuration),
115
+ )
116
+
117
+ def refusals(self, move: ProposedCommitMove) -> list[CommitMoveRefusal]:
118
+ """Every reason the move must not be made.
119
+
120
+ All of them are reported together: fixing one and re-running to discover the next
121
+ is how a move gets half made.
122
+
123
+ :param move: The proposed move.
124
+ :return: The refusals, empty when the move is safe.
125
+ """
126
+ found = []
127
+ if move.source != self.checked_out_branch:
128
+ found.append(
129
+ CommitMoveRefusal(
130
+ RefusalReason.NOT_CHECKED_OUT,
131
+ f"'{move.source}' is not checked out; '{self.checked_out_branch}' is, "
132
+ f"and its content is what would move",
133
+ )
134
+ )
135
+ if move.source != move.destination:
136
+ found.append(
137
+ CommitMoveRefusal(
138
+ RefusalReason.MISMATCHED_BRANCH_NAMES,
139
+ f"this would move '{move.source}' onto '{move.destination}'; the "
140
+ f"source and the destination must be the same branch",
141
+ )
142
+ )
143
+ if move.destination_remote != self.stack.configuration.fork_remote:
144
+ found.append(
145
+ CommitMoveRefusal(
146
+ RefusalReason.NOT_THE_FORK,
147
+ f"'{move.destination_remote}' is not the fork remote "
148
+ f"'{self.stack.configuration.fork_remote}'",
149
+ )
150
+ )
151
+ found.extend(self._false_merges(move))
152
+ return found
153
+
154
+ def _false_merges(self, move: ProposedCommitMove) -> list[CommitMoveRefusal]:
155
+ """The children of the destination this move would make GitHub call merged.
156
+
157
+ :param move: The proposed move.
158
+ :return: One refusal per child already contained in the move's source.
159
+ """
160
+ return [
161
+ CommitMoveRefusal(
162
+ RefusalReason.FALSE_MERGE,
163
+ f"'{child.name}' is already contained in '{move.source}', so this would "
164
+ f"make it an ancestor of its own parent '{move.destination}' and GitHub "
165
+ f"would close pull request #{child.pull_request_number} as merged",
166
+ )
167
+ for child in self.stack.branches
168
+ if child.parent == move.destination
169
+ and self.is_ancestor(child.name, move.source)
170
+ ]
171
+
172
+ def print_verdict(self, move: ProposedCommitMove) -> StackExitCode:
173
+ """Print whether a move may be made, and every reason it may not.
174
+
175
+ :param move: The proposed move.
176
+ :return: Success when the move is clear, refusal otherwise.
177
+ """
178
+ refusals = self.refusals(move)
179
+ if not refusals:
180
+ logger.info(
181
+ f"{move.action} {move.source} onto "
182
+ f"{move.destination_remote}/{move.destination}: clear"
183
+ )
184
+ return StackExitCode.SUCCESS
185
+ for refusal in refusals:
186
+ logger.error(f"{refusal.reason}: {refusal.explanation}")
187
+ return StackExitCode.MOVE_REFUSED
188
+
189
+
190
+ # %% asking git what contains what
191
+
192
+
193
+ @dataclass(frozen=True)
194
+ class BranchAncestry:
195
+ """
196
+ Answers containment questions about the fork's branches.
197
+
198
+ :class:`CommitMoveChecks` asks its false-merge question through this, so the
199
+ question is asked of git rather than of anything this module remembers.
200
+ """
201
+
202
+ configuration: Configuration
203
+ """
204
+ The resolved configuration naming the fork remote.
205
+ """
206
+
207
+ git: GitCommandRunner
208
+ """
209
+ The runner to ask git through.
210
+ """
211
+
212
+ def is_ancestor(self, candidate: str, descendant: str) -> bool:
213
+ """:param candidate: A fork branch that may be contained.
214
+ :param descendant: A local branch that may contain it.
215
+ :return: Whether the fork's copy of *candidate* is contained in *descendant*."""
216
+ return self.git.contains(
217
+ self.configuration.reference_on_fork(candidate), descendant
218
+ )