use serde::Serialize;
use crate::cli::adopt::AdoptArgs;
use crate::diagnostic::{Diagnostic, Reason};
use crate::error::RkError;
use crate::held;
use crate::landing::apply::{self, Prepared};
use crate::landing::manifest::{self, Provider, Style, Workflow};
use crate::landing::{self, Kind, lock};
use crate::output::Output;
use crate::projection::Placement;
#[derive(Debug, Serialize)]
struct FileEntry {
path: String,
kind: &'static str,
action: &'static str,
}
#[derive(Debug, Serialize)]
struct Report {
schema: &'static str,
mode: &'static str,
target: String,
tech: String,
forge: String,
repo: String,
workflow: &'static str,
style: &'static str,
nix: bool,
scorecard: bool,
#[serde(skip_serializing_if = "Option::is_none")]
code_scanning: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
licence_refusal: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
withheld: Option<Vec<landing::Withheld>>,
config: crate::config::Plan,
files: Vec<FileEntry>,
next: Vec<String>,
}
pub fn run(args: &AdoptArgs) -> Result<(), RkError> {
let out = Output::new(args.json);
if !args.target.is_dir() {
return Err(RkError::missing(
Diagnostic::new(
Reason::TargetNotFound,
format!("target {} is not a directory", args.target),
)
.expected("an existing repository to adopt"),
));
}
let lock = args
.apply
.then(|| lock::acquire(&args.target))
.transpose()?;
held::pause(apply::PAUSE_VAR, "locked", "proceed-locked");
let held = lock.as_ref().map_or_else(
|| apply::Held::open(&args.target),
|lock| apply::Held::open_locked(&args.target, lock),
)?;
held::pause(apply::PAUSE_VAR, "held", "proceed-held");
if landing::manifest::load(held.base())?.is_some() {
return Err(RkError::refusal(
Diagnostic::new(
Reason::StateDrift,
format!(
"{} already carries {}; it needs no adoption",
args.target,
manifest::MANIFEST_PATH
),
)
.expected("a target without a landing receipt")
.action(format!(
"rk upgrade --target {} takes it to this binary's projection",
args.target
))
.target_state("unchanged"),
));
}
let config = crate::config::load(held.base().as_std_path())?;
let params = landing::Params::resolve(
held.base(),
&landing::Inputs {
tech: args.tech.as_deref(),
forge: args.forge.as_deref(),
repo: args.repo.as_deref(),
workflow: args.workflow.as_deref().map(Workflow::parse).transpose()?,
style: args.style.as_deref().map(Style::parse).transpose()?,
nix: args.nix.then_some(true),
scorecard: args.scorecard.then_some(true),
code_scanning: args
.code_scanning
.as_deref()
.map(Provider::parse)
.transpose()?,
},
config.as_ref(),
None,
landing::Purpose::Adopt,
)?;
let workflow = params.workflow();
let style = params
.style()
.ok_or_else(|| RkError::Usage("landing style is unresolved".into()))?;
let mut prepared = apply::prepare(&held, None, ¶ms, config.as_ref())?;
let files = verify(&held, workflow, &prepared)?;
prepared.collisions.clear();
for file in &files {
out.result_line(match file.action {
"differs" => format!("differs {} (seeded, target-owned)", file.path),
action => format!("{action} {}", file.path),
});
}
for entry in &prepared.projection.omissions {
out.result_line(format!("withheld {}: {}", entry.destination, entry.reason));
}
if let Some(lock) = &lock {
apply::land(&held, None, &prepared, apply::Origin::Adopt, lock)?;
out.result_line(format!("wrote {}", manifest::MANIFEST_PATH));
}
drop(lock);
report(out, args, ¶ms, style, &prepared, files)
}
fn report(
out: Output,
args: &AdoptArgs,
params: &landing::Params,
style: Style,
prepared: &Prepared,
files: Vec<FileEntry>,
) -> Result<(), RkError> {
let tech = params.tech().to_owned();
let repo = params.repo().to_owned();
let workflow = params.workflow();
let mut next = if args.apply {
vec![
"commit the config and the receipt".to_owned(),
format!("rk status --target {} reports this landing", args.target),
]
} else {
vec![format!(
"rk adopt --tech {tech} --forge {} --repo {repo} --workflow {} --style {}{} --target {} --apply writes the config and the receipt inside .release-kit/",
params.forge(),
workflow.as_str(),
style.as_str(),
params.capability_flags(),
args.target
)]
};
if let Some(reason) = prepared.projection.licence_refusal.as_deref() {
next.insert(
0,
format!("the apply refuses until the licence condition is answered: {reason}"),
);
}
out.result_line(format!(
"{} {}\n{}",
prepared.config.action,
crate::config::CONFIG_PATH,
prepared.config.content
));
out.next(&next);
out.emit(&Report {
schema: "rk.adopt/9",
config: prepared.config.clone(),
mode: if args.apply { "apply" } else { "preview" },
target: args.target.to_string(),
tech,
forge: params.forge().to_owned(),
repo,
workflow: workflow.as_str(),
style: style.as_str(),
nix: params.nix(),
scorecard: params.scorecard(),
code_scanning: params.code_scanning().map(Provider::as_str),
licence_refusal: prepared.projection.licence_refusal.clone(),
withheld: {
let withheld: Vec<landing::Withheld> = prepared
.projection
.omissions
.iter()
.map(|omission| landing::Withheld {
path: omission.destination.clone(),
reason: omission.reason.clone(),
})
.collect();
(!withheld.is_empty()).then_some(withheld)
},
files,
next,
})
}
fn verify(
held: &apply::Held,
workflow: Workflow,
prepared: &Prepared,
) -> Result<Vec<FileEntry>, RkError> {
let target = held.display();
let mut mismatches: Vec<String> = Vec::new();
let mut missing: Vec<String> = Vec::new();
let mut files = Vec::new();
let defects: Vec<String> = prepared
.projection
.collisions
.iter()
.map(|collision| collision.reason.clone())
.collect();
for candidate in &prepared.projection.candidates {
let path = held.base().join(&candidate.destination);
let regular = std::fs::symlink_metadata(path.as_std_path())
.is_ok_and(|metadata| metadata.is_file())
|| !path.exists();
if !regular {
mismatches.push(format!("{} (is not a regular file)", candidate.destination));
continue;
}
let current = landing::read_recorded(held.base(), &candidate.destination)?;
let Some(current) = current else {
let label = if path.exists() {
format!("{} (carries no release-kit block)", candidate.destination)
} else {
format!("{} (expected and missing)", candidate.destination)
};
missing.push(label);
continue;
};
let expected: &[u8] = match candidate.placement {
Placement::Whole => &candidate.bytes,
Placement::Region { .. } => candidate.region.as_deref().unwrap_or(&candidate.bytes),
};
let action = match candidate.kind {
Kind::Rendered | Kind::Seeded if current == expected => "matches",
Kind::Rendered => {
mismatches.push(format!(
"{} (differs from the rendered candidate)",
candidate.destination
));
"differs"
}
Kind::Seeded => "differs",
Kind::State => "state",
};
files.push(FileEntry {
path: candidate.destination.clone(),
kind: candidate.kind.as_str(),
action,
});
}
if mismatches.is_empty() && missing.is_empty() && defects.is_empty() {
return Ok(files);
}
let listed: Vec<String> = mismatches
.iter()
.cloned()
.chain(missing.iter().cloned())
.chain(defects.iter().cloned())
.collect();
Err(RkError::refusal(
Diagnostic::new(
Reason::StateDrift,
format!(
"this target is not adoptable as-is, and no receipt was written: {}",
listed.join(", ")
),
)
.expected(format!(
"every rendered destination matching the {} candidate, byte for byte",
workflow.as_str()
))
.action(format!(
"align first: rk stage --target {} stages the candidate for a byte comparison, and the rk-setup skill carries the migration that brings each destination to it; then re-run, or select the other candidate with --workflow or --style{}",
target,
if mismatches.iter().any(|path| path.starts_with("SECURITY.md ")) {
". SECURITY.md states two facts a target owns: set security.contact and security.response in .release-kit/config.toml to the wording this policy already carries, and the candidate matches"
} else {
""
}
))
.target_state("unchanged"),
))
}
#[cfg(test)]
mod tests {
use super::{FileEntry, Report};
#[test]
fn the_adopt_report_schema_snapshot_holds() {
let report = Report {
schema: "rk.adopt/9",
config: crate::config::Plan {
action: "added",
changes: vec![],
content: "schema_version = 1\n".into(),
},
mode: "apply",
target: "/tmp/t".into(),
tech: "rust".into(),
forge: "github".into(),
repo: "acme/widget".into(),
workflow: "branches",
style: "trunk",
nix: false,
scorecard: false,
code_scanning: Some("semgrep"),
licence_refusal: None,
withheld: None,
files: vec![FileEntry {
path: "release-plz.toml".into(),
kind: "seeded",
action: "differs",
}],
next: vec!["commit the config and the receipt".into()],
};
assert_eq!(
serde_json::to_string(&report).expect("a report serializes"),
r#"{"schema":"rk.adopt/9","mode":"apply","target":"/tmp/t","tech":"rust","forge":"github","repo":"acme/widget","workflow":"branches","style":"trunk","nix":false,"scorecard":false,"code_scanning":"semgrep","config":{"action":"added","changes":[],"content":"schema_version = 1\n"},"files":[{"path":"release-plz.toml","kind":"seeded","action":"differs"}],"next":["commit the config and the receipt"]}"#
);
}
}