Skip to main content

release_kit/commands/
adopt.rs

1//! `rk adopt`: a pre-record target becomes a recorded one.
2//!
3//! Adoption verifies the payload before writing configuration and its record. The
4//! candidate payload is rendered first, exactly as `rk init` would
5//! produce it; every `rendered` destination must match it byte for byte,
6//! and one mismatch refuses the whole adoption listing every mismatch in
7//! one run. Blessing whatever is on disk would launder arbitrary drift
8//! into release-kit ownership, so nothing here ever takes the disk as the
9//! baseline — and no target file is ever changed: not a byte, not a mode,
10//! not a sentinel. Configuration writes before the manifest, after every check
11//! has passed.
12
13use serde::Serialize;
14
15use crate::cli::adopt::AdoptArgs;
16use crate::diagnostic::{Diagnostic, Reason};
17use crate::digest::Digest;
18use crate::error::RkError;
19use crate::landing::manifest::{self, FileRecord, Manifest, Parameters, Style, Workflow};
20use crate::landing::{self, Kind};
21use crate::output::Output;
22use crate::registry;
23
24/// One verified destination.
25#[derive(Debug, Serialize)]
26struct FileEntry {
27    /// The destination, relative to the target.
28    path: String,
29    /// The declared ownership kind.
30    kind: &'static str,
31    /// `matches`, `differs` for a seeded file, or `state`.
32    action: &'static str,
33}
34
35/// The machine form of an adoption report.
36#[derive(Debug, Serialize)]
37struct Report {
38    /// The shape version of this document.
39    schema: &'static str,
40    /// `preview` or `apply`.
41    mode: &'static str,
42    /// The target directory.
43    target: String,
44    /// The technology whose payload was verified.
45    tech: String,
46    /// The forge whose payload was verified.
47    forge: String,
48    /// The parameter the candidate was rendered under.
49    repo: String,
50    /// The working-copy mode the candidate was rendered under and the
51    /// record carries.
52    workflow: &'static str,
53    style: &'static str,
54    /// Whether the record carries the Nix capability.
55    nix: bool,
56    /// The Nix destinations excluded from the candidate, each with why;
57    /// absent where nothing was withheld.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    withheld: Option<Vec<landing::Withheld>>,
60    config: crate::config::Plan,
61    /// Every destination, with its verification result.
62    files: Vec<FileEntry>,
63    /// What plausibly follows.
64    next: Vec<String>,
65}
66
67/// Verify the target against the rendered candidate and, on `--apply`,
68/// write the config and record inside `.release-kit/`.
69///
70/// # Errors
71///
72/// Returns a refusal for a target already carrying a record, for any
73/// `rendered` mismatch or missing expected file — listing every one in
74/// one run — and [`RkError::Missing`] where detection resolves no
75/// technology, forge, or repository and no flag covers the gap.
76#[allow(
77    clippy::too_many_lines,
78    reason = "one adopt run is one linear sequence of checks against one target, and cutting it would separate a refusal from the order it is reported in"
79)]
80pub fn run(args: &AdoptArgs) -> Result<(), RkError> {
81    let out = Output::new(args.json);
82    if !args.target.is_dir() {
83        return Err(RkError::missing(
84            Diagnostic::new(
85                Reason::TargetNotFound,
86                format!("target {} is not a directory", args.target),
87            )
88            .expected("an existing repository to adopt"),
89        ));
90    }
91    if landing::manifest::load(&args.target)?.is_some() {
92        return Err(RkError::refusal(
93            Diagnostic::new(
94                Reason::StateDrift,
95                format!(
96                    "{} already carries {}; it needs no adoption",
97                    args.target,
98                    manifest::MANIFEST_PATH
99                ),
100            )
101            .expected("a target without a landing record")
102            .action(format!(
103                "rk upgrade --target {} takes it to this binary's payload",
104                args.target
105            ))
106            .target_state("unchanged"),
107        ));
108    }
109    let config = crate::config::load(args.target.as_std_path())?;
110    let params = landing::Params::resolve(
111        &args.target,
112        &landing::Inputs {
113            tech: args.tech.as_deref(),
114            forge: args.forge.as_deref(),
115            repo: args.repo.as_deref(),
116            workflow: args.workflow.as_deref().map(Workflow::parse).transpose()?,
117            style: args.style.as_deref().map(Style::parse).transpose()?,
118            nix: args.nix.then_some(true),
119        },
120        config.as_ref(),
121        None,
122        landing::Purpose::Adopt,
123    )?;
124    let config =
125        crate::config::Plan::new(args.target.as_std_path(), &params, config.as_ref(), None)?;
126    let tech = params.tech().to_owned();
127    let repo = params.repo().to_owned();
128    let workflow = params.workflow();
129    let style = params
130        .style()
131        .ok_or_else(|| RkError::Usage("landing style is unresolved".into()))?;
132    let mut entries = landing::projection(&params)?;
133    let withheld = landing::withhold_nix(&args.target, params.nix(), None, &mut entries)?;
134    let (files, records) = verify(args, workflow, &entries)?;
135
136    for file in &files {
137        out.result_line(match file.action {
138            "differs" => format!("differs {} (seeded, target-owned)", file.path),
139            action => format!("{action} {}", file.path),
140        });
141    }
142    for entry in &withheld {
143        out.result_line(format!("withheld {}: {}", entry.path, entry.reason));
144    }
145
146    if args.apply {
147        config.apply(args.target.as_std_path())?;
148        manifest::write(
149            &args.target,
150            &Manifest {
151                schema_version: manifest::SCHEMA_VERSION,
152                rk_version: env!("CARGO_PKG_VERSION").to_owned(),
153                payload_sha256: crate::commands::payload::report().payload_sha256,
154                origin: "adopt".to_owned(),
155                tech: tech.clone(),
156                forge: params.forge().to_owned(),
157                landed_at: manifest::now(),
158                parameters: Parameters {
159                    repo: repo.clone(),
160                    workflow,
161                    style: Some(style),
162                    nix: params.nix(),
163                    trunk: params.trunk().to_owned(),
164                    line_prefix: params.line_prefix().to_owned(),
165                },
166                files: records,
167                pins: registry::pins_for(&tech)
168                    .into_iter()
169                    .map(|pin| (pin.name, pin.version))
170                    .collect(),
171            },
172        )?;
173        out.result_line(format!("wrote {}", manifest::MANIFEST_PATH));
174    }
175
176    let next = if args.apply {
177        vec![
178            "commit the config and the record".to_owned(),
179            format!("rk status --target {} reports this landing", args.target),
180        ]
181    } else {
182        vec![format!(
183            "rk adopt --tech {tech} --forge {} --repo {repo} --workflow {} --style {}{} --target {} --apply writes the config and the record inside .release-kit/",
184            params.forge().to_owned(),
185            workflow.as_str(),
186            style.as_str(),
187            if params.nix() { " --nix" } else { "" },
188            args.target
189        )]
190    };
191    out.result_line(format!(
192        "{} {}\n{}",
193        config.action,
194        crate::config::CONFIG_PATH,
195        config.content
196    ));
197    out.next(&next);
198    out.emit(&Report {
199        schema: "rk.adopt/5",
200        config,
201        mode: if args.apply { "apply" } else { "preview" },
202        target: args.target.to_string(),
203        tech,
204        forge: params.forge().to_owned(),
205        repo,
206        workflow: workflow.as_str(),
207        style: style.as_str(),
208        nix: params.nix(),
209        withheld: (!withheld.is_empty()).then_some(withheld),
210        files,
211        next,
212    })
213}
214
215/// The verification pass: every destination checked against the rendered
216/// candidate, every failure collected before the one refusal, so an
217/// operator resolves everything and re-runs once.
218fn verify(
219    args: &AdoptArgs,
220    workflow: Workflow,
221    entries: &[landing::Entry],
222) -> Result<(Vec<FileEntry>, Vec<FileRecord>), RkError> {
223    let mut mismatches: Vec<String> = Vec::new();
224    let mut missing: Vec<String> = Vec::new();
225    let mut files = Vec::new();
226    let mut records = Vec::new();
227    // An ill-formed hook file lists beside the mismatches rather than
228    // refusing alone, so one run still names everything unadoptable.
229    let mut defects: Vec<String> = Vec::new();
230    if let Some(defect) = landing::hooks_file_defect(&args.target)? {
231        defects.push(defect);
232    }
233    for entry in entries {
234        let Some(bytes) = landing::read_destination(&args.target, entry)? else {
235            // A block-placed artifact reads as absent from a file that
236            // exists; the operator's remedy differs, so the label must.
237            let label = if args.target.join(&entry.destination).exists() {
238                format!("{} (carries no release-kit block)", entry.destination)
239            } else {
240                format!("{} (expected and missing)", entry.destination)
241            };
242            missing.push(label);
243            continue;
244        };
245        let action = match entry.kind {
246            Kind::Rendered | Kind::Seeded if bytes == entry.rendered => "matches",
247            Kind::Rendered => {
248                mismatches.push(entry.destination.clone());
249                "differs"
250            }
251            Kind::Seeded => "differs",
252            Kind::State => "state",
253        };
254        files.push(FileEntry {
255            path: entry.destination.clone(),
256            kind: entry.kind.as_str(),
257            action,
258        });
259        records.push(FileRecord {
260            destination: entry.destination.clone(),
261            kind: entry.kind,
262            sha256: Digest::of(&bytes),
263            baseline_sha256: match entry.kind {
264                Kind::State => None,
265                Kind::Rendered | Kind::Seeded => Some(Digest::of(&entry.baseline)),
266            },
267        });
268    }
269    if mismatches.is_empty() && missing.is_empty() && defects.is_empty() {
270        return Ok((files, records));
271    }
272    let listed: Vec<String> = mismatches
273        .iter()
274        .map(|path| format!("{path} (differs from the rendered candidate)"))
275        .chain(missing.iter().cloned())
276        .chain(defects.iter().cloned())
277        .collect();
278    Err(RkError::refusal(
279        Diagnostic::new(
280            Reason::StateDrift,
281            format!(
282                "this target is not adoptable as-is, and no record was written: {}",
283                listed.join(", ")
284            ),
285        )
286        .expected(format!(
287            "every rendered destination matching the {} candidate, byte for byte",
288            workflow.as_str()
289        ))
290        .action(
291            "align first: rk adopt without --apply lists every differing destination; bring each to the selected candidate's bytes — rk snippet and rk payload print them — then re-run, or select the other candidate with --workflow or --style",
292        )
293        .target_state("unchanged"),
294    ))
295}
296
297#[cfg(test)]
298mod tests {
299    use super::{FileEntry, Report};
300
301    /// The complete `rk.adopt/5` shape, held by snapshot.
302    #[test]
303    fn the_adopt_report_schema_snapshot_holds() {
304        let report = Report {
305            schema: "rk.adopt/5",
306            config: crate::config::Plan {
307                action: "added",
308                changes: vec![],
309                content: "schema_version = 1\n".into(),
310            },
311            mode: "apply",
312            target: "/tmp/t".into(),
313            tech: "rust".into(),
314            forge: "github".into(),
315            repo: "acme/widget".into(),
316            workflow: "branches",
317            style: "trunk",
318            nix: false,
319            withheld: None,
320            files: vec![FileEntry {
321                path: "release-plz.toml".into(),
322                kind: "seeded",
323                action: "differs",
324            }],
325            next: vec!["commit the config and the record".into()],
326        };
327        assert_eq!(
328            serde_json::to_string(&report).expect("a report serializes"),
329            r#"{"schema":"rk.adopt/5","mode":"apply","target":"/tmp/t","tech":"rust","forge":"github","repo":"acme/widget","workflow":"branches","style":"trunk","nix":false,"config":{"action":"added","changes":[],"content":"schema_version = 1\n"},"files":[{"path":"release-plz.toml","kind":"seeded","action":"differs"}],"next":["commit the config and the record"]}"#
330        );
331    }
332}