1use 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
19pub const SCHEMA: &str = "sdd.self-depend-status/2";
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum Presence {
26 Present,
28 Absent,
30}
31
32impl Presence {
33 const fn of(present: bool) -> Self {
34 if present { Self::Present } else { Self::Absent }
35 }
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum Freshness {
42 Current,
44 Behind,
46 Ahead,
48}
49
50#[derive(Debug, Clone, Serialize)]
52pub struct ManagerEntry {
53 pub manager: Manager,
55 pub present: Presence,
57 #[serde(skip_serializing_if = "Option::is_none")]
59 pub file: Option<Utf8PathBuf>,
60 pub pinned: bool,
62 #[serde(skip_serializing_if = "Option::is_none")]
64 pub version: Option<String>,
65 #[serde(skip_serializing_if = "Option::is_none")]
67 pub venue: Option<Venue>,
68 #[serde(skip_serializing_if = "Option::is_none")]
70 pub pin_lines: Option<usize>,
71 #[serde(skip_serializing_if = "Option::is_none")]
73 pub freshness: Option<Freshness>,
74 #[serde(skip_serializing_if = "Option::is_none")]
76 pub lock: Option<Presence>,
77 #[serde(skip_serializing_if = "Option::is_none")]
79 pub locked_rev: Option<String>,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
84#[serde(rename_all = "kebab-case")]
85pub enum State {
86 Ready,
88 Unwired,
90 LineAbsent,
92 OldLine,
94 Ambiguous,
96 Leftovers,
98 Host,
101}
102
103#[derive(Debug, Clone, Serialize)]
105pub struct Host {
106 pub nix: bool,
108 pub direnv: bool,
110}
111
112#[derive(Debug, Clone, Serialize)]
114pub struct Report {
115 pub schema: &'static str,
117 pub target: Utf8PathBuf,
119 pub state: State,
121 pub wired: Option<Manager>,
123 pub acquisition: Option<crate::domain::instance_config::Acquisition>,
126 pub managers: Vec<ManagerEntry>,
128 pub envrc: Presence,
130 pub envrc_check: bool,
132 pub envrc_old_line: bool,
134 pub check: Option<Entry>,
137 pub off: bool,
139 pub host: Host,
141 pub leftovers: Vec<Leftover>,
143 #[serde(skip_serializing_if = "Option::is_none")]
145 pub pending: Option<Pending>,
146 #[serde(skip_serializing_if = "Vec::is_empty")]
148 pub follows: Vec<pin::Follows>,
149 pub next: Vec<String>,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
155pub struct Pending {
156 pub latest: String,
158 pub pin: String,
160 pub text: String,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
166pub enum PinFreshness {
167 Unknown,
170 Current {
172 pin: String,
174 },
175 Behind(Pending),
177}
178
179#[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#[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#[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#[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#[must_use]
251pub fn switched_off() -> bool {
252 variable(CI_VAR).is_some() || variable(SELF_DEPEND_OFF_VAR).is_some()
253}
254
255fn 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#[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 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 (0, _, _) if acquisition.is_some() => State::Host,
292 (0, _, _) => State::Unwired,
293 (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}