Skip to main content

spec_driven_docs/self_depend/
status.rs

1//! The offline status report: what a target carries, and nothing judged.
2//!
3//! A report is not a verdict. Every state it can describe exits 0, and the
4//! `next` lines say what an operator does about each.
5
6use camino::{Utf8Path, Utf8PathBuf};
7use semver::Version;
8use serde::Serialize;
9
10use crate::domain::paths::{CI_VAR, SELF_DEPEND_OFF_VAR, UserEnv, variable};
11use crate::self_depend::cache::{self, Entry};
12use crate::self_depend::guidance;
13use crate::self_depend::leftovers::{self, Leftover};
14use crate::self_depend::manager::{self, Detected, Manager};
15use crate::self_depend::pin;
16use crate::self_depend::venue::Venue;
17use crate::self_depend::{CHECK_LINE, ENVRC, OLD_SYNC_LINE, SYNC_COMMAND};
18
19/// The machine schema `sdd self-depend status --json` declares.
20pub const SCHEMA: &str = "sdd.self-depend-status/2";
21
22/// Whether a file is on disk.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum Presence {
26    /// The file exists.
27    Present,
28    /// The file does not exist.
29    Absent,
30}
31
32impl Presence {
33    const fn of(present: bool) -> Self {
34        if present { Self::Present } else { Self::Absent }
35    }
36}
37
38/// How a recorded pin compares with the release this binary is.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum Freshness {
42    /// The pin names this binary's release.
43    Current,
44    /// The pin names an older release.
45    Behind,
46    /// The pin names a newer release than this binary.
47    Ahead,
48}
49
50/// One manager's row.
51#[derive(Debug, Clone, Serialize)]
52pub struct ManagerEntry {
53    /// Which manager.
54    pub manager: Manager,
55    /// Whether the target carries its file.
56    pub present: Presence,
57    /// The file, where present.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub file: Option<Utf8PathBuf>,
60    /// Whether the file names this tool.
61    pub pinned: bool,
62    /// The version pinned, as the file spells it.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub version: Option<String>,
65    /// The venue the entry's form selects.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub venue: Option<Venue>,
68    /// How many lines pin this tool.
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub pin_lines: Option<usize>,
71    /// The pin against this binary's release.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub freshness: Option<Freshness>,
74    /// Whether the manager's lock is on disk, where the manager keeps one.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub lock: Option<Presence>,
77    /// The revision the lock holds for this tool.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub locked_rev: Option<String>,
80}
81
82/// What the report concludes about the wiring.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
84#[serde(rename_all = "kebab-case")]
85pub enum State {
86    /// One manager pins this tool, the check line is landed, nothing is left over.
87    Ready,
88    /// No manager file names this tool.
89    Unwired,
90    /// A manager pins this tool and the shell loader carries no check line.
91    LineAbsent,
92    /// The shell loader still carries the retired sync line.
93    OldLine,
94    /// More than one manager names this tool.
95    Ambiguous,
96    /// A predecessor mechanism left a file behind.
97    Leftovers,
98    /// No manager pins this tool, and the declaration records that each
99    /// host installs it itself.
100    Host,
101}
102
103/// What the host offers.
104#[derive(Debug, Clone, Serialize)]
105pub struct Host {
106    /// Whether `nix` is on `PATH`.
107    pub nix: bool,
108    /// Whether `direnv` is on `PATH`.
109    pub direnv: bool,
110}
111
112/// The whole report.
113#[derive(Debug, Clone, Serialize)]
114pub struct Report {
115    /// The machine schema of this object.
116    pub schema: &'static str,
117    /// The target read.
118    pub target: Utf8PathBuf,
119    /// What the wiring amounts to.
120    pub state: State,
121    /// The one manager that pins this tool, where exactly one does.
122    pub wired: Option<Manager>,
123    /// The host decision the instance's declaration records, where it
124    /// records one.
125    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
126    /// Every manager, in the enum's order, absent ones included.
127    pub managers: Vec<ManagerEntry>,
128    /// Whether the shell loader file exists.
129    pub envrc: Presence,
130    /// Whether the shell loader carries the check line.
131    pub envrc_check: bool,
132    /// Whether the shell loader still carries the retired sync line.
133    pub envrc_old_line: bool,
134    /// What the version-check cache records for this checkout, where it
135    /// records anything.
136    pub check: Option<Entry>,
137    /// Whether the loop is switched off in this environment.
138    pub off: bool,
139    /// What the host offers.
140    pub host: Host,
141    /// What a predecessor mechanism left behind.
142    pub leftovers: Vec<Leftover>,
143    /// A newer release than the pin, where the cache records one.
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub pending: Option<Pending>,
146    /// The follows lines a flake target lacks on this tool's input.
147    #[serde(skip_serializing_if = "Vec::is_empty")]
148    pub follows: Vec<pin::Follows>,
149    /// What an operator does next, one line each.
150    pub next: Vec<String>,
151}
152
153/// A newer release than the pin, as the version-check cache records it.
154#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
155pub struct Pending {
156    /// The newest release the cache records.
157    pub latest: String,
158    /// The release the wired manager pins.
159    pub pin: String,
160    /// The pending text a reader prints.
161    pub text: String,
162}
163
164/// How the pin compares with the newest release the cache records.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum PinFreshness {
167    /// No single wired pin, no cache, no recorded release, or the loop is
168    /// switched off, so nothing can be said.
169    Unknown,
170    /// The pin names the newest recorded release, or a newer one.
171    Current {
172        /// The release the pin names.
173        pin: String,
174    },
175    /// A newer release is out than the pin.
176    Behind(Pending),
177}
178
179/// Read the wired pin and the version-check cache, offline, and say how
180/// they compare. Nothing here reads the network or writes a file, so every
181/// report can call it.
182///
183/// SATISFIES acquisition:every-report-names-a-pending-move
184#[must_use]
185pub fn freshness(target: &Utf8Path, env: &UserEnv) -> PinFreshness {
186    if switched_off() {
187        return PinFreshness::Unknown;
188    }
189    let detected = manager::detect(target);
190    let [held] = manager::wired(&detected)[..] else {
191        return PinFreshness::Unknown;
192    };
193    let Some(pin) = held.pin.as_ref() else {
194        return PinFreshness::Unknown;
195    };
196    let Some(latest) = env
197        .cache_root()
198        .and_then(|root| cache::read(&cache::path(&root.path, target)))
199        .and_then(|entry| entry.latest_version())
200    else {
201        return PinFreshness::Unknown;
202    };
203    if latest > pin.version {
204        PinFreshness::Behind(Pending {
205            latest: latest.to_string(),
206            pin: pin.version.to_string(),
207            text: guidance::pending(&latest, &pin.version),
208        })
209    } else {
210        PinFreshness::Current {
211            pin: pin.version.to_string(),
212        }
213    }
214}
215
216/// The pending move of a target, where the cache records a newer release.
217#[must_use]
218pub fn pending(target: &Utf8Path, env: &UserEnv) -> Option<Pending> {
219    match freshness(target, env) {
220        PinFreshness::Behind(pending) => Some(pending),
221        PinFreshness::Unknown | PinFreshness::Current { .. } => None,
222    }
223}
224
225/// The follows lines a flake target lacks on this tool's input, read from
226/// its lock, offline. Empty for every other manager.
227#[must_use]
228pub fn follows(target: &Utf8Path, manager: Option<Manager>) -> Vec<pin::Follows> {
229    if manager != Some(Manager::Flake) {
230        return Vec::new();
231    }
232    manager::Manager::Flake
233        .lock_file()
234        .and_then(|lock| std::fs::read_to_string(target.join(lock)).ok())
235        .map(|text| pin::follows_advice(&text))
236        .unwrap_or_default()
237}
238
239/// Print-ready advice for one follows line.
240#[must_use]
241pub fn follows_line(follows: &pin::Follows) -> String {
242    format!(
243        "flake.nix lacks a follows line: add `{}` inside the `{}` input, then run nix flake lock",
244        follows.line, follows.input
245    )
246}
247
248/// Whether the loop is switched off: in continuous integration, or by the
249/// operator's variable.
250#[must_use]
251pub fn switched_off() -> bool {
252    variable(CI_VAR).is_some() || variable(SELF_DEPEND_OFF_VAR).is_some()
253}
254
255/// Whether one program is on `PATH`.
256fn on_path(program: &str) -> bool {
257    std::env::var_os("PATH")
258        .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
259}
260
261/// The report for one target, offline.
262///
263/// SATISFIES acquisition:status-reports-and-never-judges
264#[must_use]
265pub fn report(target: &Utf8Path, env: &UserEnv, this: &Version) -> Report {
266    let detected = manager::detect(target);
267    let managers = detected
268        .iter()
269        .map(|held| entry(target, held, this))
270        .collect();
271    let wired = manager::wired(&detected);
272    let envrc_text = std::fs::read_to_string(target.join(ENVRC)).ok();
273    let envrc_check = envrc_text
274        .as_deref()
275        .is_some_and(leftovers::carries_check_line);
276    let envrc_old_line = envrc_text
277        .as_deref()
278        .is_some_and(leftovers::carries_old_line);
279    let leftovers = leftovers::find(target, &[]);
280    let check = env
281        .cache_root()
282        .map(|root| cache::path(&root.path, target))
283        .and_then(|path| cache::read(&path));
284    // A declaration that does not parse records no decision this report
285    // can read; `sdd verify` is what names that failure.
286    let acquisition = crate::domain::instance_config::InstanceConfig::read(target)
287        .ok()
288        .and_then(|declaration| declaration.acquisition);
289    let state = match (wired.len(), envrc_check, leftovers.is_empty()) {
290        // SATISFIES acquisition:a-host-install-is-a-recorded-decision
291        (0, _, _) if acquisition.is_some() => State::Host,
292        (0, _, _) => State::Unwired,
293        // SATISFIES acquisition:clean-swaps-the-retired-line
294        (1, _, _) if envrc_old_line => State::OldLine,
295        (1, true, true) => State::Ready,
296        (1, true, false) => State::Leftovers,
297        (1, false, _) => State::LineAbsent,
298        (_, _, _) => State::Ambiguous,
299    };
300    let pending = pending(target, env);
301    let mut next = next_lines(state, &wired, target, acquisition.as_ref());
302    if state == State::Ready
303        && let Some(pending) = pending.as_ref()
304    {
305        next.insert(0, pending.text.clone());
306    }
307    Report {
308        schema: SCHEMA,
309        target: target.to_owned(),
310        state,
311        wired: (wired.len() == 1).then(|| wired[0].manager),
312        acquisition,
313        managers,
314        envrc: Presence::of(envrc_text.is_some()),
315        envrc_check,
316        envrc_old_line,
317        check,
318        off: switched_off(),
319        host: Host {
320            nix: on_path("nix"),
321            direnv: on_path("direnv"),
322        },
323        leftovers,
324        pending,
325        follows: follows(target, (wired.len() == 1).then(|| wired[0].manager)),
326        next,
327    }
328}
329
330fn entry(target: &Utf8Path, held: &Detected, this: &Version) -> ManagerEntry {
331    let lock = held.manager.lock_file().map(|lock| {
332        let path = target.join(lock);
333        (
334            Presence::of(path.is_file()),
335            std::fs::read_to_string(&path)
336                .ok()
337                .and_then(|text| pin::locked_rev(&text)),
338        )
339    });
340    ManagerEntry {
341        manager: held.manager,
342        present: Presence::of(held.file.is_some()),
343        file: held.file.clone(),
344        pinned: held.pin.is_some(),
345        version: held.pin.as_ref().map(|pin| pin.spelled.clone()),
346        venue: held.pin.as_ref().and_then(|pin| pin.venue),
347        pin_lines: held.pin.as_ref().map(|pin| pin.lines),
348        freshness: held.pin.as_ref().map(|pin| match pin.version.cmp(this) {
349            std::cmp::Ordering::Less => Freshness::Behind,
350            std::cmp::Ordering::Equal => Freshness::Current,
351            std::cmp::Ordering::Greater => Freshness::Ahead,
352        }),
353        lock: lock.as_ref().map(|(presence, _)| *presence),
354        locked_rev: lock.and_then(|(_, rev)| rev),
355    }
356}
357
358fn next_lines(
359    state: State,
360    wired: &[&Detected],
361    target: &Utf8Path,
362    acquisition: Option<&crate::domain::instance_config::Acquisition>,
363) -> Vec<String> {
364    match state {
365        State::Host => vec![format!(
366            "each host installs sdd {} or newer itself; sdd self-depend add --target {target} --manager <manager> moves the project onto a pin",
367            acquisition.map_or("", |decision| decision.minimum.as_str())
368        )],
369        State::Ready => vec![format!(
370            "{SYNC_COMMAND} --target {target} moves the pin when a newer release is out"
371        )],
372        State::Unwired => vec![format!(
373            "sdd self-depend add --target {target} serves the fragments for the manager this project runs"
374        )],
375        State::LineAbsent => vec![format!(
376            "add `{CHECK_LINE}` to {ENVRC}; sdd self-depend add --target {target} prints it with its placement"
377        )],
378        State::OldLine => vec![format!(
379            "{ENVRC} still runs `{OLD_SYNC_LINE}`: move the pin first with {SYNC_COMMAND} --target {target}, then sdd self-depend clean --target {target} --apply swaps the line for `{CHECK_LINE}`"
380        )],
381        State::Ambiguous => {
382            let names: Vec<&str> = wired.iter().map(|held| held.manager.as_str()).collect();
383            vec![format!(
384                "one target runs one mechanism; keep one of {} and remove the others' pins",
385                names.join(", ")
386            )]
387        }
388        State::Leftovers => vec![format!(
389            "sdd self-depend clean --target {target} --apply removes what the predecessor left"
390        )],
391    }
392}