1"""The shared reserved-branch engine and its one kind-specific seam.
3Releasing and updating are the same shape underneath: cut a
4``workflow/<name>`` branch, do some work, submit through
5livery.workshop._submit.submit_flow, and either publish or just
6merge. This module runs that shared lifecycle; a
7``WorkflowDriver`` plugs in only ``prepare`` (do the work) and
8``on_merged`` (a release publishes and tags; an update does
9nothing). Re-running the engine at any point is the recovery: the
10decision extension reads the state and does the right thing.
11"""
24 WorkflowAction,
25 workflow_decision,
26)
28 WorkflowKind,
29 WorkflowState,
30 WorkflowStatus,
31 workflow_states,
32)
34#: A release in one of these states parks a coexisting update's arm.
35#: UNKNOWN counts: a gather blip must not read as "no release running".
37 {
38 WorkflowState.IN_PROGRESS,
39 WorkflowState.AWAITING_REVIEW,
40 WorkflowState.UNKNOWN,
41 }
42)
47 """What a driver's prepare hands back for the shared submit.
49 None from prepare means nothing to submit (already up to date, or
50 the work completed on its own).
51 """
58 """The only kind-specific seam; everything else is shared.
60 Structural, so a driver provides these members and inherits
61 nothing. ``branch`` is always ``workflow/<name>``: one active
62 workflow per name, the branch name is the identity, different
63 names coexist.
64 """
74 """The reserved branch, ``workflow/<name>``."""
75 ...
79 """The branch the PR merges into."""
80 ...
83 """Do the work; idempotent, called fresh and for recovery."""
84 ...
87 """Give the prepared branch up, so the next prepare starts from the base."""
88 ...
91 """After the merge: a release publishes and tags; else nothing."""
92 ...
96 driver: WorkflowDriver,
97 repo: Repository,
98 root: Path,
99 *,
100 current_user: str | None = None,
101) -> None:
102 """Drive *driver* one step: gather, decide, act.
104 Loops for MERGE_DEFAULT (re-decide on the fresh state) and for a
105 TIDY_THEN_START that removed another workflow's leftover, each
106 other name tidied at most once so the loop cannot spin. STOP
107 raises with its teaching. Everything else terminates.
108 """
109 tidied: set[str] = set()
110 while True:
111 states = workflow_states(repo, root, base=driver.base)
112 wf = next(
113 (s for s in states if s.name == driver.name),
114 WorkflowStatus(kind=None, state=WorkflowState.NONE),
115 )
116 others = tuple(s for s in states if s.name != driver.name)
117 decision = workflow_decision(
118 kind=driver.kind,
119 name=driver.name,
120 wf=wf,
121 members=driver.members,
122 branch=git.current_branch(root),
123 dirty=not git.is_clean(root),
124 behind_default=_behind_default(root, driver.base),
125 default_branch=driver.base,
126 current_user=(_forge_user(repo) if current_user is None else current_user),
127 others=others,
128 )
129 action = decision.action
131 # A bare repeat call into your own armed in-flight workflow:
132 # the idempotent submit disarms whenever the arm choice is
133 # off, so a status-check re-run would take the live schedule
134 # away while announcing a retry. Say what is true and stop.
135 if (
136 action is WorkflowAction.RETRY
137 and wf.state is WorkflowState.IN_PROGRESS
138 and wf.armed is not False
139 and not driver.armed
140 ):
141 fail(
142 f"{driver.name} is already in flight and armed. Follow it"
143 f" with `{footman.prog()} status --watch --workflow`, or re-run with"
144 " --armed to re-assert the schedule deliberately."
145 )
147 message = decision.message
148 if action is WorkflowAction.ARM and not driver.armed:148 ↛ 149line 148 didn't jump to line 149 because the condition on line 148 was never true
149 message = (
150 f"The ready {driver.name} PR stays unarmed; pass --armed to"
151 " arm auto-merge."
152 )
153 if message:
154 print(f" {message}")
156 if action is WorkflowAction.STOP:
157 raise SystemExit(f" {decision.message}")
159 if action is WorkflowAction.MERGE_DEFAULT:
160 _merge_default(root, driver.base)
161 continue
163 # A stale set re-derives in place: the prepare starts from the
164 # base again and the push replaces the branch under the same
165 # pull request.
166 force = False
167 if action is WorkflowAction.REPREPARE:167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 driver.discard()
169 force = True
171 if action is WorkflowAction.TIDY_THEN_START:
172 target = decision.tidy_target
173 tidy_leftover(repo, root, target or wf, base=driver.base)
174 if target is not None and target.name not in tidied:174 ↛ 184line 174 didn't jump to line 184 because the condition on line 174 was always true
175 tidied.add(target.name)
176 continue
177 elif action is WorkflowAction.REOPEN:
178 _reopen(repo, driver.branch)
180 # The parking rule: while any release is live, a coexisting
181 # update submits UNARMED, and the note teaches the re-run
182 # (which also raises floors) before arming. The verify
183 # backstop holds even when someone arms anyway.
184 arm = driver.armed
185 if arm and driver.kind is not WorkflowKind.RELEASE:
186 parked_by = [
187 other.name
188 for other in others
189 if other.kind is WorkflowKind.RELEASE and other.state in PARKS_UPDATES
190 ]
191 if parked_by:
192 arm = False
193 print(
194 f" Release {parked_by[0]} is in flight: submitting"
195 " unarmed. After it lands, re-run"
196 f" `{footman.prog()} workflow.update`"
197 " (the re-run also raises floors to the fresh release),"
198 " then arm."
199 )
201 started = git.current_branch(root)
202 submission = driver.prepare()
203 if submission is None:
204 print(" nothing to submit: everything is already current")
205 return
206 from livery.workshop._submit import submit_flow
208 # The engine submits and reads the immediate outcome; the
209 # long watch belongs to the drivers' own surfaces, which
210 # know their done oracle (a release watches its receipts).
211 submit_flow(
212 repo,
213 root,
214 title=submission.title,
215 body=submission.body,
216 base=driver.base,
217 armed=arm,
218 armed_reason="the workflow engine",
219 gate=False,
220 follow_to_verdict=False,
221 force=force,
222 )
223 _leave_reserved(root, driver, started)
224 if arm and driver.watch > 0 and not _merged(repo, root, driver.branch):
225 # An armed act waits the way `submit --armed` waits: from
226 # the branch it returned to, since the pull request holds
227 # the reserved branch on the remote. A blocker exits with
228 # its code, the way the submit does.
229 from livery.workshop._verdict import follow_pull_request
231 print(f" following PR of {driver.branch} to its merge")
232 follow_pull_request(repo, driver.branch, root, timeout=driver.watch)
233 if _merged(repo, root, driver.branch):
234 driver.on_merged()
235 return
239 """Return to the branch the act started from; the reserved branch lives on origin.
241 The pull request holds the reserved branch on the remote, and the
242 driver's recovery fetches it from there, so the local copy is a
243 leftover the moment the submit returns. An act started on the
244 reserved branch itself stays there: a person chose it.
245 """
246 if (
247 not started
248 or started == driver.branch
249 or git.current_branch(root) != driver.branch
250 ):
251 return
252 git.switch(root, started)
253 git.delete_branch(root, driver.branch)
254 print(
255 f" back on {started}; {driver.branch} stays on origin under its pull request"
256 )
260 repo: Repository, root: Path, wf: WorkflowStatus, *, base: str
261) -> None:
262 """Tear down a finished workflow's branches; safe, it is merged.
264 *wf* is the decision's tidy target, never assumed to be the
265 driver's own branch: passing a live branch here would close its
266 live PR, the exact mistake the target field prevents.
267 """
268 if wf.branch:268 ↛ exitline 268 didn't return from function 'tidy_leftover' because the condition on line 268 was always true
269 from livery.workshop._submit import teardown_branch
271 teardown_branch(repo, root, wf.branch, base)
275 """Whether *branch*'s pull request has merged, asked of the forge.
277 A forge that does not answer is asked again within the transient
278 budget, and then the engine stops with the forge's words: a
279 failure reason is printed, never read as "not merged".
280 """
281 from livery.workshop._forge_lane import pull_request_for
282 from livery.workshop._verdict import ForgeUnreachable, follow
284 try:
285 pr = follow(
286 repo,
287 lambda: pull_request_for(repo, root, branch),
288 subject=f"the pull request of {branch}",
289 interval=5,
290 timeout=None,
291 quiet=None,
292 )
293 except ForgeUnreachable as exc:
294 fail(exc.line.strip())
295 return pr is not None and pr.merged
299 """Who this invocation is, in the forge's namespace.
301 The forge identity, because a workflow's author comes from the
302 PR; a local git name is a different namespace and on a bot
303 checkout can never match. Offline answers empty, which the
304 decision treats as "cannot compare", never as a refusal.
305 """
306 try:
307 from livery.workshop._extensions import workspace_root
308 from livery.workshop._forge_lane import this_forge
310 root = workspace_root()
311 if root is None:
312 return ""
313 return this_forge(root).whoami()
314 except Exception:
315 return ""
319 """Commits on origin/*base* not in HEAD; 0 when none or offline."""
320 try:
321 git.fetch(root)
322 return git.behind_base(root, base)
323 except git.GitError:
324 return 0
328 """Merge origin/*base* in; a conflict stops with the resolution path."""
329 try:
330 git.integrate(root, base)
331 except git.GitError as exc:
332 raise SystemExit(
333 f" The merge from {base} stopped on a conflict. Resolve it,"
334 f" commit, and run the workflow again to resume.\n{exc}"
335 ) from None
339 """Reopen the closed PR for *branch*, reusing it over a duplicate."""
340 pr = repo.pr.find_by_head(branch, state="all")
341 if pr is not None and not pr.merged and pr.state == "closed":341 ↛ exitline 341 didn't return from function '_reopen' because the condition on line 341 was always true
342 repo.pr.reopen(pr.number)
343 print(f" reopened PR #{pr.number}")