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