Skip to main content

release_kit/setup/
before_state.rs

1//! The before-state a setup step saves ahead of a change it cannot undo.
2//!
3//! A step that removes or replaces forge state reads what it is about to
4//! change, through the same read-only calls the observers make, and
5//! writes it to the run's snapshot directory before its script runs: the
6//! repository settings behind the default branch and the merge settings,
7//! the rulesets, each ruleset a step replaces read in full, and the
8//! classic protections, and every branch
9//! `single-trunk` deletes, by name and commit, with a bundle where this
10//! clone holds the commit. A read that fails refuses the step, because a
11//! change nobody can restore is not one this setup makes. A saved state
12//! is a backup: no later run reads it to decide anything.
13//!
14//! SATISFIES forge-setup:a-step-is-idempotent
15
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use serde_json::{Value, json};
20
21use super::context::Ctx;
22use super::observe::{self, Api, Runner};
23use crate::detect::Forge;
24use crate::diagnostic::{Diagnostic, Reason};
25use crate::error::RkError;
26use crate::snapshot::{FORGE_DIR, REFS_DIR, Snapshot};
27
28/// Every step that removes or replaces forge state.
29pub const DESTRUCTIVE: [&str; 7] = [
30    "default-branch",
31    "single-trunk",
32    "merge-cleanup",
33    "protect-trunk",
34    "protect-tags",
35    "protect-release-lines",
36    "merge-on-order",
37];
38
39/// Whether `step` removes or replaces forge state.
40#[must_use]
41pub fn destructive(step: &str) -> bool {
42    DESTRUCTIVE.contains(&step)
43}
44
45/// The read-only calls that capture what `step` changes.
46#[must_use]
47pub fn reads(ctx: &Ctx, step: &str) -> Vec<String> {
48    let Some(forge) = ctx.forge else {
49        return Vec::new();
50    };
51    let trunk = ctx.trunk();
52    match forge {
53        Forge::Github => {
54            let repo = &ctx.repo;
55            match step {
56                "default-branch" | "merge-cleanup" => vec![format!("repos/{repo}")],
57                // merge-on-order disarms the open release requests.
58                "merge-on-order" => vec![format!("repos/{repo}/pulls?state=open&per_page=100")],
59                // protect-trunk also rewrites the squash settings.
60                "protect-trunk" => vec![
61                    format!("repos/{repo}"),
62                    format!("repos/{repo}/rulesets"),
63                    format!("repos/{repo}/branches/{trunk}/protection"),
64                ],
65                "protect-tags" | "protect-release-lines" => vec![format!("repos/{repo}/rulesets")],
66                "single-trunk" => candidates(ctx)
67                    .iter()
68                    .map(|branch| format!("repos/{repo}/git/ref/heads/{branch}"))
69                    .collect(),
70                _ => Vec::new(),
71            }
72        }
73        Forge::Gitlab => {
74            let project = ctx.repo.replace('/', "%2F");
75            match step {
76                "default-branch" | "merge-cleanup" => {
77                    vec![format!("projects/{project}")]
78                }
79                // merge-on-order asserts the pipeline requirement and
80                // disarms the open release requests.
81                "merge-on-order" => vec![
82                    format!("projects/{project}"),
83                    format!("projects/{project}/merge_requests?state=opened&per_page=100"),
84                ],
85                // protect-trunk also rewrites the merge settings.
86                "protect-trunk" => vec![
87                    format!("projects/{project}"),
88                    format!("projects/{project}/protected_branches"),
89                ],
90                "protect-release-lines" => {
91                    vec![format!("projects/{project}/protected_branches")]
92                }
93                "protect-tags" => vec![format!("projects/{project}/protected_tags")],
94                "single-trunk" => candidates(ctx)
95                    .iter()
96                    .map(|branch| format!("projects/{project}/repository/branches/{branch}"))
97                    .collect(),
98                _ => Vec::new(),
99            }
100        }
101    }
102}
103
104/// The rulesets `step` replaces in place, by name. The listing names
105/// them only, without their rules, conditions, or bypass actors, so each
106/// one the step finds is read in full by its id.
107fn replaced_rulesets<'c>(ctx: &'c Ctx, step: &str) -> Vec<&'c str> {
108    match (ctx.forge, step) {
109        (Some(Forge::Github), "protect-trunk") => vec![ctx.safety_ruleset(), ctx.trunk_ruleset()],
110        (Some(Forge::Github), "protect-tags") => vec![ctx.tag_ruleset()],
111        (Some(Forge::Github), "protect-release-lines") => vec![ctx.lines_ruleset()],
112        _ => Vec::new(),
113    }
114}
115
116/// The refusal of a step whose before-state this run cannot read.
117fn cannot_read(step: &str, path: &str, reason: &str) -> RkError {
118    RkError::refusal(
119        Diagnostic::new(
120            Reason::ObservationIncomplete,
121            format!(
122                "{step} changes forge state this run cannot read first ({path}: {reason}), so it did not run"
123            ),
124        )
125        .expected("the state the step changes, read and saved before it changes")
126        .action("rerun where the forge CLI can read this project's settings")
127        .target_state("unchanged")
128        .step(step),
129    )
130}
131
132/// The long-lived branches `single-trunk` may delete: every retired name
133/// but the trunk itself.
134fn candidates(ctx: &Ctx) -> Vec<String> {
135    ctx.retired_branches()
136        .iter()
137        .filter(|branch| branch.as_str() != ctx.trunk())
138        .cloned()
139        .collect()
140}
141
142/// Read and save the before-state of `step` into `snapshot`, returning
143/// where it went.
144///
145/// # Errors
146///
147/// An `observation-incomplete` refusal where a read fails for a reason
148/// other than a definite not-found, and the snapshot's own write
149/// failures.
150pub fn save(
151    ctx: &Ctx,
152    step: &str,
153    snapshot: &Snapshot,
154    run: &mut Runner,
155) -> Result<PathBuf, RkError> {
156    let mut answers = serde_json::Map::new();
157    let mut branches = Vec::new();
158    for path in reads(ctx, step) {
159        let answer = match observe::api_get(ctx, run, &path)? {
160            Api::Ok(body) => body,
161            Api::Missing => Value::Null,
162            Api::Failed(reason) => return Err(cannot_read(step, &path, &reason)),
163        };
164        if step == "single-trunk"
165            && let Some(commit) = answer
166                .pointer("/object/sha")
167                .or_else(|| answer.pointer("/commit/id"))
168                .and_then(Value::as_str)
169        {
170            let name = path.rsplit('/').next().unwrap_or_default().to_owned();
171            branches.push((name, commit.to_owned()));
172        }
173        answers.insert(path, answer);
174    }
175    let listing = format!("repos/{}/rulesets", ctx.repo);
176    for name in replaced_rulesets(ctx, step) {
177        // The script replaces the first ruleset of that name, and creates
178        // one where none is listed, which replaces nothing.
179        let Some(id) = answers
180            .get(&listing)
181            .and_then(Value::as_array)
182            .and_then(|list| list.iter().find(|ruleset| ruleset["name"] == name))
183            .and_then(|ruleset| ruleset["id"].as_u64())
184        else {
185            continue;
186        };
187        let path = format!("{listing}/{id}");
188        let answer = match observe::api_get(ctx, run, &path)? {
189            Api::Ok(body) => body,
190            // A ruleset the listing names is no absence when it reads as
191            // missing, and its definition is what the step replaces.
192            Api::Missing => {
193                return Err(cannot_read(
194                    step,
195                    &path,
196                    "the listed ruleset reads as missing",
197                ));
198            }
199            Api::Failed(reason) => return Err(cannot_read(step, &path, &reason)),
200        };
201        answers.insert(path, answer);
202    }
203    let mut bundled = Vec::new();
204    for (name, commit) in &branches {
205        if let Some(bundle) = bundle(ctx, snapshot, name, commit)? {
206            bundled.push(bundle.display().to_string());
207        }
208    }
209    let document = json!({
210        "step": step,
211        "taken_at": crate::applog::now_utc(),
212        "reads": answers,
213        "branches": branches
214            .iter()
215            .map(|(name, commit)| json!({"name": name, "commit": commit}))
216            .collect::<Vec<_>>(),
217        "bundles": bundled,
218    });
219    let bytes = serde_json::to_vec_pretty(&document).map_err(anyhow::Error::from)?;
220    snapshot.save(&Path::new(FORGE_DIR).join(format!("{step}.json")), &bytes)
221}
222
223/// Bundle `branch` at `commit` where this clone holds the commit; `None`
224/// where it does not, in which case the saved name and commit are the
225/// record, because `single-trunk` deletes only a branch the trunk
226/// already contains.
227fn bundle(
228    ctx: &Ctx,
229    snapshot: &Snapshot,
230    branch: &str,
231    commit: &str,
232) -> Result<Option<PathBuf>, RkError> {
233    let held = git(ctx)
234        .args(["cat-file", "-e", &format!("{commit}^{{commit}}")])
235        .status()
236        .is_ok_and(|status| status.success());
237    if !held {
238        return Ok(None);
239    }
240    let scratch = std::env::temp_dir().join(format!(
241        "rk-bundle-{}-{}",
242        std::process::id(),
243        branch.replace('/', "-")
244    ));
245    let _ = std::fs::remove_dir_all(&scratch);
246    std::fs::create_dir_all(&scratch)?;
247    let outcome = bundle_in(ctx, &scratch, snapshot, branch, commit);
248    let _ = std::fs::remove_dir_all(&scratch);
249    outcome
250}
251
252/// The bundle steps inside one scratch directory.
253fn bundle_in(
254    ctx: &Ctx,
255    scratch: &Path,
256    snapshot: &Snapshot,
257    branch: &str,
258    commit: &str,
259) -> Result<Option<PathBuf>, RkError> {
260    let clone = scratch.join("objects.git");
261    let file = scratch.join("branch.bundle");
262    // A bundle names refs, so the commit rides under the branch's own
263    // name in a throwaway clone that shares the objects, never as a ref
264    // of the operator's clone.
265    let cloned = git(ctx)
266        .args(["clone", "--quiet", "--bare", "--shared", "."])
267        .arg(&clone)
268        .status()
269        .is_ok_and(|status| status.success());
270    let named = cloned
271        && bare(&clone)
272            .args(["update-ref", &format!("refs/heads/{branch}"), commit])
273            .status()
274            .is_ok_and(|status| status.success());
275    let bundled = named
276        && bare(&clone)
277            .args(["bundle", "create", "--quiet"])
278            .arg(&file)
279            .arg(format!("refs/heads/{branch}"))
280            .status()
281            .is_ok_and(|status| status.success());
282    if !bundled {
283        return Ok(None);
284    }
285    let bytes = std::fs::read(&file)?;
286    snapshot
287        .save(
288            &Path::new(REFS_DIR).join(format!("{branch}.bundle")),
289            &bytes,
290        )
291        .map(Some)
292}
293
294/// A git command against the throwaway clone.
295fn bare(clone: &Path) -> Command {
296    let mut command = Command::new(crate::probes::git_bin());
297    for var in crate::maintenance::GIT_HOOK_VARS {
298        command.env_remove(var);
299    }
300    command.arg("-C").arg(clone);
301    command
302}
303
304/// A git command against the target alone.
305fn git(ctx: &Ctx) -> Command {
306    let mut command = Command::new(crate::probes::git_bin());
307    for var in crate::maintenance::GIT_HOOK_VARS {
308        command.env_remove(var);
309    }
310    command.arg("-C").arg(ctx.target.as_std_path());
311    command
312}
313
314#[cfg(test)]
315mod tests {
316    use super::{DESTRUCTIVE, destructive};
317
318    #[test]
319    fn the_destructive_steps_are_named_once() {
320        for step in DESTRUCTIVE {
321            assert!(destructive(step));
322        }
323        for step in ["package-check", "install-bot", "protections-check"] {
324            assert!(!destructive(step), "{step}");
325        }
326    }
327}