1use 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#[derive(Debug, Serialize)]
26struct FileEntry {
27 path: String,
29 kind: &'static str,
31 action: &'static str,
33}
34
35#[derive(Debug, Serialize)]
37struct Report {
38 schema: &'static str,
40 mode: &'static str,
42 target: String,
44 tech: String,
46 forge: String,
48 repo: String,
50 workflow: &'static str,
53 style: &'static str,
54 nix: bool,
56 #[serde(skip_serializing_if = "Option::is_none")]
59 withheld: Option<Vec<landing::Withheld>>,
60 config: crate::config::Plan,
61 files: Vec<FileEntry>,
63 next: Vec<String>,
65}
66
67#[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(), ¶ms, 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(¶ms)?;
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
215fn 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 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 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 #[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}