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 advice;
17pub mod check;
18pub mod discover;
19pub mod fragments;
20pub mod guard;
21pub mod leftovers;
22pub mod manager;
23pub mod matrix;
24pub mod pin;
25pub mod txn;
26pub mod venue;
27
28use std::path::PathBuf;
29
30use camino::{Utf8Path, Utf8PathBuf};
31use serde::Serialize;
32
33use crate::diagnostic::{Diagnostic, Reason};
34use crate::digest::Digest;
35use crate::error::RkError;
36
37/// Whether a file exists at its expected path.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum Presence {
41    /// The path holds a file, a symlink included.
42    Present,
43    /// Nothing is at the path.
44    Absent,
45}
46
47impl Presence {
48    /// Judge a path by `symlink_metadata`, so a dangling symlink still
49    /// counts as present: the verb would refuse to write over it.
50    #[must_use]
51    pub fn of(path: &Utf8Path) -> Self {
52        if std::fs::symlink_metadata(path).is_ok() {
53            Self::Present
54        } else {
55            Self::Absent
56        }
57    }
58
59    /// Whether the file is there.
60    #[must_use]
61    pub const fn is_present(self) -> bool {
62        matches!(self, Self::Present)
63    }
64}
65
66/// Everything the offline pass reads from a target and this host's state
67/// root. It spawns nothing and fetches nothing.
68#[derive(Debug, Clone)]
69pub struct Observed {
70    /// The target, canonical.
71    pub target: Utf8PathBuf,
72    /// Whether `flake.nix` exists.
73    pub flake: Presence,
74    /// Whether `flake.lock` exists.
75    pub lock: Presence,
76    /// What the pin matcher found in `flake.nix`.
77    pub scan: pin::Scan,
78    /// The `flake.nix` text, where the file read.
79    pub flake_text: Option<String>,
80    /// The locked commit of the `release-kit` node, where the lock names one.
81    pub locked_rev: Option<String>,
82    /// The locked ref of the `release-kit` node, where the lock names one.
83    pub locked_ref: Option<String>,
84    /// One entry per manager, in the closed order, absent ones included.
85    pub managers: Vec<manager::Entry>,
86    /// The one manager whose file names release-kit, where exactly one does.
87    pub wired: Option<manager::Manager>,
88    /// Whether `.envrc` exists. Direnv is not a manager: it loads a
89    /// shell and pins nothing, so the file is reported outside the list.
90    pub envrc: Presence,
91    /// Whether `.envrc` carries the check line.
92    pub envrc_check: bool,
93    /// Whether `.envrc` still carries the retired sync line, which an
94    /// older rk seeded and which `rk self-depend clean --apply` swaps.
95    pub envrc_old_sync: bool,
96    /// Whether a transaction marker for this checkout survives.
97    pub pending: bool,
98    /// What a predecessor bump mechanism left in the target.
99    pub leftovers: Vec<leftovers::Leftover>,
100    /// The host-install answer the target configuration records, where it
101    /// records one.
102    pub acquisition: Option<crate::config::Acquisition>,
103}
104
105impl Observed {
106    /// The per-checkout state key.
107    #[must_use]
108    pub fn key(&self) -> String {
109        state_key(&self.target)
110    }
111
112    /// The pinned tag, where the scan found exactly one pin.
113    #[must_use]
114    pub const fn pin_tag(&self) -> Option<&str> {
115        match &self.scan {
116            pin::Scan::One(pin) => Some(pin.tag.as_str()),
117            _ => None,
118        }
119    }
120
121    /// The rollup state, first match wins. It describes and never
122    /// judges: every state exits 0, and the verbs that act read the
123    /// entries rather than this word.
124    #[must_use]
125    pub fn state(&self) -> &'static str {
126        if self.pending {
127            return "pending-recovery";
128        }
129        let named: Vec<&manager::Entry> = self
130            .managers
131            .iter()
132            .filter(|entry| entry.read.names())
133            .collect();
134        // A recorded host install is a decision, not a gap: no manager names
135        // release-kit because the project chose that none does.
136        //
137        // SATISFIES packaging:a-host-install-reads-as-a-decision
138        if named.is_empty() && self.acquisition.is_some() {
139            return "host";
140        }
141        if self
142            .managers
143            .iter()
144            .all(|entry| !entry.present.is_present())
145        {
146            return "no-manager";
147        }
148        let entry = match named.as_slice() {
149            [] => return "not-wired",
150            [one] => *one,
151            _ => return "ambiguous-pin",
152        };
153        match entry.read {
154            manager::PinRead::Many { .. } => return "ambiguous-pin",
155            manager::PinRead::Unpinned { .. } => return "unpinned",
156            manager::PinRead::Absent | manager::PinRead::One { .. } => {}
157        }
158        if self.leftovers.is_empty() {
159            "ready"
160        } else {
161            "superseded"
162        }
163    }
164
165    /// The flake manager's entry: always present in the list.
166    #[must_use]
167    pub fn flake_entry(&self) -> Option<&manager::Entry> {
168        self.entry(manager::Manager::Flake)
169    }
170
171    /// One manager's entry: every manager in the enum has one.
172    #[must_use]
173    pub fn entry(&self, manager: manager::Manager) -> Option<&manager::Entry> {
174        self.managers.iter().find(|entry| entry.manager == manager)
175    }
176}
177
178/// Read a target's pin wiring across every manager, offline.
179///
180/// # Errors
181///
182/// Returns [`RkError::Missing`] for a target that is not a directory and
183/// [`RkError::Io`] where a present file does not read.
184pub fn observe(target: &Utf8Path) -> Result<Observed, RkError> {
185    let target = canonical_target(target)?;
186    let files = manager::manager_files(&target, Some(manager::DEP_NAME))?;
187    let mut managers = manager::entries(&files);
188    let flake_text = files
189        .iter()
190        .find(|file| file.manager == manager::Manager::Flake)
191        .map(|file| file.text.clone());
192    // Judged by symlink metadata, so a dangling symlink still counts as
193    // present: the verbs would refuse to write over it.
194    let flake = Presence::of(&target.join("flake.nix"));
195    let scan = flake_text.as_deref().map_or(pin::Scan::None, pin::scan);
196    let lock_path = target.join("flake.lock");
197    let lock = Presence::of(&lock_path);
198    let (locked_rev, locked_ref_name) = if lock.is_present() {
199        locked_node(&std::fs::read(&lock_path)?)
200    } else {
201        (None, None)
202    };
203    if let Some(entry) = managers
204        .iter_mut()
205        .find(|entry| entry.manager == manager::Manager::Flake)
206    {
207        entry.lock = Some(lock);
208        entry.locked_ref.clone_from(&locked_ref_name);
209        entry.locked_rev.clone_from(&locked_rev);
210    }
211    let named: Vec<manager::Manager> = managers
212        .iter()
213        .filter(|entry| entry.read.names())
214        .map(|entry| entry.manager)
215        .collect();
216    let wired = match named.as_slice() {
217        [one] => Some(*one),
218        _ => None,
219    };
220    let envrc_path = target.join(".envrc");
221    let envrc = Presence::of(&envrc_path);
222    let envrc_text = if envrc.is_present() {
223        std::fs::read_to_string(&envrc_path)?
224    } else {
225        String::new()
226    };
227    let envrc_check = has_check_line(&envrc_text);
228    let envrc_old_sync = has_sync_line(&envrc_text);
229    let key = state_key(&target);
230    let pending = marker_path(&key).is_some_and(|marker| txn::marker_is_pending(&marker));
231    let leftovers = leftovers::scan(&target)?;
232    // A configuration this binary cannot read refuses here as it does for
233    // every verb that reads one, rather than reading as no answer.
234    let acquisition =
235        crate::config::load(target.as_std_path())?.and_then(|config| config.acquisition);
236    Ok(Observed {
237        target,
238        flake,
239        lock,
240        scan,
241        flake_text,
242        locked_rev,
243        locked_ref: locked_ref_name,
244        managers,
245        wired,
246        envrc,
247        envrc_check,
248        envrc_old_sync,
249        pending,
250        leftovers,
251        acquisition,
252    })
253}
254
255/// The rk version the project pins, without a leading `v`, where exactly
256/// one manager names release-kit with one version; `None` otherwise,
257/// including a target that does not read.
258#[must_use]
259pub fn pinned_version(target: &Utf8Path) -> Option<String> {
260    let observed = observe(target).ok()?;
261    let entry = observed.entry(observed.wired?)?;
262    entry
263        .read
264        .version()
265        .map(|version| version.trim_start_matches('v').to_owned())
266}
267
268/// The follows lines that the release-kit input of a target's flake
269/// lacks, read from its `flake.lock` as it stands now. A target with no
270/// readable lock lacks none.
271#[must_use]
272pub fn missing_follows(target: &Utf8Path) -> Vec<String> {
273    std::fs::read(target.join("flake.lock"))
274        .map(|bytes| advice::follows_lines(&bytes))
275        .unwrap_or_default()
276}
277
278/// Whether an `.envrc` text carries the retired sync line: a line whose
279/// trimmed start is the verb, whatever flags follow.
280#[must_use]
281pub fn has_sync_line(text: &str) -> bool {
282    text.lines()
283        .any(|line| line.trim_start().starts_with("rk self-depend sync"))
284}
285
286/// Whether an `.envrc` text carries the check line: a line whose trimmed
287/// start is the verb, whatever follows.
288#[must_use]
289pub fn has_check_line(text: &str) -> bool {
290    text.lines()
291        .any(|line| line.trim_start().starts_with("rk self-depend check"))
292}
293
294/// The deepest chain of follows paths [`input_node`] walks before it
295/// gives up: a lock that loops reads as one naming no input.
296const MAX_FOLLOWS: usize = 32;
297
298/// The locked commit and ref of the node the root's `release-kit` input
299/// resolves to, from a `flake.lock`.
300///
301/// A lock names a node after the input that first introduced it, so a
302/// dependency's own `release-kit` input can hold the name `release-kit`
303/// while the project's input is `release-kit_2`. The root node, which the
304/// lock's `root` key names, is the one owner of the project's inputs.
305fn locked_node(bytes: &[u8]) -> (Option<String>, Option<String>) {
306    let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
307        return (None, None);
308    };
309    let nodes = &value["nodes"];
310    let root = value["root"].as_str().unwrap_or("root");
311    let Some(node) = input_node(nodes, root, root, "release-kit", 0) else {
312        return (None, None);
313    };
314    let locked = &nodes[node.as_str()]["locked"];
315    let read = |field: &str| locked[field].as_str().map(str::to_owned);
316    (read("rev"), read("ref"))
317}
318
319/// The node one input of `node` resolves to. The input names a node, or
320/// holds a follows path: a list of input names walked from the root node.
321fn input_node(
322    nodes: &serde_json::Value,
323    root: &str,
324    node: &str,
325    input: &str,
326    depth: usize,
327) -> Option<String> {
328    match &nodes[node]["inputs"][input] {
329        serde_json::Value::String(name) => Some(name.clone()),
330        serde_json::Value::Array(path) if depth < MAX_FOLLOWS => {
331            let mut at = root.to_owned();
332            for step in path {
333                at = input_node(nodes, root, &at, step.as_str()?, depth + 1)?;
334            }
335            Some(at)
336        }
337        _ => None,
338    }
339}
340
341/// The target as a canonical directory, or the missing-target refusal.
342fn canonical_target(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
343    if !target.is_dir() {
344        return Err(RkError::missing(
345            Diagnostic::new(
346                Reason::TargetNotFound,
347                format!("target {target} is not a directory"),
348            )
349            .expected("an existing project directory to read"),
350        ));
351    }
352    Ok(target.canonicalize_utf8()?)
353}
354
355/// The per-checkout key every state file is named by:
356/// `<basename>-<digest16>` over the canonical path, so two clones never
357/// share a lock, a stamp, or a backup.
358#[must_use]
359pub fn state_key(target: &Utf8Path) -> String {
360    let base = target
361        .file_name()
362        .filter(|name| !name.is_empty())
363        .unwrap_or("root");
364    let digest = Digest::of(target.as_str().as_bytes()).to_string();
365    format!("{base}-{}", &digest[..16])
366}
367
368/// The directory every devshell state file lives under:
369/// `<state root>/devshell`.
370#[must_use]
371pub fn state_dir() -> Option<PathBuf> {
372    crate::applog::state_root().map(|root| root.join("devshell"))
373}
374
375/// The single-writer lock for one checkout.
376#[must_use]
377pub fn lock_path(key: &str) -> Option<PathBuf> {
378    state_dir().map(|dir| dir.join(format!("{key}.lock")))
379}
380
381/// The directory the version check caches its answers under:
382/// `<cache root>/self-depend`.
383#[must_use]
384pub fn check_cache_dir() -> Option<PathBuf> {
385    crate::applog::cache_root().map(|root| root.join("self-depend"))
386}
387
388/// The directory a transaction backs the two files up into.
389#[must_use]
390pub fn backup_dir(key: &str) -> Option<PathBuf> {
391    state_dir().map(|dir| dir.join(key).join("backup"))
392}
393
394/// The marker an open transaction leaves until it commits or restores.
395#[must_use]
396pub fn marker_path(key: &str) -> Option<PathBuf> {
397    state_dir().map(|dir| dir.join(key).join("pending.json"))
398}
399
400/// Fold the three tag shapes — `v0.2.16`, `0.2.16`, and the release URL
401/// — to one tag with exactly one leading `v`.
402#[must_use]
403pub fn normalize_tag(raw: &str) -> Option<String> {
404    let trimmed = raw.trim().trim_end_matches('/');
405    let tail = trimmed.rsplit('/').next().unwrap_or(trimmed);
406    let bare = tail.strip_prefix('v').unwrap_or(tail);
407    let shaped = bare.chars().next().is_some_and(|c| c.is_ascii_digit())
408        && bare
409            .chars()
410            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '+'));
411    shaped.then(|| format!("v{bare}"))
412}
413
414#[cfg(test)]
415mod tests {
416    use camino::Utf8Path;
417
418    use super::{has_sync_line, locked_node, normalize_tag, state_key};
419
420    #[test]
421    fn the_tag_normalizer_folds_three_shapes_to_one() {
422        for raw in [
423            "v0.2.16",
424            "0.2.16",
425            "https://github.com/owner/release-kit/releases/tag/v0.2.16",
426            "https://github.com/owner/release-kit/releases/tag/v0.2.16/",
427            " v0.2.16\n",
428        ] {
429            assert_eq!(normalize_tag(raw).as_deref(), Some("v0.2.16"), "{raw:?}");
430        }
431        assert_eq!(normalize_tag("v0.3.0-rc.1").as_deref(), Some("v0.3.0-rc.1"));
432        assert_eq!(normalize_tag(""), None);
433        assert_eq!(normalize_tag("latest"), None);
434        assert_eq!(normalize_tag("vv0.2.16"), None, "a doubled v is not a tag");
435        assert_eq!(
436            normalize_tag("https://github.com/owner/release-kit/releases/latest"),
437            None
438        );
439    }
440
441    #[test]
442    fn the_state_key_is_stable_per_checkout() {
443        let a = state_key(Utf8Path::new("/srv/one/widget"));
444        let b = state_key(Utf8Path::new("/srv/two/widget"));
445        assert_eq!(a, state_key(Utf8Path::new("/srv/one/widget")));
446        assert_ne!(a, b, "two clones of one project key apart");
447        assert!(a.starts_with("widget-"), "{a}");
448        assert_eq!(a.len(), "widget-".len() + 16);
449        assert!(state_key(Utf8Path::new("/")).starts_with("root-"));
450    }
451
452    #[test]
453    fn the_sync_line_is_found_by_its_verb() {
454        assert!(has_sync_line(
455            "use flake\nrk self-depend sync --apply || true\n"
456        ));
457        assert!(has_sync_line("  rk self-depend sync\n"));
458        assert!(!has_sync_line("# rk self-depend sync\nuse flake\n"));
459        assert!(!has_sync_line(""));
460    }
461
462    #[test]
463    fn the_locked_node_reads_the_release_kit_input() {
464        let lock = br#"{"nodes":{"release-kit":{"locked":{"rev":"9f3c","ref":"refs/tags/v0.2.16"}},"root":{"inputs":{"release-kit":"release-kit"}}},"root":"root"}"#;
465        assert_eq!(
466            locked_node(lock),
467            (
468                Some("9f3c".to_owned()),
469                Some("refs/tags/v0.2.16".to_owned())
470            )
471        );
472        assert_eq!(locked_node(b"not json"), (None, None));
473        assert_eq!(locked_node(br#"{"nodes":{}}"#), (None, None));
474        assert_eq!(
475            locked_node(br#"{"nodes":{"release-kit":{"locked":{"rev":"9f3c"}},"root":{}}}"#),
476            (None, None),
477            "a node the root does not name is not the project's input"
478        );
479    }
480
481    #[test]
482    fn the_locked_node_follows_the_root_input() {
483        let lock = br#"{"nodes":{
484            "exobrain-tech":{"inputs":{"release-kit":"release-kit"},"locked":{"rev":"e0e0"}},
485            "release-kit":{"locked":{"rev":"0543ebe","ref":"refs/tags/v0.9.1"}},
486            "release-kit_2":{"locked":{"rev":"3fd21b5","ref":"refs/tags/v0.9.15"}},
487            "top":{"inputs":{"exobrain-tech":"exobrain-tech","release-kit":"release-kit_2"}}
488        },"root":"top","version":7}"#;
489        assert_eq!(
490            locked_node(lock),
491            (
492                Some("3fd21b5".to_owned()),
493                Some("refs/tags/v0.9.15".to_owned())
494            )
495        );
496    }
497
498    #[test]
499    fn a_followed_root_input_resolves_through_its_path() {
500        let lock = br#"{"nodes":{
501            "exobrain-tech":{"inputs":{"release-kit":"release-kit_2"}},
502            "release-kit_2":{"locked":{"rev":"3fd21b5","ref":"refs/tags/v0.9.15"}},
503            "root":{"inputs":{"exobrain-tech":"exobrain-tech","release-kit":["exobrain-tech","release-kit"]}}
504        },"root":"root","version":7}"#;
505        assert_eq!(
506            locked_node(lock),
507            (
508                Some("3fd21b5".to_owned()),
509                Some("refs/tags/v0.9.15".to_owned())
510            )
511        );
512        let chained = br#"{"nodes":{
513            "a":{"inputs":{"release-kit":["b","release-kit"]}},
514            "b":{"inputs":{"release-kit":"release-kit_3"}},
515            "release-kit_3":{"locked":{"rev":"77aa"}},
516            "root":{"inputs":{"a":"a","b":"b","release-kit":["a","release-kit"]}}
517        },"version":7}"#;
518        assert_eq!(locked_node(chained), (Some("77aa".to_owned()), None));
519        let looped = br#"{"nodes":{
520            "root":{"inputs":{"release-kit":["release-kit"]}}
521        },"version":7}"#;
522        assert_eq!(locked_node(looped), (None, None), "a loop names no input");
523        let broken = br#"{"nodes":{
524            "root":{"inputs":{"release-kit":["absent","release-kit"]}}
525        },"version":7}"#;
526        assert_eq!(locked_node(broken), (None, None));
527    }
528}