1use serde::Serialize;
17
18use camino::Utf8Path;
19
20use crate::cli::self_depend::{
21 AddArgs, Caller, CheckArgs, CleanArgs, SelfDependAction, SelfDependArgs, StatusArgs, SyncArgs,
22};
23use crate::diagnostic::{Diagnostic, Reason};
24use crate::error::RkError;
25use crate::output::Output;
26use crate::probes::{self, ProbeStatus};
27use crate::self_depend::check;
28use crate::self_depend::discover::{self, Discovery};
29use crate::self_depend::fragments::{self, Fragment};
30use crate::self_depend::guard::{self, Acquired};
31use crate::self_depend::leftovers::{self, Action, Leftover};
32use crate::self_depend::manager::{self, Entry, Manager, PinRead};
33use crate::self_depend::matrix::{self, Mode, Pair, Support};
34use crate::self_depend::txn::{self, AbortFailure, Recovery, StepFailure};
35use crate::self_depend::venue::Venue;
36use crate::self_depend::{self, Observed, Presence, pin};
37
38#[derive(Debug, Serialize)]
40struct StatusReport<'a> {
41 schema: &'static str,
43 target: &'a str,
45 state: &'static str,
49 #[serde(skip_serializing_if = "Option::is_none")]
52 acquisition: Option<&'a crate::config::Acquisition>,
53 #[serde(skip_serializing_if = "Option::is_none")]
55 wired: Option<Manager>,
56 managers: &'a [Entry],
59 envrc: Presence,
62 envrc_check: bool,
64 envrc_old_sync: bool,
66 pending: bool,
68 host: Host,
70 leftovers: &'a [Leftover],
72 next: &'a [String],
74}
75
76#[derive(Debug, Serialize)]
78struct AddReport<'a> {
79 schema: &'static str,
81 mode: &'static str,
83 target: &'a str,
85 tag: &'a str,
87 tag_source: &'static str,
89 manager: Manager,
91 venue: Venue,
93 support: Mode,
96 #[serde(skip_serializing_if = "Option::is_none")]
98 reason: Option<&'static str>,
99 file: &'a str,
102 file_present: Presence,
104 envrc: Presence,
106 written: &'a [String],
109 #[serde(skip_serializing_if = "Option::is_none")]
111 refusal: Option<&'a str>,
112 fragments: &'a [Fragment],
114 next: &'a [String],
116}
117
118#[derive(Debug, Serialize)]
120struct CleanReport<'a> {
121 schema: &'static str,
123 mode: &'static str,
125 target: &'a str,
127 leftovers: &'a [Leftover],
130 removed: &'a [String],
132 rewritten: &'a [String],
134 manual: &'a [Manual],
137 next: &'a [String],
139}
140
141#[derive(Debug, Clone, Serialize)]
143struct Manual {
144 id: &'static str,
146 file: String,
148 #[serde(skip_serializing_if = "Option::is_none")]
150 line: Option<usize>,
151 #[serde(skip_serializing_if = "Option::is_none")]
153 text: Option<String>,
154 reason: &'static str,
156}
157
158#[derive(Debug, Serialize)]
160struct SyncReport<'a> {
161 schema: &'static str,
163 mode: &'static str,
165 target: &'a str,
167 #[serde(skip_serializing_if = "Option::is_none")]
170 manager: Option<Manager>,
171 outcome: &'static str,
179 #[serde(skip_serializing_if = "Option::is_none")]
182 from: Option<&'a str>,
183 #[serde(skip_serializing_if = "Option::is_none")]
186 to: Option<&'a str>,
187 #[serde(skip_serializing_if = "Option::is_none")]
189 detail: Option<&'a str>,
190 #[serde(skip_serializing_if = "Option::is_none")]
192 steps: Option<&'a [Step]>,
193 #[serde(skip_serializing_if = "Option::is_none")]
195 restored: Option<&'a [String]>,
196 #[serde(skip_serializing_if = "Option::is_none")]
199 recovered: Option<&'a [String]>,
200 next: &'a [String],
202}
203
204#[derive(Debug, Clone, Serialize)]
206#[allow(
207 clippy::struct_field_names,
208 reason = "the fields are the keys of a serialized machine shape, so they answer to the schema rather than to the struct name"
209)]
210struct Step {
211 step: &'static str,
213 status: &'static str,
215 #[serde(skip_serializing_if = "Option::is_none")]
217 detail: Option<String>,
218}
219
220#[derive(Debug, Default)]
222struct SyncRun {
223 outcome: &'static str,
224 manager: Option<Manager>,
225 from: Option<String>,
226 to: Option<String>,
227 detail: Option<String>,
228 steps: Option<Vec<Step>>,
229 restored: Option<Vec<String>>,
230 recovered: Option<Vec<String>>,
231}
232
233#[derive(Debug, Serialize)]
235struct Host {
236 nix: &'static str,
238 direnv: &'static str,
240}
241
242pub fn run(args: &SelfDependArgs) -> Result<(), RkError> {
250 match &args.action {
251 SelfDependAction::Status(args) => status(args),
252 SelfDependAction::Add(args) => add(args),
253 SelfDependAction::Clean(args) => clean(args),
254 SelfDependAction::Sync(args) => sync(args),
255 SelfDependAction::Check(args) => check(args),
256 }
257}
258
259fn status(args: &StatusArgs) -> Result<(), RkError> {
263 let out = Output::new(args.json);
264 let observed = self_depend::observe(&args.target)?;
265 let host = Host {
266 nix: probe_word(&probes::nix()),
267 direnv: probe_word(&probes::direnv()),
268 };
269 let state = observed.state();
270 let managers: Vec<Entry> = observed
271 .managers
272 .iter()
273 .filter(|entry| args.manager.is_none_or(|wanted| entry.manager == wanted))
274 .cloned()
275 .collect();
276 out.result_line(format!("state {state}"));
277 if let Some(wired) = observed.wired {
278 out.result_line(format!("wired through {}", wired.as_str()));
279 }
280 if let Some(answer) = &observed.acquisition {
281 out.result_line(format!(
282 "host install recorded, at rk {} or newer",
283 answer.minimum
284 ));
285 }
286 for entry in &managers {
287 out.result_line(manager_line(entry));
288 }
289 out.result_line(format!(
290 ".envrc {}, check line {}",
291 word(observed.envrc),
292 if observed.envrc_check { "yes" } else { "no" }
293 ));
294 if observed.envrc_old_sync {
295 out.result_line(
296 ".envrc still carries the retired sync line, which moves no pin from 0.9.15 on",
297 );
298 }
299 if observed.pending {
300 out.result_line("an interrupted sync awaits recovery");
301 }
302 out.result_line(format!("host nix {}, direnv {}", host.nix, host.direnv));
303 for leftover in &observed.leftovers {
304 out.result_line(leftover_line(leftover));
305 }
306 let next = status_next(&observed);
307 out.next(&next);
308 out.emit(&StatusReport {
309 schema: "rk.self-depend-status/3",
310 target: observed.target.as_str(),
311 state,
312 acquisition: observed.acquisition.as_ref(),
313 wired: observed.wired,
314 managers: &managers,
315 envrc: observed.envrc,
316 envrc_check: observed.envrc_check,
317 envrc_old_sync: observed.envrc_old_sync,
318 pending: observed.pending,
319 host,
320 leftovers: &observed.leftovers,
321 next: &next,
322 })
323}
324
325#[derive(Debug, Serialize)]
327struct AddHostReport<'a> {
328 schema: &'static str,
330 mode: &'static str,
332 target: &'a str,
334 acquisition: &'a crate::config::Acquisition,
336 config: Presence,
338 written: bool,
340 next: &'a [String],
342}
343
344fn add_host(args: &AddArgs) -> Result<(), RkError> {
354 let out = Output::new(args.json);
355 let observed = self_depend::observe(&args.target)?;
356 let pinning: Vec<&str> = observed
360 .managers
361 .iter()
362 .filter(|entry| entry.read.names())
363 .map(|entry| entry.manager.as_str())
364 .collect();
365 if !pinning.is_empty() {
366 return Err(RkError::refusal(
367 Diagnostic::new(
368 Reason::DestructiveRefusal,
369 format!(
370 "the target already pins release-kit through {}; a host install beside a pin is a second mechanism",
371 pinning.join(" and ")
372 ),
373 )
374 .expected("no manager naming release-kit, or no host answer")
375 .target_state("nothing was written"),
376 ));
377 }
378 let answer = crate::config::Acquisition::host_at_this_release();
379 let config = Presence::of(&observed.target.join(crate::config::CONFIG_PATH));
380 let (content, changed) =
381 crate::config::with_acquisition(observed.target.as_std_path(), &answer)?;
382 let written = args.apply && changed;
383 if written {
384 crate::atomic::write(
385 observed
386 .target
387 .join(crate::config::CONFIG_PATH)
388 .as_std_path(),
389 content.as_bytes(),
390 )?;
391 out.result_line(format!("wrote {}", crate::config::CONFIG_PATH));
392 } else if !args.apply {
393 out.result_line("DRY RUN: --apply records the answer");
394 }
395 out.result_line(format!(
396 "acquisition: every host installs rk {} or newer",
397 answer.minimum
398 ));
399 let target = &observed.target;
400 let next = vec![format!(
401 "rk self-depend status --target {target} reports the state host once the answer is recorded"
402 )];
403 out.next(&next);
404 out.emit(&AddHostReport {
405 schema: "rk.self-depend-add-host/1",
406 mode: if args.apply { "apply" } else { "preview" },
407 target: observed.target.as_str(),
408 acquisition: &answer,
409 config,
410 written,
411 next: &next,
412 })
413}
414
415fn leftover_line(leftover: &Leftover) -> String {
417 use std::fmt::Write as _;
418 let action = match leftover.action {
419 Action::RemoveFile => "remove-file",
420 Action::ReplaceLine => "replace-line",
421 Action::Manual => "manual",
422 };
423 let mut line = format!("leftover {action} {}", leftover.file);
424 if let Some(number) = leftover.line {
425 let _ = write!(line, ":{number}");
426 }
427 if let Some(text) = &leftover.text {
428 let _ = write!(line, " {text}");
429 }
430 let _ = write!(line, " ({}: {})", leftover.id, leftover.reason);
431 line
432}
433
434#[allow(
437 clippy::too_many_lines,
438 reason = "one pass from the observation to the report, so every refusal is judged before any write"
439)]
440fn add(args: &AddArgs) -> Result<(), RkError> {
441 if args.host {
442 return add_host(args);
443 }
444 let out = Output::new(args.json);
445 let observed = self_depend::observe(&args.target)?;
446 let (tag, tag_source) = resolve_tag(args.tag.as_deref())?;
447 let pair = matrix::choose(&observed, args.manager, args.venue)?;
448 let entry = observed.entry(pair.manager);
449 let file = entry
450 .and_then(|entry| entry.file.clone())
451 .unwrap_or_else(|| pair.manager.default_file().to_owned());
452 let file_present = entry.map_or(Presence::Absent, |entry| entry.present);
453 let (support, reason) = match matrix::support(pair.manager, pair.venue) {
454 Support::Fragment if file_present.is_present() => (Mode::Fragment, None),
455 Support::Fragment => (Mode::Seed, None),
456 Support::Manual(reason) => (Mode::Manual, Some(reason)),
457 };
458 if let Some(wired) = observed.wired.filter(|wired| *wired != pair.manager) {
461 return Err(RkError::refusal(
462 Diagnostic::new(
463 Reason::DestructiveRefusal,
464 format!(
465 "the target already pins release-kit through {}; a second manager is a second bump mechanism",
466 wired.as_str()
467 ),
468 )
469 .expected(format!(
470 "one manager naming release-kit; rk self-depend add --manager {} serves that one",
471 wired.as_str()
472 ))
473 .target_state("nothing was written"),
474 ));
475 }
476 let fragments = fragments::fragments(pair, &tag, &observed);
477 let mode = if args.apply { "apply" } else { "preview" };
478 let flake_pair = pair.manager == Manager::Flake && pair.venue == Venue::Flake;
479 let mut written = Vec::new();
480 let mut owned = Vec::new();
481 if args.apply && support != Mode::Manual {
482 let mut seeds = vec![(file.clone(), file_present, fragments::seed(pair, &tag))];
483 if flake_pair {
484 seeds.push((
485 ".envrc".to_owned(),
486 observed.envrc,
487 Some(fragments::seed_envrc()),
488 ));
489 }
490 for (name, present, seed) in seeds {
491 let Some(seed) = seed else {
492 continue;
493 };
494 if present.is_present() {
495 owned.push(name);
496 } else {
497 crate::atomic::write(observed.target.join(&name).as_std_path(), seed.as_bytes())?;
498 written.push(name);
499 }
500 }
501 }
502 let refusal = (!owned.is_empty()).then(|| {
503 format!(
504 "the target already carries {}; rk self-depend add never edits a file the target owns",
505 owned.join(" and ")
506 )
507 });
508 if args.apply {
509 for name in &written {
510 out.result_line(format!("wrote {name}"));
511 }
512 } else {
513 out.result_line("DRY RUN: rk self-depend add prints the fragments; --apply seeds only the files the target lacks");
514 }
515 out.result_line(format!("tag {tag} (from the {tag_source})"));
516 out.result_line(match (support, reason) {
517 (Mode::Manual, Some(reason)) => format!(
518 "pair {} via {}: manual ({reason}); nothing is written",
519 pair.manager.as_str(),
520 pair.venue.as_str()
521 ),
522 (mode, _) => format!(
523 "pair {} via {}: {}",
524 pair.manager.as_str(),
525 pair.venue.as_str(),
526 match mode {
527 Mode::Fragment => "fragments into the present file",
528 Mode::Seed => "seeded on --apply",
529 Mode::Manual => "manual",
530 }
531 ),
532 });
533 if support != Mode::Manual {
534 out.result_line(match file_present {
535 Presence::Present => {
536 format!("{file} present: the target owns it, so its fragments are applied by hand")
537 }
538 Presence::Absent => format!("{file} absent: --apply seeds it"),
539 });
540 }
541 out.result_line(match (observed.envrc, flake_pair) {
542 (Presence::Present, _) => {
543 ".envrc present: the target owns it, so the sync line is applied by hand".to_owned()
544 }
545 (Presence::Absent, true) => ".envrc absent: --apply seeds it".to_owned(),
546 (Presence::Absent, false) => {
547 ".envrc absent: the sync line is applied by hand once the shell loads rk".to_owned()
548 }
549 });
550 for fragment in &fragments {
551 out.result_line(format!(
552 "--- {} into {} ({} at {}){}",
553 fragment.id,
554 fragment.file,
555 fragment.placement,
556 fragment.anchor.path,
557 match fragment.present {
558 Some(true) => ": already present",
559 Some(false) => ": missing",
560 None => ": not judged",
561 }
562 ));
563 out.result_line(&fragment.text);
564 }
565 let next = add_next(&observed, pair, &file, args.apply, &written);
566 out.next(&next);
567 out.emit(&AddReport {
568 schema: "rk.self-depend-add/3",
569 mode,
570 target: observed.target.as_str(),
571 tag: &tag,
572 tag_source,
573 manager: pair.manager,
574 venue: pair.venue,
575 support,
576 reason,
577 file: &file,
578 file_present,
579 envrc: observed.envrc,
580 written: &written,
581 refusal: refusal.as_deref(),
582 fragments: &fragments,
583 next: &next,
584 })?;
585 if args.apply && support == Mode::Manual {
586 return Err(RkError::Usage(format!(
587 "{} via {} is manual ({}); nothing can be written, and the report names the edit",
588 pair.manager.as_str(),
589 pair.venue.as_str(),
590 reason.unwrap_or_default()
591 )));
592 }
593 let Some(message) = refusal else {
594 return Ok(());
595 };
596 let state = if written.is_empty() {
597 "nothing was written".to_owned()
598 } else {
599 format!(
600 "wrote {}; the owned file is byte-identical",
601 written.join(", ")
602 )
603 };
604 Err(RkError::refusal(
605 Diagnostic::new(Reason::DestructiveRefusal, message)
606 .expected("a target with no file for the pair, or the fragments applied by hand")
607 .target_state(state),
608 ))
609}
610
611fn sync(args: &SyncArgs) -> Result<(), RkError> {
619 if args.caller == Caller::Envrc {
620 return Err(RkError::Usage(
621 "--caller envrc is retired: the .envrc line runs `rk self-depend check`, which warns of a newer release and moves no pin; a sync is the operator's act".to_owned(),
622 ));
623 }
624 let out = Output::new(args.json);
625 let mut observed = self_depend::observe(&args.target)?;
626 let key = observed.key();
627 let mut run = SyncRun::default();
628 let mut held = None;
629 if args.apply && guard::in_envrc() {
630 run.outcome = "refused-in-envrc";
632 run.detail = Some(format!(
633 "{} is set: an .envrc evaluation or `direnv exec`, so nothing moves; run `nix develop -c rk self-depend sync --apply` from a shell",
634 guard::IN_ENVRC_VAR
635 ));
636 out.warn(format!(
637 "rk self-depend sync: {}",
638 run.detail.as_deref().unwrap_or_default()
639 ));
640 } else {
641 gate_and_decide(args, &mut observed, &key, &mut run, &mut held, out)?;
642 }
643 render_sync(out, args, &observed, &run)?;
644 drop(held);
645 exit_for(&run)
646}
647
648fn gate_and_decide(
653 args: &SyncArgs,
654 observed: &mut Observed,
655 key: &str,
656 run: &mut SyncRun,
657 held: &mut Option<guard::Lock>,
658 out: Output,
659) -> Result<(), RkError> {
660 if args.apply {
661 match guard::acquire(key) {
662 Acquired::Held(lock) => *held = Some(lock),
663 Acquired::Contended => {
664 run.outcome = "skipped-locked";
665 run.detail = Some("another run holds this checkout".to_owned());
666 return Ok(());
667 }
668 Acquired::Unavailable(source) => {
669 run.outcome = "lock-unavailable";
670 run.detail = Some(format!("the lock cannot be taken: {source}"));
671 out.warn(format!(
672 "rk self-depend sync: the lock cannot be taken: {source}"
673 ));
674 return Ok(());
675 }
676 }
677 }
678 let mut tools = vec![crate::requirements::Tool::Git];
684 if args.apply
685 && args.manager.or(observed.wired) == Some(crate::self_depend::manager::Manager::Flake)
686 {
687 tools.push(crate::requirements::Tool::Nix);
688 }
689 let unmet = crate::requirements::unmet(&tools, Some(observed.target.as_std_path()));
690 if !unmet.is_empty() {
691 let problems: Vec<&str> = unmet.iter().map(|found| found.problem.as_str()).collect();
692 let actions: Vec<&str> = unmet.iter().map(|found| found.action.as_str()).collect();
693 run.outcome = "prerequisite-unmet";
694 run.detail = Some(format!(
695 "rk self-depend sync runs tools this host cannot serve: {}; next: {}",
696 problems.join("; "),
697 actions.join("; ")
698 ));
699 return Ok(());
700 }
701 if args.apply {
702 let recovery = match txn::recover_pending(&observed.target, key) {
705 Ok(recovery) => recovery,
706 Err(source) => {
707 run.outcome = "recovery-failed";
708 run.detail = Some(format!(
709 "the transaction marker under the state root cannot be read: {source}; remove or repair it by hand"
710 ));
711 return Ok(());
712 }
713 };
714 match recovery {
715 Some(Recovery::Restored(restored)) => {
716 run.recovered = Some(restored);
717 *observed = self_depend::observe(&args.target)?;
718 }
719 Some(Recovery::Failed(failure)) => {
720 run.outcome = "recovery-failed";
721 run.detail = Some(format!(
722 "{failure}; the backups stay under the state root for the next attempt"
723 ));
724 return Ok(());
725 }
726 Some(Recovery::Unfinished(failure)) => {
727 run.outcome = "cleanup-failed";
728 run.detail = Some(format!("both files are back, but {failure}"));
729 return Ok(());
730 }
731 Some(Recovery::Finished) => {
732 *observed = self_depend::observe(&args.target)?;
733 }
734 None => {}
735 }
736 }
737 decide(args, observed, key, run)
738}
739
740fn sync_manager(args: &SyncArgs, observed: &Observed, run: &mut SyncRun) -> Option<Manager> {
744 if let Some(manager) = args.manager {
745 return Some(manager);
746 }
747 if let Some(wired) = observed.wired {
748 return Some(wired);
749 }
750 if observed
751 .managers
752 .iter()
753 .all(|entry| !entry.present.is_present())
754 {
755 run.outcome = "no-manager";
756 return None;
757 }
758 let named: Vec<&str> = observed
759 .managers
760 .iter()
761 .filter(|entry| entry.read.names())
762 .map(|entry| entry.manager.as_str())
763 .collect();
764 if named.len() > 1 {
765 run.outcome = "ambiguous-pin";
766 run.detail = Some(format!(
767 "{} manager files name release-kit: {}",
768 named.len(),
769 named.join(" and ")
770 ));
771 } else {
772 run.outcome = "not-wired";
773 }
774 None
775}
776
777fn sync_files(manager: Manager, file: &str) -> Vec<&str> {
780 if manager == Manager::Flake {
781 vec!["flake.nix", "flake.lock"]
782 } else {
783 vec![file]
784 }
785}
786
787fn decide(
790 args: &SyncArgs,
791 observed: &Observed,
792 key: &str,
793 run: &mut SyncRun,
794) -> Result<(), RkError> {
795 if observed.pending {
796 run.outcome = "pending-recovery";
797 run.detail =
798 Some("an interrupted run left its marker; --apply recovers it first".to_owned());
799 return Ok(());
800 }
801 let Some(manager) = sync_manager(args, observed, run) else {
802 return Ok(());
803 };
804 run.manager = Some(manager);
805 let Some(entry) = observed
806 .entry(manager)
807 .filter(|entry| entry.present.is_present())
808 else {
809 run.outcome = "no-manager";
810 run.detail = Some(format!("the target carries no {} file", manager.as_str()));
811 return Ok(());
812 };
813 let file = entry.file.clone().unwrap_or_default();
814 let (line, from) = match &entry.read {
815 PinRead::Many { count } => {
816 run.outcome = "ambiguous-pin";
817 run.detail = Some(format!("{count} lines name release-kit in {file}"));
818 return Ok(());
819 }
820 PinRead::Absent => {
821 run.outcome = "not-wired";
822 return Ok(());
823 }
824 PinRead::Unpinned { line } => {
825 run.outcome = "unpinned";
826 run.detail = Some(format!(
827 "{file} line {line} names release-kit with no version"
828 ));
829 return Ok(());
830 }
831 PinRead::One { line, version } => (*line, version.clone()),
832 };
833 run.from = Some(from.clone());
834 if guard::files_dirty(&observed.target, &sync_files(manager, &file)) {
835 run.outcome = "refused-dirty";
836 run.detail = Some(format!(
837 "{} carries uncommitted edits; commit or stash them first",
838 sync_files(manager, &file).join(" or ")
839 ));
840 return Ok(());
841 }
842 let to = match args.tag.as_deref() {
843 Some(raw) => self_depend::normalize_tag(raw).ok_or_else(|| {
844 RkError::Usage(format!(
845 "--tag {raw} is not a release tag; pass v0.2.16, 0.2.16, or the release URL"
846 ))
847 })?,
848 None => match discover::latest_tag() {
849 Discovery::Tag(tag) => tag,
850 Discovery::Unreachable(detail) => {
851 run.outcome = "unreachable";
852 run.detail = Some(detail);
853 return Ok(());
854 }
855 Discovery::Unparsable(answer) => {
856 run.outcome = "unparsable";
857 run.detail = Some(format!("the release page answered no tag: {answer}"));
858 return Ok(());
859 }
860 },
861 };
862 let to = manager.recorded(&to);
863 run.to = Some(to.clone());
864 match discover::version_order(&from, &to) {
865 std::cmp::Ordering::Equal => {
866 run.outcome = "current";
867 return Ok(());
868 }
869 std::cmp::Ordering::Greater if args.tag.is_none() => {
872 run.outcome = "ahead";
873 run.detail = Some(
874 "the pin is ahead of the latest release and is never moved backward".to_owned(),
875 );
876 return Ok(());
877 }
878 std::cmp::Ordering::Greater | std::cmp::Ordering::Less => {}
879 }
880 if !args.apply {
881 run.outcome = "would-bump";
882 return Ok(());
883 }
884 if manager == Manager::Flake {
885 let pin::Scan::One(pin) = &observed.scan else {
886 run.outcome = "not-wired";
887 return Ok(());
888 };
889 return apply_bump(observed, key, pin, &to, run);
890 }
891 move_one_fact(observed, entry, &file, line, &from, &to, run);
892 Ok(())
893}
894
895fn move_one_fact(
898 observed: &Observed,
899 entry: &Entry,
900 file: &str,
901 line: usize,
902 from: &str,
903 to: &str,
904 run: &mut SyncRun,
905) {
906 let text = entry.text.as_deref().unwrap_or_default();
907 let rewritten = manager::rewrite_line(text, line, from, to);
908 let step = match crate::atomic::write(
909 observed.target.join(file).as_std_path(),
910 rewritten.as_bytes(),
911 ) {
912 Ok(()) => {
913 run.outcome = "bumped";
914 Step {
915 step: "rewrite-pin",
916 status: "ok",
917 detail: None,
918 }
919 }
920 Err(source) => {
921 run.outcome = "update-failed";
922 run.detail = Some(format!("rewrite-pin failed: {source}"));
923 run.restored = Some(Vec::new());
924 Step {
925 step: "rewrite-pin",
926 status: "failed",
927 detail: Some(source.to_string()),
928 }
929 }
930 };
931 run.steps = Some(vec![step]);
932}
933
934fn apply_bump(
937 observed: &Observed,
938 key: &str,
939 pin: &pin::Pin,
940 to: &str,
941 run: &mut SyncRun,
942) -> Result<(), RkError> {
943 let flake_text = observed.flake_text.as_deref().unwrap_or_default();
944 let rewritten = pin::rewrite(flake_text, pin, to);
945 let transaction = txn::open(&observed.target, key)?;
946 let mut steps = Vec::new();
947 let failure = transact(&observed.target, &rewritten, &mut steps);
948 match failure {
949 None => {
950 run.outcome = "bumped";
951 if let Err(failure) = transaction.commit() {
952 run.outcome = "cleanup-failed";
953 run.detail = Some(format!("the pin moved, but {failure}"));
954 }
955 }
956 Some(failed) => {
957 run.outcome = match failed.step {
958 "rewrite-pin" | "flake-update" => "update-failed",
959 _ => "build-failed",
960 };
961 match transaction.abort() {
962 Ok(restored) => {
963 run.restored = Some(restored);
964 run.detail = Some(format!("{} failed: {}", failed.step, failed.detail));
965 }
966 Err(AbortFailure::Restore(failure)) => {
967 run.outcome = "restore-failed";
968 run.detail = Some(format!(
969 "{} failed: {}; then {failure}; the backups stay under the state root for the next run",
970 failed.step, failed.detail
971 ));
972 }
973 Err(AbortFailure::Finish(failure)) => {
974 run.outcome = "cleanup-failed";
975 run.detail = Some(format!(
976 "{} failed: {}; both files are back, but {failure}",
977 failed.step, failed.detail
978 ));
979 }
980 }
981 }
982 }
983 run.steps = Some(steps);
984 Ok(())
985}
986
987type Attempt<'a> = Box<dyn Fn() -> Result<(), StepFailure> + 'a>;
989
990fn transact(target: &Utf8Path, rewritten: &str, steps: &mut Vec<Step>) -> Option<StepFailure> {
993 let attempts: [(&'static str, Attempt<'_>); 3] = [
994 (
995 "rewrite-pin",
996 Box::new(|| {
997 crate::atomic::write(target.join("flake.nix").as_std_path(), rewritten.as_bytes())
998 .map_err(|source| StepFailure {
999 step: "rewrite-pin",
1000 detail: source.to_string(),
1001 })
1002 }),
1003 ),
1004 ("flake-update", Box::new(|| txn::flake_update(target))),
1005 (
1006 "build",
1007 Box::new(|| {
1008 let system = txn::current_system(target)?;
1009 txn::build_devshell(target, &system)
1010 }),
1011 ),
1012 ];
1013 for (name, attempt) in attempts {
1014 match attempt() {
1015 Ok(()) => steps.push(Step {
1016 step: name,
1017 status: "ok",
1018 detail: None,
1019 }),
1020 Err(failed) => {
1021 steps.push(Step {
1022 step: failed.step,
1023 status: "failed",
1024 detail: Some(failed.detail.clone()),
1025 });
1026 return Some(failed);
1027 }
1028 }
1029 }
1030 None
1031}
1032
1033fn render_sync(
1035 out: Output,
1036 args: &SyncArgs,
1037 observed: &Observed,
1038 run: &SyncRun,
1039) -> Result<(), RkError> {
1040 use std::fmt::Write as _;
1041 if let Some(recovered) = &run.recovered {
1042 out.result_line(format!(
1043 "recovered an interrupted sync: restored {}",
1044 recovered.join(", ")
1045 ));
1046 }
1047 out.result_line(sync_line(run));
1048 if let Some(steps) = &run.steps {
1049 for step in steps {
1050 let mut line = format!(" {} {}", step.status, step.step);
1051 if let Some(detail) = &step.detail {
1052 let _ = write!(line, ": {detail}");
1053 }
1054 out.result_line(line);
1055 }
1056 }
1057 if let Some(restored) = &run.restored {
1058 out.result_line(format!("restored {}", restored.join(", ")));
1059 }
1060 let next = sync_next(observed, run);
1061 out.next(&next);
1062 out.emit(&SyncReport {
1063 schema: "rk.self-depend-sync/3",
1064 mode: if args.apply { "apply" } else { "preview" },
1065 target: observed.target.as_str(),
1066 manager: run.manager,
1067 outcome: run.outcome,
1068 from: run.from.as_deref(),
1069 to: run.to.as_deref(),
1070 detail: run.detail.as_deref(),
1071 steps: run.steps.as_deref(),
1072 restored: run.restored.as_deref(),
1073 recovered: run.recovered.as_deref(),
1074 next: &next,
1075 })
1076}
1077
1078fn sync_line(run: &SyncRun) -> String {
1080 use std::fmt::Write as _;
1081 let movement = match (&run.from, &run.to) {
1082 (Some(from), Some(to)) if from != to => format!(" {from} -> {to}"),
1083 (Some(from), _) => format!(" {from}"),
1084 _ => String::new(),
1085 };
1086 let mut line = format!("{}{movement}", run.outcome);
1087 if let Some(detail) = &run.detail {
1088 let _ = write!(line, ": {detail}");
1089 }
1090 line
1091}
1092
1093fn sync_next(observed: &Observed, run: &SyncRun) -> Vec<String> {
1095 let target = &observed.target;
1096 let files = run
1097 .manager
1098 .map(|manager| {
1099 let file = observed
1100 .entry(manager)
1101 .and_then(|entry| entry.file.clone())
1102 .unwrap_or_else(|| manager.default_file().to_owned());
1103 sync_files(manager, &file).join(" ")
1104 })
1105 .unwrap_or_default();
1106 let mut next = match run.outcome {
1107 "bumped" => vec![
1108 format!("git -C {target} diff -- {files} shows the change to review and commit"),
1109 "the next shell reload takes the new rk; nothing here commits".to_owned(),
1110 self_depend::advice::after_move(),
1111 ],
1112 "would-bump" => vec![
1113 format!(
1114 "rk self-depend sync --apply --target {target} moves the pin, locks it, and proves the build"
1115 ),
1116 self_depend::advice::after_move(),
1117 ],
1118 "current" => vec![format!(
1119 "rk self-depend status --target {target} reports the wiring"
1120 )],
1121 "ahead" => vec![
1122 "a pin past the latest release is a deliberate state; nothing moves it back".to_owned(),
1123 ],
1124 "pending-recovery" => vec![format!(
1125 "rk self-depend sync --apply --target {target} restores both files first"
1126 )],
1127 "no-manager" | "not-wired" | "unpinned" => vec![format!(
1128 "rk self-depend add --target {target} prints the fragments; --apply seeds the files a target lacks"
1129 )],
1130 "ambiguous-pin" => vec![format!(
1131 "leave exactly one line naming release-kit, in one manager file under {target}, then rerun"
1132 )],
1133 "refused-dirty" => vec![format!(
1134 "git -C {target} status -- {files} names the edits; commit or stash them, then rerun"
1135 )],
1136 "refused-in-envrc" => vec![format!(
1137 "nix develop -c rk self-depend sync --apply --target {target}, from a shell"
1138 )],
1139 "skipped-locked" => vec!["let the other run finish; nothing here is owed".to_owned()],
1140 "prerequisite-unmet" => vec![
1141 "install or upgrade each tool the detail names, then rerun the sync".to_owned(),
1142 ],
1143 "lock-unavailable" => vec!["make the state root writable: rk doctor reports it".to_owned()],
1144 "unreachable" | "unparsable" => vec![
1145 "retry when the release page answers; --tag <TAG> makes no request at all".to_owned(),
1146 ],
1147 "cleanup-failed" => vec![
1148 "remove the named marker by hand before the next entry; an active marker beside its backups would overwrite later edits".to_owned(),
1149 ],
1150 "recovery-failed" | "restore-failed" => vec![
1151 "a file is not back: free the path the detail names, then rerun; the backups wait under the state root".to_owned(),
1152 ],
1153 "update-failed" | "build-failed" => vec![
1154 "both files are as they were; the failing step's last line is above".to_owned(),
1155 format!(
1156 "rk self-depend sync --apply --target {target} retries after the fix"
1157 ),
1158 ],
1159 _ => Vec::new(),
1160 };
1161 if matches!(run.outcome, "bumped" | "current")
1162 && run.manager == Some(Manager::Flake)
1163 && let Some(line) = self_depend::advice::follows_next(&self_depend::missing_follows(target))
1164 {
1165 next.push(line);
1166 }
1167 if !observed.leftovers.is_empty() {
1168 next.push(format!(
1169 "rk self-depend clean --target {target}: the target still carries a predecessor bump mechanism"
1170 ));
1171 }
1172 next
1173}
1174
1175fn exit_for(run: &SyncRun) -> Result<(), RkError> {
1178 let detail = run.detail.clone().unwrap_or_default();
1179 match run.outcome {
1180 "refused-in-envrc" => Err(RkError::check_failed(
1183 Diagnostic::new(Reason::DestructiveRefusal, detail)
1184 .expected("a sync run from a shell, never from an .envrc evaluation")
1185 .action("run nix develop -c rk self-depend sync --apply from a shell")
1186 .target_state("nothing was written"),
1187 )),
1188 "prerequisite-unmet" => Err(RkError::refusal(
1189 Diagnostic::new(Reason::PrerequisiteUnmet, detail)
1190 .expected("every tool rk self-depend sync runs, on PATH and at or above its floor")
1191 .action("install or upgrade each tool the message names, then run the sync again")
1192 .target_state("nothing was written"),
1193 )),
1194 "ambiguous-pin" | "refused-dirty" => Err(RkError::refusal(
1195 Diagnostic::new(Reason::StateDrift, detail)
1196 .expected("exactly one committed pin line in one manager file")
1197 .target_state("nothing was written"),
1198 )),
1199 "unreachable" | "unparsable" => {
1200 let mut diagnostic = Diagnostic::new(Reason::ForgeTemporary, detail)
1201 .action("rerun when the release page answers, or pass --tag")
1202 .target_state("nothing was written");
1203 diagnostic.retry = Some(true);
1204 Err(RkError::subprocess(diagnostic))
1205 }
1206 "update-failed" | "build-failed" => {
1207 let step = run
1208 .steps
1209 .as_ref()
1210 .and_then(|steps| steps.iter().find(|s| s.status == "failed"))
1211 .map_or("transaction", |s| s.step);
1212 Err(RkError::subprocess(
1213 Diagnostic::new(Reason::SubprocessFailed, detail)
1214 .step(step)
1215 .target_state(format!(
1216 "restored {}",
1217 run.restored.as_deref().unwrap_or_default().join(" and ")
1218 )),
1219 ))
1220 }
1221 "lock-unavailable" | "restore-failed" | "recovery-failed" | "cleanup-failed" => {
1222 Err(RkError::Io(std::io::Error::other(detail)))
1223 }
1224 _ => Ok(()),
1225 }
1226}
1227
1228#[derive(Debug, Serialize)]
1230struct CheckReport<'a> {
1231 schema: &'static str,
1233 #[serde(skip_serializing_if = "Option::is_none")]
1235 target: Option<&'a str>,
1236 outcome: &'static str,
1239 #[serde(skip_serializing_if = "Option::is_none")]
1241 pin: Option<&'a str>,
1242 #[serde(skip_serializing_if = "Option::is_none")]
1244 latest: Option<&'a str>,
1245 #[serde(skip_serializing_if = "Option::is_none")]
1247 cache: Option<String>,
1248 fetched: bool,
1250 warnings: &'a [String],
1252}
1253
1254fn check(args: &CheckArgs) -> Result<(), RkError> {
1260 let out = Output::new(args.json);
1261 let emit = |outcome: &'static str,
1262 target: Option<&str>,
1263 pin: Option<&str>,
1264 cache: Option<&check::Cache>,
1265 path: Option<&std::path::Path>,
1266 fetched: bool,
1267 warnings: &[String]| {
1268 for line in warnings {
1269 out.warn(line);
1270 }
1271 out.emit(&CheckReport {
1272 schema: "rk.self-depend-check/1",
1273 target,
1274 outcome,
1275 pin,
1276 latest: cache.and_then(|cache| cache.latest.as_deref()),
1277 cache: path.map(|path| path.display().to_string()),
1278 fetched,
1279 warnings,
1280 })
1281 };
1282 if guard::switched_off() {
1283 return emit("disabled", None, None, None, None, false, &[]);
1284 }
1285 if guard::in_ci() {
1286 return emit("ci", None, None, None, None, false, &[]);
1287 }
1288 let observed = match self_depend::observe(&args.target) {
1289 Ok(observed) => observed,
1290 Err(error) => {
1291 let warnings = vec![format!(
1292 "rk self-depend check could not read {}: {error}",
1293 args.target
1294 )];
1295 return emit("unread", None, None, None, None, false, &warnings);
1296 }
1297 };
1298 let target = Some(observed.target.as_str());
1299 let Some(pin) = checked_pin(&observed) else {
1300 return emit("no-pin", target, None, None, None, false, &[]);
1301 };
1302 let Some(paths) = check::Paths::for_key(&observed.key()) else {
1303 let warnings = vec![
1304 "rk cannot record its version check: neither XDG_CACHE_HOME nor HOME is set."
1305 .to_owned(),
1306 ];
1307 return emit(
1308 "unwritable",
1309 target,
1310 Some(&pin),
1311 None,
1312 None,
1313 false,
1314 &warnings,
1315 );
1316 };
1317 let run = check::run(&paths, std::time::SystemTime::now());
1318 let warnings = check::warnings(Some(&pin), run.cache.as_ref(), &run.outcome, &paths.cache);
1319 emit(
1320 run.outcome.word(),
1321 target,
1322 Some(&pin),
1323 run.cache.as_ref(),
1324 Some(&paths.cache),
1325 run.fetched,
1326 &warnings,
1327 )
1328}
1329
1330fn checked_pin(observed: &Observed) -> Option<String> {
1333 let entry = observed.entry(observed.wired?)?;
1334 match &entry.read {
1335 PinRead::One { version, .. } => Some(version.clone()),
1336 _ => None,
1337 }
1338}
1339
1340fn clean(args: &CleanArgs) -> Result<(), RkError> {
1342 let out = Output::new(args.json);
1343 let observed = self_depend::observe(&args.target)?;
1344 let target = &observed.target;
1345 let mut leftovers = observed.leftovers.clone();
1346 for path in &args.also {
1347 leftovers.push(also_leftover(target, path)?);
1348 }
1349 let mode = if args.apply { "apply" } else { "preview" };
1350 let mut removed = Vec::new();
1351 let mut rewritten = Vec::new();
1352 let mut manual = Vec::new();
1353 if args.apply {
1354 for leftover in &leftovers {
1355 match leftover.action {
1356 Action::RemoveFile => {
1357 std::fs::remove_file(target.join(&leftover.file))?;
1358 removed.push(leftover.file.clone());
1359 }
1360 Action::ReplaceLine => {}
1361 Action::Manual => manual.push(Manual {
1362 id: leftover.id,
1363 file: leftover.file.clone(),
1364 line: leftover.line,
1365 text: leftover.text.clone(),
1366 reason: leftover.reason,
1367 }),
1368 }
1369 }
1370 if leftovers.iter().any(|l| l.action == Action::ReplaceLine) {
1371 let envrc = target.join(".envrc");
1372 let text = std::fs::read_to_string(&envrc)?;
1373 if let Some(swapped) = leftovers::swap_envrc(&text, &fragments::envrc_line()) {
1374 crate::atomic::write(envrc.as_std_path(), swapped.as_bytes())?;
1375 rewritten.push(".envrc".to_owned());
1376 }
1377 }
1378 }
1379 if args.apply {
1380 for file in &removed {
1381 out.result_line(format!("removed {file}"));
1382 }
1383 for file in &rewritten {
1384 out.result_line(format!(
1385 "rewrote {file}: the check line replaces the invocation"
1386 ));
1387 }
1388 for entry in &manual {
1389 out.result_line(format!(
1390 "manual {}{} {} ({}: {})",
1391 entry.file,
1392 entry.line.map(|n| format!(":{n}")).unwrap_or_default(),
1393 entry.text.as_deref().unwrap_or_default(),
1394 entry.id,
1395 entry.reason
1396 ));
1397 }
1398 if removed.is_empty() && rewritten.is_empty() && manual.is_empty() {
1399 out.result_line("nothing to remove: the target carries no predecessor mechanism");
1400 }
1401 } else {
1402 out.result_line(
1403 "DRY RUN: rk self-depend clean removes and rewrites these on --apply, and names the rest",
1404 );
1405 for leftover in &leftovers {
1406 out.result_line(leftover_line(leftover));
1407 }
1408 if leftovers.is_empty() {
1409 out.result_line("nothing to remove: the target carries no predecessor mechanism");
1410 }
1411 }
1412 let next = clean_next(&observed, args.apply, &leftovers, &manual);
1413 out.next(&next);
1414 out.emit(&CleanReport {
1415 schema: "rk.self-depend-clean/1",
1416 mode,
1417 target: target.as_str(),
1418 leftovers: &leftovers,
1419 removed: &removed,
1420 rewritten: &rewritten,
1421 manual: &manual,
1422 next: &next,
1423 })
1424}
1425
1426fn also_leftover(target: &Utf8Path, path: &Utf8Path) -> Result<Leftover, RkError> {
1429 let absolute = if path.is_absolute() {
1430 path.to_owned()
1431 } else {
1432 target.join(path)
1433 };
1434 let refuse = |why: &str| {
1435 RkError::refusal(
1436 Diagnostic::new(
1437 Reason::DestructiveRefusal,
1438 format!("--also {path} is {why}; nothing was removed"),
1439 )
1440 .expected("a regular file inside the target, named for removal"),
1441 )
1442 };
1443 let Ok(meta) = std::fs::symlink_metadata(&absolute) else {
1444 return Err(refuse("not a file that exists"));
1445 };
1446 if meta.file_type().is_symlink() {
1447 return Err(refuse("a symlink, which a file removal never follows"));
1448 }
1449 if meta.is_dir() {
1450 return Err(refuse("a directory, and the cleanup removes files alone"));
1451 }
1452 let canonical = absolute.canonicalize_utf8()?;
1453 let Ok(relative) = canonical.strip_prefix(target) else {
1454 return Err(refuse("outside the target"));
1455 };
1456 Ok(Leftover {
1457 id: "also",
1458 file: relative.to_string(),
1459 line: None,
1460 text: None,
1461 action: Action::RemoveFile,
1462 reason: "named by the operator as a predecessor file the catalog does not know",
1463 })
1464}
1465
1466fn clean_next(
1468 observed: &Observed,
1469 apply: bool,
1470 leftovers: &[Leftover],
1471 manual: &[Manual],
1472) -> Vec<String> {
1473 let target = &observed.target;
1474 let mut next = Vec::new();
1475 if !apply && !leftovers.is_empty() {
1476 next.push(format!(
1477 "rk self-depend clean --target {target} --apply removes the files and rewrites .envrc"
1478 ));
1479 }
1480 let by_hand: Vec<String> = if apply {
1481 manual
1482 .iter()
1483 .map(|entry| entry.file.clone())
1484 .collect::<std::collections::BTreeSet<_>>()
1485 .into_iter()
1486 .collect()
1487 } else {
1488 leftovers
1489 .iter()
1490 .filter(|l| l.action == Action::Manual)
1491 .map(|l| l.file.clone())
1492 .collect::<std::collections::BTreeSet<_>>()
1493 .into_iter()
1494 .collect()
1495 };
1496 if !by_hand.is_empty() {
1497 next.push(format!(
1498 "edit by hand what a line scan must not touch: {}",
1499 by_hand.join(", ")
1500 ));
1501 }
1502 next.push(format!(
1503 "rk self-depend status --target {target} reports ready once the leftovers list is empty"
1504 ));
1505 if matches!(observed.scan, pin::Scan::None) {
1506 next.push(format!(
1507 "rk self-depend add --target {target} wires the native mechanism once the predecessor is gone"
1508 ));
1509 }
1510 next
1511}
1512
1513fn resolve_tag(argument: Option<&str>) -> Result<(String, &'static str), RkError> {
1516 let Some(raw) = argument else {
1517 return Ok((format!("v{}", env!("CARGO_PKG_VERSION")), "binary"));
1518 };
1519 self_depend::normalize_tag(raw)
1520 .map(|tag| (tag, "argument"))
1521 .ok_or_else(|| {
1522 RkError::Usage(format!(
1523 "--tag {raw} is not a release tag; pass v0.2.16, 0.2.16, or the release URL"
1524 ))
1525 })
1526}
1527
1528fn add_next(
1530 observed: &Observed,
1531 pair: Pair,
1532 file: &str,
1533 apply: bool,
1534 written: &[String],
1535) -> Vec<String> {
1536 let target = &observed.target;
1537 let flake_pair = pair.manager == Manager::Flake;
1538 let mut next = Vec::new();
1539 if !observed.leftovers.is_empty() {
1540 next.push(format!(
1541 "rk self-depend clean --target {target} first: the target carries a predecessor bump mechanism, and one project runs one"
1542 ));
1543 }
1544 if let Support::Manual(reason) = matrix::support(pair.manager, pair.venue) {
1545 next.push(format!(
1546 "{} via {} is manual ({reason}): apply the edit by hand, or pick a pair the matrix renders",
1547 pair.manager.as_str(),
1548 pair.venue.as_str()
1549 ));
1550 return next;
1551 }
1552 if !apply {
1553 next.push(format!(
1554 "rk self-depend add --target {target} --apply seeds the files the target lacks; an owned file takes its fragments by hand, in the order above"
1555 ));
1556 if flake_pair {
1557 next.push(
1558 "run rk init --nix before the apply where the landed packaging capability is also wanted: a seeded flake.nix withholds it later".to_owned(),
1559 );
1560 }
1561 }
1562 if !written.is_empty() {
1563 next.push(format!(
1564 "commit {} first: the sync refuses uncommitted edits to the file it moves",
1565 written.join(" and ")
1566 ));
1567 }
1568 if flake_pair {
1569 next.push(format!(
1570 "rk self-depend sync --apply --target {target} writes the lock and proves the build; commit flake.lock, then direnv allow"
1571 ));
1572 } else {
1573 next.push(format!(
1574 "rk self-depend sync --apply --target {target} moves the pin in {file}; the manager's own install takes it from there"
1575 ));
1576 }
1577 next
1578}
1579
1580fn manager_line(entry: &Entry) -> String {
1582 use std::fmt::Write as _;
1583 let mut line = format!("manager {} {}", entry.manager.as_str(), word(entry.present));
1584 let Some(file) = &entry.file else {
1585 return line;
1586 };
1587 let _ = write!(line, " ({file})");
1588 match (entry.pin, entry.pin_lines) {
1589 ("absent", _) => line.push_str(", not named"),
1590 ("unpinned", _) => line.push_str(", named with no version"),
1591 ("ambiguous", Some(count)) => {
1592 let _ = write!(line, ", ambiguous: {count} lines name it");
1593 }
1594 _ => {
1595 let _ = write!(
1596 line,
1597 ", pinned {}",
1598 entry.version.as_deref().unwrap_or_default()
1599 );
1600 if let Some(freshness) = entry.freshness {
1601 let _ = write!(
1602 line,
1603 " ({} this binary)",
1604 match freshness {
1605 crate::self_depend::manager::Freshness::Behind => "behind",
1606 crate::self_depend::manager::Freshness::Current => "same as",
1607 crate::self_depend::manager::Freshness::Ahead => "ahead of",
1608 }
1609 );
1610 }
1611 }
1612 }
1613 if let Some(lock) = entry.lock {
1614 let _ = write!(line, ", lock {}", word(lock));
1615 }
1616 if let Some(rev) = &entry.locked_rev {
1617 let _ = write!(line, ", locked at {rev}");
1618 }
1619 line
1620}
1621
1622const fn word(presence: Presence) -> &'static str {
1624 match presence {
1625 Presence::Present => "present",
1626 Presence::Absent => "absent",
1627 }
1628}
1629
1630const fn probe_word(probe: &probes::ProbeResult) -> &'static str {
1632 match probe.status {
1633 ProbeStatus::Ok => "ok",
1634 ProbeStatus::Failed => "failed",
1635 }
1636}
1637
1638fn status_next(observed: &Observed) -> Vec<String> {
1640 let target = &observed.target;
1641 let mut next = Vec::new();
1642 if let Some(warning) = checked_pin(observed)
1643 .and_then(|pin| self_depend::advice::pending_from_cache(&observed.key(), &pin))
1644 {
1645 next.push(warning);
1646 }
1647 next.extend(status_next_by_state(observed));
1648 if observed.wired == Some(Manager::Flake)
1649 && let Some(line) = self_depend::advice::follows_next(&self_depend::missing_follows(target))
1650 {
1651 next.push(line);
1652 }
1653 if observed.envrc_old_sync {
1654 next.push(format!(
1655 "the .envrc still runs the retired sync line: rk self-depend clean --target {target} --apply swaps it for the check line, after the pin moves, as guidance/0.9.15.md step 36 states"
1656 ));
1657 }
1658 next
1659}
1660
1661fn status_next_by_state(observed: &Observed) -> Vec<String> {
1663 let target = &observed.target;
1664 match observed.state() {
1665 "pending-recovery" => vec![format!(
1666 "rk self-depend sync --target {target} recovers the interrupted run"
1667 )],
1668 "host" => vec![format!(
1669 "each host installs rk {} or newer itself; rk self-depend add --target {target} --manager <manager> moves the project onto a pin",
1670 observed
1671 .acquisition
1672 .as_ref()
1673 .map_or("", |answer| answer.minimum.as_str())
1674 )],
1675 "no-manager" | "not-wired" | "unpinned" => vec![format!(
1676 "rk self-depend add --target {target} prints the fragments; --apply seeds the files a target lacks"
1677 )],
1678 "ambiguous-pin" => vec![format!(
1679 "leave exactly one line naming release-kit, in one manager file under {target}, then rerun"
1680 )],
1681 "superseded" => vec![format!(
1682 "rk self-depend clean --target {target} previews the removal of the predecessor mechanism; --apply removes it"
1683 )],
1684 _ => vec![format!(
1685 "rk self-depend sync --target {target} reports whether the pin is current"
1686 )],
1687 }
1688}
1689
1690#[cfg(test)]
1691mod tests {
1692 use super::{
1693 AddHostReport, AddReport, CheckReport, CleanReport, Host, Manual, Mode, StatusReport, Step,
1694 SyncReport, Venue,
1695 };
1696
1697 #[test]
1699 fn the_self_depend_sync_schema_snapshot_holds() {
1700 let steps = vec![
1701 Step {
1702 step: "rewrite-pin",
1703 status: "ok",
1704 detail: None,
1705 },
1706 Step {
1707 step: "build",
1708 status: "failed",
1709 detail: Some("error: builder failed".to_owned()),
1710 },
1711 ];
1712 let restored = vec!["flake.nix".to_owned(), "flake.lock".to_owned()];
1713 let recovered = vec!["flake.nix".to_owned()];
1714 let next = vec!["both files are as they were".to_owned()];
1715 let report = SyncReport {
1716 schema: "rk.self-depend-sync/3",
1717 mode: "apply",
1718 target: "/srv/widget",
1719 manager: Some(Manager::Flake),
1720 outcome: "build-failed",
1721 from: Some("v0.2.15"),
1722 to: Some("v0.2.16"),
1723 detail: Some("build failed: error: builder failed"),
1724 steps: Some(&steps),
1725 restored: Some(&restored),
1726 recovered: Some(&recovered),
1727 next: &next,
1728 };
1729 assert_eq!(
1730 serde_json::to_string(&report).expect("a report serializes"),
1731 r#"{"schema":"rk.self-depend-sync/3","mode":"apply","target":"/srv/widget","manager":"flake","outcome":"build-failed","from":"v0.2.15","to":"v0.2.16","detail":"build failed: error: builder failed","steps":[{"step":"rewrite-pin","status":"ok"},{"step":"build","status":"failed","detail":"error: builder failed"}],"restored":["flake.nix","flake.lock"],"recovered":["flake.nix"],"next":["both files are as they were"]}"#
1732 );
1733 let bare = SyncReport {
1734 schema: "rk.self-depend-sync/3",
1735 mode: "preview",
1736 target: "/srv/widget",
1737 manager: None,
1738 outcome: "no-manager",
1739 from: None,
1740 to: None,
1741 detail: None,
1742 steps: None,
1743 restored: None,
1744 recovered: None,
1745 next: &[],
1746 };
1747 assert_eq!(
1748 serde_json::to_string(&bare).expect("a report serializes"),
1749 r#"{"schema":"rk.self-depend-sync/3","mode":"preview","target":"/srv/widget","outcome":"no-manager","next":[]}"#,
1750 "an unknown value is omitted, never null"
1751 );
1752 }
1753
1754 #[test]
1756 fn the_self_depend_check_schema_snapshot_holds() {
1757 let warnings = vec![
1758 "rk 0.10.0 is out, this project pins 0.9.15. To move: rk self-depend sync --apply, then upgrade through the rk-setup skill of the new rk."
1759 .to_owned(),
1760 ];
1761 let report = CheckReport {
1762 schema: "rk.self-depend-check/1",
1763 target: Some("/srv/widget"),
1764 outcome: "cached",
1765 pin: Some("v0.9.15"),
1766 latest: Some("v0.10.0"),
1767 cache: Some(
1768 "/srv/cache/release-kit/self-depend/widget-0123456789abcdef.json".to_owned(),
1769 ),
1770 fetched: false,
1771 warnings: &warnings,
1772 };
1773 assert_eq!(
1774 serde_json::to_string(&report).expect("a report serializes"),
1775 r#"{"schema":"rk.self-depend-check/1","target":"/srv/widget","outcome":"cached","pin":"v0.9.15","latest":"v0.10.0","cache":"/srv/cache/release-kit/self-depend/widget-0123456789abcdef.json","fetched":false,"warnings":["rk 0.10.0 is out, this project pins 0.9.15. To move: rk self-depend sync --apply, then upgrade through the rk-setup skill of the new rk."]}"#
1776 );
1777 let bare = CheckReport {
1778 schema: "rk.self-depend-check/1",
1779 target: None,
1780 outcome: "disabled",
1781 pin: None,
1782 latest: None,
1783 cache: None,
1784 fetched: false,
1785 warnings: &[],
1786 };
1787 assert_eq!(
1788 serde_json::to_string(&bare).expect("a report serializes"),
1789 r#"{"schema":"rk.self-depend-check/1","outcome":"disabled","fetched":false,"warnings":[]}"#
1790 );
1791 }
1792
1793 #[test]
1795 fn the_self_depend_clean_schema_snapshot_holds() {
1796 let leftovers = vec![Leftover {
1797 id: "bump-script",
1798 file: "scripts/rk-bump.sh".to_owned(),
1799 line: None,
1800 text: None,
1801 action: Action::RemoveFile,
1802 reason: "the file exists only for the predecessor bump mechanism",
1803 }];
1804 let removed = vec!["scripts/rk-bump.sh".to_owned()];
1805 let rewritten = vec![".envrc".to_owned()];
1806 let manual = vec![Manual {
1807 id: "just-recipe",
1808 file: "justfile".to_owned(),
1809 line: Some(42),
1810 text: Some("rk-bump:".to_owned()),
1811 reason: "a recipe body carries structure a line scan cannot judge",
1812 }];
1813 let next = vec!["rk self-depend status".to_owned()];
1814 let report = CleanReport {
1815 schema: "rk.self-depend-clean/1",
1816 mode: "apply",
1817 target: "/srv/widget",
1818 leftovers: &leftovers,
1819 removed: &removed,
1820 rewritten: &rewritten,
1821 manual: &manual,
1822 next: &next,
1823 };
1824 assert_eq!(
1825 serde_json::to_string(&report).expect("a report serializes"),
1826 r#"{"schema":"rk.self-depend-clean/1","mode":"apply","target":"/srv/widget","leftovers":[{"id":"bump-script","file":"scripts/rk-bump.sh","action":"remove-file","reason":"the file exists only for the predecessor bump mechanism"}],"removed":["scripts/rk-bump.sh"],"rewritten":[".envrc"],"manual":[{"id":"just-recipe","file":"justfile","line":42,"text":"rk-bump:","reason":"a recipe body carries structure a line scan cannot judge"}],"next":["rk self-depend status"]}"#
1827 );
1828 let bare = Manual {
1829 id: "also",
1830 file: "old.sh".to_owned(),
1831 line: None,
1832 text: None,
1833 reason: "named by the operator",
1834 };
1835 assert_eq!(
1836 serde_json::to_string(&bare).expect("an entry serializes"),
1837 r#"{"id":"also","file":"old.sh","reason":"named by the operator"}"#,
1838 "an absent line and text are omitted, never null"
1839 );
1840 }
1841 use crate::self_depend::Presence;
1842 use crate::self_depend::fragments::{Anchor, Fragment};
1843 use crate::self_depend::leftovers::{Action, Leftover};
1844 use crate::self_depend::manager::{Entry, Freshness, Manager, PinRead};
1845
1846 #[test]
1849 fn the_self_depend_add_schema_snapshot_holds() {
1850 let fragments = vec![Fragment {
1851 id: "flake-input",
1852 file: "flake.nix".to_owned(),
1853 role: "the pinned release-kit input",
1854 placement: "insert-into-attrset",
1855 anchor: Anchor {
1856 kind: "attrset",
1857 path: "inputs",
1858 needle: Some("inputs = {"),
1859 },
1860 text: "release-kit = {};".to_owned(),
1861 present: Some(false),
1862 }];
1863 let written = vec![".envrc".to_owned()];
1864 let next = vec!["direnv allow".to_owned()];
1865 let report = AddReport {
1866 schema: "rk.self-depend-add/3",
1867 mode: "apply",
1868 target: "/srv/widget",
1869 tag: "v0.2.16",
1870 tag_source: "binary",
1871 manager: Manager::Flake,
1872 venue: Venue::Flake,
1873 support: Mode::Fragment,
1874 reason: None,
1875 file: "flake.nix",
1876 file_present: Presence::Present,
1877 envrc: Presence::Absent,
1878 written: &written,
1879 refusal: Some("the target already carries flake.nix"),
1880 fragments: &fragments,
1881 next: &next,
1882 };
1883 assert_eq!(
1884 serde_json::to_string(&report).expect("a report serializes"),
1885 r#"{"schema":"rk.self-depend-add/3","mode":"apply","target":"/srv/widget","tag":"v0.2.16","tag_source":"binary","manager":"flake","venue":"flake","support":"fragment","file":"flake.nix","file_present":"present","envrc":"absent","written":[".envrc"],"refusal":"the target already carries flake.nix","fragments":[{"id":"flake-input","file":"flake.nix","role":"the pinned release-kit input","placement":"insert-into-attrset","anchor":{"kind":"attrset","path":"inputs","needle":"inputs = {"},"text":"release-kit = {};","present":false}],"next":["direnv allow"]}"#
1886 );
1887 let manual = AddReport {
1888 schema: "rk.self-depend-add/3",
1889 mode: "preview",
1890 target: "/srv/widget",
1891 tag: "v0.2.16",
1892 tag_source: "binary",
1893 manager: Manager::Asdf,
1894 venue: Venue::Crates,
1895 support: Mode::Manual,
1896 reason: Some("asdf-plugin-unknown"),
1897 file: ".tool-versions",
1898 file_present: Presence::Absent,
1899 envrc: Presence::Absent,
1900 written: &[],
1901 refusal: None,
1902 fragments: &[],
1903 next: &[],
1904 };
1905 assert_eq!(
1906 serde_json::to_string(&manual).expect("a report serializes"),
1907 r#"{"schema":"rk.self-depend-add/3","mode":"preview","target":"/srv/widget","tag":"v0.2.16","tag_source":"binary","manager":"asdf","venue":"crates","support":"manual","reason":"asdf-plugin-unknown","file":".tool-versions","file_present":"absent","envrc":"absent","written":[],"fragments":[],"next":[]}"#,
1908 "a manual pair carries its reason and no refusal"
1909 );
1910 let bare = Fragment {
1911 id: "envrc-check",
1912 file: ".envrc".to_owned(),
1913 role: "the weekly version check on directory entry",
1914 placement: "append-line",
1915 anchor: Anchor {
1916 kind: "file",
1917 path: ".envrc",
1918 needle: None,
1919 },
1920 text: "line".to_owned(),
1921 present: None,
1922 };
1923 assert_eq!(
1924 serde_json::to_string(&bare).expect("a fragment serializes"),
1925 r#"{"id":"envrc-check","file":".envrc","role":"the weekly version check on directory entry","placement":"append-line","anchor":{"kind":"file","path":".envrc"},"text":"line"}"#,
1926 "an unjudged presence and a missing needle are omitted, never null"
1927 );
1928 }
1929
1930 #[test]
1933 fn the_status_schema_is_versioned_and_snapshot_tested() {
1934 let leftovers = vec![
1935 Leftover {
1936 id: "just-recipe",
1937 file: "justfile".to_owned(),
1938 line: Some(42),
1939 text: Some("rk-bump:".to_owned()),
1940 action: Action::Manual,
1941 reason: "a recipe body carries structure a line scan cannot judge",
1942 },
1943 Leftover {
1944 id: "bump-script",
1945 file: "scripts/rk-bump.sh".to_owned(),
1946 line: None,
1947 text: None,
1948 action: Action::RemoveFile,
1949 reason: "the file exists only for the predecessor bump mechanism",
1950 },
1951 ];
1952 let managers = vec![
1953 Entry {
1954 manager: Manager::Flake,
1955 present: Presence::Present,
1956 file: Some("flake.nix".to_owned()),
1957 pin: "pinned",
1958 version: Some("v0.2.16".to_owned()),
1959 pin_lines: Some(1),
1960 freshness: Some(Freshness::Behind),
1961 lock: Some(Presence::Present),
1962 locked_ref: Some("refs/tags/v0.2.16".to_owned()),
1963 locked_rev: Some("9f3c".to_owned()),
1964 read: PinRead::One {
1965 line: 4,
1966 version: "v0.2.16".to_owned(),
1967 },
1968 text: None,
1969 },
1970 Entry::absent(Manager::Mise),
1971 ];
1972 let next = vec![
1973 "rk self-depend sync --target /srv/widget reports whether the pin is current"
1974 .to_owned(),
1975 ];
1976 let report = StatusReport {
1977 schema: "rk.self-depend-status/3",
1978 target: "/srv/widget",
1979 state: "ready",
1980 acquisition: None,
1981 wired: Some(Manager::Flake),
1982 managers: &managers,
1983 envrc: Presence::Present,
1984 envrc_check: true,
1985 envrc_old_sync: false,
1986 pending: false,
1987 host: Host {
1988 nix: "ok",
1989 direnv: "failed",
1990 },
1991 leftovers: &leftovers,
1992 next: &next,
1993 };
1994 assert_eq!(
1995 serde_json::to_string(&report).expect("a report serializes"),
1996 r#"{"schema":"rk.self-depend-status/3","target":"/srv/widget","state":"ready","wired":"flake","managers":[{"manager":"flake","present":"present","file":"flake.nix","pin":"pinned","version":"v0.2.16","pin_lines":1,"freshness":"behind","lock":"present","locked_ref":"refs/tags/v0.2.16","locked_rev":"9f3c"},{"manager":"mise","present":"absent","pin":"absent"}],"envrc":"present","envrc_check":true,"envrc_old_sync":false,"pending":false,"host":{"nix":"ok","direnv":"failed"},"leftovers":[{"id":"just-recipe","file":"justfile","line":42,"text":"rk-bump:","action":"manual","reason":"a recipe body carries structure a line scan cannot judge"},{"id":"bump-script","file":"scripts/rk-bump.sh","action":"remove-file","reason":"the file exists only for the predecessor bump mechanism"}],"next":["rk self-depend sync --target /srv/widget reports whether the pin is current"]}"#
1997 );
1998 let bare = StatusReport {
1999 schema: "rk.self-depend-status/3",
2000 target: "/srv/widget",
2001 state: "no-manager",
2002 acquisition: None,
2003 wired: None,
2004 managers: &[],
2005 envrc: Presence::Absent,
2006 envrc_check: false,
2007 envrc_old_sync: false,
2008 pending: false,
2009 host: Host {
2010 nix: "failed",
2011 direnv: "failed",
2012 },
2013 leftovers: &[],
2014 next: &[],
2015 };
2016 assert_eq!(
2017 serde_json::to_string(&bare).expect("a report serializes"),
2018 r#"{"schema":"rk.self-depend-status/3","target":"/srv/widget","state":"no-manager","managers":[],"envrc":"absent","envrc_check":false,"envrc_old_sync":false,"pending":false,"host":{"nix":"failed","direnv":"failed"},"leftovers":[],"next":[]}"#,
2019 "an unknown value must be omitted, not serialized as null"
2020 );
2021 }
2022
2023 #[test]
2025 fn the_host_answer_schema_snapshots_hold() {
2026 let answer = crate::config::Acquisition {
2027 source: crate::config::AcquisitionSource::Host,
2028 minimum: "0.8.7".to_owned(),
2029 };
2030 let host = StatusReport {
2031 schema: "rk.self-depend-status/3",
2032 target: "/srv/widget",
2033 state: "host",
2034 acquisition: Some(&answer),
2035 wired: None,
2036 managers: &[],
2037 envrc: Presence::Absent,
2038 envrc_check: false,
2039 envrc_old_sync: false,
2040 pending: false,
2041 host: Host {
2042 nix: "failed",
2043 direnv: "failed",
2044 },
2045 leftovers: &[],
2046 next: &[],
2047 };
2048 assert_eq!(
2049 serde_json::to_string(&host).expect("a report serializes"),
2050 r#"{"schema":"rk.self-depend-status/3","target":"/srv/widget","state":"host","acquisition":{"source":"host","minimum":"0.8.7"},"managers":[],"envrc":"absent","envrc_check":false,"envrc_old_sync":false,"pending":false,"host":{"nix":"failed","direnv":"failed"},"leftovers":[],"next":[]}"#
2051 );
2052 let added = AddHostReport {
2053 schema: "rk.self-depend-add-host/1",
2054 mode: "apply",
2055 target: "/srv/widget",
2056 acquisition: &answer,
2057 config: Presence::Absent,
2058 written: true,
2059 next: &[],
2060 };
2061 assert_eq!(
2062 serde_json::to_string(&added).expect("a report serializes"),
2063 r#"{"schema":"rk.self-depend-add-host/1","mode":"apply","target":"/srv/widget","acquisition":{"source":"host","minimum":"0.8.7"},"config":"absent","written":true,"next":[]}"#
2064 );
2065 }
2066}