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 let landed = apply::land(&held, None, &prepared, apply::Origin::Init, &lock)?;
208 drop(lock);
209 report_apply(out, args, &held, ¶ms, &prepared, &landed)
210 } else {
211 let mut prepared = apply::prepare(&held, None, ¶ms, config.as_ref())?;
212 apply::name_replacements(&mut prepared, &args.replace)?;
213 let repo = (params.repo() != landing::REPO_PLACEHOLDER && !params.repo().is_empty())
214 .then(|| params.repo().to_owned());
215 if params.repo() == landing::REPO_PLACEHOLDER {
216 out.frame(
217 "note: no repository detected; an apply derives the owner from --repo <path>",
218 );
219 }
220 preview(out, args, ¶ms, repo, &prepared)
221 }
222}
223
224const SCHEMA: &str = "rk.init/11";
226
227const fn answered(args: &InitArgs) -> bool {
229 !args.profile.is_empty()
230 || args.nix_packaging
231 || args.reporting_policy
232 || args.scorecard
233 || args.workflow_guards
234 || args.workflow_only
235 || args.code_scanning.is_some()
236}
237
238fn selection_of(prepared: &Prepared) -> Vec<CapabilityNote> {
240 prepared
241 .projection
242 .capabilities
243 .iter()
244 .map(|selection| CapabilityNote::of(selection, &prepared.projection))
245 .collect()
246}
247
248pub(crate) fn describe_selection(out: Output, prepared: &Prepared) {
250 for note in selection_of(prepared) {
251 let mut line = format!("capability {}: {}", note.id, note.status);
252 if let Some(reason) = ¬e.reason {
253 line.push_str(" (");
254 line.push_str(reason);
255 line.push(')');
256 }
257 out.result_line(line);
258 if let Some(action) = ¬e.action {
259 out.result_line(format!(" action: {action}"));
260 }
261 }
262}
263
264#[allow(
267 clippy::too_many_lines,
268 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"
269)]
270fn preview(
271 out: Output,
272 args: &InitArgs,
273 params: &landing::Params,
274 repo: Option<String>,
275 prepared: &Prepared,
276) -> Result<(), RkError> {
277 let flags = params.canonical_flags();
278 let flags = if params.forge().is_some() && repo.is_none() {
279 format!("{flags} --repo <owner/name>")
280 } else {
281 flags
282 };
283 let capabilities = params.capability_flags();
284 let mut next = vec![format!(
285 "rk init{flags}{capabilities} --target {} --apply",
286 args.target
287 )];
288 if let Some(reason) = prepared.projection.release_unavailable() {
289 next.insert(
290 0,
291 format!("the apply refuses until the release automation resolves: {reason}"),
292 );
293 }
294 if !prepared.collisions.is_empty() {
295 next.insert(
296 0,
297 "answer each collision above: --replace <path> saves a copy of a conflict and replaces it; the apply refuses every one not named"
298 .to_owned(),
299 );
300 }
301 if let Some(reason) = prepared.projection.licence_refusal.as_deref() {
302 next.insert(
303 0,
304 format!("the apply refuses until the licence condition is answered: {reason}"),
305 );
306 }
307 next.push(format!(
308 "rk stage --target {} stages the complete candidate for a byte comparison",
309 args.target
310 ));
311 out.result_line(format!(
312 "DRY RUN: rk init writes these files into {}; re-run with --apply",
313 args.target
314 ));
315 out.result_line(format!(
316 "profile: {}",
317 crate::commands::profile::describe(
318 params.profile(),
319 params.git(),
320 params.capabilities(),
321 params.repo()
322 )
323 ));
324 describe_selection(out, prepared);
325 for decision in &prepared.decisions {
326 out.result_line(format!(
327 "{} {}",
328 decision.action.as_str(),
329 decision.destination
330 ));
331 }
332 for collision in &prepared.collisions {
333 out.result_line(format!(
334 "collision {}: {}",
335 collision.path, collision.reason
336 ));
337 }
338 out.result_line(format!(
339 "{} {}\n{}",
340 prepared.config.action,
341 crate::config::CONFIG_PATH,
342 prepared.config.content
343 ));
344 for entry in &prepared.projection.omissions {
345 out.result_line(format!("withheld {}: {}", entry.destination, entry.reason));
346 if let Some(action) = &entry.action {
347 out.result_line(format!(" action: {action}"));
348 }
349 }
350 out.next(&next);
351 out.emit(&Report {
352 schema: SCHEMA,
353 config: prepared.config.clone(),
354 mode: "preview",
355 target: args.target.to_string(),
356 profile: params.profile().clone(),
357 git: params.git().clone(),
358 capabilities: params.capabilities().clone(),
359 repo,
360 selection: selection_of(prepared),
361 release_unavailable: prepared.projection.release_unavailable().map(str::to_owned),
362 licence_refusal: prepared.projection.licence_refusal.clone(),
363 withheld: withheld_of(prepared),
364 collisions: (!prepared.collisions.is_empty()).then(|| prepared.collisions.clone()),
365 replaced: apply::previewed_replacements(prepared),
366 files: prepared
367 .decisions
368 .iter()
369 .map(|decision| FileEntry {
370 path: decision.destination.clone(),
371 kind: decision.kind.as_str(),
372 action: decision.action.as_str(),
373 })
374 .chain(prepared.collisions.iter().map(|collision| FileEntry {
375 path: collision.path.clone(),
376 kind: landing::kind_of(&collision.path).map_or("unknown", landing::Kind::as_str),
377 action: "collision",
378 }))
379 .collect(),
380 sentinels: None,
381 next,
382 })
383}
384
385#[allow(
388 clippy::too_many_arguments,
389 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"
390)]
391#[allow(
392 clippy::too_many_lines,
393 reason = "one pass reports the profile, the selection, every decision, and the sentinels the operator still owes"
394)]
395fn report_apply(
396 out: Output,
397 args: &InitArgs,
398 held: &apply::Held,
399 params: &landing::Params,
400 prepared: &Prepared,
401 landed: &apply::Landed,
402) -> Result<(), RkError> {
403 let mut file_entries = Vec::new();
404 let mut sentinels = Vec::new();
405 out.result_line(format!(
406 "profile: {}",
407 crate::commands::profile::describe(
408 params.profile(),
409 params.git(),
410 params.capabilities(),
411 params.repo()
412 )
413 ));
414 describe_selection(out, prepared);
415 for decision in &prepared.decisions {
416 out.result_line(describe(decision));
417 if decision.action != Action::Released {
418 let bytes =
419 landing::read_recorded(held.base(), &decision.destination)?.unwrap_or_default();
420 collect_sentinels(
421 held.display(),
422 &decision.destination,
423 &bytes,
424 &mut sentinels,
425 );
426 }
427 file_entries.push(FileEntry {
428 path: decision.destination.clone(),
429 kind: decision.kind.as_str(),
430 action: decision.action.as_str(),
431 });
432 }
433 for entry in &prepared.projection.omissions {
434 out.result_line(format!("withheld {}: {}", entry.destination, entry.reason));
435 if let Some(action) = &entry.action {
436 out.result_line(format!(" action: {action}"));
437 }
438 }
439 out.result_line(format!(
440 "{} {}",
441 prepared.config.action,
442 crate::config::CONFIG_PATH
443 ));
444 let gated = prepared.projection.capabilities.iter().any(|selection| {
447 matches!(
448 selection.id,
449 crate::profile::catalog::TITLE_CHECK | crate::profile::catalog::COMMIT_CHECK
450 ) && selection.lands()
451 });
452 for (key, empty_line) in [
453 ("setup.required_check", "required_check = \"\""),
454 ("setup.bot.app_id", "app_id = \"\""),
455 ] {
456 if key == "setup.required_check" && !gated {
457 continue;
458 }
459 if let Some((index, _)) = prepared
460 .config
461 .content
462 .lines()
463 .enumerate()
464 .find(|(_, line)| line.starts_with(empty_line))
465 {
466 sentinels.push(SentinelEntry {
467 path: crate::config::CONFIG_PATH.into(),
468 line: index + 1,
469 text: format!("set {key} before forge setup"),
470 });
471 }
472 }
473 for entry in &landed.replaced {
474 if let Some(saved) = &entry.saved_to {
475 out.result_line(format!("saved {} to {saved}", entry.path));
476 }
477 }
478 out.result_line(format!("wrote {}", manifest::MANIFEST_PATH));
479 debug_assert_eq!(
480 landed.completed.last().map(String::as_str),
481 Some(manifest::MANIFEST_PATH)
482 );
483
484 if sentinels.is_empty() {
485 out.result_line("no sentinels to fill");
486 } else {
487 out.result_line("fill these sentinels before the workflow runs:");
488 for sentinel in &sentinels {
489 out.result_line(format!(
490 "{}:{}: {}",
491 sentinel.path, sentinel.line, sentinel.text
492 ));
493 }
494 }
495 let mut next = vec![
496 if sentinels.is_empty() {
497 "commit the landed files, the receipt included".to_owned()
498 } else {
499 "fill each sentinel above, then commit the landed files, the receipt included"
500 .to_owned()
501 },
502 format!("rk status --target {} reports this landing", args.target),
503 ];
504 if params.release_mode() == crate::profile::ReleaseMode::Automatic {
507 next.push("rk method setup orders what follows".to_owned());
508 } else if params.forge().is_some() {
509 next.push("rk setup --target . previews the applicable forge steps".to_owned());
510 }
511 out.next(&next);
512 out.emit(&Report {
513 schema: SCHEMA,
514 config: prepared.config.clone(),
515 mode: "apply",
516 target: args.target.to_string(),
517 profile: params.profile().clone(),
518 git: params.git().clone(),
519 capabilities: params.capabilities().clone(),
520 repo: (!params.repo().is_empty()).then(|| params.repo().to_owned()),
521 selection: selection_of(prepared),
522 release_unavailable: None,
523 licence_refusal: prepared.projection.licence_refusal.clone(),
524 withheld: withheld_of(prepared),
525 collisions: None,
526 replaced: landed.replaced.clone(),
527 files: file_entries,
528 sentinels: Some(sentinels),
529 next,
530 })
531}
532
533pub(crate) fn describe(decision: &apply::Decision) -> String {
535 match decision.action {
536 Action::Preserved | Action::Drift => format!(
537 "{} {} ({}, target-owned)",
538 decision.action.as_str(),
539 decision.destination,
540 decision.kind.as_str()
541 ),
542 Action::Released => format!(
543 "released {} (no longer produced; target-owned from this landing)",
544 decision.destination
545 ),
546 Action::Matched => format!(
547 "matched {} (already holds the candidate's bytes)",
548 decision.destination
549 ),
550 Action::Created | Action::Replaced => {
551 format!("{} {}", decision.action.as_str(), decision.destination)
552 }
553 }
554}
555
556fn refuse_a_recorded_target(held: &apply::Held) -> Result<(), RkError> {
559 if landing::manifest::load(held.base())?.is_none() {
560 return Ok(());
561 }
562 let target = held.display();
563 Err(RkError::refusal(
564 Diagnostic::new(
565 Reason::StateDrift,
566 format!(
567 "{target} already carries {}, and nothing was written",
568 manifest::MANIFEST_PATH
569 ),
570 )
571 .expected("a target without a landing receipt")
572 .action(format!(
573 "rk upgrade --target {target} takes it to this binary's projection"
574 ))
575 .target_state("unchanged"),
576 ))
577}
578
579fn collect_sentinels(
582 target: &Utf8Path,
583 destination: &str,
584 bytes: &[u8],
585 found: &mut Vec<SentinelEntry>,
586) {
587 let text = String::from_utf8_lossy(bytes);
588 for (idx, line) in text.lines().enumerate() {
589 if line.contains(embedded::SENTINEL) {
590 found.push(SentinelEntry {
591 path: target.join(destination).to_string(),
592 line: idx + 1,
593 text: line.trim().to_owned(),
594 });
595 }
596 }
597}
598
599#[cfg(test)]
600mod tests {
601 use super::{FileEntry, Report, SentinelEntry};
602 use crate::landing::CheckoutMode;
603 use crate::landing::Integration;
604 use crate::profile::{
605 CapabilityRequests, GitWorkflow, ProfileSnapshot, ReleaseIntent, ReleaseMode,
606 };
607 use crate::stage::CapabilityNote;
608
609 #[test]
613 fn the_init_report_schema_snapshot_holds() {
614 let apply = Report {
615 schema: super::SCHEMA,
616 config: crate::config::Plan {
617 action: "added",
618 changes: vec![],
619 content: "schema_version = 2\n".into(),
620 },
621 mode: "apply",
622 target: "/tmp/t".into(),
623 profile: ProfileSnapshot {
624 technologies: vec!["rust".into()],
625 forge: Some("github".into()),
626 release: ReleaseIntent {
627 mode: ReleaseMode::Automatic,
628 driver: Some("rust".into()),
629 style: Some(crate::landing::Style::Trunk),
630 line_prefix: Some("release/".into()),
631 },
632 },
633 git: GitWorkflow {
634 trunk: "master".into(),
635 checkout_mode: CheckoutMode::LinkedWorktree,
636 integration: Integration::Local,
637 merge_form: crate::landing::MergeForm::Squash,
638 },
639 capabilities: CapabilityRequests {
640 nix_packaging: true,
641 reporting_policy: true,
642 scorecard: true,
643 code_scanning: Some(crate::landing::Provider::CodeQl),
644 workflow_guards: Some(false),
645 },
646 repo: Some("acme/widget".into()),
647 selection: vec![CapabilityNote {
648 id: "git.guards".into(),
649 status: "selected".into(),
650 reason: None,
651 action: None,
652 destinations: vec!["AGENTS.md".into()],
653 }],
654 release_unavailable: None,
655 licence_refusal: None,
656 withheld: Some(vec![crate::landing::Withheld {
657 path: "flake.nix".into(),
658 reason: "the target already carries flake.nix".into(),
659 }]),
660 collisions: None,
661 replaced: vec![],
662 files: vec![FileEntry {
663 path: "release-plz.toml".into(),
664 kind: "seeded",
665 action: "created",
666 }],
667 sentinels: Some(vec![SentinelEntry {
668 path: "/tmp/t/release-plz.toml".into(),
669 line: 3,
670 text: "# TODO(release-kit): keep false for a binary-only crate".into(),
671 }]),
672 next: vec!["commit the landed files, the receipt included".into()],
673 };
674 assert_eq!(
675 serde_json::to_string(&apply).expect("a report serializes"),
676 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"]}"##
677 );
678 let preview = Report {
679 sentinels: None,
680 repo: None,
681 mode: "preview",
682 capabilities: CapabilityRequests {
683 nix_packaging: false,
684 reporting_policy: false,
685 scorecard: false,
686 code_scanning: None,
687 workflow_guards: Some(false),
688 },
689 selection: vec![],
690 release_unavailable: Some(
691 "the release automation at (python, gitlab) has no landable files".to_owned(),
692 ),
693 licence_refusal: Some("the target's Cargo.toml declares no license field".to_owned()),
694 withheld: None,
695 collisions: Some(vec![super::Collision {
696 path: "SECURITY.md".into(),
697 reason: "exists, and no receipt attributes it to release-kit".into(),
698 replaceable: true,
699 }]),
700 replaced: vec![super::Replaced {
701 path: "SECURITY.md".into(),
702 saved_to: None,
703 }],
704 ..apply
705 };
706 assert_eq!(
707 serde_json::to_string(&preview).expect("a report serializes"),
708 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"]}"#,
709 "a preview omits the sentinels, the unresolved repo, and an empty withheld list rather than serializing null"
710 );
711 }
712}