1use camino::Utf8Path;
19use serde::Serialize;
20
21use crate::cli::init::InitArgs;
22use crate::diagnostic::{Diagnostic, Reason};
23use crate::embedded;
24use crate::error::RkError;
25use crate::held;
26use crate::landing::apply::{self, Action, Collision, Prepared, Replaced};
27use crate::landing::manifest::{self, Provider};
28use crate::landing::{self, lock};
29use crate::output::Output;
30use crate::profile::{CapabilityRequests, GitWorkflow, ProfileSnapshot};
31use crate::stage::CapabilityNote;
32
33#[derive(Debug, Serialize)]
35struct FileEntry {
36 path: String,
38 kind: &'static str,
40 action: &'static str,
43}
44
45#[derive(Debug, Serialize)]
47struct SentinelEntry {
48 path: String,
50 line: usize,
52 text: String,
54}
55
56#[derive(Debug, Serialize)]
58struct Report {
59 schema: &'static str,
61 mode: &'static str,
63 target: String,
65 profile: ProfileSnapshot,
67 git: GitWorkflow,
69 capabilities: CapabilityRequests,
71 #[serde(skip_serializing_if = "Option::is_none")]
73 repo: Option<String>,
74 selection: Vec<CapabilityNote>,
76 #[serde(skip_serializing_if = "Option::is_none")]
80 release_unavailable: Option<String>,
81 #[serde(skip_serializing_if = "Option::is_none")]
85 licence_refusal: Option<String>,
86 #[serde(skip_serializing_if = "Option::is_none")]
89 withheld: Option<Vec<landing::Withheld>>,
90 #[serde(skip_serializing_if = "Option::is_none")]
93 collisions: Option<Vec<Collision>>,
94 replaced: Vec<Replaced>,
97 config: crate::config::Plan,
98 files: Vec<FileEntry>,
100 #[serde(skip_serializing_if = "Option::is_none")]
102 sentinels: Option<Vec<SentinelEntry>>,
103 next: Vec<String>,
105}
106
107fn withheld_of(prepared: &Prepared) -> Option<Vec<landing::Withheld>> {
109 let withheld: Vec<landing::Withheld> = prepared
110 .projection
111 .omissions
112 .iter()
113 .map(|omission| landing::Withheld {
114 path: omission.destination.clone(),
115 reason: omission.reason.clone(),
116 })
117 .collect();
118 (!withheld.is_empty()).then_some(withheld)
119}
120
121pub fn run(args: &InitArgs) -> Result<(), RkError> {
130 let out = Output::new(args.json);
131 if !args.target.is_dir() {
132 return Err(RkError::refusal(
133 Diagnostic::new(
134 Reason::TargetNotFound,
135 format!(
136 "target {} is not a directory; nothing was written",
137 args.target
138 ),
139 )
140 .expected("an existing directory to land into")
141 .target_state("unchanged"),
142 ));
143 }
144 let lock = args
148 .apply
149 .then(|| lock::acquire(&args.target))
150 .transpose()?;
151 held::pause(apply::PAUSE_VAR, "locked", "proceed-locked");
156 let held = lock.as_ref().map_or_else(
157 || apply::Held::open(&args.target),
158 |lock| apply::Held::open_locked(&args.target, lock),
159 )?;
160 held::pause(apply::PAUSE_VAR, "held", "proceed-held");
162 let config = crate::config::load(held.base().as_std_path())?;
163 let purpose = if args.apply {
164 landing::Purpose::Init
165 } else {
166 landing::Purpose::Preview
167 };
168 let params = if let Some(root) = args.stage.as_deref() {
169 if answered(args) {
170 return Err(crate::stage::read::answered_twice());
171 }
172 let canonical = std::fs::canonicalize(args.target.as_std_path())?;
173 let receipt = crate::stage::read::load(root, &canonical)?;
174 let params = landing::Params::resolve(
175 held.base(),
176 &crate::stage::read::inputs(&receipt.parameters),
177 config.as_ref(),
178 None,
179 purpose,
180 )?;
181 crate::stage::read::confirm(¶ms, &receipt, root)?;
182 params
183 } else {
184 let inputs = landing::Inputs {
185 nix: args.nix_packaging.then_some(true),
186 reporting_policy: args.reporting_policy.then_some(true),
187 scorecard: args.scorecard.then_some(true),
188 workflow_guards: args.workflow_guards.then_some(true),
189 code_scanning: args
190 .code_scanning
191 .as_deref()
192 .map(Provider::parse)
193 .transpose()?,
194 ..args.profile.inputs()?
195 };
196 let inputs = if args.workflow_only {
197 crate::cli::profile_flags::workflow_only(inputs)?
198 } else {
199 inputs
200 };
201 landing::Params::resolve(held.base(), &inputs, config.as_ref(), None, purpose)?
202 };
203 if let Some(lock) = lock {
204 refuse_a_recorded_target(&held)?;
205 let mut prepared = apply::prepare(&held, None, ¶ms, config.as_ref())?;
206 apply::name_replacements(&mut prepared, &args.replace)?;
207 report_moved_secrets(out, &held, &prepared)?;
208 let landed = apply::land(&held, None, &prepared, apply::Origin::Init, &lock)?;
209 drop(lock);
210 report_apply(out, args, &held, ¶ms, &prepared, &landed)
211 } else {
212 let mut prepared = apply::prepare(&held, None, ¶ms, config.as_ref())?;
213 apply::name_replacements(&mut prepared, &args.replace)?;
214 report_moved_secrets(out, &held, &prepared)?;
215 let repo = (params.repo() != landing::REPO_PLACEHOLDER && !params.repo().is_empty())
216 .then(|| params.repo().to_owned());
217 if params.repo() == landing::REPO_PLACEHOLDER {
218 out.frame(
219 "note: no repository detected; an apply derives the owner from --repo <path>",
220 );
221 }
222 preview(out, args, ¶ms, repo, &prepared)
223 }
224}
225
226pub fn report_moved_secrets(
235 out: Output,
236 held: &apply::Held,
237 prepared: &Prepared,
238) -> Result<(), RkError> {
239 for moved in apply::replaced_secrets(held, prepared)? {
240 out.result_line(moved.line());
241 }
242 Ok(())
243}
244
245const SCHEMA: &str = "rk.init/11";
247
248const fn answered(args: &InitArgs) -> bool {
250 !args.profile.is_empty()
251 || args.nix_packaging
252 || args.reporting_policy
253 || args.scorecard
254 || args.workflow_guards
255 || args.workflow_only
256 || args.code_scanning.is_some()
257}
258
259fn selection_of(prepared: &Prepared) -> Vec<CapabilityNote> {
261 prepared
262 .projection
263 .capabilities
264 .iter()
265 .map(|selection| CapabilityNote::of(selection, &prepared.projection))
266 .collect()
267}
268
269pub(crate) fn describe_selection(out: Output, prepared: &Prepared) {
271 for note in selection_of(prepared) {
272 let mut line = format!("capability {}: {}", note.id, note.status);
273 if let Some(reason) = ¬e.reason {
274 line.push_str(" (");
275 line.push_str(reason);
276 line.push(')');
277 }
278 out.result_line(line);
279 if let Some(action) = ¬e.action {
280 out.result_line(format!(" action: {action}"));
281 }
282 }
283}
284
285#[allow(
288 clippy::too_many_lines,
289 reason = "one pass prints the profile, the selection, every decision, and the follow-up, and splitting it would separate a line from the value behind it"
290)]
291fn preview(
292 out: Output,
293 args: &InitArgs,
294 params: &landing::Params,
295 repo: Option<String>,
296 prepared: &Prepared,
297) -> Result<(), RkError> {
298 let flags = params.canonical_flags();
299 let flags = if params.forge().is_some() && repo.is_none() {
300 format!("{flags} --repo <owner/name>")
301 } else {
302 flags
303 };
304 let capabilities = params.capability_flags();
305 let mut next = vec![format!(
306 "rk init{flags}{capabilities} --target {} --apply",
307 args.target
308 )];
309 if let Some(reason) = prepared.projection.release_unavailable() {
310 next.insert(
311 0,
312 format!("the apply refuses until the release automation resolves: {reason}"),
313 );
314 }
315 if !prepared.collisions.is_empty() {
316 next.insert(
317 0,
318 "answer each collision above: --replace <path> saves a copy of a conflict and replaces it; the apply refuses every one not named"
319 .to_owned(),
320 );
321 }
322 if let Some(reason) = prepared.projection.licence_refusal.as_deref() {
323 next.insert(
324 0,
325 format!("the apply refuses until the licence condition is answered: {reason}"),
326 );
327 }
328 next.push(format!(
329 "rk stage --target {} stages the complete candidate for a byte comparison",
330 args.target
331 ));
332 out.result_line(format!(
333 "DRY RUN: rk init writes these files into {}; re-run with --apply",
334 args.target
335 ));
336 out.result_line(format!(
337 "profile: {}",
338 crate::commands::profile::describe(
339 params.profile(),
340 params.git(),
341 params.capabilities(),
342 params.repo()
343 )
344 ));
345 describe_selection(out, prepared);
346 for decision in &prepared.decisions {
347 out.result_line(format!(
348 "{} {}",
349 decision.action.as_str(),
350 decision.destination
351 ));
352 }
353 for collision in &prepared.collisions {
354 out.result_line(format!(
355 "collision {}: {}",
356 collision.path, collision.reason
357 ));
358 }
359 out.result_line(format!(
360 "{} {}\n{}",
361 prepared.config.action,
362 crate::config::CONFIG_PATH,
363 prepared.config.content
364 ));
365 for entry in &prepared.projection.omissions {
366 out.result_line(format!("withheld {}: {}", entry.destination, entry.reason));
367 if let Some(action) = &entry.action {
368 out.result_line(format!(" action: {action}"));
369 }
370 }
371 out.next(&next);
372 out.emit(&Report {
373 schema: SCHEMA,
374 config: prepared.config.clone(),
375 mode: "preview",
376 target: args.target.to_string(),
377 profile: params.profile().clone(),
378 git: params.git().clone(),
379 capabilities: params.capabilities().clone(),
380 repo,
381 selection: selection_of(prepared),
382 release_unavailable: prepared.projection.release_unavailable().map(str::to_owned),
383 licence_refusal: prepared.projection.licence_refusal.clone(),
384 withheld: withheld_of(prepared),
385 collisions: (!prepared.collisions.is_empty()).then(|| prepared.collisions.clone()),
386 replaced: apply::previewed_replacements(prepared),
387 files: prepared
388 .decisions
389 .iter()
390 .map(|decision| FileEntry {
391 path: decision.destination.clone(),
392 kind: decision.kind.as_str(),
393 action: decision.action.as_str(),
394 })
395 .chain(prepared.collisions.iter().map(|collision| FileEntry {
396 path: collision.path.clone(),
397 kind: landing::kind_of(&collision.path).map_or("unknown", landing::Kind::as_str),
398 action: "collision",
399 }))
400 .collect(),
401 sentinels: None,
402 next,
403 })
404}
405
406#[allow(
409 clippy::too_many_arguments,
410 reason = "the report reads the landed files through the held target and names them by the path the operator gave, which are two arguments for one target"
411)]
412#[allow(
413 clippy::too_many_lines,
414 reason = "one pass reports the profile, the selection, every decision, and the sentinels the operator still owes"
415)]
416fn report_apply(
417 out: Output,
418 args: &InitArgs,
419 held: &apply::Held,
420 params: &landing::Params,
421 prepared: &Prepared,
422 landed: &apply::Landed,
423) -> Result<(), RkError> {
424 let mut file_entries = Vec::new();
425 let mut sentinels = Vec::new();
426 out.result_line(format!(
427 "profile: {}",
428 crate::commands::profile::describe(
429 params.profile(),
430 params.git(),
431 params.capabilities(),
432 params.repo()
433 )
434 ));
435 describe_selection(out, prepared);
436 for decision in &prepared.decisions {
437 out.result_line(describe(decision));
438 if decision.action != Action::Released {
439 let bytes =
440 landing::read_recorded(held.base(), &decision.destination)?.unwrap_or_default();
441 collect_sentinels(
442 held.display(),
443 &decision.destination,
444 &bytes,
445 &mut sentinels,
446 );
447 }
448 file_entries.push(FileEntry {
449 path: decision.destination.clone(),
450 kind: decision.kind.as_str(),
451 action: decision.action.as_str(),
452 });
453 }
454 for entry in &prepared.projection.omissions {
455 out.result_line(format!("withheld {}: {}", entry.destination, entry.reason));
456 if let Some(action) = &entry.action {
457 out.result_line(format!(" action: {action}"));
458 }
459 }
460 out.result_line(format!(
461 "{} {}",
462 prepared.config.action,
463 crate::config::CONFIG_PATH
464 ));
465 let gated = prepared.projection.capabilities.iter().any(|selection| {
468 matches!(
469 selection.id,
470 crate::profile::catalog::TITLE_CHECK | crate::profile::catalog::COMMIT_CHECK
471 ) && selection.lands()
472 });
473 for (key, empty_line) in [
474 ("setup.required_check", "required_check = \"\""),
475 ("setup.bot.app_id", "app_id = \"\""),
476 ] {
477 if key == "setup.required_check" && !gated {
478 continue;
479 }
480 if let Some((index, _)) = prepared
481 .config
482 .content
483 .lines()
484 .enumerate()
485 .find(|(_, line)| line.starts_with(empty_line))
486 {
487 sentinels.push(SentinelEntry {
488 path: crate::config::CONFIG_PATH.into(),
489 line: index + 1,
490 text: format!("set {key} before forge setup"),
491 });
492 }
493 }
494 for entry in &landed.replaced {
495 if let Some(saved) = &entry.saved_to {
496 out.result_line(format!("saved {} to {saved}", entry.path));
497 }
498 }
499 out.result_line(format!("wrote {}", manifest::MANIFEST_PATH));
500 debug_assert_eq!(
501 landed.completed.last().map(String::as_str),
502 Some(manifest::MANIFEST_PATH)
503 );
504
505 if sentinels.is_empty() {
506 out.result_line("no sentinels to fill");
507 } else {
508 out.result_line("fill these sentinels before the workflow runs:");
509 for sentinel in &sentinels {
510 out.result_line(format!(
511 "{}:{}: {}",
512 sentinel.path, sentinel.line, sentinel.text
513 ));
514 }
515 }
516 let mut next = vec![
517 if sentinels.is_empty() {
518 "commit the landed files, the receipt included".to_owned()
519 } else {
520 "fill each sentinel above, then commit the landed files, the receipt included"
521 .to_owned()
522 },
523 format!("rk status --target {} reports this landing", args.target),
524 ];
525 if params.release_mode() == crate::profile::ReleaseMode::Automatic {
528 next.push("rk method setup orders what follows".to_owned());
529 } else if params.forge().is_some() {
530 next.push("rk setup --target . previews the applicable forge steps".to_owned());
531 }
532 out.next(&next);
533 out.emit(&Report {
534 schema: SCHEMA,
535 config: prepared.config.clone(),
536 mode: "apply",
537 target: args.target.to_string(),
538 profile: params.profile().clone(),
539 git: params.git().clone(),
540 capabilities: params.capabilities().clone(),
541 repo: (!params.repo().is_empty()).then(|| params.repo().to_owned()),
542 selection: selection_of(prepared),
543 release_unavailable: None,
544 licence_refusal: prepared.projection.licence_refusal.clone(),
545 withheld: withheld_of(prepared),
546 collisions: None,
547 replaced: landed.replaced.clone(),
548 files: file_entries,
549 sentinels: Some(sentinels),
550 next,
551 })
552}
553
554pub(crate) fn describe(decision: &apply::Decision) -> String {
556 match decision.action {
557 Action::Preserved | Action::Drift => format!(
558 "{} {} ({}, target-owned)",
559 decision.action.as_str(),
560 decision.destination,
561 decision.kind.as_str()
562 ),
563 Action::Released => format!(
564 "released {} (no longer produced; target-owned from this landing)",
565 decision.destination
566 ),
567 Action::Matched => format!(
568 "matched {} (already holds the candidate's bytes)",
569 decision.destination
570 ),
571 Action::Created | Action::Replaced => {
572 format!("{} {}", decision.action.as_str(), decision.destination)
573 }
574 }
575}
576
577fn refuse_a_recorded_target(held: &apply::Held) -> Result<(), RkError> {
580 if landing::manifest::load(held.base())?.is_none() {
581 return Ok(());
582 }
583 let target = held.display();
584 Err(RkError::refusal(
585 Diagnostic::new(
586 Reason::StateDrift,
587 format!(
588 "{target} already carries {}, and nothing was written",
589 manifest::MANIFEST_PATH
590 ),
591 )
592 .expected("a target without a landing receipt")
593 .action(format!(
594 "rk upgrade --target {target} takes it to this binary's projection"
595 ))
596 .target_state("unchanged"),
597 ))
598}
599
600fn collect_sentinels(
603 target: &Utf8Path,
604 destination: &str,
605 bytes: &[u8],
606 found: &mut Vec<SentinelEntry>,
607) {
608 let text = String::from_utf8_lossy(bytes);
609 for (idx, line) in text.lines().enumerate() {
610 if line.contains(embedded::SENTINEL) {
611 found.push(SentinelEntry {
612 path: target.join(destination).to_string(),
613 line: idx + 1,
614 text: line.trim().to_owned(),
615 });
616 }
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use super::{FileEntry, Report, SentinelEntry};
623 use crate::landing::CheckoutMode;
624 use crate::landing::Integration;
625 use crate::profile::{
626 CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
627 };
628 use crate::stage::CapabilityNote;
629
630 #[test]
634 fn the_init_report_schema_snapshot_holds() {
635 let apply = Report {
636 schema: super::SCHEMA,
637 config: crate::config::Plan {
638 action: "added",
639 changes: vec![],
640 content: "schema_version = 2\n".into(),
641 },
642 mode: "apply",
643 target: "/tmp/t".into(),
644 profile: ProfileSnapshot {
645 technologies: vec!["rust".into()],
646 forge: Some("github".into()),
647 release: ReleaseIntent {
648 mode: ReleaseMode::Automatic,
649 driver: Some("rust".into()),
650 style: Some(crate::landing::Style::Trunk),
651 line_prefix: Some("release/".into()),
652 registry: None,
653 },
654 },
655 git: GitWorkflow {
656 trunk: "master".into(),
657 checkout_mode: CheckoutMode::LinkedWorktree,
658 integration: Integration::Local,
659 merge_form: crate::landing::MergeForm::Squash,
660 },
661 capabilities: CapabilityRequests {
662 nix_packaging: true,
663 reporting_policy: true,
664 scorecard: true,
665 code_scanning: Some(crate::landing::Provider::CodeQl),
666 workflow_guards: Some(false),
667 },
668 repo: Some("acme/widget".into()),
669 selection: vec![CapabilityNote {
670 id: "git.guards".into(),
671 status: "selected".into(),
672 reason: None,
673 action: None,
674 destinations: vec!["AGENTS.md".into()],
675 }],
676 release_unavailable: None,
677 licence_refusal: None,
678 withheld: Some(vec![crate::landing::Withheld {
679 path: "flake.nix".into(),
680 reason: "the target already carries flake.nix".into(),
681 }]),
682 collisions: None,
683 replaced: vec![],
684 files: vec![FileEntry {
685 path: "release-plz.toml".into(),
686 kind: "seeded",
687 action: "created",
688 }],
689 sentinels: Some(vec![SentinelEntry {
690 path: "/tmp/t/release-plz.toml".into(),
691 line: 3,
692 text: "# TODO(release-kit): keep false for a binary-only crate".into(),
693 }]),
694 next: vec!["commit the landed files, the receipt included".into()],
695 };
696 assert_eq!(
697 serde_json::to_string(&apply).expect("a report serializes"),
698 r##"{"schema":"rk.init/11","mode":"apply","target":"/tmp/t","profile":{"technologies":["rust"],"forge":"github","release":{"mode":"automatic","driver":"rust","style":"trunk","line_prefix":"release/"}},"git":{"trunk":"master","checkout_mode":"linked-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":true,"reporting_policy":true,"scorecard":true,"code_scanning":"codeql","workflow_guards":false},"repo":"acme/widget","selection":[{"id":"git.guards","status":"selected","destinations":["AGENTS.md"]}],"withheld":[{"path":"flake.nix","reason":"the target already carries flake.nix"}],"replaced":[],"config":{"action":"added","changes":[],"content":"schema_version = 2\n"},"files":[{"path":"release-plz.toml","kind":"seeded","action":"created"}],"sentinels":[{"path":"/tmp/t/release-plz.toml","line":3,"text":"# TODO(release-kit): keep false for a binary-only crate"}],"next":["commit the landed files, the receipt included"]}"##
699 );
700 let preview = Report {
701 sentinels: None,
702 repo: None,
703 mode: "preview",
704 capabilities: CapabilityRequests {
705 nix_packaging: false,
706 reporting_policy: false,
707 scorecard: false,
708 code_scanning: None,
709 workflow_guards: Some(false),
710 },
711 selection: vec![],
712 release_unavailable: Some(
713 "the release automation at (python, gitlab) has no landable files".to_owned(),
714 ),
715 licence_refusal: Some("the target's Cargo.toml declares no license field".to_owned()),
716 withheld: None,
717 collisions: Some(vec![super::Collision {
718 path: "SECURITY.md".into(),
719 reason: "exists, and no receipt attributes it to release-kit".into(),
720 replaceable: true,
721 }]),
722 replaced: vec![super::Replaced {
723 path: "SECURITY.md".into(),
724 saved_to: None,
725 }],
726 ..apply
727 };
728 assert_eq!(
729 serde_json::to_string(&preview).expect("a report serializes"),
730 r#"{"schema":"rk.init/11","mode":"preview","target":"/tmp/t","profile":{"technologies":["rust"],"forge":"github","release":{"mode":"automatic","driver":"rust","style":"trunk","line_prefix":"release/"}},"git":{"trunk":"master","checkout_mode":"linked-worktree","integration":"local","merge_form":"squash"},"capabilities":{"nix_packaging":false,"reporting_policy":false,"scorecard":false,"workflow_guards":false},"selection":[],"release_unavailable":"the release automation at (python, gitlab) has no landable files","licence_refusal":"the target's Cargo.toml declares no license field","collisions":[{"path":"SECURITY.md","reason":"exists, and no receipt attributes it to release-kit","replaceable":true}],"replaced":[{"path":"SECURITY.md","saved_to":null}],"config":{"action":"added","changes":[],"content":"schema_version = 2\n"},"files":[{"path":"release-plz.toml","kind":"seeded","action":"created"}],"next":["commit the landed files, the receipt included"]}"#,
731 "a preview omits the sentinels, the unresolved repo, and an empty withheld list rather than serializing null"
732 );
733 }
734}