Skip to main content

release_kit/commands/
versions.rs

1//! `rk versions`: the pinned-tool registry, and its freshness check.
2//!
3//! Plain `rk versions` prints the registry exactly as authored, offline.
4//! `--check` is the canon-side freshness answer and, beside `rk devshell
5//! sync`, one of the two verbs that fetch: it consults each pin's check
6//! URL and reports per pin, where
7//! an unreachable or unparsable source is a reported result at exit 0,
8//! not an error — and it never edits `versions.toml`, because a pin
9//! update is a reviewed change in this repository. The fetch goes through
10//! `curl`, resolved like the forge CLIs with `RK_CURL_BIN` as the
11//! override, so the check needs no HTTP stack of its own and a test can
12//! substitute the network.
13
14use serde::Serialize;
15
16use crate::cli::versions::VersionsArgs;
17use crate::error::RkError;
18use crate::output::Output;
19use crate::{embedded, registry};
20
21/// One pin's check result.
22#[derive(Debug, Serialize)]
23struct PinResult {
24    /// The tool's registry name.
25    tool: String,
26    /// The pinned version.
27    pinned: String,
28    /// `current`, `update-available`, `source-unreachable`,
29    /// `source-unparsable`, or — for a pin whose freshness lives in its
30    /// ref alone — `no-version-source`.
31    result: &'static str,
32    /// The version the source serves, where one was read.
33    #[serde(skip_serializing_if = "Option::is_none")]
34    available: Option<String>,
35    /// The immutable execution commit, where the pin is an action.
36    #[serde(skip_serializing_if = "Option::is_none")]
37    commit: Option<String>,
38    /// How the discovery ref moves, from the registry.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    ref_class: Option<String>,
41    /// `ref-unmoved`, `ref-moved`, `ref-unreachable`, or
42    /// `ref-unparsable`, for a pin carrying an action and a commit.
43    #[serde(skip_serializing_if = "Option::is_none")]
44    ref_result: Option<&'static str>,
45    /// The commit the discovery ref names today, where it was read.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    ref_commit: Option<String>,
48}
49
50/// The machine form of a check report.
51#[derive(Debug, Serialize)]
52struct Report {
53    /// The shape version of this document.
54    schema: &'static str,
55    /// One result per pin, in registry order.
56    pins: Vec<PinResult>,
57}
58
59/// Print the registry, or check each pin upstream under `--check`.
60///
61/// # Errors
62///
63/// Returns [`RkError::Other`] only when the report cannot serialize; an
64/// unreachable or unparsable source is a reported result, not a failure.
65pub fn run(args: &VersionsArgs) -> Result<(), RkError> {
66    if !args.check {
67        Output::human().result_raw(embedded::VERSIONS);
68        return Ok(());
69    }
70    let out = Output::new(args.json);
71    let mut results = Vec::new();
72    for pin in registry::pins() {
73        let mut result = pin.check.as_deref().map_or_else(
74            || PinResult {
75                tool: pin.name.clone(),
76                pinned: pin.version.clone(),
77                // A pin can live without a version source only where its
78                // freshness signal is the discovery ref itself.
79                result: if pin.action.is_some() && pin.commit.is_some() {
80                    "no-version-source"
81                } else {
82                    "source-unreachable"
83                },
84                available: None,
85                commit: None,
86                ref_class: None,
87                ref_result: None,
88                ref_commit: None,
89            },
90            |url| check_one(&pin.name, &pin.version, url),
91        );
92        if let (Some(action), Some(commit)) = (&pin.action, &pin.commit) {
93            let (ref_result, ref_commit) = resolve_ref(action, commit);
94            result.commit = Some(commit.clone());
95            result.ref_class.clone_from(&pin.ref_class);
96            result.ref_result = Some(ref_result);
97            result.ref_commit = ref_commit;
98        }
99        out.result_line(match (&result.result, &result.available) {
100            (&"update-available", Some(available)) => format!(
101                "update-available {} {} pinned, {available} at the source",
102                result.tool, result.pinned
103            ),
104            _ => format!("{} {} {}", result.result, result.tool, result.pinned),
105        });
106        if let Some(ref_result) = result.ref_result {
107            let reference = pin
108                .action
109                .as_deref()
110                .and_then(|action| action.split_once('@'))
111                .map_or_else(String::new, |(_, reference)| reference.to_owned());
112            out.result_line(match (ref_result, &result.ref_commit) {
113                // Movement of a discovery ref is normal and by design: it
114                // is an update signal the pinned commit already contains,
115                // never something the tool can call an attack.
116                ("ref-moved", Some(now)) => format!(
117                    "ref-moved {}: {reference} now names {now}; an update to review, not an incident",
118                    result.tool
119                ),
120                ("ref-unmoved", _) => format!(
121                    "ref-unmoved {}: {reference} still names the pinned commit",
122                    result.tool
123                ),
124                _ => format!("{ref_result} {}: {reference}", result.tool),
125            });
126        }
127        results.push(result);
128    }
129    out.next(&[
130        "a pin update is a reviewed change to versions.toml, with its checked date".to_owned(),
131    ]);
132    out.emit(&Report {
133        schema: "rk.versions-check/2",
134        pins: results,
135    })
136}
137
138/// Resolve an action's discovery ref to the commit it names today and
139/// compare it against the pinned execution commit.
140fn resolve_ref(action: &str, pinned_commit: &str) -> (&'static str, Option<String>) {
141    let Some((repo, reference)) = action.split_once('@') else {
142        return ("ref-unparsable", None);
143    };
144    let url = format!("https://api.github.com/repos/{repo}/commits/{reference}");
145    let curl = std::env::var_os("RK_CURL_BIN").unwrap_or_else(|| "curl".into());
146    let fetched = std::process::Command::new(curl)
147        .args(["-fsSL", "--max-time", "10", &url])
148        .output();
149    let body = match fetched {
150        Ok(output) if output.status.success() => output.stdout,
151        _ => return ("ref-unreachable", None),
152    };
153    let Some(sha) = serde_json::from_slice::<serde_json::Value>(&body)
154        .ok()
155        .and_then(|value| {
156            value
157                .get("sha")
158                .and_then(serde_json::Value::as_str)
159                .map(str::to_owned)
160        })
161    else {
162        return ("ref-unparsable", None);
163    };
164    if sha == pinned_commit {
165        ("ref-unmoved", Some(sha))
166    } else {
167        ("ref-moved", Some(sha))
168    }
169}
170
171/// The page bound for a paged answer: at 100 entries a page, ten pages is
172/// a thousand tags, past any project this registry pins. A source deeper
173/// than that reads as unreachable rather than as a version this check
174/// silently guessed.
175const MAX_PAGES: u32 = 10;
176
177/// One GET, or `None` where the fetch failed.
178fn fetch(url: &str) -> Option<Vec<u8>> {
179    let curl = std::env::var_os("RK_CURL_BIN").unwrap_or_else(|| "curl".into());
180    let fetched = std::process::Command::new(curl)
181        .args(["-fsSL", "--max-time", "10", url])
182        .output();
183    match fetched {
184        Ok(output) if output.status.success() => Some(output.stdout),
185        _ => None,
186    }
187}
188
189/// The same URL at a later page, in the query form every paged source here
190/// takes.
191fn paged(url: &str, page: u32) -> String {
192    let joiner = if url.contains('?') { '&' } else { '?' };
193    format!("{url}{joiner}page={page}")
194}
195
196/// Fetch one check URL and classify the answer.
197///
198/// An object answer — a crates.io crate, a forge's latest release — is one
199/// GET. An array answer is a page of a list, and the endpoint documents no
200/// ordering, so reading one page would compute the greatest of an arbitrary
201/// subset and could report a stale pin as current. Every page is therefore
202/// read, to the bound above, and the greatest version across all of them
203/// wins.
204///
205/// Reaching the bound with a page still full is not an answer: the list
206/// continues past what was read, so the greatest version is unknown. That
207/// reads as `source-unreachable`, the same as a failed fetch, rather than
208/// as the greatest of the pages that happened to fit.
209fn check_one(tool: &str, pinned: &str, url: &str) -> PinResult {
210    let result = |result, available| PinResult {
211        tool: tool.to_owned(),
212        pinned: pinned.to_owned(),
213        result,
214        available,
215        commit: None,
216        ref_class: None,
217        ref_result: None,
218        ref_commit: None,
219    };
220    let Some(body) = fetch(url) else {
221        return result("source-unreachable", None);
222    };
223    let mut best = latest_version(&body);
224    if is_page(&body) && !is_empty_page(&body) {
225        let mut ended = false;
226        for page in 2..=MAX_PAGES {
227            let Some(body) = fetch(&paged(url, page)) else {
228                return result("source-unreachable", None);
229            };
230            // Every page of a list is a list. A later page that answers
231            // some other shape is a source this reader does not
232            // understand, and feeding it to the object parser would mint
233            // a version out of an answer that names no tag.
234            if !is_page(&body) {
235                return result("source-unparsable", None);
236            }
237            if is_empty_page(&body) {
238                ended = true;
239                break;
240            }
241            best = greater(best, latest_version(&body));
242        }
243        if !ended {
244            return result("source-unreachable", None);
245        }
246    }
247    let Some(available) = best else {
248        return result("source-unparsable", None);
249    };
250    if is_current(pinned, &available) {
251        result("current", Some(available))
252    } else {
253        result("update-available", Some(available))
254    }
255}
256
257/// Whether the answer is one page of a list rather than a single object.
258fn is_page(body: &[u8]) -> bool {
259    serde_json::from_slice::<serde_json::Value>(body).is_ok_and(|value| value.is_array())
260}
261
262/// Whether the answer is a page past the end of the list.
263fn is_empty_page(body: &[u8]) -> bool {
264    serde_json::from_slice::<serde_json::Value>(body)
265        .is_ok_and(|value| value.as_array().is_some_and(Vec::is_empty))
266}
267
268/// The greater of two versions, comparing numerically component by
269/// component, with an absent version losing to any present one.
270fn greater(left: Option<String>, right: Option<String>) -> Option<String> {
271    match (left, right) {
272        (Some(left), Some(right)) => {
273            if numeric_parts(&right) > numeric_parts(&left) {
274                Some(right)
275            } else {
276                Some(left)
277            }
278        }
279        (some, None) | (None, some) => some,
280    }
281}
282
283/// The latest version a source's JSON names, across the three answer
284/// shapes: `max_stable_version` from a crates.io answer, `tag_name` from a
285/// forge's releases answer, and the greatest `name` from a forge's tags
286/// answer, which is an array.
287///
288/// The tags shape exists for a project that publishes tags and cuts no
289/// releases, so no releases answer names its latest version. The greatest
290/// is taken rather than the first, because the endpoint promises no
291/// ordering.
292fn latest_version(body: &[u8]) -> Option<String> {
293    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
294    if let Some(tags) = value.as_array() {
295        return tags
296            .iter()
297            .filter_map(|tag| tag.get("name").and_then(serde_json::Value::as_str))
298            .filter_map(number_from)
299            .max_by(|left, right| numeric_parts(left).cmp(&numeric_parts(right)));
300    }
301    let raw = value
302        .get("crate")
303        .and_then(|krate| krate.get("max_stable_version"))
304        .or_else(|| value.get("tag_name"))
305        .and_then(serde_json::Value::as_str)?;
306    number_from(raw)
307}
308
309/// A ref name from its first digit on: a tag may prefix the number —
310/// `v2.13.1`, or a name before it.
311fn number_from(raw: &str) -> Option<String> {
312    let start = raw.find(|c: char| c.is_ascii_digit())?;
313    Some(raw[start..].to_owned())
314}
315
316/// A version's numeric components, so that 2.10 orders above 2.9 rather
317/// than below it; the first component that is not a number ends the list,
318/// which keeps a suffixed variant below its plain sibling.
319fn numeric_parts(version: &str) -> Vec<u64> {
320    version
321        .split('.')
322        .map_while(|part| part.parse::<u64>().ok())
323        .collect()
324}
325
326/// Whether the pin already matches the source: exactly, or — for a pin
327/// naming only a major, as the action pins do — by major version.
328fn is_current(pinned: &str, available: &str) -> bool {
329    if pinned == available {
330        return true;
331    }
332    !pinned.contains('.') && available.split('.').next() == Some(pinned)
333}
334
335#[cfg(test)]
336mod tests {
337    #![allow(clippy::expect_used)]
338
339    use super::{PinResult, Report, is_current, latest_version};
340
341    #[test]
342    fn a_source_version_is_read_from_both_answer_shapes() {
343        assert_eq!(
344            latest_version(br#"{"crate":{"max_stable_version":"0.3.170"}}"#),
345            Some("0.3.170".to_owned())
346        );
347        assert_eq!(
348            latest_version(br#"{"tag_name":"v2.13.1"}"#),
349            Some("2.13.1".to_owned())
350        );
351        assert_eq!(
352            latest_version(br#"{"tag_name":"release-plz-v0.3.160"}"#),
353            Some("0.3.160".to_owned())
354        );
355        assert_eq!(latest_version(b"not json"), None);
356        assert_eq!(latest_version(br#"{"unrelated":true}"#), None);
357    }
358
359    /// The tags shape, for a project that publishes tags and cuts no
360    /// releases. The greatest wins, not the first, because the endpoint
361    /// promises no ordering; and 2.10 is above 2.9, not below it.
362    #[test]
363    fn a_tags_answer_reads_the_greatest_name() {
364        assert_eq!(
365            latest_version(br#"[{"name":"2.35.0"},{"name":"2.35.2"},{"name":"2.34.8"}]"#),
366            Some("2.35.2".to_owned())
367        );
368        assert_eq!(
369            latest_version(br#"[{"name":"2.9.0"},{"name":"2.10.0"}]"#),
370            Some("2.10.0".to_owned())
371        );
372        assert_eq!(
373            latest_version(br#"[{"name":"v1.2.3"}]"#),
374            Some("1.2.3".to_owned())
375        );
376        assert_eq!(latest_version(b"[]"), None);
377        assert_eq!(latest_version(br#"[{"sha":"abc"}]"#), None);
378    }
379
380    #[test]
381    fn a_major_only_pin_is_current_within_its_major() {
382        assert!(is_current("0.3.160", "0.3.160"));
383        assert!(!is_current("0.3.160", "0.3.170"));
384        assert!(is_current("4", "4.3.1"));
385        assert!(!is_current("4", "5.0.0"));
386    }
387
388    /// The complete `rk.versions-check/2` shape, held by snapshot.
389    #[test]
390    fn the_versions_check_schema_snapshot_holds() {
391        let report = Report {
392            schema: "rk.versions-check/2",
393            pins: vec![PinResult {
394                tool: "release-plz".into(),
395                pinned: "0.3.160".into(),
396                result: "update-available",
397                available: Some("0.3.170".into()),
398                commit: Some("2eb1d8bcb770b4c48ccfaad919734b38b51958c9".into()),
399                ref_class: Some("moving-minor-tag".into()),
400                ref_result: Some("ref-unmoved"),
401                ref_commit: Some("2eb1d8bcb770b4c48ccfaad919734b38b51958c9".into()),
402            }],
403        };
404        assert_eq!(
405            serde_json::to_string(&report).expect("a report serializes"),
406            r#"{"schema":"rk.versions-check/2","pins":[{"tool":"release-plz","pinned":"0.3.160","result":"update-available","available":"0.3.170","commit":"2eb1d8bcb770b4c48ccfaad919734b38b51958c9","ref_class":"moving-minor-tag","ref_result":"ref-unmoved","ref_commit":"2eb1d8bcb770b4c48ccfaad919734b38b51958c9"}]}"#
407        );
408    }
409}