Coverage for packages/workshop/src/livery/workshop/_submit.py: 90%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_variables.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_sweep.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_metrics.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_balance.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_extensions_conan.py ran.

1"""``fm submit``: get the branch onto the remote, verified, and landed.
2
3Local gate first (the gate the CI legs run, so a red gate costs
4zero network calls), then the
5closes-link resolution with existence probes, disarm-before-push,
6push, find-or-open with the title rules, arm per the arming ladder,
7and follow until it lands or says what stopped it. Exits 10 and 17 self-heal by
8integrating the base and re-submitting; every other code surfaces
9unchanged, because skills, hooks, and humans branch on them.
10
11``fm abandon`` is the exit: disarm, close the pull request, delete
12both branches, return to the base. ``fm submit.merge`` merges a
13green pull request that was deliberately left unarmed, and refuses
14anything less than green. ``fm submit.arm`` and ``fm submit.disarm``
15set and take off a pull request's auto-merge and leave it open. The
16three act on this branch's pull request, or on the one a number
17names, from any checkout.
18
19The arming ladder, highest wins: ``--armed``/``--no-armed`` for one
20invocation; ``WORKSHOP_AUTOMERGE`` as the per-user standing preference;
21the workspace contract's ``[ci] automerge`` as committed repo policy;
22off. The ladder is footman's option ladder; only the printed reason
23is derived here.
24"""
25
26from __future__ import annotations
27
28import contextlib
29import os
30import re
31import tomllib
32from collections.abc import Callable, Generator
33from dataclasses import dataclass
34from pathlib import Path
35from typing import Annotated, ParamSpec
36
37import livery.footman as footman
38from livery import git
39from livery.footman import Arg, doc, fail, group, suggest
40from livery.forge import ForgeError, PullRequest, Repository, Unsupported
41from livery.workshop import _stack
42from livery.workshop._contract import load_contract
43from livery.workshop._conventional import TITLE_RE, TYPES
44from livery.workshop._extensions import workspace_root
45from livery.workshop._points import EVERY_RUNNER_LABEL
46from livery.workshop._traces import drop_run
47from livery.workshop._verdict import (
48 EXIT_BEHIND,
49 EXIT_CONFLICTS,
50 EXIT_DISARMED,
51 EXIT_UNREACHABLE,
52 ForgeUnreachable,
53 Pending,
54 follow,
55 follow_pull_request,
56)
57
58submit = group(
59 "submit", help="Gate, push, open-or-reuse the PR, arm, and watch it land"
60)
61
62#: Branch names submit accepts: the conventional type, a slash, a slug
63#: that may open with an issue number (``feat/41-title-rules``).
64_BRANCH_TYPES = TYPES
65_BRANCH_RE = re.compile(rf"^({'|'.join(_BRANCH_TYPES)})/.+$")
66_BRANCH_ISSUE_RE = re.compile(r"^[a-z]+/(\d+)-")
67
68#: PR titles follow the published commit convention, breaking
69#: marker included.
70_TITLE_RE = TITLE_RE
71
72#: Self-heal ceiling. Exits 10 and 17 are cured by one integrate and
73#: re-push; needing a third round means the base is moving faster than
74#: the heal, and a person should look rather than a loop spin.
75_MAX_HEALS = 2
76
77#: How many times arming is re-tried when the forge silently loses the
78#: schedule (the lost-auto-merge-schedule quirk): armed is verified by
79#: read-back, never assumed from a 2xx.
80_ARM_RETRIES = 3
81
82_P = ParamSpec("_P")
83
84#: How often a followed merge hold re-tries or re-reads, seconds.
85_HOLD_POLL = 3.0
86
87
88def _contract_forge_kind(root: Path) -> str:
89 """The forge the contract names; [livery.workshop._forge_lane.forge_kind][]."""
90 from livery.workshop._forge_lane import forge_kind
91
92 return forge_kind(root)
93
94
95def _reported_context_names(repo: Repository, sha: str) -> tuple[str, ...]:
96 """The status contexts CI actually reports for *sha*.
97
98 Derived from the runs and their jobs in the grammar the forge
99 reports under ("<workflow> / <job> (<event>)"), so a required
100 context can be judged against what exists rather than what was
101 hoped for.
102 """
103 names: list[str] = []
104 for run in repo.checks.runs(head_sha=sha):
105 base = run.workflow.rsplit("/", 1)[-1]
106 base = base.removesuffix(".yml").removesuffix(".yaml")
107 for job in repo.checks.jobs(run.id):
108 names.append(f"{base} / {job.name} ({run.event})")
109 return tuple(dict.fromkeys(names))
110
111
112def _refuse_unreported_contexts(repo: Repository, number: int) -> None:
113 """Fail when protection requires a context nothing reports.
114
115 The never-converging cousin of the settling beat: the checks
116 read green, protection waits for a context name CI never emits,
117 and waiting would hang forever. The refusal names both sides.
118 """
119 pr = repo.pr.get(number)
120 if pr is None:
121 return
122 protection = repo.protection(pr.base_branch)
123 if protection is None:
124 return
125 reported = _reported_context_names(repo, pr.head_sha)
126 missing = [c for c in protection.required_contexts if c not in reported]
127 if missing:
128 fail(
129 f"protection requires contexts CI never reports:"
130 f" {', '.join(missing)}. Reported:"
131 f" {', '.join(reported) or 'nothing'}. Fix the required"
132 " context names to match what CI reports."
133 )
134
135
136def _wait_for_verdict(repo: Repository, number: int, *, local_head: str = "") -> None:
137 """Wait until *number*'s head has a completed combined verdict.
138
139 No inner deadline: merge means merge as soon as possible, so a
140 running CI is followed to its verdict and the task's own timeout
141 is the backstop. Progress prints on state changes and every
142 minute, so a long wait stays visible. A head that moves during
143 the wait is followed, and the move is said: the old and new
144 heads, whether the new one is *local_head* (this clone's own
145 push) or arrived from elsewhere, and the newest run for it, so
146 the cancelled run it leaves behind needs no investigation. A
147 forge unreachable past the transient budget exits 15.
148 """
149 pr = repo.pr.get(number)
150 if pr is None:150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true
151 return
152 head = pr.head_sha
153
154 def read() -> str | Pending:
155 nonlocal head
156 current = repo.pr.get(number)
157 if current is not None and current.head_sha and current.head_sha != head:
158 print(_head_moved_line(repo, number, head, current.head_sha, local_head))
159 head = current.head_sha
160 state = repo.checks.status(head).state
161 if state not in ("pending", "none"):
162 return state
163 return Pending(f" waiting: checks are {state} for PR #{number}", key=state)
164
165 try:
166 follow(
167 repo,
168 read,
169 subject=f"PR #{number}",
170 interval=_HOLD_POLL,
171 timeout=None,
172 quiet=60,
173 )
174 except ForgeUnreachable as exc:
175 print(exc.line)
176 raise SystemExit(EXIT_UNREACHABLE) from None
177
178
179def _head_moved_line(
180 repo: Repository, number: int, old: str, new: str, local_head: str
181) -> str:
182 """The one line for a pull request whose head moved under the watch."""
183 if local_head and new == local_head:
184 whose = "this clone's own push"
185 elif local_head:185 ↛ 188line 185 didn't jump to line 188 because the condition on line 185 was always true
186 whose = "pushed from elsewhere, not this clone's HEAD"
187 else:
188 whose = "a newer push"
189 try:
190 runs = repo.checks.runs(head_sha=new)
191 except (ForgeError, Unsupported):
192 runs = ()
193 newest = max(runs, key=lambda run: run.id, default=None)
194 run_words = (
195 f"; following run {newest.id}" if newest is not None else "; following it"
196 )
197 return (
198 f" PR #{number}: the head moved from {old[:12]} to {new[:12]}"
199 f" ({whose}){run_words}"
200 )
201
202
203def _follow_merge_state(
204 repo: Repository,
205 kind: str,
206 number: int,
207 act: Callable[_P, object],
208 *args: _P.args,
209 **kwargs: _P.kwargs,
210) -> None:
211 """Drive *act* to a decided state; merge means as soon as possible.
212
213 A 405, or the 422 GitLab answers while its mergeability recompute
214 runs, classifies through [livery.forge.classify_merge_refusal][]
215 with the pull request, its combined status and the forge's
216 published hold fetched fresh.
217 In-progress states follow through to completion, the task's own
218 timeout the only backstop; recoverable and terminal states fail
219 with the user-facing message and the forge's words verbatim;
220 discovered-merged walks past quietly. Entering the settling
221 state first verifies every required context has a reporter,
222 because a context nothing reports never settles.
223 """
224 from livery.forge import classify_merge_refusal
225
226 settling_checked = False
227 local_head = str(kwargs.pop("local_head", "") or "")
228
229 def read() -> bool | Pending:
230 nonlocal settling_checked
231 try:
232 act(*args, **kwargs)
233 return True
234 except ForgeError as exc:
235 if exc.status not in (405, 422):
236 raise
237 pr = repo.pr.get(number)
238 if pr is None:238 ↛ 239line 238 didn't jump to line 239 because the condition on line 238 was never true
239 raise
240 hold = classify_merge_refusal(
241 kind,
242 str(exc),
243 combined=repo.checks.status(pr.head_sha),
244 item_state=pr.state,
245 merged=pr.merged,
246 hold=repo.pr.merge_hold(number),
247 )
248 if hold.category == "success":248 ↛ 249line 248 didn't jump to line 249 because the condition on line 248 was never true
249 print(f" PR #{number}: {hold.message}; walking past")
250 return True
251 if hold.category == "in-progress":
252 if hold.state == "contexts-settling" and not settling_checked:252 ↛ 253line 252 didn't jump to line 253 because the condition on line 252 was never true
253 settling_checked = True
254 _refuse_unreported_contexts(repo, number)
255 if hold.state == "ci-running":255 ↛ 256line 255 didn't jump to line 256 because the condition on line 255 was never true
256 _wait_for_verdict(repo, number, local_head=local_head)
257 return Pending(f" waiting: {hold.message}", key=hold.state)
258 native = f"\n the forge said: {hold.native}" if hold.native else ""
259 fail(f"PR #{number}: {hold.message}{native}")
260
261 # A refusal other than the merge endpoint's two hold codes is the
262 # forge's answer, not a transient: it reaches the caller unretried.
263 follow(
264 repo,
265 read,
266 subject=f"PR #{number}",
267 interval=_HOLD_POLL,
268 timeout=None,
269 quiet=None,
270 retried=(),
271 )
272
273
274def _root() -> Path:
275 root = workspace_root()
276 if root is None:
277 fail("no workspace: no workshop.toml above the working directory")
278 return root
279
280
281def ci_automerge() -> bool:
282 """The committed repo policy: the workspace contract's ``[ci] automerge``."""
283 root = workspace_root()
284 if root is None:
285 return False(empty)
286 contract = load_contract(root / "workshop.toml")
287 return bool((contract.get("ci") or {}).get("automerge", False))
288
289
290def arming_reason(*, armed: bool, flag_given: bool) -> str:
291 """One sentence naming the ladder level that decided *armed*."""
292 if flag_given:
293 return f"--{'' if armed else 'no-'}armed (this invocation)"
294 if os.environ.get("WORKSHOP_AUTOMERGE") is not None:
295 return "WORKSHOP_AUTOMERGE (per-user standing preference)"
296 root = workspace_root()
297 if root is not None:
298 contract = load_contract(root / "workshop.toml")
299 if "automerge" in (contract.get("ci") or {}):299 ↛ 301line 299 didn't jump to line 301 because the condition on line 299 was always true
300 return "[ci] automerge in workshop.toml (committed repo policy)"
301 return "the default (auto-merge is opt-in; nothing configured)"
302
303
304def branch_issue(branch: str) -> int | None:
305 """The issue number a ``<type>/<number>-slug`` branch carries, or None."""
306 match = _BRANCH_ISSUE_RE.match(branch)
307 return int(match.group(1)) if match else None
308
309
310def parse_number(token: str) -> int | None:
311 """Read the issue or pull request number *token* spells; None when it spells none.
312
313 The one rule every verb that takes a number from a person reads it
314 by. A leading ``#`` is accepted, as the forges print a number, so
315 ``#123`` and ``123`` are the same number. Anything else that is
316 not all decimal digits spells no number.
317 """
318 bare = token.lstrip("#")
319 return int(bare) if bare.isdecimal() else None
320
321
322def with_closes(body: str, number: int) -> str:
323 """*body* with its ``Closes #number`` trailer, present exactly once."""
324 trailer = f"Closes #{number}"
325 if trailer in body:
326 return body
327 return f"{body}\n\n{trailer}" if body else trailer
328
329
330def resolve_closes(repo: Repository, branch: str, closes_flag: int) -> int | None:
331 """The issue submit will link, per the three guards.
332
333 The flag beats the branch-name parse; a disagreement is printed,
334 never silently resolved; and the issue must exist before
335 ``Closes #N`` is written. A branch-parsed number that does not
336 exist drops the link with a note (plain branches always work); an
337 explicit ``--closes`` that does not exist refuses.
338 """
339 parsed = branch_issue(branch)
340 if closes_flag:
341 if parsed is not None and parsed != closes_flag:341 ↛ 343line 341 didn't jump to line 343 because the condition on line 341 was always true
342 print(f" note: --closes {closes_flag} beats the branch's #{parsed}")
343 if repo.issue.get(closes_flag) is None:343 ↛ 345line 343 didn't jump to line 345 because the condition on line 343 was always true
344 fail(f"--closes {closes_flag} refused: the issue does not exist")
345 return closes_flag
346 if parsed is None:
347 return None
348 if repo.issue.get(parsed) is None:
349 print(
350 f" note: branch names issue #{parsed}, which does not exist;"
351 " submitting without a Closes link"
352 )
353 return None
354 return parsed
355
356
357@dataclass(frozen=True)
358class Plan:
359 """Everything a push and pull request need, validated, no network.
360
361 Attributes:
362 branch: The feature branch being submitted.
363 base: The branch the pull request targets.
364 title: The pull request title, validated.
365 body: The pull request body.
366 title_given: Whether the title came from the caller. A
367 defaulted title tracks HEAD, so only a given title may
368 overwrite an existing pull request's.
369 body_given: Whether the body came from the caller; the same
370 rule for an existing pull request's body.
371 subjects: The subjects of the commits the branch carries beyond
372 ``origin/<base>``, read once for the checks that need them.
373 """
374
375 branch: str
376 base: str
377 title: str
378 body: str
379 title_given: bool
380 body_given: bool = False
381 subjects: tuple[str, ...] = ()
382
383
384def prepare(
385 root: Path,
386 *,
387 title: str = "",
388 body: str = "",
389 base: str = "main",
390 branch: str = "",
391) -> Plan:
392 """Validate the branch and assemble the pull request shape.
393
394 *branch* is the checked-out branch when the caller read it already;
395 read here otherwise.
396 """
397 branch = branch or git.current_branch(root)
398 if not branch or branch == base:398 ↛ 399line 398 didn't jump to line 399 because the condition on line 398 was never true
399 fail(
400 f"not on a feature branch (on {branch or '(detached)'!r}, base is"
401 f" {base!r}): create a <type>/<slug> branch first"
402 )
403 if not _BRANCH_RE.match(branch) and not branch.startswith("workflow/"):
404 # Reserved workflow branches are the engine's, named by their
405 # workflow identity, outside the feature grammar on purpose.
406 fail(
407 f"branch {branch!r} does not match <type>/<slug>"
408 f" (types: {', '.join(_BRANCH_TYPES)})"
409 )
410 # A merge commit (the engine's MERGE_DEFAULT, `fm integrate`) can
411 # be HEAD, and "Merge branch ..." is never the intent: the last
412 # real subject is. The squash erases the merge commits anyway.
413 default_title, default_body = git.head_message(root)
414 subjects = tuple(git.subjects_ahead(root, base))
415 if not title and default_title.startswith("Merge "):
416 real = [subject for subject in subjects if not subject.startswith("Merge ")]
417 if real:417 ↛ 419line 417 didn't jump to line 419 because the condition on line 417 was always true
418 default_title = real[-1]
419 resolved_title = title or default_title
420 if not _TITLE_RE.match(resolved_title):
421 fail(
422 f"PR title rejected: {resolved_title!r}\n"
423 ' pass a valid one: --title="type(scope): subject"'
424 )
425 return Plan(
426 branch=branch,
427 base=base,
428 title=resolved_title,
429 body=body or default_body,
430 title_given=bool(title),
431 body_given=bool(body),
432 subjects=subjects,
433 )
434
435
436def resolve_base(root: Path, base: str, *, given: bool, branch: str = "") -> str:
437 """The branch the pull request targets.
438
439 A ``--base`` flag wins. Otherwise the parent ``fm start --from``
440 recorded for the branch is the target while origin still has it,
441 and *base* once it is gone: a merged parent's branch is deleted,
442 and the forge retargets the child's pull request to the parent's
443 own base at that moment.
444
445 Origin is asked for the branch, never the remote-tracking ref: a
446 plain fetch does not prune, so the tracking ref of a branch the
447 forge deleted at the merge survives, and a pull request against a
448 branch that is gone is refused with a validation error rather than
449 a sentence.
450 """
451 if given:
452 return base
453 parent, _tip = _stack.stack(root, branch or git.current_branch(root))
454 if not parent:
455 return base
456 if parent in git.remote_branches(root, parent):
457 print(f" base: {parent}, the parent `{footman.prog()} start --from` recorded")
458 return parent
459 print(f" base: {base}; the recorded parent {parent} is gone from origin (merged)")
460 return base
461
462
463def abort_if_merged(repo: Repository, root: Path, branch: str) -> int | None:
464 """Stop before pushing into a pull request that already merged.
465
466 The merge took the pre-push head, so pushing on would open a
467 second pull request carrying the follow-up. That is only true
468 when the local branch still carries the merged head: a branch
469 with the same name cut fresh off the merged base is a new cycle
470 (the release train reuses its reserved branch name every
471 release), and it proceeds. Detection is best-effort: a merged
472 pull request whose head branch is already deleted is found by
473 head sha instead, and one invisible both ways surfaces later as
474 the stray-PR symptom the message names.
475
476 Returns the merged pull request's number when HEAD is the head it
477 merged: there is nothing to push, and the re-run's job is to
478 report the merge. None when no merged pull request claims the
479 branch or the branch is a fresh cycle.
480 """
481 pr = merged_pull_request(repo, root, branch)
482 if pr is None:
483 return None
484 if pr.head_sha and not git.is_ancestor(root, pr.head_sha, "HEAD"):
485 return None
486 if pr.head_sha and pr.head_sha == git.head_sha(root):
487 return pr.number
488 fail(
489 f"PR #{pr.number} for {branch} has already merged.\n"
490 " Your commit is NOT in it and has not been pushed: the merge took"
491 " the pre-push head.\n"
492 " Start a fresh branch off the merged base; check for a stray PR"
493 " before re-running."
494 )
495
496
497def disarm_before_push(repo: Repository, root: Path, branch: str) -> int | None:
498 """Disarm an armed pull request before pushing to it.
499
500 A push to an armed pull request races auto-merge: the merge can
501 take the pre-push head. The disarm narrows that window; it cannot
502 close it, so the merged check runs after it on every path. An
503 unreadable arming state must not block the submit; the push itself
504 surfaces a real transport problem. Returns what
505 livery.workshop._submit.abort_if_merged returns: the number of a
506 pull request that already merged this very head, else None.
507 """
508 try:
509 pr = repo.pr.find_by_head(branch)
510 if pr is not None and repo.pr.is_armed(pr.number):
511 repo.pr.disarm(pr.number)
512 print(f" disarmed PR #{pr.number} before pushing (the race)")
513 except ForgeError as exc:
514 print(f" note: could not read the arming state before pushing ({exc})")
515 return abort_if_merged(repo, root, branch)
516
517
518def _arm_verified(
519 repo: Repository, number: int, *, title: str, message: str, kind: str = ""
520) -> bool:
521 """Arm and read back, retrying a silently lost schedule.
522
523 Each arm attempt follows the merge holds first (the arm shares
524 the merge endpoint): the two quirks are separate, so each keeps
525 its own loop.
526
527 Returns:
528 Whether the pull request merged before this returned, rather
529 than waiting armed for its checks.
530 """
531 for attempt in range(1, _ARM_RETRIES + 1):
532 try:
533 _follow_merge_state(
534 repo, kind, number, repo.pr.arm, number, title=title, message=message
535 )
536 except ForgeError as error:
537 # GitHub arms only a pull request that something blocks, so one
538 # already green is refused with "in clean status", and it refuses
539 # a squash subject it finds too long whatever the state. Merged
540 # when green was the intent either way: a running CI is followed
541 # to its verdict, and a green one merges now.
542 pr = repo.pr.get(number)
543 if pr is None or pr.merged or pr.state != "open":543 ↛ 544line 543 didn't jump to line 544 because the condition on line 543 was never true
544 raise
545 state = repo.checks.status(pr.head_sha).state
546 if state in ("pending", "none"):
547 print(
548 f" arming refused ({error}); CI is still running, so the"
549 " submit follows it and merges when green"
550 )
551 _wait_for_verdict(repo, number)
552 pr = repo.pr.get(number) or pr
553 state = repo.checks.status(pr.head_sha).state
554 elif state == "success":
555 print(
556 f" arming refused ({error}); the pull request is already"
557 " green, so it is merged now"
558 )
559 if state != "success":
560 fail(
561 f"PR #{number}: arming was refused ({error}), and CI is {state}:"
562 f" fix it and `{footman.prog()} submit`. A red pull request"
563 " is never merged."
564 )
565 _follow_merge_state(
566 repo,
567 kind,
568 number,
569 repo.pr.merge_now,
570 number,
571 title=title,
572 message=message,
573 )
574 return True
575 pr = repo.pr.get(number)
576 if pr is not None and pr.merged:
577 return True # the arm found green checks and merged on the spot
578 if repo.pr.is_armed(number):
579 if attempt > 1:579 ↛ 580line 579 didn't jump to line 580 because the condition on line 579 was never true
580 print(f" armed on attempt {attempt} (the forge lost a schedule)")
581 return False
582 fail(
583 f"PR #{number}: the forge lost the auto-merge schedule"
584 f" {_ARM_RETRIES} times; arm it by hand or re-run"
585 )
586
587
588def _arm_and_say(
589 repo: Repository, number: int, *, title: str, message: str, kind: str
590) -> None:
591 """Arm *number* through the verified arm, and print how it ended."""
592 merged = _arm_verified(repo, number, title=title, message=message, kind=kind)
593 print(
594 f" merged: PR #{number}"
595 if merged
596 else f" armed: PR #{number} merges when green"
597 )
598
599
600def _disarm_and_say(repo: Repository, number: int) -> bool:
601 """Take auto-merge off *number*, printing that it did; whether one was set."""
602 if not repo.pr.disarm(number):
603 return False
604 print(f" disarmed PR #{number}")
605 return True
606
607
608def _merge_title(repo: Repository, plan: Plan) -> str:
609 """The subject the squash will carry: the pull request's, not HEAD's.
610
611 A defaulted title tracks HEAD, so a bare re-run on an open
612 many-commit pull request would silently rewrite the squash subject
613 to the last fixup's. A given title wins; otherwise the open pull
614 request's existing title does.
615 """
616 if plan.title_given:
617 return plan.title
618 try:
619 pr = repo.pr.find_by_head(plan.branch)
620 except ForgeError:
621 return plan.title
622 return (pr.title.strip() if pr else "") or plan.title
623
624
625#: The words git uses when origin holds commits a pushed branch does not.
626_BEHIND = ("non-fast-forward", "fetch first", "stale info")
627
628
629def _behind_origin(refusal: str) -> bool:
630 """Whether git refused a push because origin holds commits it lacks.
631
632 A push the forge rejected for its own reasons (``(Internal Server
633 Error)``, a rule) also says "rejected", and reading it as this
634 would name the wrong cause and the wrong advice.
635 """
636 return any(words in refusal for words in _BEHIND)
637
638
639def _push(
640 root: Path, branch: str, *, force: bool, repo: Repository | None = None
641) -> None:
642 """Push *branch*, or force it with a lease and full disclosure.
643
644 With *repo*, the runs still moving for the head the push
645 supersedes are cancelled afterwards (livery.workshop._ci_tasks.
646 cancel_superseded_runs): a stale head's runs would delay the new
647 head's on a shared runner and prove nothing.
648
649 A force is refused on ``workflow/`` branches: recovery reads the
650 ref, the branch's commits are the durable record of what was
651 prepared, and the engine re-prepares instead of rewriting. Before
652 a force, the commits it discards from origin are named: the flag
653 is consent to discard those commits, not consent in the abstract
654 (the flow fetched already, so the listing is current up to the
655 push itself, which the lease guards).
656 """
657 previous = ""
658 if repo is not None:
659 try:
660 previous = git.remote_head(root, branch)
661 except git.GitError:
662 previous = ""
663 if not force:
664 try:
665 git.push(root, branch)
666 except git.GitError as error:
667 if not _behind_origin(str(error)):
668 # The forge refused or failed the push for a reason of
669 # its own (a server error, a rule): its words, verbatim.
670 fail(
671 f"the push of {branch} failed: {error}\n run"
672 f" `{footman.prog()} submit` again once the forge"
673 " answers; nothing was pushed"
674 )
675 fail(
676 f"the push of {branch} was rejected: origin holds commits"
677 " this branch does not. Add the fix as a new commit (the"
678 " squash collapses it anyway) and re-submit; or, if you"
679 " rewrote history deliberately (a rebase onto the base),"
680 f" re-run with `{footman.prog()} submit --force`."
681 )
682 return
683 if branch.startswith("workflow/"):
684 fail(
685 "a workflow branch is never force-pushed: its commits are the"
686 " record recovery reads, and the engine re-prepares instead."
687 f" Re-run the workflow verb, or `{footman.prog()} workflow.abort` it."
688 )
689 if git.remote_head(root, branch):
690 discards = git.run(
691 root, "log", "--format=%s", f"{branch}..origin/{branch}"
692 ).strip()
693 if discards:693 ↛ 697line 693 didn't jump to line 697 because the condition on line 693 was always true
694 listed = "\n".join(f" - {line}" for line in discards.splitlines())
695 print(f" forcing discards these commits on origin/{branch}:\n{listed}")
696 else:
697 print(" forcing; origin holds nothing this branch does not")
698 try:
699 git.push_force(root, branch)
700 except git.GitError as error:
701 if "stale info" not in str(error) and "rejected" not in str(error):
702 raise
703 fail(
704 f"the lease refused the force: origin/{branch} moved past what"
705 f" this clone last saw.\n{error}\n Fetch to see what arrived"
706 " (`git fetch origin`), then decide again and re-run."
707 )
708 if repo is not None and previous and previous != git.head_sha(root):
709 from livery.workshop._ci_tasks import cancel_superseded_runs
710
711 for line in cancel_superseded_runs(repo, previous):711 ↛ 712line 711 didn't jump to line 712 because the loop on line 711 never started
712 print(line)
713
714
715def _required_context_at(root: Path, ref: str) -> str:
716 """The contract's required context at *ref*; "" when unreadable."""
717 try:
718 text = git.run(root, "show", f"{ref}:workshop.toml")
719 except git.GitError:
720 return ""
721 data = tomllib.loads(text)
722 return str((data.get("ci") or {}).get("required-context") or "gate")
723
724
725def _heal_context_rename(
726 repo: Repository, root: Path, plan: Plan, *, fix: bool
727) -> None:
728 """The one order-sensitive transition: a renamed required context.
729
730 The renaming branch produces the new context while protection
731 still demands the old, so its PR can never go green and the
732 post-merge apply never runs. Submit owns the heal because the
733 gate is offline by contract and submit already talks to the
734 forge: detected offline from the branch diff, refused teaching
735 that protection must move before the merge, healed under --fix
736 through the admin ladder with a read-compare keeping re-runs
737 quietly green. Between the apply and this PR's merge other
738 armed merges park (never fail) on the old context, so the
739 teaching recommends `fm submit --fix --armed` to close that
740 window at CI speed; --fix never implies --armed.
741 """
742 ours = _required_context_at(root, plan.branch)
743 theirs = _required_context_at(root, f"origin/{plan.base}")
744 if not ours or not theirs or ours == theirs:
745 return
746 from livery.workshop._extensions import workspace_root
747 from livery.workshop._forge_lane import this_forge
748
749 heal_root = workspace_root()
750 if heal_root is not None and not this_forge(heal_root).supports(
751 "required_contexts"
752 ):
753 # A forge whose protection cannot name contexts has nothing
754 # to move: the rename only renames the emitted pipeline job,
755 # and the pull request goes green on its own.
756 print(
757 f" required context renamed ({theirs!r} -> {ours!r}); this"
758 " forge names no contexts in protection, nothing to heal"
759 )
760 return
761 if fix:
762 from livery.workshop._forge_lane import admin_repository
763
764 admin_repo, admin_var = admin_repository(root)
765 try:
766 # Read through the admin ladder too: GitHub gates the
767 # protection read on admin, and an unreadable state must
768 # not turn the quiet re-run into a re-apply.
769 protection = admin_repo.protection(plan.base)
770 except ForgeError:
771 protection = None
772
773 from livery.workshop._workflow_tasks import required_context_string
774
775 contract = load_contract(root / "workshop.toml")
776 kind = str((contract.get("forge") or {}).get("kind", ""))
777 spelled = required_context_string(kind, ours)
778 if protection is not None and spelled in protection.required_contexts:
779 return # already applied: the re-run is quietly green
780 from livery.forge import RepoConfig
781
782 try:
783 admin_repo.configure(RepoConfig(required_contexts=(spelled,)))
784 except ForgeError as error:
785 used = admin_var or "the everyday token"
786 fail(
787 f"the context rename could not be applied using {used}:\n"
788 f"{error}\n An administrator sets the per-kind admin"
789 f" variable and re-runs `{footman.prog()} submit --fix --armed`,"
790 " or runs"
791 f" `{footman.prog()} workflow.configure` from this branch."
792 )
793 print(
794 f" protection now requires {ours!r} (was {theirs!r}); other"
795 " armed merges park on the old context until this PR lands,"
796 " so keep the rename diff minimal and land it fast."
797 )
798 return
799 fail(
800 f"this branch renames the required CI context ({theirs!r} ->"
801 f" {ours!r}), and protection still demands the old name, so this"
802 " PR can never go green until protection moves BEFORE the merge."
803 f" Heal and submit in one step: `{footman.prog()} submit --fix --armed` (the"
804 " apply parks other armed merges until this lands; --fix never"
805 " implies --armed). Without an admin token in reach, an"
806 f" administrator runs `{footman.prog()} workflow.configure` from this branch."
807 )
808
809
810def label_every_runner(repo: Repository, number: int) -> None:
811 """Put [livery.workshop.EVERY_RUNNER_LABEL][] on pull request *number*.
812
813 The gate then runs every runner for it, where its check legs run on
814 fewer. Idempotent: a label the
815 pull request already carries stays. A forge that refuses, one
816 whose repository does not carry the label among them, fails with
817 the forge's words; the pull request exists by then, so a re-run
818 labels the same one.
819 """
820 try:
821 repo.pr.add_labels(number, (EVERY_RUNNER_LABEL,))
822 except ForgeError as error:
823 fail(
824 f"PR #{number} exists, but {EVERY_RUNNER_LABEL} could not be set on"
825 f" it: {error}\n `{footman.prog()} workflow.configure` creates the"
826 " label on the repository; then re-run"
827 f" `{footman.prog()} submit --every-runner`"
828 )
829 print(
830 f" every runner: labelled {EVERY_RUNNER_LABEL}; the gate runs every"
831 " runner for this pull request"
832 )
833
834
835def push_and_pr(
836 repo: Repository,
837 root: Path,
838 plan: Plan,
839 *,
840 closes: int | None,
841 armed: bool,
842 force: bool = False,
843 every_runner: bool = False,
844) -> int:
845 """Disarm, push, find-or-open the pull request, label and arm as asked."""
846 body = with_closes(plan.body, closes) if closes is not None else plan.body
847 merged = disarm_before_push(repo, root, plan.branch)
848 if merged is not None:
849 # Re-running the submit is its recovery procedure: a head the
850 # pull request already merged has nothing to push, open, or
851 # arm, and the caller's follow reports the merge.
852 print(f" PR #{merged} already merged this head; nothing to push")
853 return merged
854 # Found by branch name, so no push is needed first - and the
855 # refusal below must run before the push: a refusal that leaves a
856 # branch on the remote makes the next submit of a rebuilt branch
857 # fail non-fast-forward.
858 pr = repo.pr.find_by_head(plan.branch)
859 if pr is None:
860 _push(root, plan.branch, force=force, repo=repo)
861 pr = repo.pr.open(plan.branch, plan.base, plan.title, body)
862 print(f" opened PR #{pr.number}: {pr.title}")
863 else:
864 _push(root, plan.branch, force=force, repo=repo)
865 print(f" reusing PR #{pr.number}")
866 if plan.title_given and pr.title != plan.title:
867 repo.pr.update_title(pr.number, plan.title)
868 print(f" title updated: {plan.title}")
869 if plan.body_given and pr.body != body:
870 repo.pr.update_body(pr.number, body)
871 print(" body updated")
872 if every_runner:
873 label_every_runner(repo, pr.number)
874 if armed:
875 _arm_and_say(
876 repo,
877 pr.number,
878 title=_merge_title(repo, plan),
879 message=body,
880 kind=_contract_forge_kind(root),
881 )
882 return pr.number
883
884
885def refuse_ambiguous_title(root: Path, plan: Plan) -> None:
886 """Refuse a defaulted title on a branch more than one commit ahead.
887
888 A defaulted title is trustworthy only when it is unambiguous: one
889 commit ahead, its subject is the intent. More, and whichever
890 commit is HEAD would name the pull request, a guess dressed as a
891 default, so it refuses instead, listing the subjects. A given
892 title never refuses, and a pull request that already exists keeps
893 its title, so the caller asks only on a first open.
894 """
895 if plan.title_given:
896 return
897 subjects = [
898 subject for subject in plan.subjects if not subject.startswith("Merge ")
899 ]
900 if len(subjects) > 1:
901 listed = "\n".join(f" - {subject}" for subject in subjects)
902 fail(
903 f"the branch is {len(subjects)} commits ahead, so no"
904 " commit subject can default the PR title:\n"
905 f"{listed}\n"
906 ' pass the intent: --title="type(scope): subject"'
907 )
908
909
910def _restack_before_push(
911 root: Path, *, branch: str = "", stack: tuple[str, str] | None = None
912) -> bool:
913 """Move a stacked branch onto its moved or merged parent; whether it moved.
914
915 The pull request of a branch whose parent merged is retargeted to
916 main, and a merge of main into it replays the parent's squash
917 against the parent's own commits; the restack moves the branch's
918 own commits alone ([livery.workshop._sync.restack][]), so the push
919 that follows needs the lease. A dirty tree is left to the gate's
920 fold, and a restack with conflicts refuses naming the verb that
921 resolves it.
922 """
923 branch = branch or git.current_branch(root)
924 stack = stack if stack is not None else _stack.stack(root, branch)
925 parent, _tip = stack
926 if not parent or not git.is_clean(root):
927 return False
928 from livery.workshop._sync import restack
929
930 moved = restack(root, branch, interactive=False, stack=stack)
931 if moved is None:931 ↛ 932line 931 didn't jump to line 932 because the condition on line 931 was never true
932 fail(
933 f"{branch} could not follow its parent without conflicts: run"
934 f" `{footman.prog()} sync` where a person can resolve them, then"
935 f" `{footman.prog()} submit` again"
936 )
937 return moved
938
939
940def submit_flow(
941 repo: Repository,
942 root: Path,
943 *,
944 title: str = "",
945 body: str = "",
946 base: str = "main",
947 closes: int = 0,
948 close: bool = True,
949 armed: bool = False,
950 armed_reason: str = "",
951 local_check: bool = True,
952 fix: bool = False,
953 force: bool = False,
954 every_runner: bool = False,
955 follow_to_verdict: bool = True,
956 interval: float = 15,
957 timeout: float = 1800,
958) -> int:
959 """The whole submitting act; returns the pull request number.
960
961 The task shell resolves the repository, the git seam, and the
962 arming ladder; everything after that lives here so tests drive the
963 same flow against livery.forge.testing.FakeForge and a temporary
964 repository.
965 """
966 # Every refusal the arguments decide comes before the gate: the
967 # branch's name, the title's shape, and whether a title can
968 # default at all. A person never pays minutes of gate for a flag
969 # they could have passed, and the title is decided from the
970 # branch as it is, before a fold adds a commit of its own.
971 git.fetch(root)
972 branch = git.current_branch(root)
973 # The stack, read once for the flow: a restack that moved the branch
974 # may have forgotten it, so it is read again after one.
975 stack = _stack.stack(root, branch)
976 moved = _restack_before_push(root, branch=branch, stack=stack)
977 if moved:
978 stack = _stack.stack(root, branch)
979 force = moved or force
980 plan = prepare(root, title=title, body=body, base=base, branch=branch)
981 # A first open only: a pull request that exists, open, merged, or
982 # closed, keeps its title, and the merged and closed cases get
983 # their own refusals further on.
984 if repo.pr.find_by_head(plan.branch, state="all") is None:
985 if not plan.subjects:
986 fail(
987 f"{plan.branch} has no commits beyond origin/{plan.base}, so"
988 " there is nothing to submit: commit first"
989 f' (`{footman.prog()} commit <type> "<subject>"`), then re-run'
990 f" `{footman.prog()} submit`"
991 )
992 refuse_ambiguous_title(root, plan)
993 # The check CI's setup makes with `sync --locked`, made before the
994 # push and before the gate's minutes: a lock that is not current
995 # refuses here, on this machine.
996 from livery.workshop._sync import stale_locks
997
998 for problem in stale_locks(root):
999 fail(
1000 f"{problem}. CI's setup refuses a lock that is not current:"
1001 f" `{footman.prog()} sync` writes it; commit it, then re-run"
1002 f" `{footman.prog()} submit`"
1003 )
1004 if local_check:
1005 _gate(fix, root=root, base=base)
1006 if fix and not git.is_clean(root):
1007 _fold_fixes(root, base)
1008 else:
1009 print(" local check skipped (--no-local-check): CI is now the first verifier")
1010 _heal_context_rename(repo, root, plan, fix=fix)
1011 linked = resolve_closes(repo, plan.branch, closes) if close else None
1012 if linked is not None:1012 ↛ 1013line 1012 didn't jump to line 1013 because the condition on line 1012 was never true
1013 print(f" Closes #{linked} on merge")
1014 elif not close:
1015 print(" closes nothing (--no-close): the branch's issue stays open")
1016 parent, _tip = stack
1017 if armed and parent and plan.base == parent:
1018 # The forge refuses to arm a pull request into a branch with no
1019 # required checks, and arming into the parent would land the
1020 # child there, not on main: the arm waits for the parent's merge.
1021 armed = False
1022 print(
1023 f" arming: off - {parent} is still open; after it merges, run"
1024 f" `{footman.prog()} sync` then `{footman.prog()} submit --armed`"
1025 )
1026 elif armed_reason:
1027 print(f" arming: {'on' if armed else 'off'} - decided by {armed_reason}")
1028 number = push_and_pr(
1029 repo,
1030 root,
1031 plan,
1032 closes=linked,
1033 armed=armed,
1034 force=force,
1035 every_runner=every_runner,
1036 )
1037 if not follow_to_verdict:
1038 return number
1039 heals = 0
1040
1041 def trace_the_run() -> None:
1042 """Hand the run just followed to this command's own trace, if any.
1043
1044 Called at every way out of the watch, a red run included: a timeline
1045 is wanted most where something went wrong. Nothing is kept in the
1046 ordinary case, and nothing here can fail the submit.
1047 """
1048 if traced := drop_run(repo, root):
1049 print(f" {traced}")
1050
1051 while True:
1052 try:
1053 follow_pull_request(
1054 repo, plan.branch, root, interval=interval, timeout=timeout
1055 )
1056 except SystemExit as exc:
1057 code = exc.code if isinstance(exc.code, int) else 1
1058 if code == EXIT_DISARMED and not armed:
1059 # The submit was asked not to arm, so a green parked PR is
1060 # this run finishing its job, not a blocker: prose above
1061 # already said where it is parked, and the exit is clean.
1062 # 11 still surfaces on an *armed* submit, where a gone
1063 # schedule means something interfered.
1064 print(f" done: CI is green and PR #{number} awaits your call")
1065 trace_the_run()
1066 return number
1067 if code in (EXIT_CONFLICTS, EXIT_BEHIND) and heals < _MAX_HEALS:
1068 heals += 1
1069 print(
1070 f" exit {code}: integrating origin/{plan.base} and"
1071 f" re-submitting (self-heal {heals}/{_MAX_HEALS})"
1072 )
1073 disarm_before_push(repo, root, plan.branch)
1074 before = git.head_sha(root)
1075 try:
1076 git.integrate(root, plan.base)
1077 except git.GitError as exc2:
1078 fail(
1079 f"the merge stopped on a conflict; resolve it, commit,"
1080 f" and re-run `{footman.prog()} submit`:\n{exc2}"
1081 )
1082 # The merge can bring the code this process runs, and the
1083 # gate must judge the merged tree with the code it carries:
1084 # the rest is a fresh submit on that code. Re-running the
1085 # verb is the recovery, so nothing is lost by the handoff.
1086 from livery.workshop._sync import continue_on_moved_code
1087
1088 continue_on_moved_code(root, before, git.head_sha(root), verb="submit")
1089 if local_check:
1090 _gate(root=root, base=plan.base)
1091 number = push_and_pr(
1092 repo,
1093 root,
1094 plan,
1095 closes=linked,
1096 armed=armed,
1097 force=force,
1098 every_runner=every_runner,
1099 )
1100 continue
1101 trace_the_run()
1102 raise
1103 # Before the tidy moves this checkout off the branch, whose head is
1104 # how the run is found.
1105 trace_the_run()
1106 _tidy_after_merge(repo, root, plan.branch, plan.base, number)
1107 return number
1108
1109
1110def _gate(fix: bool = False, *, root: Path, base: str = "main") -> None:
1111 """The local gate; red raises before any network call.
1112
1113 Asks the proved record (`livery.workshop._proved`) whether every
1114 unit for the current checkout is already proved green; skips when
1115 all units are proved, otherwise runs ``fm check`` (which runs only
1116 the unproved units).
1117 """
1118 from livery.git import fetched_snapshot
1119 from livery.workshop._ci_context import state_store
1120 from livery.workshop._quality import _proved_decision, check, say_skipped
1121 from livery.workshop._shard import ONE
1122
1123 with contextlib.suppress(git.GitError):
1124 git.fetch(root)
1125 with fetched_snapshot(state_store(root)):
1126 decided = _proved_decision(root, run=None, point="", shard=ONE)
1127 if decided is not None:
1128 _ctx_all, decision, _plat = decided
1129 if not decision.running:1129 ↛ 1133line 1129 didn't jump to line 1133 because the condition on line 1129 was always true
1130 total = len(decision.proved)
1131 say_skipped(f"gate: all {total} unit(s) proved green; skipping")
1132 return
1133 n = len(decision.running)
1134 print(f" gate: {n} unit(s) not proved green; running the gate")
1135 else:
1136 print(" gate: no proved record yet; running the gate")
1137 check(fix=fix, base=base)
1138
1139
1140def _fold_fixes(root: Path, base: str) -> None:
1141 """Put the gate's rewrites into the branch, consented by ``--fix``.
1142
1143 Amended into HEAD while the commit is still the branch's own and
1144 unpushed; otherwise a follow-up commit, which the squash merge
1145 collapses away. Amending is never applied to a pushed or base
1146 commit: rewriting either would force-push or rewrite history the
1147 remote already trusts.
1148 """
1149 git.fetch(root)
1150 branch, head = git.position(root)
1151 pushed = git.remote_head(root, branch) == head
1152 if pushed or not git.subjects_ahead(root, base):
1153 git.commit_all(root, "chore: apply gate fixes")
1154 print(" gate fixes committed (the squash merge collapses this)")
1155 else:
1156 git.amend_all(root)
1157 print(" gate fixes amended into HEAD")
1158
1159
1160@submit.default(serial=True)
1161def submit_default(
1162 title: Annotated[str, doc("PR title; defaults to HEAD's subject")] = "",
1163 body: Annotated[str, doc("PR body; defaults to HEAD's body")] = "",
1164 base: Annotated[str, doc("target branch")] = "main",
1165 closes: Annotated[int, doc("issue to close on merge; 0 = from branch name")] = 0,
1166 close: Annotated[bool, doc("close the branch's issue on merge")] = True,
1167 armed: Annotated[
1168 bool,
1169 footman.env("WORKSHOP_AUTOMERGE"),
1170 footman.default(ci_automerge),
1171 doc("arm auto-merge (ladder: flag, WORKSHOP_AUTOMERGE, [ci] automerge)"),
1172 ] = False,
1173 local_check: Annotated[
1174 bool, doc(f"run `{footman.prog()} check` locally before pushing")
1175 ] = True,
1176 fix: Annotated[bool, doc("heal mechanical gate findings, fold into HEAD")] = False,
1177 force: Annotated[
1178 bool, doc("force-push with a lease after a deliberate history rewrite")
1179 ] = False,
1180 every_runner: Annotated[
1181 bool,
1182 doc(
1183 f"label the PR {EVERY_RUNNER_LABEL} so the gate runs every runner: for"
1184 " a change only another platform reaches while the pull request's"
1185 " legs run on fewer"
1186 ),
1187 ] = False,
1188 follow: Annotated[bool, doc("watch until it lands or says what stopped it")] = True,
1189 interval: Annotated[int, doc("watch poll seconds")] = 15,
1190 timeout: Annotated[int, doc("watch deadline seconds")] = 1800,
1191) -> None:
1192 """Gate, push, open-or-reuse the PR, arm, and watch it land.
1193
1194 Idempotent: re-running it is the recovery procedure. Exits 10 and
1195 17 self-heal by integrating the base and re-submitting; the other
1196 verdict codes surface unchanged (see livery.workshop._verdict).
1197 ``--fix`` runs the gate's format and lint in their fix modes and
1198 folds any rewrites into the branch before pushing: amended into
1199 HEAD while unpushed, a follow-up commit otherwise. ``--no-close``
1200 submits without the close footer, for a branch that carries
1201 preparatory work on an issue the merge must leave open.
1202 ``--every-runner`` labels the pull request ``ci:every-runner``, so
1203 the gate runs every runner for it where its check legs run on
1204 fewer: for a change to a line only another platform reaches, which
1205 a narrowed run judges red by name.
1206 """
1207 root = _root()
1208 from livery.workshop._forge_lane import this_repository
1209
1210 repo = this_repository(root)
1211 reason = arming_reason(armed=armed, flag_given=footman.given("armed"))
1212 base = resolve_base(root, base, given=footman.given("base"))
1213 with forge_failures_named():
1214 submit_flow(
1215 repo,
1216 root,
1217 title=title,
1218 body=body,
1219 base=base,
1220 closes=closes,
1221 close=close,
1222 armed=armed,
1223 armed_reason=reason,
1224 local_check=local_check,
1225 force=force,
1226 fix=fix,
1227 every_runner=every_runner,
1228 follow_to_verdict=follow,
1229 interval=interval,
1230 timeout=timeout,
1231 )
1232
1233
1234@contextlib.contextmanager
1235def forge_failures_named() -> Generator[None]:
1236 """Fail with the forge's own words when it refuses or does not answer.
1237
1238 A submit is safe to run again, so a read that timed out or a write
1239 the forge refused ends the run with the forge's message and that
1240 advice, not a traceback.
1241 """
1242 try:
1243 yield
1244 except ForgeError as error:
1245 fail(
1246 f"{error}\n `{footman.prog()} submit` is safe to run again: it"
1247 " starts from what the forge already has"
1248 )
1249
1250
1251def worktree_for(root: Path, branch: str) -> str:
1252 """The linked worktree holding *branch*; "" when none does or *root* does."""
1253 listing = git.run(root, "worktree", "list", "--porcelain")
1254 tree = ""
1255 current: dict[str, str] = {}
1256 for line in [*listing.splitlines(), ""]:
1257 if not line.strip():
1258 if current.get("branch", "").endswith(f"refs/heads/{branch}"):
1259 tree = current.get("worktree", "")
1260 current = {}
1261 continue
1262 key, _, value = line.partition(" ")
1263 current[key] = value
1264 if tree and Path(tree).resolve() == root.resolve():
1265 return ""
1266 return tree
1267
1268
1269def only_local_work(root: Path, branch: str, *, merged_head: str = "") -> str:
1270 """Why *branch* holds work that exists nowhere else; "" when safe.
1271
1272 The one keep-or-drop rule: ``fm issue.close``, ``fm issue.stop``,
1273 the submit's own teardown after a merge, the sweep, and ``fm sync``
1274 all ask it, so what they destroy is decided in one place. Dirt is
1275 looked for where the branch actually lives: this checkout when it
1276 stands on the branch, the branch's linked worktree otherwise.
1277
1278 *merged_head* is the head a merged pull request took. A tip equal
1279 to it holds nothing only here: the merge took every commit, and
1280 the squash rewrote them, so the remote's ancestry says nothing
1281 (after a squash the branch's commits are never ancestors of the
1282 base, and the forge deletes the remote branch). A tip past it
1283 holds the commits made after the merge. A tip the merged head
1284 does not reach was rewritten after the merge, and the ancestry
1285 rule below judges it. Without a merged head, ahead is measured
1286 against the remote branch when one exists, and against the base
1287 when none does.
1288 """
1289 if git.current_branch(root) == branch and not git.is_clean(root):
1290 return "uncommitted changes"
1291 tree = worktree_for(root, branch)
1292 if tree:
1293 status = git.run(root, "-C", tree, "status", "--porcelain").strip()
1294 if status:
1295 return f"uncommitted changes in the worktree {tree}"
1296 if merged_head:
1297 tip = git.object_id(root, f"refs/heads/{branch}")
1298 if tip == merged_head:
1299 return ""
1300 if git.is_ancestor(root, merged_head, tip):1300 ↛ 1305line 1300 didn't jump to line 1305 because the condition on line 1300 was always true
1301 count = git.run(
1302 root, "rev-list", "--count", f"{merged_head}..{tip}"
1303 ).strip()
1304 return f"{count} commit(s) past the merged head"
1305 remote = f"origin/{branch}"
1306 upstream = remote if branch in git.remote_branches(root, "") else "origin/main"
1307 count = git.run(root, "rev-list", "--count", f"{upstream}..{branch}").strip()
1308 if count.isdigit() and int(count) > 0:
1309 where = "the remote branch" if upstream == remote else "any remote"
1310 return f"{count} commit(s) not on {where}"
1311 return ""
1312
1313
1314def merged_pull_request(
1315 repo: Repository, root: Path, branch: str
1316) -> PullRequest | None:
1317 """The merged pull request *branch* was the head of, or None.
1318
1319 [livery.workshop._forge_lane.pull_request_for][] finds it, by head
1320 branch and then by the branch's head commit; a forge that cannot
1321 be asked raises.
1322 """
1323 from livery.workshop._forge_lane import pull_request_for
1324
1325 pr = pull_request_for(repo, root, branch)
1326 return pr if pr is not None and pr.merged else None
1327
1328
1329def _tidy_after_merge(
1330 repo: Repository, root: Path, branch: str, base: str, number: int
1331) -> None:
1332 """Remove the linked worktree a merged submission stood in.
1333
1334 The submit is the flow that opened the tree (through ``fm start``),
1335 so it removes the tree when the follow sees the merge, the way
1336 ``fm issue.close`` does from inside one; the janitor is the net
1337 for a submit that was not followed to the end. A tree that holds
1338 something the merge did not take is kept and named. The main
1339 checkout keeps its branch: a person reads the run's logs from it,
1340 and the janitor's branch rule drops it later.
1341
1342 The janitor runs with any ``fm`` command, so another one may sweep
1343 the tree once its branch merged, before or while this tidy runs.
1344 That leaves nothing to do: the tidy says so and moves the process
1345 out of the directory that is gone. A missing executable is not
1346 that, and still raises.
1347 """
1348 try:
1349 _tidy_tree(repo, root, branch, base, number)
1350 except (FileNotFoundError, NotADirectoryError):
1351 # A process started in a directory that is gone raises
1352 # FileNotFoundError on POSIX and NotADirectoryError on Windows.
1353 if root.is_dir():
1354 raise
1355 _swept(root)
1356
1357
1358def _swept(root: Path) -> None:
1359 """Say the tree at *root* was swept already, standing the process somewhere real."""
1360 print(f" the worktree {root} is gone already: swept after the merge")
1361 home = root.parent
1362 while not home.is_dir() and home != home.parent:1362 ↛ 1363line 1362 didn't jump to line 1363 because the condition on line 1362 was never true
1363 home = home.parent
1364 os.chdir(home)
1365
1366
1367def _tidy_tree(
1368 repo: Repository, root: Path, branch: str, base: str, number: int
1369) -> None:
1370 """The tidy itself, for a tree that may vanish under it."""
1371 if not root.is_dir():
1372 _swept(root)
1373 return
1374 try:
1375 git_dir = git.run(root, "rev-parse", "--git-dir").strip()
1376 common_dir = git.run(root, "rev-parse", "--git-common-dir").strip()
1377 except git.GitError:
1378 return # no checkout to speak of, so no linked worktree to remove
1379 if git_dir == common_dir:
1380 return
1381 pr = repo.pr.get(number)
1382 merged_head = pr.head_sha if pr is not None and pr.merged else ""
1383 why = only_local_work(root, branch, merged_head=merged_head)
1384 if why:
1385 print(
1386 f" kept the worktree {root}: it holds {why};"
1387 f" `{footman.prog()} issue.close --discard` or"
1388 f" `{footman.prog()} abandon` removes it"
1389 )
1390 return
1391 teardown_branch(repo, root, branch, base)
1392
1393
1394def teardown_branch(
1395 repo: Repository,
1396 root: Path,
1397 branch: str,
1398 base: str,
1399) -> None:
1400 """The one branch teardown every stop verb wears; idempotent.
1401
1402 Disarm, close the PR (a merged one is left alone), delete the
1403 remote and local branch, and step back onto an up-to-date *base*
1404 when standing on *branch*. Mechanism only: state gates, forces,
1405 and refusals are the calling policy's job
1406 (livery.workshop._submit.abandon_flow for a feature,
1407 ``workflow.abort`` for a reserved workflow), so the policies can
1408 never drift apart. Removing a
1409 linked worktree moves the process into the main checkout first:
1410 Windows refuses to remove a directory a process stands in, and
1411 the shell that ran the verb is told where to go. A real move of
1412 the process directory is a serial task's to make (footman refuses
1413 it in a parallel one), so every verb that reaches this from
1414 inside a worktree is declared ``serial``.
1415 """
1416 pr = repo.pr.find_by_head(branch)
1417 if pr is not None and not pr.merged:
1418 _disarm_and_say(repo, pr.number)
1419 repo.pr.close(pr.number)
1420 print(f" closed PR #{pr.number}")
1421 if repo.branch_exists(branch):
1422 repo.delete_branch(branch)
1423 print(f" deleted origin/{branch}")
1424 git_dir = git.run(root, "rev-parse", "--git-dir").strip()
1425 common_dir = git.run(root, "rev-parse", "--git-common-dir").strip()
1426 standing = git.current_branch(root) == branch
1427 if standing and git_dir != common_dir:
1428 # A linked worktree cannot switch to *base*: the main
1429 # checkout holds it. The worktree itself is the leftover, so
1430 # it is removed from the main checkout, branch and all. The
1431 # shell that ran this stands in a deleted directory afterwards
1432 # and is told where to go.
1433 import os
1434
1435 main_root = git.main_checkout(root)
1436 os.chdir(main_root)
1437 git.run(main_root, "worktree", "remove", "--force", str(root))
1438 if git.local_branch_exists(main_root, branch):1438 ↛ 1440line 1438 didn't jump to line 1440 because the condition on line 1438 was always true
1439 git.delete_branch(main_root, branch)
1440 print(f" removed the worktree {root} and deleted {branch}")
1441 print(f" this shell's directory is gone: cd {main_root}")
1442 return
1443 if standing:
1444 git.switch(root, base)
1445 git.integrate(root, base)
1446 else:
1447 tree = worktree_for(root, branch)
1448 if tree:
1449 git.run(root, "worktree", "remove", "--force", tree)
1450 print(f" removed the worktree {tree}")
1451 if git.local_branch_exists(root, branch):
1452 git.delete_branch(root, branch)
1453 # Only a checkout that stood on the branch moved to the base.
1454 print(f" deleted {branch}" + (f"; back on {base}" if standing else ""))
1455
1456
1457def abandon_flow(repo: Repository, root: Path, branch: str, base: str) -> None:
1458 """Give the feature up: close the PR, delete both branches; idempotent.
1459
1460 A dirty tree refuses before anything else moves: abandoning
1461 deletes the branch, and uncommitted work must be a person's
1462 explicit loss, not a side effect.
1463 """
1464 if not branch or branch == base:1464 ↛ 1465line 1464 didn't jump to line 1465 because the condition on line 1464 was never true
1465 fail(f"not on a feature branch (on {branch or '(detached)'!r})")
1466 if branch == git.current_branch(root):
1467 if not git.is_clean(root):
1468 fail(
1469 "the working tree has uncommitted changes; commit or discard"
1470 " them before abandoning"
1471 )
1472 else:
1473 tree = worktree_for(root, branch)
1474 if tree and git.run(root, "-C", tree, "status", "--porcelain").strip():
1475 fail(
1476 f"the worktree {tree} has uncommitted changes; commit or"
1477 " discard them before abandoning"
1478 )
1479 pr = repo.pr.find_by_head(branch)
1480 if pr is not None and pr.merged:1480 ↛ 1481line 1480 didn't jump to line 1481 because the condition on line 1480 was never true
1481 fail(f"PR #{pr.number} already merged: nothing to abandon")
1482 if pr is None:
1483 print(f" no open pull request for {branch}")
1484 teardown_branch(repo, root, branch, base)
1485
1486
1487@footman.task(serial=True)
1488def abandon(
1489 branch: Annotated[Arg[str], doc("a branch to give up; this one when absent")] = "",
1490) -> None:
1491 """Give up a feature: close the PR, delete the branches, return to base.
1492
1493 This branch when none is named, or the named one from anywhere:
1494 its linked worktree goes with it. Disarms and closes the pull
1495 request, deletes the remote and the local branch, and leaves this
1496 checkout on an up-to-date base when it stood on the branch. A
1497 dirty tree, here or in the branch's worktree, refuses first.
1498 Idempotent: a second run finds nothing left to undo.
1499 """
1500 root = _root()
1501 from livery.workshop._forge_lane import this_repository
1502
1503 abandon_flow(
1504 this_repository(root), root, branch or git.current_branch(root), "main"
1505 )
1506
1507
1508def pull_request_named(
1509 repo: Repository, root: Path, ref: str, *, allow_closed: bool = False
1510) -> PullRequest:
1511 """Find the pull request *ref* numbers; this branch's when *ref* is empty.
1512
1513 *ref* is read by [livery.workshop._submit.parse_number][], the
1514 rule the issue verbs read an issue number by, so ``#123`` and
1515 ``123`` name the same pull request. On the current branch the open
1516 pull request is looked up by the branch's name, and when there is
1517 none, a merged one by the branch's head commit, which outlives a
1518 head branch the merge deleted: after a merge, the answer is that
1519 it merged. Every other answer fails and names the next action: a
1520 *ref* that is no number, a number no pull request has, a branch
1521 without an open or merged pull request, and, unless *allow_closed*
1522 is set, a pull request closed without merging.
1523
1524 Args:
1525 repo: The workspace's repository on its forge.
1526 root: The checkout whose current branch an empty *ref* means.
1527 ref: A pull request number, with or without ``#``; empty for
1528 the current branch's.
1529 allow_closed: Return a closed-unmerged pull request instead of
1530 failing (for read-only inspection verbs such as ``status``,
1531 ``ci.status``, and ``ci.logs``).
1532
1533 Returns:
1534 The pull request. What a merged or closed one means is the
1535 verb's to decide.
1536 """
1537 prog = footman.prog()
1538 if ref:
1539 number = parse_number(ref)
1540 if number is None:
1541 fail(
1542 f"{ref!r} is not a pull request number: name one, 123 or"
1543 " #123, or none for this branch's"
1544 )
1545 pr = repo.pr.get(number)
1546 if pr is None:
1547 fail(f"no pull request #{number} on the forge: check the number")
1548 else:
1549 branch = git.current_branch(root)
1550 if not branch:
1551 fail("HEAD is detached, so no branch names a pull request: name its number")
1552 pr = repo.pr.find_by_head(branch)
1553 if pr is None:
1554 done = repo.pr.find_by_head_sha(git.head_sha(root))
1555 pr = done if done is not None and done.merged else None
1556 if pr is None:
1557 fail(
1558 f"no open pull request for {branch}: `{prog} submit` opens"
1559 " one, or name a pull request's number"
1560 )
1561 if not allow_closed and pr.state != "open" and not pr.merged:
1562 fail(
1563 f"PR #{pr.number} is closed: `{prog} submit` on {pr.head_branch}"
1564 " opens a new one"
1565 )
1566 return pr
1567
1568
1569def _merged_already(pr: PullRequest) -> bool:
1570 """Whether *pr* has merged, printing that nothing is left to do when it has."""
1571 if pr.merged:
1572 print(f" PR #{pr.number} has already merged; nothing to do")
1573 return pr.merged
1574
1575
1576def arm_flow(repo: Repository, root: Path, pr: PullRequest) -> None:
1577 """Arm *pr* to merge when green, as ``fm submit --armed`` arms; idempotent.
1578
1579 The squash takes the pull request's own title and body. An armed
1580 pull request is left as it is, and a merged one is the end the arm
1581 aims at: each line says so, and neither is an error.
1582 """
1583 if _merged_already(pr):
1584 return
1585 if repo.pr.is_armed(pr.number):
1586 print(f" PR #{pr.number} is armed already; nothing changed")
1587 return
1588 _arm_and_say(
1589 repo,
1590 pr.number,
1591 title=pr.title.strip(),
1592 message=pr.body,
1593 kind=_contract_forge_kind(root),
1594 )
1595
1596
1597def disarm_flow(repo: Repository, pr: PullRequest) -> None:
1598 """Take auto-merge off *pr* and leave it open; idempotent.
1599
1600 An unarmed pull request is left as it is, and the line says so. A
1601 merged one refuses: the merge the disarm was to prevent has
1602 happened.
1603 """
1604 if pr.merged:
1605 fail(f"PR #{pr.number} has already merged: too late to disarm")
1606 if not _disarm_and_say(repo, pr.number):
1607 print(f" PR #{pr.number} is not armed; nothing changed")
1608
1609
1610def merge_flow(
1611 repo: Repository, root: Path, pr: PullRequest, *, title: str = ""
1612) -> None:
1613 """Merge the pull request *pr* as soon as possible; a merged one is done.
1614
1615 Merge means merge asap, never merge-if-instant-else-fail: checks
1616 still running are followed to their verdict, the forge's own
1617 holds (the mergeability recompute, the settling beat) are
1618 followed to completion, and the task's timeout is the only
1619 backstop. Red refuses at once naming the state, behind base
1620 teaches integrate, and merging red stays a person's act in the
1621 forge's own interface.
1622
1623 Whether *pr* is behind its base is judged at HEAD when *pr* is
1624 this branch's pull request, since HEAD is what the next submit
1625 pushes, and at the head the forge holds for any other, which the
1626 fetch brings here. A head this clone cannot see is left to the
1627 forge's own refusal.
1628 """
1629 if _merged_already(pr):
1630 return
1631 own = pr.head_branch == git.current_branch(root)
1632 _wait_for_verdict(repo, pr.number, local_head=git.head_sha(root) if own else "")
1633 # The wait follows a head that moves, so the verdict is read for
1634 # the head it settled on, not the one *pr* was read with.
1635 pr = repo.pr.get(pr.number) or pr
1636 status = repo.checks.status(pr.head_sha)
1637 if status.state == "failure":
1638 fail(
1639 f"CI is red for PR #{pr.number}: fix it and `{footman.prog()} submit`."
1640 " This verb never merges red."
1641 )
1642 git.fetch(root)
1643 head = "HEAD" if own else git.sha_of(root, pr.head_sha)
1644 if head and not git.is_ancestor(root, f"origin/{pr.base_branch}", head):
1645 where = "" if own else f" on {pr.head_branch},"
1646 fail(
1647 f"PR #{pr.number} is behind {pr.base_branch}:{where}"
1648 f" `{footman.prog()} integrate`, then `{footman.prog()} submit`,"
1649 " and merge again"
1650 )
1651 subject = title or pr.title
1652 _follow_merge_state(
1653 repo,
1654 _contract_forge_kind(root),
1655 pr.number,
1656 repo.pr.merge_now,
1657 pr.number,
1658 title=subject,
1659 )
1660 print(f" merged PR #{pr.number}")
1661
1662
1663def _named(ref: str) -> tuple[Repository, Path, PullRequest]:
1664 """The workspace's repository, its root, and the pull request *ref* names."""
1665 root = _root()
1666 from livery.workshop._forge_lane import this_repository
1667
1668 repo = this_repository(root)
1669 return repo, root, pull_request_named(repo, root, ref)
1670
1671
1672def _open_pull_numbers() -> list[str]:
1673 """Completion: the open pull request numbers, newest first; never raises.
1674
1675 Offline, token-less, or outside a repository costs the
1676 suggestions, never the command.
1677 """
1678 try:
1679 from livery.workshop._forge_lane import this_repository
1680
1681 repo = this_repository(_root())
1682 return [str(row.number) for row in repo.pr.list(state="open")]
1683 except Exception:
1684 return []
1685
1686
1687#: The pull request argument the PR verbs share: its help text, and
1688#: the open pull requests' numbers as its completion. Module level,
1689#: because footman reads a task's annotations in its module's namespace.
1690PullRef = Annotated[
1691 Arg[str],
1692 doc("a pull request number; this branch's when absent"),
1693 suggest(_open_pull_numbers, strict=False),
1694]
1695_PullRef = PullRef
1696
1697
1698@submit.task(name="merge")
1699def submit_merge(
1700 pr: _PullRef = "",
1701 title: Annotated[str, doc("squash subject; defaults to the PR title")] = "",
1702) -> None:
1703 """Merge a PR as soon as possible: this branch's, or the one numbered.
1704
1705 Waits for a running CI's verdict and follows the forge's own
1706 holds to completion; refuses red or behind-base at once, saying
1707 why, and refuses a pull request closed without merging. A pull
1708 request that has merged already is done: the verb says so and
1709 succeeds, so a re-run is the recovery. A merge that lands while it
1710 runs is success too, as livery.forge.PullRequests.merge_now reads
1711 one.
1712 """
1713 repo, root, found = _named(pr)
1714 merge_flow(repo, root, found, title=title)
1715
1716
1717@submit.task(name="arm")
1718def submit_arm(pr: _PullRef = "") -> None:
1719 """Arm a PR to merge when green: this branch's, or the one numbered.
1720
1721 Arms as ``fm submit --armed`` arms, with the pull request's own
1722 title as the squash subject, and reads the schedule back. A pull
1723 request already green is merged at once, since a forge that arms
1724 only a blocked pull request refuses. An armed one is left as it
1725 is, and a merged one is done: the verb says so and succeeds, also
1726 on the branch once its head branch is gone. One closed without
1727 merging refuses.
1728 """
1729 repo, root, found = _named(pr)
1730 arm_flow(repo, root, found)
1731
1732
1733@submit.task(name="disarm")
1734def submit_disarm(pr: _PullRef = "") -> None:
1735 """Take auto-merge off a PR and leave it open: this branch's, or the one numbered.
1736
1737 The pull request and its branch stay as they are, so it waits
1738 unmerged until ``fm submit.arm`` arms it again. An unarmed one is
1739 left as it is. A merged one refuses, since the merge the disarm
1740 was to prevent has happened, and so does one closed without
1741 merging.
1742 """
1743 repo, _root_dir, found = _named(pr)
1744 disarm_flow(repo, found)