1"""``fm submit``: get the branch onto the remote, verified, and landed.
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.
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.
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"""
48 EXIT_BEHIND,
49 EXIT_CONFLICTS,
50 EXIT_DISARMED,
51 EXIT_UNREACHABLE,
52 ForgeUnreachable,
53 Pending,
54 follow,
55 follow_pull_request,
56)
59 "submit", help="Gate, push, open-or-reuse the PR, arm, and watch it land"
60)
62#: Branch names submit accepts: the conventional type, a slash, a slug
63#: that may open with an issue number (``feat/41-title-rules``).
68#: PR titles follow the published commit convention, breaking
69#: marker included.
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.
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.
84#: How often a followed merge hold re-tries or re-reads, seconds.
89 """The forge the contract names; [livery.workshop._forge_lane.forge_kind][]."""
90 from livery.workshop._forge_lane import forge_kind
92 return forge_kind(root)
96 """The status contexts CI actually reports for *sha*.
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))
113 """Fail when protection requires a context nothing reports.
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 )
137 """Wait until *number*'s head has a completed combined verdict.
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
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)
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
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 )
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.
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
226 settling_checked = False
227 local_head = str(kwargs.pop("local_head", "") or "")
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}")
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 )
275 root = workspace_root()
276 if root is None:
277 fail("no workspace: no workshop.toml above the working directory")
278 return root
282 """The committed repo policy: the workspace contract's ``[ci] automerge``."""
283 root = workspace_root()
284 if root is None:
286 contract = load_contract(root / "workshop.toml")
287 return bool((contract.get("ci") or {}).get("automerge", False))
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)"
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
311 """Read the issue or pull request number *token* spells; None when it spells none.
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
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
331 """The issue submit will link, per the three guards.
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
359 """Everything a push and pull request need, validated, no network.
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 """
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.
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 )
437 """The branch the pull request targets.
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.
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
464 """Stop before pushing into a pull request that already merged.
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.
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 )
498 """Disarm an armed pull request before pushing to it.
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)
519 repo: Repository, number: int, *, title: str, message: str, kind: str = ""
520) -> bool:
521 """Arm and read back, retrying a silently lost schedule.
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.
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 )
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 )
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
609 """The subject the squash will carry: the pull request's, not HEAD's.
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
625#: The words git uses when origin holds commits a pushed branch does not.
630 """Whether git refused a push because origin holds commits it lacks.
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)
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.
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.
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
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)
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")
726 repo: Repository, root: Path, plan: Plan, *, fix: bool
727) -> None:
728 """The one order-sensitive transition: a renamed required context.
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
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
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
773 from livery.workshop._workflow_tasks import required_context_string
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
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 )
811 """Put [livery.workshop.EVERY_RUNNER_LABEL][] on pull request *number*.
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 )
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
886 """Refuse a defaulted title on a branch more than one commit ahead.
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 )
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.
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
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
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 gate: 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.
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
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 gate:
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(" gate skipped (--no-gate): 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
1041 def trace_the_run() -> None:
1042 """Hand the run just followed to this command's own trace, if any.
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}")
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
1088 continue_on_moved_code(root, before, git.head_sha(root), verb="submit")
1089 if gate:
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
1111 """The local gate; red raises before any network call.
1113 The chain of this machine's own green gates
1114 (`livery.workshop._gate_record`) is walked from HEAD's tree: a
1115 chain that reaches a root, a full gate here or a tree in HEAD's
1116 history that CI's record holds, proves the tree and the gate is
1117 skipped, saying so. Otherwise the reflex runs, ``fm check`` as a person
1118 runs it, which gates the delta from the nearest proved tree and
1119 records HEAD's tree at its end. *fix* runs format and lint in
1120 their fix modes, so mechanical findings heal instead of failing;
1121 the caller folds any rewrites into the branch before pushing.
1122 """
1123 from livery.workshop._gate_record import covering
1124 from livery.workshop._quality import check, say_skipped
1126 with contextlib.suppress(git.GitError):
1127 git.fetch(root)
1128 proof, why = covering(root, base=base)
1129 if proof is not None:
1130 by = " by fm check" if proof.steps else ""
1131 say_skipped(
1132 f"gate: tree {proof.tree[:12]} proved green{by}"
1133 f" ({proof.describe()}); skipping"
1134 )
1135 return
1136 print(f" gate: {why}; running the gate")
1137 check(fix=fix, base=base)
1141 """Put the gate's rewrites into the branch, consented by ``--fix``.
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")
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 gate: Annotated[bool, doc(f"run `{footman.prog()} check` first")] = True,
1174 fix: Annotated[bool, doc("heal mechanical gate findings, fold into HEAD")] = False,
1175 force: Annotated[
1176 bool, doc("force-push with a lease after a deliberate history rewrite")
1177 ] = False,
1178 every_runner: Annotated[
1179 bool,
1180 doc(
1181 f"label the PR {EVERY_RUNNER_LABEL} so the gate runs every runner: for"
1182 " a change only another platform reaches while the pull request's"
1183 " legs run on fewer"
1184 ),
1185 ] = False,
1186 follow: Annotated[bool, doc("watch until it lands or says what stopped it")] = True,
1187 interval: Annotated[int, doc("watch poll seconds")] = 15,
1188 timeout: Annotated[int, doc("watch deadline seconds")] = 1800,
1189) -> None:
1190 """Gate, push, open-or-reuse the PR, arm, and watch it land.
1192 Idempotent: re-running it is the recovery procedure. Exits 10 and
1193 17 self-heal by integrating the base and re-submitting; the other
1194 verdict codes surface unchanged (see livery.workshop._verdict).
1195 ``--fix`` runs the gate's format and lint in their fix modes and
1196 folds any rewrites into the branch before pushing: amended into
1197 HEAD while unpushed, a follow-up commit otherwise. ``--no-close``
1198 submits without the close footer, for a branch that carries
1199 preparatory work on an issue the merge must leave open.
1200 ``--every-runner`` labels the pull request ``ci:every-runner``, so
1201 the gate runs every runner for it where its check legs run on
1202 fewer: for a change to a line only another platform reaches, which
1203 a narrowed run judges red by name.
1204 """
1205 root = _root()
1206 from livery.workshop._forge_lane import this_repository
1208 repo = this_repository(root)
1209 reason = arming_reason(armed=armed, flag_given=footman.given("armed"))
1210 base = resolve_base(root, base, given=footman.given("base"))
1211 with forge_failures_named():
1212 submit_flow(
1213 repo,
1214 root,
1215 title=title,
1216 body=body,
1217 base=base,
1218 closes=closes,
1219 close=close,
1220 armed=armed,
1221 armed_reason=reason,
1222 gate=gate,
1223 force=force,
1224 fix=fix,
1225 every_runner=every_runner,
1226 follow_to_verdict=follow,
1227 interval=interval,
1228 timeout=timeout,
1229 )
1234 """Fail with the forge's own words when it refuses or does not answer.
1236 A submit is safe to run again, so a read that timed out or a write
1237 the forge refused ends the run with the forge's message and that
1238 advice, not a traceback.
1239 """
1240 try:
1241 yield
1242 except ForgeError as error:
1243 fail(
1244 f"{error}\n `{footman.prog()} submit` is safe to run again: it"
1245 " starts from what the forge already has"
1246 )
1250 """The linked worktree holding *branch*; "" when none does or *root* does."""
1251 listing = git.run(root, "worktree", "list", "--porcelain")
1252 tree = ""
1253 current: dict[str, str] = {}
1254 for line in [*listing.splitlines(), ""]:
1255 if not line.strip():
1256 if current.get("branch", "").endswith(f"refs/heads/{branch}"):
1257 tree = current.get("worktree", "")
1258 current = {}
1259 continue
1260 key, _, value = line.partition(" ")
1261 current[key] = value
1262 if tree and Path(tree).resolve() == root.resolve():
1263 return ""
1264 return tree
1268 """Why *branch* holds work that exists nowhere else; "" when safe.
1270 The one keep-or-drop rule: ``fm issue.close``, ``fm issue.stop``,
1271 the submit's own teardown after a merge, the sweep, and ``fm sync``
1272 all ask it, so what they destroy is decided in one place. Dirt is
1273 looked for where the branch actually lives: this checkout when it
1274 stands on the branch, the branch's linked worktree otherwise.
1276 *merged_head* is the head a merged pull request took. A tip equal
1277 to it holds nothing only here: the merge took every commit, and
1278 the squash rewrote them, so the remote's ancestry says nothing
1279 (after a squash the branch's commits are never ancestors of the
1280 base, and the forge deletes the remote branch). A tip past it
1281 holds the commits made after the merge. A tip the merged head
1282 does not reach was rewritten after the merge, and the ancestry
1283 rule below judges it. Without a merged head, ahead is measured
1284 against the remote branch when one exists, and against the base
1285 when none does.
1286 """
1287 if git.current_branch(root) == branch and not git.is_clean(root):
1288 return "uncommitted changes"
1289 tree = worktree_for(root, branch)
1290 if tree:
1291 status = git.run(root, "-C", tree, "status", "--porcelain").strip()
1292 if status:
1293 return f"uncommitted changes in the worktree {tree}"
1294 if merged_head:
1295 tip = git.object_id(root, f"refs/heads/{branch}")
1296 if tip == merged_head:
1297 return ""
1298 if git.is_ancestor(root, merged_head, tip):1298 ↛ 1303line 1298 didn't jump to line 1303 because the condition on line 1298 was always true
1299 count = git.run(
1300 root, "rev-list", "--count", f"{merged_head}..{tip}"
1301 ).strip()
1302 return f"{count} commit(s) past the merged head"
1303 remote = f"origin/{branch}"
1304 upstream = remote if branch in git.remote_branches(root, "") else "origin/main"
1305 count = git.run(root, "rev-list", "--count", f"{upstream}..{branch}").strip()
1306 if count.isdigit() and int(count) > 0:
1307 where = "the remote branch" if upstream == remote else "any remote"
1308 return f"{count} commit(s) not on {where}"
1309 return ""
1313 repo: Repository, root: Path, branch: str
1314) -> PullRequest | None:
1315 """The merged pull request *branch* was the head of, or None.
1317 [livery.workshop._forge_lane.pull_request_for][] finds it, by head
1318 branch and then by the branch's head commit; a forge that cannot
1319 be asked raises.
1320 """
1321 from livery.workshop._forge_lane import pull_request_for
1323 pr = pull_request_for(repo, root, branch)
1324 return pr if pr is not None and pr.merged else None
1328 repo: Repository, root: Path, branch: str, base: str, number: int
1329) -> None:
1330 """Remove the linked worktree a merged submission stood in.
1332 The submit is the flow that opened the tree (through ``fm start``),
1333 so it removes the tree when the follow sees the merge, the way
1334 ``fm issue.close`` does from inside one; the janitor is the net
1335 for a submit that was not followed to the end. A tree that holds
1336 something the merge did not take is kept and named. The main
1337 checkout keeps its branch: a person reads the run's logs from it,
1338 and the janitor's branch rule drops it later.
1340 The janitor runs with any ``fm`` command, so another one may sweep
1341 the tree once its branch merged, before or while this tidy runs.
1342 That leaves nothing to do: the tidy says so and moves the process
1343 out of the directory that is gone. A missing executable is not
1344 that, and still raises.
1345 """
1346 try:
1347 _tidy_tree(repo, root, branch, base, number)
1348 except (FileNotFoundError, NotADirectoryError):
1349 # A process started in a directory that is gone raises
1350 # FileNotFoundError on POSIX and NotADirectoryError on Windows.
1351 if root.is_dir():
1352 raise
1353 _swept(root)
1357 """Say the tree at *root* was swept already, standing the process somewhere real."""
1358 print(f" the worktree {root} is gone already: swept after the merge")
1359 home = root.parent
1360 while not home.is_dir() and home != home.parent:1360 ↛ 1361line 1360 didn't jump to line 1361 because the condition on line 1360 was never true
1361 home = home.parent
1362 os.chdir(home)
1366 repo: Repository, root: Path, branch: str, base: str, number: int
1367) -> None:
1368 """The tidy itself, for a tree that may vanish under it."""
1369 if not root.is_dir():
1370 _swept(root)
1371 return
1372 try:
1373 git_dir = git.run(root, "rev-parse", "--git-dir").strip()
1374 common_dir = git.run(root, "rev-parse", "--git-common-dir").strip()
1375 except git.GitError:
1376 return # no checkout to speak of, so no linked worktree to remove
1377 if git_dir == common_dir:
1378 return
1379 pr = repo.pr.get(number)
1380 merged_head = pr.head_sha if pr is not None and pr.merged else ""
1381 why = only_local_work(root, branch, merged_head=merged_head)
1382 if why:
1383 print(
1384 f" kept the worktree {root}: it holds {why};"
1385 f" `{footman.prog()} issue.close --discard` or"
1386 f" `{footman.prog()} abandon` removes it"
1387 )
1388 return
1389 teardown_branch(repo, root, branch, base)
1393 repo: Repository,
1394 root: Path,
1395 branch: str,
1396 base: str,
1397) -> None:
1398 """The one branch teardown every stop verb wears; idempotent.
1400 Disarm, close the PR (a merged one is left alone), delete the
1401 remote and local branch, and step back onto an up-to-date *base*
1402 when standing on *branch*. Mechanism only: state gates, forces,
1403 and refusals are the calling policy's job
1404 (livery.workshop._submit.abandon_flow for a feature,
1405 ``workflow.abort`` for a reserved workflow), so the policies can
1406 never drift apart. Removing a
1407 linked worktree moves the process into the main checkout first:
1408 Windows refuses to remove a directory a process stands in, and
1409 the shell that ran the verb is told where to go. A real move of
1410 the process directory is a serial task's to make (footman refuses
1411 it in a parallel one), so every verb that reaches this from
1412 inside a worktree is declared ``serial``.
1413 """
1414 pr = repo.pr.find_by_head(branch)
1415 if pr is not None and not pr.merged:
1416 _disarm_and_say(repo, pr.number)
1417 repo.pr.close(pr.number)
1418 print(f" closed PR #{pr.number}")
1419 if repo.branch_exists(branch):
1420 repo.delete_branch(branch)
1421 print(f" deleted origin/{branch}")
1422 git_dir = git.run(root, "rev-parse", "--git-dir").strip()
1423 common_dir = git.run(root, "rev-parse", "--git-common-dir").strip()
1424 standing = git.current_branch(root) == branch
1425 if standing and git_dir != common_dir:
1426 # A linked worktree cannot switch to *base*: the main
1427 # checkout holds it. The worktree itself is the leftover, so
1428 # it is removed from the main checkout, branch and all. The
1429 # shell that ran this stands in a deleted directory afterwards
1430 # and is told where to go.
1431 import os
1433 main_root = git.main_checkout(root)
1434 os.chdir(main_root)
1435 git.run(main_root, "worktree", "remove", "--force", str(root))
1436 if git.local_branch_exists(main_root, branch):1436 ↛ 1438line 1436 didn't jump to line 1438 because the condition on line 1436 was always true
1437 git.delete_branch(main_root, branch)
1438 print(f" removed the worktree {root} and deleted {branch}")
1439 print(f" this shell's directory is gone: cd {main_root}")
1440 return
1441 if standing:
1442 git.switch(root, base)
1443 git.integrate(root, base)
1444 else:
1445 tree = worktree_for(root, branch)
1446 if tree:
1447 git.run(root, "worktree", "remove", "--force", tree)
1448 print(f" removed the worktree {tree}")
1449 if git.local_branch_exists(root, branch):
1450 git.delete_branch(root, branch)
1451 # Only a checkout that stood on the branch moved to the base.
1452 print(f" deleted {branch}" + (f"; back on {base}" if standing else ""))
1456 """Give the feature up: close the PR, delete both branches; idempotent.
1458 A dirty tree refuses before anything else moves: abandoning
1459 deletes the branch, and uncommitted work must be a person's
1460 explicit loss, not a side effect.
1461 """
1462 if not branch or branch == base:1462 ↛ 1463line 1462 didn't jump to line 1463 because the condition on line 1462 was never true
1463 fail(f"not on a feature branch (on {branch or '(detached)'!r})")
1464 if branch == git.current_branch(root):
1465 if not git.is_clean(root):
1466 fail(
1467 "the working tree has uncommitted changes; commit or discard"
1468 " them before abandoning"
1469 )
1470 else:
1471 tree = worktree_for(root, branch)
1472 if tree and git.run(root, "-C", tree, "status", "--porcelain").strip():
1473 fail(
1474 f"the worktree {tree} has uncommitted changes; commit or"
1475 " discard them before abandoning"
1476 )
1477 pr = repo.pr.find_by_head(branch)
1478 if pr is not None and pr.merged:1478 ↛ 1479line 1478 didn't jump to line 1479 because the condition on line 1478 was never true
1479 fail(f"PR #{pr.number} already merged: nothing to abandon")
1480 if pr is None:
1481 print(f" no open pull request for {branch}")
1482 teardown_branch(repo, root, branch, base)
1487 branch: Annotated[Arg[str], doc("a branch to give up; this one when absent")] = "",
1488) -> None:
1489 """Give up a feature: close the PR, delete the branches, return to base.
1491 This branch when none is named, or the named one from anywhere:
1492 its linked worktree goes with it. Disarms and closes the pull
1493 request, deletes the remote and the local branch, and leaves this
1494 checkout on an up-to-date base when it stood on the branch. A
1495 dirty tree, here or in the branch's worktree, refuses first.
1496 Idempotent: a second run finds nothing left to undo.
1497 """
1498 root = _root()
1499 from livery.workshop._forge_lane import this_repository
1501 abandon_flow(
1502 this_repository(root), root, branch or git.current_branch(root), "main"
1503 )
1507 """Find the pull request *ref* numbers; this branch's when *ref* is empty.
1509 *ref* is read by [livery.workshop._submit.parse_number][], the
1510 rule the issue verbs read an issue number by, so ``#123`` and
1511 ``123`` name the same pull request. On the current branch the open
1512 pull request is looked up by the branch's name, and when there is
1513 none, a merged one by the branch's head commit, which outlives a
1514 head branch the merge deleted: after a merge, the answer is that
1515 it merged. Every other answer fails and names the next action: a
1516 *ref* that is no number, a number no pull request has, a branch
1517 without an open or merged pull request, and a pull request closed
1518 without merging.
1520 Args:
1521 repo: The workspace's repository on its forge.
1522 root: The checkout whose current branch an empty *ref* means.
1523 ref: A pull request number, with or without ``#``; empty for
1524 the current branch's.
1526 Returns:
1527 The pull request, open or merged. What a merged one means is
1528 the verb's to decide.
1529 """
1530 prog = footman.prog()
1531 if ref:
1532 number = parse_number(ref)
1533 if number is None:
1534 fail(
1535 f"{ref!r} is not a pull request number: name one, 123 or"
1536 " #123, or none for this branch's"
1537 )
1538 pr = repo.pr.get(number)
1539 if pr is None:
1540 fail(f"no pull request #{number} on the forge: check the number")
1541 else:
1542 branch = git.current_branch(root)
1543 if not branch:
1544 fail("HEAD is detached, so no branch names a pull request: name its number")
1545 pr = repo.pr.find_by_head(branch)
1546 if pr is None:
1547 done = repo.pr.find_by_head_sha(git.head_sha(root))
1548 pr = done if done is not None and done.merged else None
1549 if pr is None:
1550 fail(
1551 f"no open pull request for {branch}: `{prog} submit` opens"
1552 " one, or name a pull request's number"
1553 )
1554 if pr.state != "open" and not pr.merged:
1555 fail(
1556 f"PR #{pr.number} is closed: `{prog} submit` on {pr.head_branch}"
1557 " opens a new one"
1558 )
1559 return pr
1563 """Whether *pr* has merged, printing that nothing is left to do when it has."""
1564 if pr.merged:
1565 print(f" PR #{pr.number} has already merged; nothing to do")
1566 return pr.merged
1570 """Arm *pr* to merge when green, as ``fm submit --armed`` arms; idempotent.
1572 The squash takes the pull request's own title and body. An armed
1573 pull request is left as it is, and a merged one is the end the arm
1574 aims at: each line says so, and neither is an error.
1575 """
1576 if _merged_already(pr):
1577 return
1578 if repo.pr.is_armed(pr.number):
1579 print(f" PR #{pr.number} is armed already; nothing changed")
1580 return
1581 _arm_and_say(
1582 repo,
1583 pr.number,
1584 title=pr.title.strip(),
1585 message=pr.body,
1586 kind=_contract_forge_kind(root),
1587 )
1591 """Take auto-merge off *pr* and leave it open; idempotent.
1593 An unarmed pull request is left as it is, and the line says so. A
1594 merged one refuses: the merge the disarm was to prevent has
1595 happened.
1596 """
1597 if pr.merged:
1598 fail(f"PR #{pr.number} has already merged: too late to disarm")
1599 if not _disarm_and_say(repo, pr.number):
1600 print(f" PR #{pr.number} is not armed; nothing changed")
1604 repo: Repository, root: Path, pr: PullRequest, *, title: str = ""
1605) -> None:
1606 """Merge the pull request *pr* as soon as possible; a merged one is done.
1608 Merge means merge asap, never merge-if-instant-else-fail: checks
1609 still running are followed to their verdict, the forge's own
1610 holds (the mergeability recompute, the settling beat) are
1611 followed to completion, and the task's timeout is the only
1612 backstop. Red refuses at once naming the state, behind base
1613 teaches integrate, and merging red stays a person's act in the
1614 forge's own interface.
1616 Whether *pr* is behind its base is judged at HEAD when *pr* is
1617 this branch's pull request, since HEAD is what the next submit
1618 pushes, and at the head the forge holds for any other, which the
1619 fetch brings here. A head this clone cannot see is left to the
1620 forge's own refusal.
1621 """
1622 if _merged_already(pr):
1623 return
1624 own = pr.head_branch == git.current_branch(root)
1625 _wait_for_verdict(repo, pr.number, local_head=git.head_sha(root) if own else "")
1626 # The wait follows a head that moves, so the verdict is read for
1627 # the head it settled on, not the one *pr* was read with.
1628 pr = repo.pr.get(pr.number) or pr
1629 status = repo.checks.status(pr.head_sha)
1630 if status.state == "failure":
1631 fail(
1632 f"CI is red for PR #{pr.number}: fix it and `{footman.prog()} submit`."
1633 " This verb never merges red."
1634 )
1635 git.fetch(root)
1636 head = "HEAD" if own else git.sha_of(root, pr.head_sha)
1637 if head and not git.is_ancestor(root, f"origin/{pr.base_branch}", head):
1638 where = "" if own else f" on {pr.head_branch},"
1639 fail(
1640 f"PR #{pr.number} is behind {pr.base_branch}:{where}"
1641 f" `{footman.prog()} integrate`, then `{footman.prog()} submit`,"
1642 " and merge again"
1643 )
1644 subject = title or pr.title
1645 _follow_merge_state(
1646 repo,
1647 _contract_forge_kind(root),
1648 pr.number,
1649 repo.pr.merge_now,
1650 pr.number,
1651 title=subject,
1652 )
1653 print(f" merged PR #{pr.number}")
1657 """The workspace's repository, its root, and the pull request *ref* names."""
1658 root = _root()
1659 from livery.workshop._forge_lane import this_repository
1661 repo = this_repository(root)
1662 return repo, root, pull_request_named(repo, root, ref)
1666 """Completion: the open pull request numbers, newest first; never raises.
1668 Offline, token-less, or outside a repository costs the
1669 suggestions, never the command.
1670 """
1671 try:
1672 from livery.workshop._forge_lane import this_repository
1674 repo = this_repository(_root())
1675 return [str(row.number) for row in repo.pr.list(state="open")]
1676 except Exception:
1677 return []
1680#: The pull request argument the three verbs share: its help text, and
1681#: the open pull requests' numbers as its completion. Module level,
1682#: because footman reads a task's annotations in its module's namespace.
1684 Arg[str],
1685 doc("a pull request number; this branch's when absent"),
1686 suggest(_open_pull_numbers, strict=False),
1687]
1691def submit_merge(
1692 pr: _PullRef = "",
1693 title: Annotated[str, doc("squash subject; defaults to the PR title")] = "",
1694) -> None:
1695 """Merge a PR as soon as possible: this branch's, or the one numbered.
1697 Waits for a running CI's verdict and follows the forge's own
1698 holds to completion; refuses red or behind-base at once, saying
1699 why, and refuses a pull request closed without merging. A pull
1700 request that has merged already is done: the verb says so and
1701 succeeds, so a re-run is the recovery. A merge that lands while it
1702 runs is success too, as livery.forge.PullRequests.merge_now reads
1703 one.
1704 """
1705 repo, root, found = _named(pr)
1706 merge_flow(repo, root, found, title=title)
1710def submit_arm(pr: _PullRef = "") -> None:
1711 """Arm a PR to merge when green: this branch's, or the one numbered.
1713 Arms as ``fm submit --armed`` arms, with the pull request's own
1714 title as the squash subject, and reads the schedule back. A pull
1715 request already green is merged at once, since a forge that arms
1716 only a blocked pull request refuses. An armed one is left as it
1717 is, and a merged one is done: the verb says so and succeeds, also
1718 on the branch once its head branch is gone. One closed without
1719 merging refuses.
1720 """
1721 repo, root, found = _named(pr)
1722 arm_flow(repo, root, found)
1726def submit_disarm(pr: _PullRef = "") -> None:
1727 """Take auto-merge off a PR and leave it open: this branch's, or the one numbered.
1729 The pull request and its branch stay as they are, so it waits
1730 unmerged until ``fm submit.arm`` arms it again. An unarmed one is
1731 left as it is. A merged one refuses, since the merge the disarm
1732 was to prevent has happened, and so does one closed without
1733 merging.
1734 """
1735 repo, _root_dir, found = _named(pr)
1736 disarm_flow(repo, found)