spec_driven_docs/self_depend/
status.rs1use 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::leftovers::{self, Leftover};
12use crate::self_depend::manager::{self, Detected, Manager};
13use crate::self_depend::pin;
14use crate::self_depend::stamp;
15use crate::self_depend::venue::Venue;
16use crate::self_depend::{ENVRC, SYNC_LINE};
17
18pub const SCHEMA: &str = "sdd.self-depend-status/1";
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum Presence {
25 Present,
27 Absent,
29}
30
31impl Presence {
32 const fn of(present: bool) -> Self {
33 if present { Self::Present } else { Self::Absent }
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum Freshness {
41 Current,
43 Behind,
45 Ahead,
47}
48
49#[derive(Debug, Clone, Serialize)]
51pub struct ManagerEntry {
52 pub manager: Manager,
54 pub present: Presence,
56 #[serde(skip_serializing_if = "Option::is_none")]
58 pub file: Option<Utf8PathBuf>,
59 pub pinned: bool,
61 #[serde(skip_serializing_if = "Option::is_none")]
63 pub version: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
66 pub venue: Option<Venue>,
67 #[serde(skip_serializing_if = "Option::is_none")]
69 pub pin_lines: Option<usize>,
70 #[serde(skip_serializing_if = "Option::is_none")]
72 pub freshness: Option<Freshness>,
73 #[serde(skip_serializing_if = "Option::is_none")]
75 pub lock: Option<Presence>,
76 #[serde(skip_serializing_if = "Option::is_none")]
78 pub locked_rev: Option<String>,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
83#[serde(rename_all = "kebab-case")]
84pub enum State {
85 Ready,
87 Unwired,
89 LineAbsent,
91 Ambiguous,
93 Leftovers,
95 Host,
98}
99
100#[derive(Debug, Clone, Serialize)]
102pub struct Host {
103 pub nix: bool,
105 pub direnv: bool,
107}
108
109#[derive(Debug, Clone, Serialize)]
111pub struct Report {
112 pub schema: &'static str,
114 pub target: Utf8PathBuf,
116 pub state: State,
118 pub wired: Option<Manager>,
120 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
123 pub managers: Vec<ManagerEntry>,
125 pub envrc: Presence,
127 pub envrc_sync: bool,
129 pub stamp: Option<String>,
131 pub off: bool,
133 pub host: Host,
135 pub leftovers: Vec<Leftover>,
137 pub next: Vec<String>,
139}
140
141#[must_use]
144pub fn switched_off() -> bool {
145 variable(CI_VAR).is_some() || variable(SELF_DEPEND_OFF_VAR).is_some()
146}
147
148fn on_path(program: &str) -> bool {
150 std::env::var_os("PATH")
151 .is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(program).is_file()))
152}
153
154#[must_use]
158pub fn report(target: &Utf8Path, env: &UserEnv, this: &Version) -> Report {
159 let detected = manager::detect(target);
160 let managers = detected
161 .iter()
162 .map(|held| entry(target, held, this))
163 .collect();
164 let wired = manager::wired(&detected);
165 let envrc_text = std::fs::read_to_string(target.join(ENVRC)).ok();
166 let envrc_sync = envrc_text
167 .as_deref()
168 .is_some_and(|text| text.contains(SYNC_LINE));
169 let leftovers = leftovers::find(target, &[]);
170 let stamp = env
171 .state_root()
172 .map(|root| stamp::path(&root.path, target))
173 .and_then(|path| stamp::read(&path))
174 .map(|day| day.to_string());
175 let acquisition = crate::domain::instance_config::InstanceConfig::read(target)
178 .ok()
179 .and_then(|declaration| declaration.acquisition);
180 let state = match (wired.len(), envrc_sync, leftovers.is_empty()) {
181 (0, _, _) if acquisition.is_some() => State::Host,
183 (0, _, _) => State::Unwired,
184 (1, true, true) => State::Ready,
185 (1, true, false) => State::Leftovers,
186 (1, false, _) => State::LineAbsent,
187 (_, _, _) => State::Ambiguous,
188 };
189 let next = next_lines(state, &wired, target, acquisition.as_ref());
190 Report {
191 schema: SCHEMA,
192 target: target.to_owned(),
193 state,
194 wired: (wired.len() == 1).then(|| wired[0].manager),
195 acquisition,
196 managers,
197 envrc: Presence::of(envrc_text.is_some()),
198 envrc_sync,
199 stamp,
200 off: switched_off(),
201 host: Host {
202 nix: on_path("nix"),
203 direnv: on_path("direnv"),
204 },
205 leftovers,
206 next,
207 }
208}
209
210fn entry(target: &Utf8Path, held: &Detected, this: &Version) -> ManagerEntry {
211 let lock = held.manager.lock_file().map(|lock| {
212 let path = target.join(lock);
213 (
214 Presence::of(path.is_file()),
215 std::fs::read_to_string(&path)
216 .ok()
217 .and_then(|text| pin::locked_rev(&text)),
218 )
219 });
220 ManagerEntry {
221 manager: held.manager,
222 present: Presence::of(held.file.is_some()),
223 file: held.file.clone(),
224 pinned: held.pin.is_some(),
225 version: held.pin.as_ref().map(|pin| pin.spelled.clone()),
226 venue: held.pin.as_ref().and_then(|pin| pin.venue),
227 pin_lines: held.pin.as_ref().map(|pin| pin.lines),
228 freshness: held.pin.as_ref().map(|pin| match pin.version.cmp(this) {
229 std::cmp::Ordering::Less => Freshness::Behind,
230 std::cmp::Ordering::Equal => Freshness::Current,
231 std::cmp::Ordering::Greater => Freshness::Ahead,
232 }),
233 lock: lock.as_ref().map(|(presence, _)| *presence),
234 locked_rev: lock.and_then(|(_, rev)| rev),
235 }
236}
237
238fn next_lines(
239 state: State,
240 wired: &[&Detected],
241 target: &Utf8Path,
242 acquisition: Option<&crate::domain::instance_config::Acquisition>,
243) -> Vec<String> {
244 match state {
245 State::Host => vec![format!(
246 "each host installs sdd {} or newer itself; sdd self-depend add --target {target} --manager <manager> moves the project onto a pin",
247 acquisition.map_or("", |decision| decision.minimum.as_str())
248 )],
249 State::Ready => vec![format!(
250 "sdd self-depend sync --caller operator --target {target} moves the pin by hand"
251 )],
252 State::Unwired => vec![format!(
253 "sdd self-depend add --target {target} serves the fragments for the manager this project runs"
254 )],
255 State::LineAbsent => vec![format!(
256 "add `{SYNC_LINE}` to {ENVRC}; sdd self-depend add --target {target} prints it with its placement"
257 )],
258 State::Ambiguous => {
259 let names: Vec<&str> = wired.iter().map(|held| held.manager.as_str()).collect();
260 vec![format!(
261 "one target runs one mechanism; keep one of {} and remove the others' pins",
262 names.join(", ")
263 )]
264 }
265 State::Leftovers => vec![format!(
266 "sdd self-depend clean --target {target} --apply removes what the predecessor left"
267 )],
268 }
269}