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,769 @@
1
+ """
2
+ What a restack does to one branch, one step at a time.
3
+
4
+ A step either concludes the branch - returning the outcome its owner acts on - or lets
5
+ the next one run. The order they run in is the procedure itself, and lives with the pass
6
+ that runs them rather than here.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from abc import ABC, abstractmethod
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass, field
14
+ from enum import StrEnum
15
+ from typing import Any
16
+
17
+ from basstler.git.commands import (
18
+ CommitTrailer,
19
+ GitCommandResult,
20
+ GitCommandRunner,
21
+ IntegrationStrategy,
22
+ ProposedPush,
23
+ )
24
+ from basstler.github.constants import MaintenanceText, MergeableState
25
+ from basstler.github.pull_request_record import (
26
+ PullRequestField,
27
+ )
28
+ from basstler.github.repository_access import ForkPullRequests
29
+ from basstler.stack.commit_move import (
30
+ CommitMoveAction,
31
+ CommitMoveChecks,
32
+ ProposedCommitMove,
33
+ RefusalReason,
34
+ )
35
+ from basstler.stack.label_write import LabelWrite
36
+ from basstler.stack.model import ParentSituation, Stack, StackBranch
37
+ from basstler.stack.settings import Configuration
38
+
39
+ # %% what became of one branch
40
+
41
+
42
+ class RestackOutcome(StrEnum):
43
+ """
44
+ What became of one branch during a restack.
45
+ """
46
+
47
+ PUSHED = "pushed"
48
+ """
49
+ Its parent was integrated and the result published.
50
+ """
51
+
52
+ UP_TO_DATE = "up-to-date"
53
+ """
54
+ Its parent's tip was already contained in it.
55
+ """
56
+
57
+ CONFLICT = "conflict"
58
+ """
59
+ Its parent could not be integrated cleanly; nothing was published.
60
+ """
61
+
62
+ INTEGRATION_FAILED = "integration-failed"
63
+ """
64
+ Integrating its parent failed without conflicting on anything, so the branch is not
65
+ the thing to fix and its owner was not told; nothing was published.
66
+ """
67
+
68
+ REFUSED = "refused"
69
+ """
70
+ Move check refused the push; nothing was published.
71
+ """
72
+
73
+ PUSH_REJECTED = "push-rejected"
74
+ """
75
+ The fork rejected the push, so the branch moved under this pass; nothing was
76
+ published, and nothing was forced over whatever moved it.
77
+ """
78
+
79
+ WITHHELD = "withheld"
80
+ """
81
+ It is still conflicted against its base from a previous pass, so it was left
82
+ untouched rather than re-reported.
83
+ """
84
+
85
+ BLOCKED_BY_ANCESTOR = "blocked-by-ancestor"
86
+ """
87
+ A branch below it was left unpublished this pass, so its parent's tip is not what
88
+ the pass meant it to hold; it was not attempted, and nothing was published.
89
+ """
90
+
91
+ PARENT_GONE = "parent-gone"
92
+ """
93
+ Nothing this stack can see carries its parent's commits, so there is no base to
94
+ build on; nothing was published.
95
+ """
96
+
97
+ UNPUBLISHED_LOCAL_COMMITS = "unpublished-local-commits"
98
+ """
99
+ The checkout holds commits on it that the fork lacks, which restacking from the
100
+ fork's copy would drop; it was left as it is and nothing was published.
101
+ """
102
+
103
+ @property
104
+ def blocks_branches_above(self) -> bool:
105
+ """
106
+ :return: Whether the branch was left without its parent's tip because of
107
+ something about the branch itself, so the branches stacked on it cannot take
108
+ what the pass meant them to. An :attr:`INTEGRATION_FAILED` is the pass's own
109
+ environment, which the branches above report for themselves.
110
+ """
111
+ return self in {
112
+ RestackOutcome.CONFLICT,
113
+ RestackOutcome.REFUSED,
114
+ RestackOutcome.PUSH_REJECTED,
115
+ RestackOutcome.WITHHELD,
116
+ RestackOutcome.BLOCKED_BY_ANCESTOR,
117
+ RestackOutcome.PARENT_GONE,
118
+ RestackOutcome.UNPUBLISHED_LOCAL_COMMITS,
119
+ }
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class BranchOutcome:
124
+ """
125
+ What became of one branch, in terms its owner can act on.
126
+ """
127
+
128
+ branch: str
129
+ """
130
+ The branch this is about.
131
+ """
132
+
133
+ parent: str
134
+ """
135
+ The branch whose tip was to be integrated into it.
136
+ """
137
+
138
+ strategy: IntegrationStrategy
139
+ """
140
+ How the parent was to be integrated.
141
+ """
142
+
143
+ outcome: RestackOutcome
144
+ """
145
+ What became of it.
146
+ """
147
+
148
+ conflicting_paths: tuple[str, ...] = ()
149
+ """
150
+ The paths that conflicted, empty unless the outcome is a conflict.
151
+ """
152
+
153
+ refusals: tuple[RefusalReason, ...] = ()
154
+ """
155
+ Why the push was refused, empty unless the outcome is a refusal.
156
+ """
157
+
158
+ pushed_commit: str | None = None
159
+ """
160
+ The commit published, absent unless the outcome is a push.
161
+ """
162
+
163
+ explanation: str | None = None
164
+ """
165
+ Why this outcome happened in words its owner can act on, absent unless the outcome
166
+ carries one.
167
+ """
168
+
169
+ reported_at: str | None = None
170
+ """
171
+ URL of the comment telling this branch's owner about it, absent unless one was
172
+ posted.
173
+ """
174
+
175
+ blocking_ancestor: str | None = None
176
+ """
177
+ The branch below this one that was left unpublished, absent unless the outcome is
178
+ :attr:`RestackOutcome.BLOCKED_BY_ANCESTOR`.
179
+ """
180
+
181
+
182
+ # %% who answers a collision
183
+
184
+
185
+ @dataclass(frozen=True)
186
+ class ConflictResponse(ABC):
187
+ """
188
+ What becomes of a branch whose parent could not be integrated cleanly.
189
+
190
+ The collision itself is never resolved by a pass - that is a change to somebody's
191
+ branch, made by whoever is in a position to judge which side is right. Who that is
192
+ depends on why the pass is running, which is what the members of this family differ
193
+ on.
194
+ """
195
+
196
+ @classmethod
197
+ def chosen_for(cls, stacked_on: str | None) -> ConflictResponse:
198
+ """
199
+ The response a pass answers its collisions through.
200
+
201
+ :param stacked_on: The branch whose subtree is being restacked, or ``None`` when
202
+ the whole board is.
203
+ :return: The response to answer through.
204
+ """
205
+ if stacked_on is None:
206
+ return TellTheBranchOwner()
207
+ return LeaveItToTheCaller()
208
+
209
+ @abstractmethod
210
+ def answer(
211
+ self, restacking: BranchUnderRestack, conflicting_paths: Sequence[str]
212
+ ) -> BranchOutcome:
213
+ """
214
+ Conclude the branch that could not take its parent's tip.
215
+
216
+ :param restacking: The branch being restacked.
217
+ :param conflicting_paths: The paths that conflicted.
218
+ :return: The outcome concluding the branch.
219
+ """
220
+
221
+ @abstractmethod
222
+ def answer_gone_parent(self, restacking: BranchUnderRestack) -> BranchOutcome:
223
+ """
224
+ Conclude the branch whose parent's commits are in nothing the stack can see.
225
+
226
+ :param restacking: The branch being restacked.
227
+ :return: The outcome concluding the branch.
228
+ """
229
+
230
+
231
+ @dataclass(frozen=True)
232
+ class TellTheBranchOwner(ConflictResponse):
233
+ """
234
+ Labels the branch and comments on its pull request.
235
+
236
+ What an unattended pass over the whole board owes a branch it had to leave alone:
237
+ nobody is watching the run, so a report reaching only its summary reaches nobody.
238
+ The label is what makes the next pass withhold the branch rather than re-report the
239
+ same collision.
240
+ """
241
+
242
+ def answer(
243
+ self, restacking: BranchUnderRestack, conflicting_paths: Sequence[str]
244
+ ) -> BranchOutcome:
245
+ """:param restacking: The branch being restacked.
246
+ :param conflicting_paths: The paths that conflicted.
247
+ :return: The outcome, carrying where its owner was told."""
248
+ return restacking.concluded(
249
+ RestackOutcome.CONFLICT,
250
+ conflicting_paths=conflicting_paths,
251
+ reported_at=restacking.hand_back(
252
+ restacking.write_conflict_report(conflicting_paths)
253
+ ),
254
+ )
255
+
256
+ def answer_gone_parent(self, restacking: BranchUnderRestack) -> BranchOutcome:
257
+ """:param restacking: The branch being restacked.
258
+ :return: The outcome, carrying where its owner was told."""
259
+ return restacking.concluded(
260
+ RestackOutcome.PARENT_GONE,
261
+ explanation=restacking.gone_parent_explanation,
262
+ reported_at=restacking.hand_back(restacking.write_gone_parent_report()),
263
+ )
264
+
265
+
266
+ @dataclass(frozen=True)
267
+ class LeaveItToTheCaller(ConflictResponse):
268
+ """
269
+ Returns the collision without writing anything to the fork.
270
+
271
+ What a pass over one named subtree owes it instead: the caller named that subtree
272
+ because a fix they just made is what the parent carries, so they are present, the
273
+ judgement is theirs, and both writes would be addressed to themselves.
274
+ """
275
+
276
+ def answer(
277
+ self, restacking: BranchUnderRestack, conflicting_paths: Sequence[str]
278
+ ) -> BranchOutcome:
279
+ """:param restacking: The branch being restacked.
280
+ :param conflicting_paths: The paths that conflicted.
281
+ :return: The outcome, naming the branch, its parent and what collided."""
282
+ return restacking.concluded(
283
+ RestackOutcome.CONFLICT, conflicting_paths=conflicting_paths
284
+ )
285
+
286
+ def answer_gone_parent(self, restacking: BranchUnderRestack) -> BranchOutcome:
287
+ """:param restacking: The branch being restacked.
288
+ :return: The outcome, naming the branch and the base that leads nowhere."""
289
+ return restacking.concluded(
290
+ RestackOutcome.PARENT_GONE, explanation=restacking.gone_parent_explanation
291
+ )
292
+
293
+
294
+ @dataclass(frozen=True)
295
+ class BranchUnderRestack:
296
+ """
297
+ One branch's restack, and everything a step needs to carry it out.
298
+ """
299
+
300
+ branch: StackBranch
301
+ """
302
+ The branch being restacked.
303
+ """
304
+
305
+ parent: str
306
+ """
307
+ The branch whose tip is to be integrated into it.
308
+ """
309
+
310
+ strategy: IntegrationStrategy
311
+ """
312
+ How that parent is to be integrated, which is also what authorises a rewrite.
313
+ """
314
+
315
+ stack: Stack
316
+ """
317
+ The derived stack it belongs to.
318
+ """
319
+
320
+ git: GitCommandRunner
321
+ """
322
+ The runner to execute through.
323
+ """
324
+
325
+ fork: ForkPullRequests
326
+ """
327
+ The fork, read for conflict state and written to when reporting.
328
+ """
329
+
330
+ checks: CommitMoveChecks
331
+ """
332
+ The checks its push is put through.
333
+ """
334
+
335
+ conflict_response: ConflictResponse = field(default_factory=TellTheBranchOwner)
336
+ """
337
+ How a collision with the parent is answered.
338
+ """
339
+
340
+ @property
341
+ def configuration(self) -> Configuration:
342
+ """:return: The resolved configuration."""
343
+ return self.stack.configuration
344
+
345
+ @property
346
+ def branch_reference(self) -> str:
347
+ """:return: The fork's copy of this branch, which every step starts from."""
348
+ return self.configuration.reference_on_fork(self.branch.name)
349
+
350
+ @property
351
+ def parent_reference(self) -> str:
352
+ """:return: The fork's copy of the parent being integrated."""
353
+ return self.configuration.reference_on_fork(self.parent)
354
+
355
+ @property
356
+ def merge_message(self) -> str:
357
+ """:return: The message of the merge integrating the parent, marked as the
358
+ restack's own by :attr:`CommitTrailer.RESTACKED_PARENT` and
359
+ :attr:`CommitTrailer.RESTACKED_PARENT_COMMIT`."""
360
+ return (
361
+ f"Merge {self.parent_reference} into {self.branch.name}\n\n"
362
+ f"{CommitTrailer.RESTACKED_PARENT}: {self.parent_reference}\n"
363
+ f"{CommitTrailer.RESTACKED_PARENT_COMMIT}: "
364
+ f"{self.git.commit_at(self.parent_reference)}"
365
+ )
366
+
367
+ def concluded(self, outcome: RestackOutcome, **detail: Any) -> BranchOutcome:
368
+ """
369
+ Finish this branch with an outcome its owner can act on.
370
+
371
+ :param outcome: What became of it.
372
+ :param detail: Whatever that outcome carries.
373
+ :return: The outcome, naming this branch and its parent.
374
+ """
375
+ return BranchOutcome(
376
+ self.branch.name, self.parent, self.strategy, outcome, **detail
377
+ )
378
+
379
+ @property
380
+ def gone_parent_explanation(self) -> str:
381
+ """:return: Why there is nothing to build this branch on, in words its owner can
382
+ act on."""
383
+ return (
384
+ f"its base '{self.parent}' is in neither the upstream base nor any other "
385
+ f"open branch"
386
+ )
387
+
388
+ @property
389
+ def conflict_resolution(self) -> str:
390
+ """:return: How this branch's owner resolves and publishes a conflict, which
391
+ depends on whether the pass merges or rebases it."""
392
+ advice = (
393
+ MaintenanceText.REBASE_RESOLUTION
394
+ if self.strategy is IntegrationStrategy.REBASE
395
+ else MaintenanceText.MERGE_RESOLUTION
396
+ )
397
+ return advice.format(parent=self.parent)
398
+
399
+ def write_conflict_report(self, conflicting_paths: Sequence[str]) -> str:
400
+ """
401
+ Write the comment telling this branch's owner that integrating the parent conflicts.
402
+
403
+ :param conflicting_paths: The paths that conflicted.
404
+ :return: The comment body.
405
+ """
406
+ files = "\n".join(f"- `{path}`" for path in conflicting_paths)
407
+ return (
408
+ f"{MaintenanceText.CONFLICT_COMMENT_PREFIX} integrating `{self.parent}` into "
409
+ f"`{self.branch.name}` conflicts, so this branch was left untouched and "
410
+ f"skipped.\n\n"
411
+ f"Conflicting files:\n{files}\n\n"
412
+ f"{self.conflict_resolution} This branch is labelled "
413
+ f"`{self.configuration.needs_resolution_label}` so later passes skip it rather than re-reporting the same "
414
+ f"conflict; the label is cleared automatically once it merges cleanly again, "
415
+ f"and the branch rejoins the pass.{self.branch.owner_address}"
416
+ )
417
+
418
+ def write_gone_parent_report(self) -> str:
419
+ """
420
+ Write the comment telling this branch's owner that its base leads nowhere.
421
+
422
+ :return: The comment body.
423
+ """
424
+ return (
425
+ f"{MaintenanceText.CONFLICT_COMMENT_PREFIX} this branch is based on "
426
+ f"`{self.parent}`, whose commits are neither in the upstream base nor in any "
427
+ f"other open branch of the stack, so there is nothing to retarget it at.\n\n"
428
+ f"Rebase it onto whatever superseded that base, or close this pull request "
429
+ f"if the work went with it.\n\n"
430
+ f"Nothing was changed here. This branch is labelled "
431
+ f"`{self.configuration.needs_resolution_label}` so later passes skip it, and it rejoins the pass once its base leads "
432
+ f"somewhere again.{self.branch.owner_address}"
433
+ )
434
+
435
+ def hand_back(self, report: str) -> str:
436
+ """
437
+ Hand this branch back to its owner: label it, then tell them why.
438
+
439
+ The label is what makes a later pass withhold the branch rather than re-report
440
+ the same thing, so the two always happen together.
441
+
442
+ :param report: The comment body to post.
443
+ :return: The URL of the comment posted.
444
+ """
445
+ self.fork.replace_labels(
446
+ self.branch.pull_request_number,
447
+ LabelWrite.replacing(
448
+ self.branch.labels,
449
+ added=[self.configuration.needs_resolution_label],
450
+ ).labels,
451
+ )
452
+ return self.fork.add_comment(self.branch.pull_request_number, report)
453
+
454
+
455
+ # %% merges a restack replaces
456
+
457
+
458
+ @dataclass(frozen=True)
459
+ class SupersededMerges:
460
+ """
461
+ The merges at a branch's tip that a restack made and that only brought in what the
462
+ branch is about to hold anyway.
463
+
464
+ Every restack merges the parent's moved tip in, so a branch waiting through many
465
+ passes would collect one merge per pass. A merge is superseded when a restack made it,
466
+ the parent and the branch's own line beneath it together hold every change it brought
467
+ in, and its content is exactly what merging its two parents produces - so it carries
468
+ no work of its own, and merging the parent's current tip into the commit beneath it
469
+ reproduces everything it held. A restack's merge carries both
470
+ :class:`CommitTrailer` trailers, the commit one naming the parent commit it merged in;
471
+ a merge a person made, even one reusing a restack's message, is never superseded.
472
+ """
473
+
474
+ git: GitCommandRunner
475
+ """
476
+ The runner to read history through.
477
+ """
478
+
479
+ parent_reference: str
480
+ """
481
+ The fork's copy of the parent about to be integrated.
482
+ """
483
+
484
+ def replacement_start_points(self, tip: str) -> list[str]:
485
+ """
486
+ :param tip: The branch's published tip.
487
+ :return: The commit beneath each superseded merge at *tip*, deepest first, so a
488
+ merge onto the first replaces them all; empty when *tip* is not one.
489
+ """
490
+ start_points = []
491
+ commit = tip
492
+ while self.is_superseded(commit):
493
+ commit = self.git.parents_of(commit)[0]
494
+ start_points.append(commit)
495
+ return start_points[::-1]
496
+
497
+ def is_superseded(self, commit: str) -> bool:
498
+ """:param commit: A commit on the branch's own line.
499
+ :return: Whether it is a restack's merge the parent's current tip supersedes."""
500
+ match self.git.parents_of(commit):
501
+ case (own_line, merged_in):
502
+ return (
503
+ self.git.trailer_value(commit, CommitTrailer.RESTACKED_PARENT) != ""
504
+ and self.git.trailer_value(
505
+ commit, CommitTrailer.RESTACKED_PARENT_COMMIT
506
+ )
507
+ == merged_in
508
+ and not self.git.contains(own_line, self.parent_reference)
509
+ and self.git.adds_only_merges(
510
+ merged_in, self.parent_reference, own_line
511
+ )
512
+ and self.git.automatic_merge_tree(own_line, merged_in)
513
+ == self.git.tree_of(commit)
514
+ )
515
+ case _:
516
+ return False
517
+
518
+
519
+ # %% the steps themselves
520
+
521
+
522
+ @dataclass(frozen=True)
523
+ class RestackStep(ABC):
524
+ """
525
+ One step of a branch's restack.
526
+
527
+ A step either concludes the branch - returning the outcome its owner acts on - or
528
+ returns nothing and lets the next step run. Adding a step is writing a subclass and
529
+ placing it in :func:`basstler.maintenance.restack_procedure.restack_steps`, whose order is
530
+ the procedure.
531
+ """
532
+
533
+ @abstractmethod
534
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
535
+ """
536
+ Carry out this step.
537
+
538
+ :param restacking: The branch being restacked.
539
+ :return: The outcome concluding the branch, or ``None`` to continue.
540
+ """
541
+
542
+
543
+ @dataclass(frozen=True)
544
+ class WithholdBranchStillConflicting(RestackStep):
545
+ """
546
+ Leaves a branch alone while it is still conflicted from an earlier pass.
547
+
548
+ Clears the label as a side effect when it is not, since that is what lets the branch
549
+ rejoin the pass without anybody remembering to remove it by hand.
550
+ """
551
+
552
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
553
+ """:param restacking: The branch being restacked.
554
+ :return: A withheld outcome while it still conflicts, otherwise ``None``."""
555
+ branch = restacking.branch
556
+ label = restacking.configuration.needs_resolution_label
557
+ if label not in branch.labels:
558
+ return None
559
+ state = PullRequestField.MERGEABLE_STATE.read(
560
+ restacking.fork.pull_request(branch.pull_request_number),
561
+ branch.pull_request_number,
562
+ )
563
+ if state == MergeableState.DIRTY:
564
+ return restacking.concluded(
565
+ RestackOutcome.WITHHELD,
566
+ explanation="still conflicted against its base since a previous pass",
567
+ )
568
+ restacking.fork.replace_labels(
569
+ branch.pull_request_number,
570
+ LabelWrite.replacing(branch.labels, removed=[label]).labels,
571
+ )
572
+ return None
573
+
574
+
575
+ @dataclass(frozen=True)
576
+ class ReportAParentThatIsGone(RestackStep):
577
+ """
578
+ Hands back a branch whose base no longer leads anywhere.
579
+
580
+ A base whose own pull request closed without merging leaves its child unable to
581
+ reach the upstream at all, and no rule can say what should replace it - the work that
582
+ superseded it is the owner's to name. Merging it every pass would only keep building
583
+ on a branch nobody is going to land.
584
+ """
585
+
586
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
587
+ """:param restacking: The branch being restacked.
588
+ :return: A gone-parent outcome when nothing carries its base, otherwise
589
+ ``None``."""
590
+ situation = restacking.stack.effective_parent(restacking.branch).situation
591
+ if situation is not ParentSituation.GONE:
592
+ return None
593
+ return restacking.conflict_response.answer_gone_parent(restacking)
594
+
595
+
596
+ @dataclass(frozen=True)
597
+ class SkipBranchAlreadyCurrent(RestackStep):
598
+ """
599
+ Leaves a branch alone when its parent's tip is already contained in it.
600
+ """
601
+
602
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
603
+ """:param restacking: The branch being restacked.
604
+ :return: An up-to-date outcome when nothing has to move, otherwise ``None``."""
605
+ if restacking.git.contains(
606
+ restacking.parent_reference, restacking.branch_reference
607
+ ):
608
+ return restacking.concluded(RestackOutcome.UP_TO_DATE)
609
+ return None
610
+
611
+
612
+ @dataclass(frozen=True)
613
+ class LeaveUnpublishedLocalCommits(RestackStep):
614
+ """
615
+ Leaves a branch alone while the checkout holds commits on it that the fork lacks.
616
+
617
+ A restack starts from the fork's copy and moves the checkout's own copy of the
618
+ branch there, so anything only the checkout has - a resolved conflict not yet pushed
619
+ - would be dropped without a word.
620
+ """
621
+
622
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
623
+ """:param restacking: The branch being restacked.
624
+ :return: An unpublished-local-commits outcome when the checkout's copy is not
625
+ contained in the fork's, otherwise ``None``."""
626
+ git = restacking.git
627
+ local = git.local_commit(restacking.branch.name)
628
+ if local is None or git.contains(local, restacking.branch_reference):
629
+ return None
630
+ return restacking.concluded(
631
+ RestackOutcome.UNPUBLISHED_LOCAL_COMMITS,
632
+ explanation=f"this checkout holds commits on it the fork lacks (at {local})"
633
+ "; publish or discard them, then run the pass again",
634
+ )
635
+
636
+
637
+ @dataclass(frozen=True)
638
+ class IntegrateParent(RestackStep):
639
+ """
640
+ Integrates the parent's tip, answering a conflict through the branch's
641
+ :class:`ConflictResponse`.
642
+
643
+ A conflict is never resolved here - that is a change to somebody else's branch.
644
+
645
+ A merge is made onto the deepest commit beneath the branch's
646
+ :class:`SupersededMerges` it succeeds on, so the branch carries as few merges of its
647
+ parent as merge cleanly however many passes it waits through. When every such merge
648
+ fails, the parent is merged onto the published tip instead, so replacing earlier
649
+ merges never turns a clean restack into a reported conflict.
650
+
651
+ Unmerged paths are what make a failed integration a conflict, not its exit status:
652
+ a merge also refuses when an untracked file is in the way, when the histories are
653
+ unrelated, or when a reference does not resolve. Labelling those would name a
654
+ branch that merges perfectly well, and the branch's owner would have nothing to
655
+ fix - so they are reported as a plain failure of the pass instead.
656
+ """
657
+
658
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
659
+ """:param restacking: The branch being restacked.
660
+ :return: A conflict outcome when the parent left unmerged paths, a failure
661
+ outcome when the integration failed without any, otherwise ``None``."""
662
+ git = restacking.git
663
+ integration = self._integrate(restacking)
664
+ if integration.succeeded:
665
+ return None
666
+ conflicting = git.unmerged_paths()
667
+ git.abandon(restacking.strategy)
668
+ if not conflicting:
669
+ return restacking.concluded(
670
+ RestackOutcome.INTEGRATION_FAILED,
671
+ explanation=integration.error_output,
672
+ )
673
+ return restacking.conflict_response.answer(restacking, conflicting)
674
+
675
+ @classmethod
676
+ def _integrate(cls, restacking: BranchUnderRestack) -> GitCommandResult:
677
+ """
678
+ :param restacking: The branch being restacked.
679
+ :return: The integration that stands - the deepest merge replacing superseded
680
+ merges that succeeded, otherwise the one onto the published tip.
681
+ """
682
+ tip = restacking.branch_reference
683
+ if restacking.strategy is IntegrationStrategy.REBASE:
684
+ return cls._integrate_onto(restacking, tip)
685
+ superseded = SupersededMerges(restacking.git, restacking.parent_reference)
686
+ for start_point in superseded.replacement_start_points(tip):
687
+ replacing = cls._integrate_onto(restacking, start_point)
688
+ if replacing.succeeded:
689
+ return replacing
690
+ restacking.git.abandon(restacking.strategy)
691
+ return cls._integrate_onto(restacking, tip)
692
+
693
+ @staticmethod
694
+ def _integrate_onto(
695
+ restacking: BranchUnderRestack, start_point: str
696
+ ) -> GitCommandResult:
697
+ """
698
+ :param restacking: The branch being restacked.
699
+ :param start_point: The commit to put the branch at before integrating.
700
+ :return: The finished integration of the parent's tip.
701
+ """
702
+ git = restacking.git
703
+ git.checkout(restacking.branch.name, start_point)
704
+ if restacking.strategy is IntegrationStrategy.REBASE:
705
+ return git.rebase(restacking.parent_reference)
706
+ return git.merge(restacking.parent_reference, restacking.merge_message)
707
+
708
+
709
+ @dataclass(frozen=True)
710
+ class RefuseAnUnsafeMove(RestackStep):
711
+ """
712
+ Puts the push through the checks before it is made, without exception.
713
+ """
714
+
715
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome | None:
716
+ """:param restacking: The branch being restacked.
717
+ :return: A refused outcome carrying every reason, otherwise ``None``."""
718
+ checks = CommitMoveChecks(
719
+ stack=restacking.checks.stack,
720
+ checked_out_branch=restacking.git.checked_out_branch(),
721
+ is_ancestor=restacking.checks.is_ancestor,
722
+ )
723
+ refusals = tuple(
724
+ refusal.reason
725
+ for refusal in checks.refusals(
726
+ ProposedCommitMove(
727
+ action=CommitMoveAction.RESTACK,
728
+ source=restacking.branch.name,
729
+ destination=restacking.branch.name,
730
+ destination_remote=restacking.configuration.fork_remote,
731
+ )
732
+ )
733
+ )
734
+ if refusals:
735
+ return restacking.concluded(RestackOutcome.REFUSED, refusals=refusals)
736
+ return None
737
+
738
+
739
+ @dataclass(frozen=True)
740
+ class PublishBranch(RestackStep):
741
+ """
742
+ Publishes the integrated branch, reporting rather than forcing a rejection.
743
+
744
+ A merge that no longer contains the published tip replaced superseded merges, which
745
+ is the one rewrite a merge publishes - under a lease, like a rebase.
746
+ """
747
+
748
+ def attempt(self, restacking: BranchUnderRestack) -> BranchOutcome:
749
+ """:param restacking: The branch being restacked.
750
+ :return: What became of the push - this step always concludes the branch."""
751
+ git = restacking.git
752
+ push = git.push(
753
+ ProposedPush.publishing(
754
+ restacking.configuration.fork_remote,
755
+ restacking.branch.name,
756
+ restacking.strategy,
757
+ replaces_superseded_merges=not git.contains(
758
+ restacking.branch_reference, "HEAD"
759
+ ),
760
+ )
761
+ )
762
+ if not push.succeeded:
763
+ return restacking.concluded(
764
+ RestackOutcome.PUSH_REJECTED, explanation=push.error_output
765
+ )
766
+ git.fetch(restacking.configuration.fork_remote, restacking.branch.name)
767
+ return restacking.concluded(
768
+ RestackOutcome.PUSHED, pushed_commit=git.commit_at("HEAD")
769
+ )