Skip to main content

release_kit/
self_depend.rs

1//! `rk self-depend`: release-kit as a consumer project's development
2//! dependency, kept fresh.
3//!
4//! A consumer obtains `rk` through whatever tool manager it already
5//! runs, and `manager` owns that axis: the closed list, the detection,
6//! and the per-manager pin reader. The flake manager carries two facts:
7//! the tag in `flake.nix` is the version, and the `release-kit` node in
8//! `flake.lock` is the content. This module owns the offline observation
9//! across every manager and the per-checkout state key; `pin` owns the
10//! flake line grammar, `fragments` the authored texts `add` serves,
11//! `leftovers` the predecessor catalog `clean` removes, `discover` the
12//! one network call, `txn` the fenced two-file transaction, `guard` the
13//! gates around it, `venue` where a release is published, and `matrix`
14//! which manager and venue pairs render.
15
16pub mod discover;
17pub mod fragments;
18pub mod guard;
19pub mod leftovers;
20pub mod manager;
21pub mod matrix;
22pub mod pin;
23pub mod txn;
24pub mod venue;
25
26use std::path::PathBuf;
27
28use camino::{Utf8Path, Utf8PathBuf};
29use serde::Serialize;
30
31use crate::diagnostic::{Diagnostic, Reason};
32use crate::digest::Digest;
33use crate::error::RkError;
34
35/// Whether a file exists at its expected path.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum Presence {
39    /// The path holds a file, a symlink included.
40    Present,
41    /// Nothing is at the path.
42    Absent,
43}
44
45impl Presence {
46    /// Judge a path by `symlink_metadata`, so a dangling symlink still
47    /// counts as present: the verb would refuse to write over it.
48    #[must_use]
49    pub fn of(path: &Utf8Path) -> Self {
50        if std::fs::symlink_metadata(path).is_ok() {
51            Self::Present
52        } else {
53            Self::Absent
54        }
55    }
56
57    /// Whether the file is there.
58    #[must_use]
59    pub const fn is_present(self) -> bool {
60        matches!(self, Self::Present)
61    }
62}
63
64/// Everything the offline pass reads from a target and this host's state
65/// root. It spawns nothing and fetches nothing.
66#[derive(Debug, Clone)]
67pub struct Observed {
68    /// The target, canonical.
69    pub target: Utf8PathBuf,
70    /// Whether `flake.nix` exists.
71    pub flake: Presence,
72    /// Whether `flake.lock` exists.
73    pub lock: Presence,
74    /// What the pin matcher found in `flake.nix`.
75    pub scan: pin::Scan,
76    /// The `flake.nix` text, where the file read.
77    pub flake_text: Option<String>,
78    /// The locked commit of the `release-kit` node, where the lock names one.
79    pub locked_rev: Option<String>,
80    /// The locked ref of the `release-kit` node, where the lock names one.
81    pub locked_ref: Option<String>,
82    /// One entry per manager, in the closed order, absent ones included.
83    pub managers: Vec<manager::Entry>,
84    /// The one manager whose file names release-kit, where exactly one does.
85    pub wired: Option<manager::Manager>,
86    /// Whether `.envrc` exists. Direnv is not a manager: it loads a
87    /// shell and pins nothing, so the file is reported outside the list.
88    pub envrc: Presence,
89    /// Whether `.envrc` carries the sync line.
90    pub envrc_sync: bool,
91    /// Whether a transaction marker for this checkout survives.
92    pub pending: bool,
93    /// The day of the last sync attempt for this checkout, where stamped.
94    pub stamp: Option<String>,
95    /// What a predecessor bump mechanism left in the target.
96    pub leftovers: Vec<leftovers::Leftover>,
97}
98
99impl Observed {
100    /// The per-checkout state key.
101    #[must_use]
102    pub fn key(&self) -> String {
103        state_key(&self.target)
104    }
105
106    /// The pinned tag, where the scan found exactly one pin.
107    #[must_use]
108    pub const fn pin_tag(&self) -> Option<&str> {
109        match &self.scan {
110            pin::Scan::One(pin) => Some(pin.tag.as_str()),
111            _ => None,
112        }
113    }
114
115    /// The rollup state, first match wins. It describes and never
116    /// judges: every state exits 0, and the verbs that act read the
117    /// entries rather than this word.
118    #[must_use]
119    pub fn state(&self) -> &'static str {
120        if self.pending {
121            return "pending-recovery";
122        }
123        if self
124            .managers
125            .iter()
126            .all(|entry| !entry.present.is_present())
127        {
128            return "no-manager";
129        }
130        let named: Vec<&manager::Entry> = self
131            .managers
132            .iter()
133            .filter(|entry| entry.read.names())
134            .collect();
135        let entry = match named.as_slice() {
136            [] => return "not-wired",
137            [one] => *one,
138            _ => return "ambiguous-pin",
139        };
140        match entry.read {
141            manager::PinRead::Many { .. } => return "ambiguous-pin",
142            manager::PinRead::Unpinned { .. } => return "unpinned",
143            manager::PinRead::Absent | manager::PinRead::One { .. } => {}
144        }
145        if self.leftovers.is_empty() {
146            "ready"
147        } else {
148            "superseded"
149        }
150    }
151
152    /// The flake manager's entry: always present in the list.
153    #[must_use]
154    pub fn flake_entry(&self) -> Option<&manager::Entry> {
155        self.entry(manager::Manager::Flake)
156    }
157
158    /// One manager's entry: every manager in the enum has one.
159    #[must_use]
160    pub fn entry(&self, manager: manager::Manager) -> Option<&manager::Entry> {
161        self.managers.iter().find(|entry| entry.manager == manager)
162    }
163}
164
165/// Read a target's pin wiring across every manager, offline.
166///
167/// # Errors
168///
169/// Returns [`RkError::Missing`] for a target that is not a directory and
170/// [`RkError::Io`] where a present file does not read.
171pub fn observe(target: &Utf8Path) -> Result<Observed, RkError> {
172    let target = canonical_target(target)?;
173    let files = manager::manager_files(&target, Some(manager::DEP_NAME))?;
174    let mut managers = manager::entries(&files);
175    let flake_text = files
176        .iter()
177        .find(|file| file.manager == manager::Manager::Flake)
178        .map(|file| file.text.clone());
179    // Judged by symlink metadata, so a dangling symlink still counts as
180    // present: the verbs would refuse to write over it.
181    let flake = Presence::of(&target.join("flake.nix"));
182    let scan = flake_text.as_deref().map_or(pin::Scan::None, pin::scan);
183    let lock_path = target.join("flake.lock");
184    let lock = Presence::of(&lock_path);
185    let (locked_rev, locked_ref_name) = if lock.is_present() {
186        locked_node(&std::fs::read(&lock_path)?)
187    } else {
188        (None, None)
189    };
190    if let Some(entry) = managers
191        .iter_mut()
192        .find(|entry| entry.manager == manager::Manager::Flake)
193    {
194        entry.lock = Some(lock);
195        entry.locked_ref.clone_from(&locked_ref_name);
196        entry.locked_rev.clone_from(&locked_rev);
197    }
198    let named: Vec<manager::Manager> = managers
199        .iter()
200        .filter(|entry| entry.read.names())
201        .map(|entry| entry.manager)
202        .collect();
203    let wired = match named.as_slice() {
204        [one] => Some(*one),
205        _ => None,
206    };
207    let envrc_path = target.join(".envrc");
208    let envrc = Presence::of(&envrc_path);
209    let envrc_sync = envrc.is_present() && has_sync_line(&std::fs::read_to_string(&envrc_path)?);
210    let key = state_key(&target);
211    let pending = marker_path(&key).is_some_and(|marker| txn::marker_is_pending(&marker));
212    let stamp = read_stamp(&key);
213    let leftovers = leftovers::scan(&target)?;
214    Ok(Observed {
215        target,
216        flake,
217        lock,
218        scan,
219        flake_text,
220        locked_rev,
221        locked_ref: locked_ref_name,
222        managers,
223        wired,
224        envrc,
225        envrc_sync,
226        pending,
227        stamp,
228        leftovers,
229    })
230}
231
232/// Whether an `.envrc` text carries the sync line: a line whose
233/// trimmed start is the verb, whatever flags follow.
234#[must_use]
235pub fn has_sync_line(text: &str) -> bool {
236    text.lines()
237        .any(|line| line.trim_start().starts_with("rk self-depend sync"))
238}
239
240/// The `release-kit` node's locked commit and ref, from a `flake.lock`.
241fn locked_node(bytes: &[u8]) -> (Option<String>, Option<String>) {
242    let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
243        return (None, None);
244    };
245    let locked = &value["nodes"]["release-kit"]["locked"];
246    let read = |field: &str| locked[field].as_str().map(str::to_owned);
247    (read("rev"), read("ref"))
248}
249
250/// The target as a canonical directory, or the missing-target refusal.
251fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
252    if !target.is_dir() {
253        return Err(RkError::missing(
254            Diagnostic::new(
255                Reason::TargetNotFound,
256                format!("target {target} is not a directory"),
257            )
258            .expected("an existing project directory to read"),
259        ));
260    }
261    Ok(target.canonicalize_utf8()?)
262}
263
264/// The per-checkout key every state file is named by:
265/// `<basename>-<digest16>` over the canonical path, so two clones never
266/// share a lock, a stamp, or a backup.
267#[must_use]
268pub fn state_key(target: &Utf8Path) -> String {
269    let base = target
270        .file_name()
271        .filter(|name| !name.is_empty())
272        .unwrap_or("root");
273    let digest = Digest::of(target.as_str().as_bytes()).to_string();
274    format!("{base}-{}", &digest[..16])
275}
276
277/// The directory every devshell state file lives under:
278/// `<state root>/devshell`.
279#[must_use]
280pub fn state_dir() -> Option<PathBuf> {
281    crate::applog::state_root().map(|root| root.join("devshell"))
282}
283
284/// The single-writer lock for one checkout.
285#[must_use]
286pub fn lock_path(key: &str) -> Option<PathBuf> {
287    state_dir().map(|dir| dir.join(format!("{key}.lock")))
288}
289
290/// The daily stamp for one checkout.
291#[must_use]
292pub fn stamp_path(key: &str) -> Option<PathBuf> {
293    state_dir().map(|dir| dir.join(format!("{key}.stamp")))
294}
295
296/// The directory a transaction backs the two files up into.
297#[must_use]
298pub fn backup_dir(key: &str) -> Option<PathBuf> {
299    state_dir().map(|dir| dir.join(key).join("backup"))
300}
301
302/// The marker an open transaction leaves until it commits or restores.
303#[must_use]
304pub fn marker_path(key: &str) -> Option<PathBuf> {
305    state_dir().map(|dir| dir.join(key).join("pending.json"))
306}
307
308/// The day the last sync attempt was stamped, where one was.
309#[must_use]
310pub fn read_stamp(key: &str) -> Option<String> {
311    let text = std::fs::read_to_string(stamp_path(key)?).ok()?;
312    let day = text.trim();
313    (day.len() == 10).then(|| day.to_owned())
314}
315
316/// Fold the three tag shapes — `v0.2.16`, `0.2.16`, and the release URL
317/// — to one tag with exactly one leading `v`.
318#[must_use]
319pub fn normalize_tag(raw: &str) -> Option<String> {
320    let trimmed = raw.trim().trim_end_matches('/');
321    let tail = trimmed.rsplit('/').next().unwrap_or(trimmed);
322    let bare = tail.strip_prefix('v').unwrap_or(tail);
323    let shaped = bare.chars().next().is_some_and(|c| c.is_ascii_digit())
324        && bare
325            .chars()
326            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'));
327    shaped.then(|| format!("v{bare}"))
328}
329
330#[cfg(test)]
331mod tests {
332    use camino::Utf8Path;
333
334    use super::{has_sync_line, locked_node, normalize_tag, state_key};
335
336    #[test]
337    fn the_tag_normalizer_folds_three_shapes_to_one() {
338        for raw in [
339            "v0.2.16",
340            "0.2.16",
341            "https://github.com/owner/release-kit/releases/tag/v0.2.16",
342            "https://github.com/owner/release-kit/releases/tag/v0.2.16/",
343            " v0.2.16\n",
344        ] {
345            assert_eq!(normalize_tag(raw).as_deref(), Some("v0.2.16"), "{raw:?}");
346        }
347        assert_eq!(normalize_tag("v0.3.0-rc.1").as_deref(), Some("v0.3.0-rc.1"));
348        assert_eq!(normalize_tag(""), None);
349        assert_eq!(normalize_tag("latest"), None);
350        assert_eq!(normalize_tag("vv0.2.16"), None, "a doubled v is not a tag");
351        assert_eq!(
352            normalize_tag("https://github.com/owner/release-kit/releases/latest"),
353            None
354        );
355    }
356
357    #[test]
358    fn the_state_key_is_stable_per_checkout() {
359        let a = state_key(Utf8Path::new("/srv/one/widget"));
360        let b = state_key(Utf8Path::new("/srv/two/widget"));
361        assert_eq!(a, state_key(Utf8Path::new("/srv/one/widget")));
362        assert_ne!(a, b, "two clones of one project key apart");
363        assert!(a.starts_with("widget-"), "{a}");
364        assert_eq!(a.len(), "widget-".len() + 16);
365        assert!(state_key(Utf8Path::new("/")).starts_with("root-"));
366    }
367
368    #[test]
369    fn the_sync_line_is_found_by_its_verb() {
370        assert!(has_sync_line(
371            "use flake\nrk self-depend sync --apply || true\n"
372        ));
373        assert!(has_sync_line("  rk self-depend sync\n"));
374        assert!(!has_sync_line("# rk self-depend sync\nuse flake\n"));
375        assert!(!has_sync_line(""));
376    }
377
378    #[test]
379    fn the_locked_node_reads_the_release_kit_input() {
380        let lock = br#"{"nodes":{"release-kit":{"locked":{"rev":"9f3c","ref":"refs/tags/v0.2.16"}},"root":{}}}"#;
381        assert_eq!(
382            locked_node(lock),
383            (
384                Some("9f3c".to_owned()),
385                Some("refs/tags/v0.2.16".to_owned())
386            )
387        );
388        assert_eq!(locked_node(b"not json"), (None, None));
389        assert_eq!(locked_node(br#"{"nodes":{}}"#), (None, None));
390    }
391}