gitpoulpi_core/workflow/flow/mod.rs
1//! Workflow **actions**: start, finish, sync, promote, set-parent. This
2//! module is the wire vocabulary (what `OperationKind::FlowPlan` and
3//! `OperationKind::FlowRun` carry) and the pure planner (`plan.rs`); the
4//! daemon gathers the facts, runs the steps and journals them.
5//!
6//! One request type serves both operations: `FlowPlan` answers a
7//! [`FlowPlan`] (every git step the action would do, plus blockers and
8//! warnings, nothing changes), `FlowRun` plans again and executes, answering
9//! a [`FlowOutcome`]. A run that stops on a conflict is resumed with the
10//! same action and `resume: continue`, or given up with `resume: abort`.
11
12mod plan;
13
14use serde::{Deserialize, Serialize};
15
16use super::{Fields, FinishMode, MergeStrategy};
17
18pub use plan::{branch_title, plan_flow, FlowFacts};
19
20fn is_false(b: &bool) -> bool {
21 !*b
22}
23
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum FlowAction {
27 #[default]
28 Start,
29 Finish,
30 Sync,
31 Promote,
32 SetParent,
33 /// Take over a branch a host or bot made (host-driven flows): create the
34 /// local tracking branch of `remote/branch`, record its parent, check it out.
35 PickUp,
36}
37
38impl FlowAction {
39 pub fn word(self) -> &'static str {
40 match self {
41 FlowAction::Start => "start",
42 FlowAction::Finish => "finish",
43 FlowAction::Sync => "sync",
44 FlowAction::Promote => "promote",
45 FlowAction::SetParent => "set-parent",
46 FlowAction::PickUp => "pick-up",
47 }
48 }
49}
50
51/// What to do with a flow a conflict stopped.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum FlowResume {
55 /// Resolve the conflict first; this finishes the step it stopped at
56 /// (commits the merge) and runs the remaining ones.
57 Continue,
58 /// Abort the git operation in progress, go back to the branch the flow
59 /// started on and forget the remaining steps. Steps already completed
60 /// stay (take them back with Undo).
61 Abort,
62}
63
64/// How `sync` brings the parent's commits in.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum SyncMethod {
68 Merge,
69 Rebase,
70}
71
72/// The arguments of `FlowPlan` and `FlowRun`. Every field but `action` is
73/// optional; which ones matter depends on the action.
74#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(default)]
76pub struct FlowRequest {
77 pub action: FlowAction,
78 /// start: the topic type id (`feature`, `hotfix`, ...).
79 pub topic: Option<String>,
80 /// start: the values of the pattern's tokens (`slug`, `version`, ...).
81 /// `user` and `date` default to the user name and today.
82 pub fields: Fields,
83 /// start: the start point (a branch, a remote branch, a tag); default is
84 /// the type's parent.
85 pub from: Option<String>,
86 /// start: push the new branch with `-u` afterwards.
87 pub publish: bool,
88 /// pick-up: the branch to take over, as named on the remote (without the
89 /// remote). finish, sync, promote, set-parent: the branch; finish and sync
90 /// default to the checked-out one.
91 pub branch: Option<String>,
92 /// set-parent: the new parent. pick-up: the branch the merge request
93 /// targets (recorded as the parent when it exists locally).
94 pub parent: Option<String>,
95 /// set-parent: forget the recorded parent instead.
96 pub clear: bool,
97 /// sync: also update the branches stacked on this one, in order.
98 pub stack: bool,
99 /// sync: merge or rebase; default follows the branch's configured
100 /// strategy (a `rebase` strategy rebases, anything else merges).
101 pub method: Option<SyncMethod>,
102 /// finish: `local-merge` or `merge-request`; needed when the type says
103 /// `ask`, overrides it otherwise.
104 pub finish_mode: Option<FinishMode>,
105 /// finish: the merge request / squash commit title (default from the
106 /// branch name).
107 pub title: Option<String>,
108 /// finish: delete the local branch afterwards (default: the type's
109 /// `delete_after_finish`).
110 pub delete: Option<bool>,
111 /// finish: also delete the branch on its remote (needs `delete`).
112 pub delete_remote: bool,
113 /// The remote to publish to / open the merge request from (default
114 /// `origin`, else the only one).
115 pub remote: Option<String>,
116 /// Run the configured hooks. They are shell commands from a file the
117 /// team shares, so they never run unless asked for.
118 pub run_hooks: bool,
119 /// finish, promote: go on although the target is behind its remote.
120 pub allow_behind: bool,
121 /// Resume or abort a flow a conflict stopped (`action` must be the one
122 /// that stopped).
123 pub resume: Option<FlowResume>,
124}
125
126/// One thing a flow does. Serialized with an `op` tag.
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(tag = "op", rename_all = "snake_case")]
129pub enum FlowStep {
130 Checkout {
131 branch: String,
132 },
133 CreateBranch {
134 name: String,
135 /// A branch, a remote branch (`origin/x`), a tag or any revision.
136 from: String,
137 },
138 /// `git branch --set-upstream-to`: the local `branch` tracks `upstream`
139 /// (`origin/x`).
140 SetUpstream {
141 branch: String,
142 upstream: String,
143 },
144 /// `branch.<name>.gitpoulpi-parent`; `None` removes it.
145 RecordParent {
146 branch: String,
147 parent: Option<String>,
148 },
149 Push {
150 remote: String,
151 branch: String,
152 set_upstream: bool,
153 },
154 /// Merge `branch` into the checked-out `into`.
155 Merge {
156 branch: String,
157 into: String,
158 strategy: MergeStrategy,
159 /// Always make a merge commit (git-flow's `--no-ff`); without it a
160 /// fast-forward is taken when possible. Only for `merge`.
161 #[serde(default, skip_serializing_if = "is_false")]
162 no_ff: bool,
163 /// The commit message of a squash.
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 message: Option<String>,
166 },
167 /// Check `branch` out and rebase it onto `onto`.
168 Rebase {
169 branch: String,
170 onto: String,
171 },
172 /// An annotated tag at the tip of `at`.
173 Tag {
174 name: String,
175 at: String,
176 message: String,
177 },
178 DeleteBranch {
179 name: String,
180 },
181 DeleteRemoteBranch {
182 remote: String,
183 name: String,
184 },
185 /// Done by the client (it holds the hosting token), after the daemon's
186 /// steps: the outcome carries the [`MergeRequestSpec`].
187 OpenMergeRequest {
188 source: String,
189 target: String,
190 title: String,
191 },
192 Hook {
193 /// `after_start` or `before_finish`.
194 phase: String,
195 command: String,
196 /// The command comes from this user's own override, never from the
197 /// committed file: it runs without a trust question. A saved state
198 /// without the field is not personal (the safe side).
199 #[serde(default, skip_serializing_if = "is_false")]
200 personal: bool,
201 },
202}
203
204impl FlowStep {
205 /// One line for a preview.
206 pub fn describe(&self) -> String {
207 match self {
208 FlowStep::Checkout { branch } => format!("Check out {branch}"),
209 FlowStep::CreateBranch { name, from } => format!("Create branch {name} from {from}"),
210 FlowStep::SetUpstream { branch, upstream } => {
211 format!("Make {branch} track {upstream}")
212 }
213 FlowStep::RecordParent { branch, parent } => match parent {
214 Some(p) => format!("Record {p} as the parent of {branch}"),
215 None => format!("Forget the recorded parent of {branch}"),
216 },
217 FlowStep::Push {
218 remote,
219 branch,
220 set_upstream,
221 } => format!(
222 "Push {branch} to {remote}{}",
223 if *set_upstream { " and track it" } else { "" }
224 ),
225 FlowStep::Merge {
226 branch,
227 into,
228 strategy,
229 no_ff,
230 ..
231 } => match strategy {
232 MergeStrategy::Merge if *no_ff => {
233 format!("Merge {branch} into {into} with a merge commit")
234 }
235 MergeStrategy::Merge => format!("Merge {branch} into {into}"),
236 MergeStrategy::Squash => format!("Squash {branch} into {into} as one commit"),
237 MergeStrategy::Rebase | MergeStrategy::FastForward => {
238 format!("Fast-forward {into} to {branch}")
239 }
240 },
241 FlowStep::Rebase { branch, onto } => format!("Rebase {branch} onto {onto}"),
242 FlowStep::Tag { name, at, .. } => format!("Tag {at} as {name}"),
243 FlowStep::DeleteBranch { name } => format!("Delete the local branch {name}"),
244 FlowStep::DeleteRemoteBranch { remote, name } => {
245 format!("Delete {name} on {remote}")
246 }
247 FlowStep::OpenMergeRequest { source, target, .. } => {
248 format!("Open a merge request from {source} into {target} on the host")
249 }
250 FlowStep::Hook { phase, command, .. } => format!("Run the {phase} hook: {command}"),
251 }
252 }
253
254 /// The git commands this step amounts to, for a preview that wants to
255 /// show exactly what happens.
256 pub fn git(&self) -> Vec<String> {
257 match self {
258 FlowStep::Checkout { branch } => vec![format!("git checkout {branch}")],
259 FlowStep::CreateBranch { name, from } => vec![format!("git branch {name} {from}")],
260 FlowStep::SetUpstream { branch, upstream } => {
261 vec![format!("git branch --set-upstream-to={upstream} {branch}")]
262 }
263 FlowStep::RecordParent { branch, parent } => match parent {
264 Some(p) => vec![format!(
265 "git config branch.{branch}.{} {p}",
266 super::RECORDED_PARENT_VARIABLE
267 )],
268 None => vec![format!(
269 "git config --unset branch.{branch}.{}",
270 super::RECORDED_PARENT_VARIABLE
271 )],
272 },
273 FlowStep::Push {
274 remote,
275 branch,
276 set_upstream,
277 } => vec![format!(
278 "git push{} {remote} {branch}",
279 if *set_upstream { " -u" } else { "" }
280 )],
281 FlowStep::Merge {
282 branch,
283 strategy,
284 no_ff,
285 message,
286 ..
287 } => match strategy {
288 MergeStrategy::Merge if *no_ff => vec![format!("git merge --no-ff {branch}")],
289 MergeStrategy::Merge => vec![format!("git merge {branch}")],
290 MergeStrategy::Squash => vec![
291 format!("git merge --squash {branch}"),
292 format!(
293 "git commit -m \"{}\"",
294 message.as_deref().unwrap_or("Squashed commit")
295 ),
296 ],
297 MergeStrategy::Rebase | MergeStrategy::FastForward => {
298 vec![format!("git merge --ff-only {branch}")]
299 }
300 },
301 FlowStep::Rebase { branch, onto } => {
302 vec![
303 format!("git checkout {branch}"),
304 format!("git rebase {onto}"),
305 ]
306 }
307 FlowStep::Tag { name, at, message } => {
308 vec![format!("git tag -a {name} {at} -m \"{message}\"")]
309 }
310 FlowStep::DeleteBranch { name } => vec![format!("git branch -d {name}")],
311 FlowStep::DeleteRemoteBranch { remote, name } => {
312 vec![format!("git push {remote} --delete {name}")]
313 }
314 FlowStep::OpenMergeRequest { .. } => Vec::new(),
315 FlowStep::Hook { command, .. } => vec![command.clone()],
316 }
317 }
318
319 /// Whether Undo cannot take the step back. A push and a merge request
320 /// live on the host; a remote branch deletion is taken back (the branch
321 /// is pushed back as it was, without force).
322 pub fn irreversible(&self) -> bool {
323 matches!(
324 self,
325 FlowStep::Push { .. } | FlowStep::OpenMergeRequest { .. } | FlowStep::Hook { .. }
326 )
327 }
328}
329
330/// A merge request the client has to open (the daemon has no hosting
331/// credentials): its source branch is already pushed.
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
333pub struct MergeRequestSpec {
334 pub source: String,
335 pub target: String,
336 pub title: String,
337 pub remote: String,
338}
339
340/// A configured hook, listed in a preview whether it will run or not.
341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
342pub struct HookInfo {
343 pub phase: String,
344 pub command: String,
345 /// From this user's own override: it never needs trust.
346 #[serde(default, skip_serializing_if = "is_false")]
347 pub personal: bool,
348}
349
350/// Whether the committed hooks of a workflow may run (filled by the daemon
351/// from the repository's trust records).
352#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(rename_all = "snake_case")]
354pub enum HooksTrust {
355 /// The hooks are this user's own: they never ask.
356 Personal,
357 /// The shared hooks (or none) are trusted as they are now.
358 #[default]
359 Trusted,
360 /// The shared hooks must be trusted before they run. `hash` is what
361 /// `FlowTrustHooks` takes; `previous` is the last trusted list when the
362 /// hooks changed since.
363 Untrusted {
364 hash: String,
365 previous: Option<Vec<HookInfo>>,
366 },
367}
368
369/// Args of `FlowTrustHooks`: the hash to trust, or none to only report.
370#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
371#[serde(default)]
372pub struct TrustHooksArgs {
373 pub hash: Option<String>,
374}
375
376/// Answer of `FlowTrustHooks`: the committed hooks as the file has them now
377/// and whether they are trusted.
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379pub struct HooksReport {
380 /// `hooks_hash` of the committed file's hooks (empty when it has none).
381 pub hash: String,
382 pub hooks: Vec<HookInfo>,
383 pub trusted: bool,
384}
385
386/// What an action would do. Answer of `FlowPlan`.
387#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
388pub struct FlowPlan {
389 pub action: FlowAction,
390 /// One line: "Finish feature/x".
391 pub title: String,
392 /// The branch the action is about (the new one for a start).
393 pub branch: Option<String>,
394 /// Every step, in order. Hooks are in here only when `run_hooks` was
395 /// asked for.
396 pub steps: Vec<FlowStep>,
397 /// The hooks the workflow configures for this action, run or not.
398 pub hooks: Vec<HookInfo>,
399 /// Whether the hooks are among the steps.
400 pub hooks_run: bool,
401 /// Whether those hooks are trusted to run (the daemon sets it; a plan
402 /// from `plan_flow` alone is `trusted`).
403 #[serde(default)]
404 pub hooks_trust: HooksTrust,
405 /// Things worth knowing; the action still runs.
406 pub warnings: Vec<String>,
407 /// Reasons the action cannot run; a run with blockers is refused.
408 pub blockers: Vec<String>,
409 /// Whether the working tree has changes (checkouts may need the
410 /// auto-stash setting).
411 pub dirty: bool,
412 /// Whether Undo takes the whole action back (false when a step is
413 /// irreversible; the rest is still undone).
414 pub undoable: bool,
415 /// What Undo will not take back, in words.
416 pub irreversible: Vec<String>,
417 /// The merge request the client opens at the end, if any.
418 pub merge_request: Option<MergeRequestSpec>,
419 /// This plan is the rest of a flow a conflict stopped.
420 #[serde(default, skip_serializing_if = "is_false")]
421 pub resumed: bool,
422}
423
424impl FlowPlan {
425 pub fn can_run(&self) -> bool {
426 self.blockers.is_empty()
427 }
428
429 /// Every step as `describe()` lines, numbered, for a terminal.
430 pub fn lines(&self) -> Vec<String> {
431 self.steps
432 .iter()
433 .enumerate()
434 .map(|(i, s)| format!("{}. {}", i + 1, s.describe()))
435 .collect()
436 }
437}
438
439#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
440#[serde(rename_all = "snake_case")]
441pub enum FlowStatus {
442 /// Every step ran.
443 Done,
444 /// A merge or rebase stopped on conflicts: resolve them, then
445 /// `resume: continue` (or `abort`).
446 Conflicted,
447 /// A step failed (a hook exited non-zero, git refused); the flow
448 /// stopped there. What ran before stays.
449 Failed,
450 /// `resume: abort` ran.
451 Aborted,
452 /// There was nothing to do.
453 NothingToDo,
454}
455
456#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
457#[serde(rename_all = "snake_case")]
458pub enum StepStatus {
459 Done,
460 /// Nothing to do (already up to date, already checked out).
461 Skipped,
462 Failed,
463 Conflicted,
464 /// Left for the client (opening the merge request).
465 Pending,
466 /// Not reached.
467 NotRun,
468}
469
470/// One step of a run and how it went.
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472pub struct StepReport {
473 pub step: FlowStep,
474 pub status: StepStatus,
475 /// A hook's output (stdout and stderr), a git error, a note.
476 #[serde(default, skip_serializing_if = "Option::is_none")]
477 pub output: Option<String>,
478 /// A hook's exit code.
479 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub exit_code: Option<i32>,
481}
482
483/// Answer of `FlowRun`.
484#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
485pub struct FlowOutcome {
486 pub action: FlowAction,
487 pub status: FlowStatus,
488 pub branch: Option<String>,
489 pub steps: Vec<StepReport>,
490 /// The paths in conflict when `status` is `conflicted`.
491 #[serde(default, skip_serializing_if = "Vec::is_empty")]
492 pub conflicts: Vec<String>,
493 /// A line for a human: what happened, or what to do next.
494 pub message: String,
495 /// The merge request to open (the daemon pushed the branch).
496 #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub merge_request: Option<MergeRequestSpec>,
498 /// A conflict or a failure left a flow that `resume` can go on with.
499 #[serde(default, skip_serializing_if = "is_false")]
500 pub resumable: bool,
501 /// The branches this run deleted on a remote, with the commit each held
502 /// right before (undoing the run pushes them back).
503 #[serde(default, skip_serializing_if = "Vec::is_empty")]
504 pub remote_deleted: Vec<crate::journal::RemoteRefChange>,
505}
506
507/// What the daemon persists to resume a stopped flow
508/// (`<git-dir>/gitpoulpi/flow-state.json`).
509#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
510pub struct FlowState {
511 pub request: FlowRequest,
512 pub steps: Vec<FlowStep>,
513 /// The step the flow stopped at (it is finished first when resumed).
514 pub next: usize,
515 /// It stopped on a conflict (the step is completed by committing or
516 /// continuing); otherwise it failed there and the step is run again.
517 #[serde(default)]
518 pub conflict: bool,
519 /// The branch that was checked out when the flow started.
520 pub original_head: Option<String>,
521 /// A squash that stopped on conflicts: the commit message to use once
522 /// they are resolved.
523 #[serde(default)]
524 pub squash_message: Option<String>,
525 #[serde(default)]
526 pub merge_request: Option<MergeRequestSpec>,
527}