1use 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
28pub 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#[must_use]
41pub fn destructive(step: &str) -> bool {
42 DESTRUCTIVE.contains(&step)
43}
44
45#[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" => vec![format!("repos/{repo}/pulls?state=open&per_page=100")],
59 "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" => vec![
82 format!("projects/{project}"),
83 format!("projects/{project}/merge_requests?state=opened&per_page=100"),
84 ],
85 "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
104fn 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
116fn 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
132fn 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
142pub 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 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 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
223fn 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
252fn 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 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
294fn 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
304fn 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}