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/// Fetch one check URL and classify the answer.
172fn check_one(tool: &str, pinned: &str, url: &str) -> PinResult {
173    let result = |result, available| PinResult {
174        tool: tool.to_owned(),
175        pinned: pinned.to_owned(),
176        result,
177        available,
178        commit: None,
179        ref_class: None,
180        ref_result: None,
181        ref_commit: None,
182    };
183    let curl = std::env::var_os("RK_CURL_BIN").unwrap_or_else(|| "curl".into());
184    let fetched = std::process::Command::new(curl)
185        .args(["-fsSL", "--max-time", "10", url])
186        .output();
187    let body = match fetched {
188        Ok(output) if output.status.success() => output.stdout,
189        _ => return result("source-unreachable", None),
190    };
191    let Some(available) = latest_version(&body) else {
192        return result("source-unparsable", None);
193    };
194    if is_current(pinned, &available) {
195        result("current", Some(available))
196    } else {
197        result("update-available", Some(available))
198    }
199}
200
201/// The latest version a source's JSON names: `max_stable_version` from a
202/// crates.io answer, `tag_name` from a forge's releases answer.
203fn latest_version(body: &[u8]) -> Option<String> {
204    let value: serde_json::Value = serde_json::from_slice(body).ok()?;
205    let raw = value
206        .get("crate")
207        .and_then(|krate| krate.get("max_stable_version"))
208        .or_else(|| value.get("tag_name"))
209        .and_then(serde_json::Value::as_str)?;
210    // A tag may prefix the number — `v2.13.1`, or a name before it — so
211    // the version starts at the first digit.
212    let start = raw.find(|c: char| c.is_ascii_digit())?;
213    Some(raw[start..].to_owned())
214}
215
216/// Whether the pin already matches the source: exactly, or — for a pin
217/// naming only a major, as the action pins do — by major version.
218fn is_current(pinned: &str, available: &str) -> bool {
219    if pinned == available {
220        return true;
221    }
222    !pinned.contains('.') && available.split('.').next() == Some(pinned)
223}
224
225#[cfg(test)]
226mod tests {
227    #![allow(clippy::expect_used)]
228
229    use super::{PinResult, Report, is_current, latest_version};
230
231    #[test]
232    fn a_source_version_is_read_from_both_answer_shapes() {
233        assert_eq!(
234            latest_version(br#"{"crate":{"max_stable_version":"0.3.170"}}"#),
235            Some("0.3.170".to_owned())
236        );
237        assert_eq!(
238            latest_version(br#"{"tag_name":"v2.13.1"}"#),
239            Some("2.13.1".to_owned())
240        );
241        assert_eq!(
242            latest_version(br#"{"tag_name":"release-plz-v0.3.160"}"#),
243            Some("0.3.160".to_owned())
244        );
245        assert_eq!(latest_version(b"not json"), None);
246        assert_eq!(latest_version(br#"{"unrelated":true}"#), None);
247    }
248
249    #[test]
250    fn a_major_only_pin_is_current_within_its_major() {
251        assert!(is_current("0.3.160", "0.3.160"));
252        assert!(!is_current("0.3.160", "0.3.170"));
253        assert!(is_current("4", "4.3.1"));
254        assert!(!is_current("4", "5.0.0"));
255    }
256
257    /// The complete `rk.versions-check/2` shape, held by snapshot.
258    #[test]
259    fn the_versions_check_schema_snapshot_holds() {
260        let report = Report {
261            schema: "rk.versions-check/2",
262            pins: vec![PinResult {
263                tool: "release-plz".into(),
264                pinned: "0.3.160".into(),
265                result: "update-available",
266                available: Some("0.3.170".into()),
267                commit: Some("2eb1d8bcb770b4c48ccfaad919734b38b51958c9".into()),
268                ref_class: Some("moving-minor-tag".into()),
269                ref_result: Some("ref-unmoved"),
270                ref_commit: Some("2eb1d8bcb770b4c48ccfaad919734b38b51958c9".into()),
271            }],
272        };
273        assert_eq!(
274            serde_json::to_string(&report).expect("a report serializes"),
275            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"}]}"#
276        );
277    }
278}