Skip to main content

spec_driven_docs/self_depend/
pin.rs

1//! The pin each manager records, read and rewritten in its own form.
2//!
3//! ```text
4//! flake input      github:<owner>/<repo>/<tag> in flake.nix, locked in flake.lock
5//! mise, registry   "cargo:<crate>" = "<version>"
6//! mise, release    "ubi:<owner>/<repo>" = { version = "<version>", exe = "<binary>" }
7//! asdf             <tool> <version>, one line in .tool-versions
8//! devbox           "github:<owner>/<repo>/<tag>#<output>", one entry in packages
9//! ```
10//!
11//! A registry entry names the crate as the registry knows it, and an archive
12//! entry names the binary inside the archive. The reader below accepts each
13//! form where its manager writes it and nowhere else.
14
15use semver::Version;
16use serde::Serialize;
17
18use crate::self_depend::manager::Manager;
19use crate::self_depend::registry::CRATE_NAME;
20use crate::self_depend::venue::Venue;
21use crate::self_depend::{BINARY_NAME, slug};
22
23/// One recorded pin, located in its file.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
25pub struct Pin {
26    /// The released triple the pin names.
27    pub version: Version,
28    /// The version as the file spells it, `v` prefix included where present.
29    pub spelled: String,
30    /// The venue the entry's form selects, where the form says.
31    pub venue: Option<Venue>,
32    /// The one-based line the pin sits on.
33    pub line: usize,
34    /// How many lines in the file pin this tool.
35    pub lines: usize,
36    /// The byte span of the spelled version in the file text.
37    #[serde(skip)]
38    pub span: (usize, usize),
39}
40
41/// The pin a manager file records for this tool, where it records one.
42#[must_use]
43pub fn read(manager: Manager, text: &str) -> Option<Pin> {
44    let mut found: Vec<Pin> = Vec::new();
45    let mut offset = 0;
46    for (index, line) in text.split_inclusive('\n').enumerate() {
47        if let Some((start, end, venue)) = locate(manager, line) {
48            let spelled = line[start..end].to_string();
49            let bare = spelled.strip_prefix('v').unwrap_or(&spelled);
50            if let Ok(version) = bare.parse::<Version>() {
51                found.push(Pin {
52                    version,
53                    spelled,
54                    venue,
55                    line: index + 1,
56                    lines: 0,
57                    span: (offset + start, offset + end),
58                });
59            }
60        }
61        offset += line.len();
62    }
63    let lines = found.len();
64    let mut first = found.into_iter().next()?;
65    first.lines = lines;
66    Some(first)
67}
68
69/// Where one line spells the version, and which venue the form selects.
70fn locate(manager: Manager, line: &str) -> Option<(usize, usize, Option<Venue>)> {
71    match manager {
72        Manager::Flake => {
73            let needle = format!("github:{}/", slug());
74            let start = line.find(&needle)? + needle.len();
75            let end = start
76                + line[start..]
77                    .find(['"', '#', '?', '\''])
78                    .unwrap_or(line.len() - start);
79            (end > start).then_some((start, end, Some(Venue::Flake)))
80        }
81        Manager::Devbox => {
82            let needle = format!("github:{}/", slug());
83            let start = line.find(&needle)? + needle.len();
84            let end = start + line[start..].find(['#', '"']).unwrap_or(line.len() - start);
85            (end > start).then_some((start, end, Some(Venue::Flake)))
86        }
87        Manager::Mise => {
88            let trimmed = line.trim_start();
89            let registry = format!("\"cargo:{CRATE_NAME}\"");
90            let archive = format!("\"ubi:{}\"", slug());
91            if trimmed.starts_with(&registry) {
92                let (start, end) = quoted_after(line, "=")?;
93                return Some((start, end, Some(Venue::Crates)));
94            }
95            if trimmed.starts_with(&archive) {
96                let (start, end) = quoted_after(line, "version")?;
97                return Some((start, end, Some(Venue::GithubRelease)));
98            }
99            None
100        }
101        Manager::Asdf => {
102            let mut parts = line.split_whitespace();
103            let tool = parts.next()?;
104            if tool != CRATE_NAME && tool != BINARY_NAME {
105                return None;
106            }
107            let version = parts.next()?;
108            let start = line.find(version)?;
109            Some((start, start + version.len(), None))
110        }
111    }
112}
113
114/// The span of the first quoted string after `marker` in `line`.
115fn quoted_after(line: &str, marker: &str) -> Option<(usize, usize)> {
116    let at = line.find(marker)? + marker.len();
117    let open = at + line[at..].find('"')? + 1;
118    let close = open + line[open..].find('"')?;
119    Some((open, close))
120}
121
122/// The same file text with the pin moved to `to`, in the spelling the file
123/// already uses.
124///
125/// # Errors
126///
127/// A message where the file no longer records the pin it was read with.
128pub fn rewrite(manager: Manager, text: &str, to: &Version) -> Result<(String, Pin), String> {
129    let held = read(manager, text).ok_or_else(|| "the file no longer records a pin".to_string())?;
130    let spelled = if held.spelled.starts_with('v') {
131        format!("v{to}")
132    } else {
133        to.to_string()
134    };
135    let mut moved = String::with_capacity(text.len());
136    moved.push_str(&text[..held.span.0]);
137    moved.push_str(&spelled);
138    moved.push_str(&text[held.span.1..]);
139    Ok((moved, held))
140}
141
142/// The deepest chain of follows paths [`input_node`] walks before it gives
143/// up: a lock that loops reads as one naming no input.
144const MAX_FOLLOWS: usize = 32;
145
146/// The revision `flake.lock` holds for this tool's input, where it holds one.
147///
148/// A lock names a node after the input that first introduced it, so a
149/// dependency's own input on this tool can hold the plain name while the
150/// project's input reads `spec-driven-docs_2`. The root node, which the
151/// lock's `root` key names, is the one owner of the project's inputs, so
152/// the revision is read from the node one of its inputs resolves to. That
153/// input is found by the repository its node names, never by its name.
154#[must_use]
155pub fn locked_rev(lock: &str) -> Option<String> {
156    let value: serde_json::Value = serde_json::from_str(lock).ok()?;
157    let (owner, repo) = crate::self_depend::coordinates();
158    let nodes = &value["nodes"];
159    let root = value["root"].as_str().unwrap_or("root");
160    let inputs = nodes[root]["inputs"].as_object()?;
161    inputs.keys().find_map(|input| {
162        let name = input_node(nodes, root, root, input, 0)?;
163        let node = &nodes[name.as_str()];
164        let original = &node["original"];
165        let same = |key: &str, want: &str| {
166            original[key]
167                .as_str()
168                .is_some_and(|held| held.eq_ignore_ascii_case(want))
169        };
170        (same("owner", owner) && same("repo", repo))
171            .then(|| node["locked"]["rev"].as_str().map(str::to_string))
172            .flatten()
173    })
174}
175
176/// The node one input of `node` resolves to. The input names a node, or
177/// holds a follows path: a list of input names walked from the root node.
178fn input_node(
179    nodes: &serde_json::Value,
180    root: &str,
181    node: &str,
182    input: &str,
183    depth: usize,
184) -> Option<String> {
185    match &nodes[node]["inputs"][input] {
186        serde_json::Value::String(name) => Some(name.clone()),
187        serde_json::Value::Array(path) if depth < MAX_FOLLOWS => {
188            let mut at = root.to_owned();
189            for step in path {
190                at = input_node(nodes, root, &at, step.as_str()?, depth + 1)?;
191            }
192            Some(at)
193        }
194        _ => None,
195    }
196}
197
198/// The name of the flake input whose URL names this tool.
199///
200/// The input is found by the URL it names, never by its name: a consumer
201/// calls the input whatever it likes. The name is read from the attribute
202/// that holds the URL, either `name.url = "..."` or `name = { url = ... }`.
203#[must_use]
204pub fn input_name(flake: &str) -> Option<String> {
205    let needle = format!("github:{}/", slug());
206    let lines: Vec<&str> = flake.lines().collect();
207    let at = lines.iter().position(|line| line.contains(&needle))?;
208    if let Some(name) = attribute_before(lines[at], ".url") {
209        return Some(name);
210    }
211    lines[..at]
212        .iter()
213        .rev()
214        .find_map(|line| attribute_before(line, " ="))
215        .or_else(|| {
216            lines[..at]
217                .iter()
218                .rev()
219                .find_map(|line| attribute_before(line, "="))
220        })
221}
222
223/// The identifier that opens `line` before `suffix`, where the line reads
224/// `  <ident><suffix>...` and the identifier is an attribute name.
225fn attribute_before(line: &str, suffix: &str) -> Option<String> {
226    let trimmed = line.trim_start();
227    let end = trimmed.find(suffix)?;
228    let name = &trimmed[..end];
229    let is_ident = !name.is_empty()
230        && name
231            .bytes()
232            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
233    if !is_ident || name == "url" || name == "inputs" {
234        return None;
235    }
236    // `name = {` opens an attribute set; `name = "..."` does not hold a URL.
237    if suffix != ".url"
238        && !trimmed[end..]
239            .trim_start_matches(suffix)
240            .trim_start()
241            .starts_with('{')
242    {
243        return None;
244    }
245    Some(name.to_string())
246}
247
248#[cfg(test)]
249mod tests {
250    #![allow(clippy::unwrap_used, reason = "a test panics as its failure signal")]
251
252    use super::*;
253
254    fn flake() -> String {
255        format!(
256            "{{\n  inputs = {{\n    nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\";\n    sdd = {{\n      url = \"github:{}/v0.10.1\";\n      inputs.nixpkgs.follows = \"nixpkgs\";\n    }};\n  }};\n}}\n",
257            slug()
258        )
259    }
260
261    /// VERIFIES acquisition:a-fragment-names-the-venue-form
262    #[test]
263    fn a_flake_pin_reads_and_rewrites_in_place() {
264        let text = flake();
265        let pin = read(Manager::Flake, &text).unwrap();
266        assert_eq!(pin.version.to_string(), "0.10.1");
267        assert_eq!(pin.spelled, "v0.10.1");
268        assert_eq!(pin.venue, Some(Venue::Flake));
269        assert_eq!(pin.line, 5);
270        assert_eq!(pin.lines, 1);
271        let (moved, _) = rewrite(Manager::Flake, &text, &"0.10.2".parse().unwrap()).unwrap();
272        assert!(moved.contains(&format!("github:{}/v0.10.2\"", slug())));
273        assert_eq!(moved.len(), text.len());
274        assert_eq!(input_name(&text).as_deref(), Some("sdd"));
275    }
276
277    #[test]
278    fn a_dotted_flake_input_names_itself_on_the_url_line() {
279        let text = format!(
280            "{{ inputs = {{\n  tool.url = \"github:{}/v0.9.0\";\n }}; }}\n",
281            slug()
282        );
283        assert_eq!(input_name(&text).as_deref(), Some("tool"));
284    }
285
286    #[test]
287    fn a_mise_pin_reads_both_forms() {
288        let registry = format!("[tools]\n\"cargo:{CRATE_NAME}\" = \"0.10.1\"\n");
289        let pin = read(Manager::Mise, &registry).unwrap();
290        assert_eq!(pin.venue, Some(Venue::Crates));
291        assert_eq!(pin.spelled, "0.10.1");
292        let archive = format!(
293            "[tools]\n\"ubi:{}\" = {{ version = \"0.10.1\", exe = \"{BINARY_NAME}\" }}\n",
294            slug()
295        );
296        let pin = read(Manager::Mise, &archive).unwrap();
297        assert_eq!(pin.venue, Some(Venue::GithubRelease));
298        let (moved, _) = rewrite(Manager::Mise, &archive, &"0.11.0".parse().unwrap()).unwrap();
299        assert!(moved.contains("version = \"0.11.0\""));
300    }
301
302    #[test]
303    fn an_asdf_pin_reads_the_second_token() {
304        let text = format!("nodejs 20.0.0\n{CRATE_NAME} 0.10.1\n");
305        let pin = read(Manager::Asdf, &text).unwrap();
306        assert_eq!(pin.version.to_string(), "0.10.1");
307        assert_eq!(pin.venue, None);
308        assert!(read(Manager::Asdf, "nodejs 20.0.0\n").is_none());
309    }
310
311    #[test]
312    fn a_devbox_pin_reads_up_to_the_output() {
313        let text = format!(
314            "{{ \"packages\": [\"github:{}/v0.10.1#default\"] }}\n",
315            slug()
316        );
317        let pin = read(Manager::Devbox, &text).unwrap();
318        assert_eq!(pin.spelled, "v0.10.1");
319        let (moved, _) = rewrite(Manager::Devbox, &text, &"0.10.2".parse().unwrap()).unwrap();
320        assert!(moved.contains("v0.10.2#default"));
321    }
322
323    #[test]
324    fn the_lock_revision_is_found_by_the_repository_it_names() {
325        let (owner, repo) = crate::self_depend::coordinates();
326        let lock = format!(
327            "{{\"nodes\":{{\"root\":{{\"inputs\":{{\"sdd\":\"sdd\"}}}},\"sdd\":{{\"locked\":{{\"rev\":\"abc123\"}},\"original\":{{\"owner\":\"{owner}\",\"repo\":\"{repo}\",\"type\":\"github\"}}}}}},\"version\":7}}"
328        );
329        assert_eq!(locked_rev(&lock).as_deref(), Some("abc123"));
330        assert_eq!(locked_rev("{\"nodes\":{}}"), None);
331    }
332
333    /// A node that names this tool's repository, locked at `rev`.
334    fn node(rev: &str) -> String {
335        let (owner, repo) = crate::self_depend::coordinates();
336        format!(
337            "{{\"locked\":{{\"rev\":\"{rev}\"}},\"original\":{{\"owner\":\"{owner}\",\"repo\":\"{repo}\",\"type\":\"github\"}}}}"
338        )
339    }
340
341    #[test]
342    fn a_nested_node_does_not_shadow_the_root_input() {
343        let lock = format!(
344            "{{\"nodes\":{{\"exobrain-tech\":{{\"inputs\":{{\"spec-driven-docs\":\"spec-driven-docs\"}}}},\"spec-driven-docs\":{},\"spec-driven-docs_2\":{},\"top\":{{\"inputs\":{{\"exobrain-tech\":\"exobrain-tech\",\"sdd\":\"spec-driven-docs_2\"}}}}}},\"root\":\"top\",\"version\":7}}",
345            node("nested"),
346            node("own")
347        );
348        assert_eq!(locked_rev(&lock).as_deref(), Some("own"));
349    }
350
351    #[test]
352    fn a_followed_root_input_resolves_through_its_path() {
353        let lock = format!(
354            "{{\"nodes\":{{\"exobrain-tech\":{{\"inputs\":{{\"spec-driven-docs\":\"spec-driven-docs_2\"}}}},\"spec-driven-docs_2\":{},\"root\":{{\"inputs\":{{\"exobrain-tech\":\"exobrain-tech\",\"sdd\":[\"exobrain-tech\",\"spec-driven-docs\"]}}}}}},\"root\":\"root\",\"version\":7}}",
355            node("followed")
356        );
357        assert_eq!(locked_rev(&lock).as_deref(), Some("followed"));
358        let chained = format!(
359            "{{\"nodes\":{{\"a\":{{\"inputs\":{{\"tool\":[\"b\",\"tool\"]}}}},\"b\":{{\"inputs\":{{\"tool\":\"tool_3\"}}}},\"tool_3\":{},\"root\":{{\"inputs\":{{\"a\":\"a\",\"b\":\"b\",\"sdd\":[\"a\",\"tool\"]}}}}}},\"version\":7}}",
360            node("chained")
361        );
362        assert_eq!(locked_rev(&chained).as_deref(), Some("chained"));
363    }
364
365    #[test]
366    fn a_looped_or_broken_follows_path_names_no_input() {
367        let looped = format!(
368            "{{\"nodes\":{{\"spec-driven-docs\":{},\"root\":{{\"inputs\":{{\"sdd\":[\"sdd\"]}}}}}},\"version\":7}}",
369            node("never")
370        );
371        assert_eq!(locked_rev(&looped), None, "a loop names no input");
372        let broken = format!(
373            "{{\"nodes\":{{\"spec-driven-docs\":{},\"root\":{{\"inputs\":{{\"sdd\":[\"absent\",\"sdd\"]}}}}}},\"version\":7}}",
374            node("never")
375        );
376        assert_eq!(locked_rev(&broken), None);
377    }
378
379    #[test]
380    fn a_node_the_root_does_not_reach_is_not_the_project_input() {
381        let lock = format!(
382            "{{\"nodes\":{{\"spec-driven-docs\":{},\"root\":{{\"inputs\":{{\"nixpkgs\":\"nixpkgs\"}}}},\"nixpkgs\":{{\"locked\":{{\"rev\":\"n1\"}}}}}},\"version\":7}}",
383            node("stray")
384        );
385        assert_eq!(locked_rev(&lock), None);
386    }
387}