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::leftovers::{self, Leftover};
13use crate::self_depend::manager::{self, Detected, Manager};
14use crate::self_depend::pin;
15use crate::self_depend::venue::Venue;
16use crate::self_depend::{CHECK_LINE, ENVRC, OLD_SYNC_LINE, SYNC_COMMAND};
17
18/// The machine schema `sdd self-depend status --json` declares.
19pub const SCHEMA: &str = "sdd.self-depend-status/2";
20
21/// Whether a file is on disk.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum Presence {
25    /// The file exists.
26    Present,
27    /// The file does not exist.
28    Absent,
29}
30
31impl Presence {
32    const fn of(present: bool) -> Self {
33        if present { Self::Present } else { Self::Absent }
34    }
35}
36
37/// How a recorded pin compares with the release this binary is.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum Freshness {
41    /// The pin names this binary's release.
42    Current,
43    /// The pin names an older release.
44    Behind,
45    /// The pin names a newer release than this binary.
46    Ahead,
47}
48
49/// One manager's row.
50#[derive(Debug, Clone, Serialize)]
51pub struct ManagerEntry {
52    /// Which manager.
53    pub manager: Manager,
54    /// Whether the target carries its file.
55    pub present: Presence,
56    /// The file, where present.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub file: Option<Utf8PathBuf>,
59    /// Whether the file names this tool.
60    pub pinned: bool,
61    /// The version pinned, as the file spells it.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub version: Option<String>,
64    /// The venue the entry's form selects.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub venue: Option<Venue>,
67    /// How many lines pin this tool.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub pin_lines: Option<usize>,
70    /// The pin against this binary's release.
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub freshness: Option<Freshness>,
73    /// Whether the manager's lock is on disk, where the manager keeps one.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub lock: Option<Presence>,
76    /// The revision the lock holds for this tool.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub locked_rev: Option<String>,
79}
80
81/// What the report concludes about the wiring.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
83#[serde(rename_all = "kebab-case")]
84pub enum State {
85    /// One manager pins this tool, the check line is landed, nothing is left over.
86    Ready,
87    /// No manager file names this tool.
88    Unwired,
89    /// A manager pins this tool and the shell loader carries no check line.
90    LineAbsent,
91    /// The shell loader still carries the retired sync line.
92    OldLine,
93    /// More than one manager names this tool.
94    Ambiguous,
95    /// A predecessor mechanism left a file behind.
96    Leftovers,
97    /// No manager pins this tool, and the declaration records that each
98    /// host installs it itself.
99    Host,
100}
101
102/// What the host offers.
103#[derive(Debug, Clone, Serialize)]
104pub struct Host {
105    /// Whether `nix` is on `PATH`.
106    pub nix: bool,
107    /// Whether `direnv` is on `PATH`.
108    pub direnv: bool,
109}
110
111/// The whole report.
112#[derive(Debug, Clone, Serialize)]
113pub struct Report {
114    /// The machine schema of this object.
115    pub schema: &'static str,
116    /// The target read.
117    pub target: Utf8PathBuf,
118    /// What the wiring amounts to.
119    pub state: State,
120    /// The one manager that pins this tool, where exactly one does.
121    pub wired: Option<Manager>,
122    /// The host decision the instance's declaration records, where it
123    /// records one.
124    pub acquisition: Option<crate::domain::instance_config::Acquisition>,
125    /// Every manager, in the enum's order, absent ones included.
126    pub managers: Vec<ManagerEntry>,
127    /// Whether the shell loader file exists.
128    pub envrc: Presence,
129    /// Whether the shell loader carries the check line.
130    pub envrc_check: bool,
131    /// Whether the shell loader still carries the retired sync line.
132    pub envrc_old_line: bool,
133    /// What the version-check cache records for this checkout, where it
134    /// records anything.
135    pub check: Option<Entry>,
136    /// Whether the loop is switched off in this environment.
137    pub off: bool,
138    /// What the host offers.
139    pub host: Host,
140    /// What a predecessor mechanism left behind.
141    pub leftovers: Vec<Leftover>,
142    /// What an operator does next, one line each.
143    pub next: Vec<String>,
144}
145
146/// Whether the loop is switched off: in continuous integration, or by the
147/// operator's variable.
148#[must_use]
149pub fn switched_off() -> bool {
150    variable(CI_VAR).is_some() || variable(SELF_DEPEND_OFF_VAR).is_some()
151}
152
153/// Whether one program is on `PATH`.
154fn on_path(program: &str) -> bool {
155    std::env::var_os("PATH")
156        .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
157}
158
159/// The report for one target, offline.
160///
161/// SATISFIES acquisition:status-reports-and-never-judges
162#[must_use]
163pub fn report(target: &Utf8Path, env: &UserEnv, this: &Version) -> Report {
164    let detected = manager::detect(target);
165    let managers = detected
166        .iter()
167        .map(|held| entry(target, held, this))
168        .collect();
169    let wired = manager::wired(&detected);
170    let envrc_text = std::fs::read_to_string(target.join(ENVRC)).ok();
171    let envrc_check = envrc_text
172        .as_deref()
173        .is_some_and(leftovers::carries_check_line);
174    let envrc_old_line = envrc_text
175        .as_deref()
176        .is_some_and(leftovers::carries_old_line);
177    let leftovers = leftovers::find(target, &[]);
178    let check = env
179        .cache_root()
180        .map(|root| cache::path(&root.path, target))
181        .and_then(|path| cache::read(&path));
182    // A declaration that does not parse records no decision this report
183    // can read; `sdd verify` is what names that failure.
184    let acquisition = crate::domain::instance_config::InstanceConfig::read(target)
185        .ok()
186        .and_then(|declaration| declaration.acquisition);
187    let state = match (wired.len(), envrc_check, leftovers.is_empty()) {
188        // SATISFIES acquisition:a-host-install-is-a-recorded-decision
189        (0, _, _) if acquisition.is_some() => State::Host,
190        (0, _, _) => State::Unwired,
191        // SATISFIES acquisition:clean-swaps-the-retired-line
192        (1, _, _) if envrc_old_line => State::OldLine,
193        (1, true, true) => State::Ready,
194        (1, true, false) => State::Leftovers,
195        (1, false, _) => State::LineAbsent,
196        (_, _, _) => State::Ambiguous,
197    };
198    let next = next_lines(state, &wired, target, acquisition.as_ref());
199    Report {
200        schema: SCHEMA,
201        target: target.to_owned(),
202        state,
203        wired: (wired.len() == 1).then(|| wired[0].manager),
204        acquisition,
205        managers,
206        envrc: Presence::of(envrc_text.is_some()),
207        envrc_check,
208        envrc_old_line,
209        check,
210        off: switched_off(),
211        host: Host {
212            nix: on_path("nix"),
213            direnv: on_path("direnv"),
214        },
215        leftovers,
216        next,
217    }
218}
219
220fn entry(target: &Utf8Path, held: &Detected, this: &Version) -> ManagerEntry {
221    let lock = held.manager.lock_file().map(|lock| {
222        let path = target.join(lock);
223        (
224            Presence::of(path.is_file()),
225            std::fs::read_to_string(&path)
226                .ok()
227                .and_then(|text| pin::locked_rev(&text)),
228        )
229    });
230    ManagerEntry {
231        manager: held.manager,
232        present: Presence::of(held.file.is_some()),
233        file: held.file.clone(),
234        pinned: held.pin.is_some(),
235        version: held.pin.as_ref().map(|pin| pin.spelled.clone()),
236        venue: held.pin.as_ref().and_then(|pin| pin.venue),
237        pin_lines: held.pin.as_ref().map(|pin| pin.lines),
238        freshness: held.pin.as_ref().map(|pin| match pin.version.cmp(this) {
239            std::cmp::Ordering::Less => Freshness::Behind,
240            std::cmp::Ordering::Equal => Freshness::Current,
241            std::cmp::Ordering::Greater => Freshness::Ahead,
242        }),
243        lock: lock.as_ref().map(|(presence, _)| *presence),
244        locked_rev: lock.and_then(|(_, rev)| rev),
245    }
246}
247
248fn next_lines(
249    state: State,
250    wired: &[&Detected],
251    target: &Utf8Path,
252    acquisition: Option<&crate::domain::instance_config::Acquisition>,
253) -> Vec<String> {
254    match state {
255        State::Host => vec![format!(
256            "each host installs sdd {} or newer itself; sdd self-depend add --target {target} --manager <manager> moves the project onto a pin",
257            acquisition.map_or("", |decision| decision.minimum.as_str())
258        )],
259        State::Ready => vec![format!(
260            "{SYNC_COMMAND} --target {target} moves the pin when a newer release is out"
261        )],
262        State::Unwired => vec![format!(
263            "sdd self-depend add --target {target} serves the fragments for the manager this project runs"
264        )],
265        State::LineAbsent => vec![format!(
266            "add `{CHECK_LINE}` to {ENVRC}; sdd self-depend add --target {target} prints it with its placement"
267        )],
268        State::OldLine => vec![format!(
269            "{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}`"
270        )],
271        State::Ambiguous => {
272            let names: Vec<&str> = wired.iter().map(|held| held.manager.as_str()).collect();
273            vec![format!(
274                "one target runs one mechanism; keep one of {} and remove the others' pins",
275                names.join(", ")
276            )]
277        }
278        State::Leftovers => vec![format!(
279            "sdd self-depend clean --target {target} --apply removes what the predecessor left"
280        )],
281    }
282}