1use std::fmt::Write as _;
13
14use camino::{Utf8Path, Utf8PathBuf};
15use serde::Serialize;
16
17use crate::cli::stage::{StageAction, StageArgs};
18use crate::diagnostic::{Diagnostic, Reason};
19use crate::error::RkError;
20use crate::landing::manifest::{self, Provider};
21use crate::landing::{self, Params};
22use crate::output::Output;
23use crate::projection::{Projection, ProjectionInput, TargetEvidence};
24use crate::stage::{self, OutputSource, Receipt, clean};
25
26#[derive(Debug, Serialize)]
29struct Report<'a> {
30 #[serde(flatten)]
32 receipt: &'a Receipt,
33 output_source: &'static str,
35 next: Vec<String>,
37}
38
39#[derive(Debug, Serialize)]
41struct CleanReport {
42 schema: &'static str,
44 stage_root: String,
46 target: String,
48 removed: bool,
50 recovery: String,
52 next: Vec<String>,
54}
55
56pub fn run(args: &StageArgs) -> Result<(), RkError> {
66 match &args.action {
67 Some(StageAction::Clean { path, json }) => remove(Output::new(*json), path),
68 Some(StageAction::Compare { root, target, json }) => {
69 crate::requirements::require("rk stage compare", &[crate::requirements::Tool::Git])?;
70 compare(Output::new(*json), root, target)
71 }
72 None => {
73 crate::requirements::require("rk stage", &[crate::requirements::Tool::Git])?;
74 create(args)
75 }
76 }
77}
78
79fn compare(out: Output, root: &Utf8Path, target: &Utf8Path) -> Result<(), RkError> {
81 if !target.is_dir() {
82 return Err(RkError::missing(
83 Diagnostic::new(
84 Reason::TargetNotFound,
85 format!("target {target} is not a directory"),
86 )
87 .expected("the repository the stage was taken for"),
88 ));
89 }
90 let report = stage::compare::compare(root, target)?;
91 out.result_line(format!("stage: {}", report.stage_root));
92 out.result_line(format!("target: {}", report.target));
93 if let Some(reason) = &report.history.reason {
94 out.result_line(format!("history: {reason}"));
95 }
96 for row in &report.rows {
97 let mut line = format!("{} {} ({}, {})", row.state, row.path, row.kind, row.word);
98 if let Some(provenance) = row.provenance {
99 let _ = write!(line, ", provenance {provenance}");
100 }
101 if row.word == "retired" {
102 line.push_str(if row.state == "retired" {
103 ", pending: the landing removes it"
104 } else {
105 ", settled: gone from the disk and the record"
106 });
107 }
108 if let Some(edited) = row.edited_after_added {
109 line.push_str(if edited {
110 ", edited after the commit that brought it"
111 } else {
112 ", untouched since the commit that brought it"
113 });
114 }
115 out.result_line(line);
116 }
117 let next = if stage::compare::rendered_equal(&report) {
118 vec!["every rendered destination is equal: the landing is proven".to_owned()]
119 } else {
120 let mut next: Vec<String> = report
121 .rows
122 .iter()
123 .filter(|row| row.state == "retired")
124 .map(|row| {
125 format!(
126 "a retirement is pending: the landing removes {}, and the proof waits for it",
127 row.path
128 )
129 })
130 .collect();
131 next.extend([
132 "a conflict reads collision: answer it, then name it with --replace <path> on the landing verb".to_owned(),
133 format!(
134 "rk init, rk upgrade, or rk adopt --stage {} --target {} previews the landing",
135 report.stage_root, report.target
136 ),
137 ]);
138 next
139 };
140 out.next(&next);
141 out.emit(&report)
142}
143
144fn create(args: &StageArgs) -> Result<(), RkError> {
145 let out = Output::new(args.json);
146 if !args.target.is_dir() {
147 return Err(RkError::missing(
148 Diagnostic::new(
149 Reason::TargetNotFound,
150 format!("target {} is not a directory", args.target),
151 )
152 .expected("an existing repository to stage the candidate for"),
153 ));
154 }
155 let target = canonical(&args.target)?;
156 let config = crate::config::load(target.as_std_path())?;
157 let record = match manifest::load(&target) {
161 Ok(record) => record,
162 Err(error) => {
163 out.warn(format!(
164 "the landing record was not read, so the candidate is computed as a first landing: {error}"
165 ));
166 None
167 }
168 };
169 let receipt_schema_version = stage::recorded_schema_version(&target);
170 let params = Params::resolve(
171 &target,
172 &landing::Inputs {
173 nix: args.nix_packaging.then_some(true),
174 reporting_policy: args.reporting_policy.then_some(true),
175 scorecard: args.scorecard.then_some(true),
176 workflow_guards: args.workflow_guards.then_some(true),
177 code_scanning: args
178 .code_scanning
179 .as_deref()
180 .map(Provider::parse)
181 .transpose()?,
182 ..args.profile.inputs()?
183 },
184 config.as_ref(),
185 record.as_ref(),
186 stage::purpose(&target, config.as_ref(), record.is_some())?,
187 )?;
188 let evidence = TargetEvidence::gather(&target, record.as_ref())?;
189 let projection = Projection::compute(&ProjectionInput {
190 params: params.clone(),
191 evidence,
192 })?;
193 landing::accepted_drift_faults(&projection, record.as_ref(), config.as_ref())?;
194 let (output, source) = stage::resolve_output(args.output.as_deref(), target.as_std_path())?;
195 let prepared = stage::prepare(&output, source, target.as_std_path())?;
196 let dropped = match record.as_ref() {
197 Some(record) => crate::landing::apply::dropped(
198 &crate::landing::apply::Held::open(&target)?,
199 record,
200 &projection,
201 )?,
202 None => Vec::new(),
203 };
204 let composed = stage::compose(
205 &projection,
206 ¶ms,
207 target.as_std_path(),
208 prepared.resolved(),
209 record.as_ref(),
210 &dropped,
211 receipt_schema_version,
212 );
213 stage::write(&prepared, &composed)?;
214 let receipt = &composed.receipt;
215 let next = vec![
216 format!(
217 "read {}/{} for the candidate inventory and its reasons",
218 receipt.stage_root,
219 stage::RECEIPT_NAME
220 ),
221 format!(
222 "compare {}/{} with {} before anything lands",
223 receipt.stage_root,
224 stage::ARTIFACTS_DIR,
225 receipt.target
226 ),
227 format!(
228 "rk stage clean {} removes the stage once the landing is verified",
229 receipt.stage_root
230 ),
231 ];
232 render(out, receipt, source);
233 out.next(&next);
234 out.emit(&Report {
235 receipt,
236 output_source: source.as_str(),
237 next,
238 })
239}
240
241fn render(out: Output, receipt: &Receipt, source: OutputSource) {
243 out.result_line(format!("stage: {}", receipt.stage_root));
244 out.result_line(format!("output: from {}", source.as_str()));
245 out.result_line(format!("target: {}", receipt.target));
246 let parameters = &receipt.parameters;
247 out.result_line(format!(
248 "parameters: {}",
249 crate::commands::profile::describe(
250 ¶meters.profile,
251 ¶meters.git,
252 ¶meters.capabilities,
253 ¶meters.repo
254 )
255 ));
256 for note in &receipt.capabilities {
257 out.result_line(format!(
258 "capability {}: {}{}",
259 note.id,
260 note.status,
261 note.reason
262 .as_deref()
263 .map_or_else(String::new, |reason| format!(" ({reason})"))
264 ));
265 }
266 out.result_line(format!(
267 "landing record: {}",
268 receipt.receipt_schema_version.map_or_else(
269 || "none".to_owned(),
270 |version| format!("schema_version {version}")
271 )
272 ));
273 out.result_line(format!("candidates: {}", receipt.candidates.len()));
274 for candidate in &receipt.candidates {
275 out.result_line(format!(
276 " {}/{} ({}, {})",
277 stage::ARTIFACTS_DIR,
278 candidate.destination,
279 candidate.kind.as_str(),
280 candidate.placement
281 ));
282 }
283 for note in &receipt.omissions {
284 out.result_line(format!("omitted {}: {}", note.destination, note.reason));
285 if let Some(action) = ¬e.action {
286 out.result_line(format!(" action: {action}"));
287 }
288 }
289 for note in &receipt.collisions {
290 out.result_line(format!("collision {}: {}", note.destination, note.reason));
291 }
292 for destination in &receipt.retired {
293 out.result_line(format!(
294 "retired {destination}: recorded, no longer produced, and unedited; a landing removes it"
295 ));
296 }
297 for destination in &receipt.dropped {
298 out.result_line(format!(
299 "dropped {destination}: recorded and no longer produced; a landing keeps it as the target's own"
300 ));
301 }
302 for moved in &receipt.secrets_moved {
303 out.result_line(moved.line());
304 }
305 for destination in &receipt.seeded_present {
306 out.result_line(format!("seeded present {destination}: a landing keeps it"));
307 }
308 for destination in &receipt.state_present {
309 out.result_line(format!("state present {destination}: a landing keeps it"));
310 }
311 out.result_line(format!(
312 "reference: {}",
313 receipt
314 .reference
315 .iter()
316 .map(|root| format!("{}/{root}", stage::REFERENCE_DIR))
317 .collect::<Vec<_>>()
318 .join(", ")
319 ));
320}
321
322fn remove(out: Output, path: &Utf8Path) -> Result<(), RkError> {
323 let validated = clean::validate(path.as_std_path())?;
324 clean::remove(&validated)?;
325 let stage_root = validated.resolved().display().to_string();
326 let target = validated.target().to_owned();
327 let recovery = format!("rk stage --target {target} --output {stage_root}");
328 out.result_line(format!("removed {stage_root}"));
329 out.result_line(format!("recovery: {recovery} stages the candidate again"));
330 let next = vec![
331 format!("rk status --target {target} reports what the target holds"),
332 format!("rk stage --target {target} stages this binary's candidate again"),
333 ];
334 out.next(&next);
335 out.emit(&CleanReport {
336 schema: "rk.stage-clean/1",
337 stage_root,
338 target,
339 removed: true,
340 recovery,
341 next,
342 })
343}
344
345fn canonical(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
347 let path = std::fs::canonicalize(target)?;
348 Utf8PathBuf::from_path_buf(path)
349 .map_err(|path| RkError::Usage(format!("the target path is not UTF-8: {}", path.display())))
350}
351
352#[cfg(test)]
353mod tests {
354 use super::{CleanReport, Report};
355 use crate::landing::Integration;
356 use crate::stage::{Parameters, Receipt, STAGE_SCHEMA};
357
358 #[test]
361 fn the_stage_report_schema_snapshot_holds() {
362 let receipt = Receipt {
363 schema: STAGE_SCHEMA.to_owned(),
364 rk_version: "0.0.0".into(),
365 target: "/tmp/t".into(),
366 stage_root: "/tmp/s".into(),
367 parameters: Parameters {
368 profile: crate::profile::ProfileSnapshot {
369 technologies: vec!["rust".into()],
370 forge: Some("github".into()),
371 release: crate::profile::ReleaseIntent {
372 mode: crate::profile::ReleaseMode::Automatic,
373 driver: Some("rust".into()),
374 style: None,
375 line_prefix: Some("release/".into()),
376 registry: None,
377 build: None,
378 },
379 },
380 git: crate::profile::GitWorkflow {
381 trunk: "main".into(),
382 checkout_mode: crate::landing::CheckoutMode::MainWorktree,
383 integration: Integration::Local,
384 merge_form: crate::landing::MergeForm::Squash,
385 },
386 capabilities: crate::profile::CapabilityRequests {
387 nix_packaging: true,
388 reporting_policy: true,
389 scorecard: false,
390 code_scanning: None,
391 workflow_guards: Some(false),
392 },
393 repo: "acme/widget".into(),
394 security_contact: String::new(),
395 required_check: String::new(),
396 dev_environment: None,
397 security_response: "best-effort".into(),
398 security_scope: String::new(),
399 },
400 capabilities: vec![],
401 receipt_schema_version: None,
402 candidates: vec![],
403 omissions: vec![],
404 collisions: vec![],
405 retired: vec![],
406 dropped: vec![],
407 seeded_present: vec![],
408 state_present: vec![],
409 secrets_moved: Vec::new(),
410 reference: vec!["CHANGELOG.md".into()],
411 };
412 let report = Report {
413 receipt: &receipt,
414 output_source: "--output",
415 next: vec![
416 "rk stage clean /tmp/s removes the stage once the landing is verified".into(),
417 ],
418 };
419 assert_eq!(
420 serde_json::to_string(&report).expect("a report serializes"),
421 r#"{"schema":"rk.stage/9","rk_version":"0.0.0","target":"/tmp/t","stage_root":"/tmp/s","parameters":{"profile":{"technologies":["rust"],"forge":"github","release":{"mode":"automatic","driver":"rust","line_prefix":"release/"}},"git":{"trunk":"main","checkout_mode":"main-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":true,"reporting_policy":true,"scorecard":false,"workflow_guards":false},"repo":"acme/widget","security_contact":"","security_response":"best-effort","required_check":""},"capabilities":[],"receipt_schema_version":null,"candidates":[],"omissions":[],"collisions":[],"retired":[],"dropped":[],"seeded_present":[],"state_present":[],"secrets_moved":[],"reference":["CHANGELOG.md"],"output_source":"--output","next":["rk stage clean /tmp/s removes the stage once the landing is verified"]}"#
422 );
423 }
424
425 #[test]
427 fn the_stage_clean_report_schema_snapshot_holds() {
428 let report = CleanReport {
429 schema: "rk.stage-clean/1",
430 stage_root: "/tmp/s".into(),
431 target: "/tmp/t".into(),
432 removed: true,
433 recovery: "rk stage --target /tmp/t --output /tmp/s".into(),
434 next: vec!["rk status --target /tmp/t reports what the target holds".into()],
435 };
436 assert_eq!(
437 serde_json::to_string(&report).expect("a report serializes"),
438 r#"{"schema":"rk.stage-clean/1","stage_root":"/tmp/s","target":"/tmp/t","removed":true,"recovery":"rk stage --target /tmp/t --output /tmp/s","next":["rk status --target /tmp/t reports what the target holds"]}"#
439 );
440 }
441}