Skip to main content

release_kit/commands/
stage.rs

1//! `rk stage`: write the candidate this binary would land into a
2//! disposable stage, and `rk stage clean`: remove exactly one such stage.
3//!
4//! The create verb reads the target the way the landing verbs do, resolves
5//! the same parameters, computes the one pure projection, and materializes
6//! it under the resolved output. It writes nothing inside the target, and
7//! nothing about it changes what a production landing does: `rk init`,
8//! `rk upgrade`, `rk adopt`, and `rk status` never read a stage. The
9//! clean verb removes one directory whose own receipt names it, through
10//! held descriptors, and refuses everything else.
11
12use camino::{Utf8Path, Utf8PathBuf};
13use serde::Serialize;
14
15use crate::cli::stage::{StageAction, StageArgs};
16use crate::diagnostic::{Diagnostic, Reason};
17use crate::error::RkError;
18use crate::landing::manifest::{self, Style, Workflow};
19use crate::landing::{self, Params};
20use crate::output::Output;
21use crate::projection::{Projection, ProjectionInput, TargetEvidence};
22use crate::stage::{self, OutputSource, Receipt, clean};
23
24/// The machine form of a staging: the receipt as written, plus where the
25/// output path came from and what follows.
26#[derive(Debug, Serialize)]
27struct Report<'a> {
28    /// The receipt, its `schema` first.
29    #[serde(flatten)]
30    receipt: &'a Receipt,
31    /// `--output`, `RK_STAGE_ROOT`, or `state root`.
32    output_source: &'static str,
33    /// What plausibly follows.
34    next: Vec<String>,
35}
36
37/// The machine form of a cleanup.
38#[derive(Debug, Serialize)]
39struct CleanReport {
40    /// The shape version of this document.
41    schema: &'static str,
42    /// The stage that was removed.
43    stage_root: String,
44    /// The target its receipt named.
45    target: String,
46    /// Whether the directory is gone.
47    removed: bool,
48    /// The command that recreates it.
49    recovery: String,
50    /// What plausibly follows.
51    next: Vec<String>,
52}
53
54/// Stage the candidate, or remove a stage.
55///
56/// # Errors
57///
58/// Returns [`RkError::Missing`] for a target that is not a directory, the
59/// parameter resolution's own failures, a `destructive-refusal` for a
60/// stage root inside the target, a `state-drift` refusal for an existing
61/// nonempty output, and [`RkError::Io`] for a write that fails;
62/// `clean` returns the refusals `crate::stage::clean::validate` names.
63pub fn run(args: &StageArgs) -> Result<(), RkError> {
64    match &args.action {
65        Some(StageAction::Clean { path, json }) => remove(Output::new(*json), path),
66        None => create(args),
67    }
68}
69
70fn create(args: &StageArgs) -> Result<(), RkError> {
71    let out = Output::new(args.json);
72    if !args.target.is_dir() {
73        return Err(RkError::missing(
74            Diagnostic::new(
75                Reason::TargetNotFound,
76                format!("target {} is not a directory", args.target),
77            )
78            .expected("an existing repository to stage the candidate for"),
79        ));
80    }
81    let target = canonical(&args.target)?;
82    let config = crate::config::load(target.as_std_path())?;
83    // The record explains the target to the projection; a record this
84    // binary cannot read is reported and stands aside, because a stage is
85    // evidence and refusing to explain would leave the agent with less.
86    let record = match manifest::load(&target) {
87        Ok(record) => record,
88        Err(error) => {
89            out.warn(format!(
90                "the landing record was not read, so the candidate is computed as a first landing: {error}"
91            ));
92            None
93        }
94    };
95    let receipt_schema_version = stage::recorded_schema_version(&target);
96    let params = Params::resolve(
97        &target,
98        &landing::Inputs {
99            tech: args.tech.as_deref(),
100            forge: args.forge.as_deref(),
101            repo: args.repo.as_deref(),
102            workflow: args.workflow.as_deref().map(Workflow::parse).transpose()?,
103            style: args.style.as_deref().map(Style::parse).transpose()?,
104            nix: args.nix.then_some(true),
105        },
106        config.as_ref(),
107        record.as_ref(),
108        if record.is_some() {
109            landing::Purpose::Upgrade
110        } else {
111            landing::Purpose::Init
112        },
113    )?;
114    let evidence = TargetEvidence::gather(&target, record.as_ref())?;
115    let projection = Projection::compute(&ProjectionInput {
116        params: params.clone(),
117        evidence,
118    })?;
119    let (output, source) = stage::resolve_output(args.output.as_deref(), target.as_std_path())?;
120    let prepared = stage::prepare(&output, source, target.as_std_path())?;
121    let composed = stage::compose(
122        &projection,
123        &params,
124        target.as_std_path(),
125        prepared.resolved(),
126        record.as_ref(),
127        receipt_schema_version,
128    );
129    stage::write(&prepared, &composed)?;
130    let receipt = &composed.receipt;
131    let next = vec![
132        format!(
133            "read {}/{} for the candidate inventory and its reasons",
134            receipt.stage_root,
135            stage::RECEIPT_NAME
136        ),
137        format!(
138            "compare {}/{} with {} before anything lands",
139            receipt.stage_root,
140            stage::ARTIFACTS_DIR,
141            receipt.target
142        ),
143        format!(
144            "rk stage clean {} removes the stage once the landing is verified",
145            receipt.stage_root
146        ),
147    ];
148    render(out, receipt, source);
149    out.next(&next);
150    out.emit(&Report {
151        receipt,
152        output_source: source.as_str(),
153        next,
154    })
155}
156
157/// The human report, one fact per line.
158fn render(out: Output, receipt: &Receipt, source: OutputSource) {
159    out.result_line(format!("stage: {}", receipt.stage_root));
160    out.result_line(format!("output: from {}", source.as_str()));
161    out.result_line(format!("target: {}", receipt.target));
162    let parameters = &receipt.parameters;
163    out.result_line(format!(
164        "parameters: tech {}, forge {}, repo {}, workflow {}, style {}, nix {}",
165        parameters.tech,
166        parameters.forge,
167        parameters.repo,
168        parameters.workflow.as_str(),
169        parameters.style.map_or("unresolved", Style::as_str),
170        if parameters.nix { "on" } else { "off" }
171    ));
172    out.result_line(format!(
173        "landing record: {}",
174        receipt.receipt_schema_version.map_or_else(
175            || "none".to_owned(),
176            |version| format!("schema_version {version}")
177        )
178    ));
179    out.result_line(format!("candidates: {}", receipt.candidates.len()));
180    for candidate in &receipt.candidates {
181        out.result_line(format!(
182            "  {}/{} ({}, {})",
183            stage::ARTIFACTS_DIR,
184            candidate.destination,
185            candidate.kind.as_str(),
186            candidate.placement
187        ));
188    }
189    for note in &receipt.omissions {
190        out.result_line(format!("omitted {}: {}", note.destination, note.reason));
191    }
192    for note in &receipt.collisions {
193        out.result_line(format!("collision {}: {}", note.destination, note.reason));
194    }
195    for destination in &receipt.retired {
196        out.result_line(format!(
197            "retired {destination}: recorded, no longer produced; target-owned from the next landing"
198        ));
199    }
200    for destination in &receipt.seeded_present {
201        out.result_line(format!("seeded present {destination}: a landing keeps it"));
202    }
203    for destination in &receipt.state_present {
204        out.result_line(format!("state present {destination}: a landing keeps it"));
205    }
206    out.result_line(format!(
207        "reference: {}",
208        receipt
209            .reference
210            .iter()
211            .map(|root| format!("{}/{root}", stage::REFERENCE_DIR))
212            .collect::<Vec<_>>()
213            .join(", ")
214    ));
215}
216
217fn remove(out: Output, path: &Utf8Path) -> Result<(), RkError> {
218    let validated = clean::validate(path.as_std_path())?;
219    clean::remove(&validated)?;
220    let stage_root = validated.resolved().display().to_string();
221    let target = validated.target().to_owned();
222    let recovery = format!("rk stage --target {target} --output {stage_root}");
223    out.result_line(format!("removed {stage_root}"));
224    out.result_line(format!("recovery: {recovery} stages the candidate again"));
225    let next = vec![
226        format!("rk status --target {target} reports what the target holds"),
227        format!("rk stage --target {target} stages this binary's candidate again"),
228    ];
229    out.next(&next);
230    out.emit(&CleanReport {
231        schema: "rk.stage-clean/1",
232        stage_root,
233        target,
234        removed: true,
235        recovery,
236        next,
237    })
238}
239
240/// The canonical absolute target, as text.
241fn canonical(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
242    let path = std::fs::canonicalize(target)?;
243    Utf8PathBuf::from_path_buf(path)
244        .map_err(|path| RkError::Usage(format!("the target path is not UTF-8: {}", path.display())))
245}
246
247#[cfg(test)]
248mod tests {
249    use super::{CleanReport, Report};
250    use crate::stage::{Parameters, Receipt, STAGE_SCHEMA};
251
252    /// The `rk stage --json` report is the receipt with the output source
253    /// and the next lines beside it, held by snapshot.
254    #[test]
255    fn the_stage_report_schema_snapshot_holds() {
256        let receipt = Receipt {
257            schema: STAGE_SCHEMA.to_owned(),
258            rk_version: "0.0.0".into(),
259            target: "/tmp/t".into(),
260            stage_root: "/tmp/s".into(),
261            parameters: Parameters {
262                tech: "rust".into(),
263                forge: "github".into(),
264                repo: "acme/widget".into(),
265                workflow: crate::landing::Workflow::Branches,
266                style: None,
267                nix: true,
268                trunk: "main".into(),
269                line_prefix: "release/".into(),
270                security_contact: String::new(),
271                security_response: "best-effort".into(),
272            },
273            receipt_schema_version: None,
274            candidates: vec![],
275            omissions: vec![],
276            collisions: vec![],
277            retired: vec![],
278            seeded_present: vec![],
279            state_present: vec![],
280            reference: vec!["CHANGELOG.md".into()],
281        };
282        let report = Report {
283            receipt: &receipt,
284            output_source: "--output",
285            next: vec![
286                "rk stage clean /tmp/s removes the stage once the landing is verified".into(),
287            ],
288        };
289        assert_eq!(
290            serde_json::to_string(&report).expect("a report serializes"),
291            r#"{"schema":"rk.stage/1","rk_version":"0.0.0","target":"/tmp/t","stage_root":"/tmp/s","parameters":{"tech":"rust","forge":"github","repo":"acme/widget","workflow":"branches","style":null,"nix":true,"trunk":"main","line_prefix":"release/","security_contact":"","security_response":"best-effort"},"receipt_schema_version":null,"candidates":[],"omissions":[],"collisions":[],"retired":[],"seeded_present":[],"state_present":[],"reference":["CHANGELOG.md"],"output_source":"--output","next":["rk stage clean /tmp/s removes the stage once the landing is verified"]}"#
292        );
293    }
294
295    /// The complete `rk.stage-clean/1` shape, held by snapshot.
296    #[test]
297    fn the_stage_clean_report_schema_snapshot_holds() {
298        let report = CleanReport {
299            schema: "rk.stage-clean/1",
300            stage_root: "/tmp/s".into(),
301            target: "/tmp/t".into(),
302            removed: true,
303            recovery: "rk stage --target /tmp/t --output /tmp/s".into(),
304            next: vec!["rk status --target /tmp/t reports what the target holds".into()],
305        };
306        assert_eq!(
307            serde_json::to_string(&report).expect("a report serializes"),
308            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"]}"#
309        );
310    }
311}