Skip to main content

release_kit/self_depend/
discover.rs

1//! The one network call the devshell verb makes: which release is the
2//! latest.
3//!
4//! The answer is the redirect of the forge's `releases/latest` page. It
5//! costs no API quota and no token, and it excludes prereleases, which
6//! the tag list does not. The fetch goes through `crate::http`, the one
7//! owner of the requests rk sends, whose test seam lets a test serve the
8//! network locally.
9
10use std::cmp::Ordering;
11
12use super::normalize_tag;
13use super::pin::PIN_PREFIX;
14
15/// What discovery found.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Discovery {
18    /// The latest release's tag, normalized.
19    Tag(String),
20    /// The source did not answer; the detail is the client's reason.
21    Unreachable(String),
22    /// The source answered something that names no tag.
23    Unparsable(String),
24}
25
26/// The page whose redirect names the latest release, derived from the
27/// pin grammar so the project path has one owner.
28#[must_use]
29pub fn latest_url() -> String {
30    let path = PIN_PREFIX
31        .trim_start_matches("github:")
32        .trim_end_matches('/');
33    format!("https://github.com/{path}/releases/latest")
34}
35
36/// The latest release's tag, through one request that follows the
37/// redirect and reads the URL that answered.
38#[must_use]
39pub fn latest_tag() -> Discovery {
40    let fetched = crate::http::send(
41        &crate::http::Request::get(&latest_url(), std::time::Duration::from_secs(10)).following(),
42    );
43    let answer = match fetched {
44        Ok(answer) if answer.ok() => answer,
45        Ok(answer) => {
46            return Discovery::Unreachable(format!(
47                "{} answered {}",
48                answer.final_url, answer.status
49            ));
50        }
51        Err(reason) => return Discovery::Unreachable(reason),
52    };
53    let url = answer.final_url;
54    match url.rsplit_once("/releases/tag/") {
55        Some((_, tail)) => {
56            normalize_tag(tail).map_or_else(|| Discovery::Unparsable(url.clone()), Discovery::Tag)
57        }
58        None => Discovery::Unparsable(url),
59    }
60}
61
62/// Semantic version order over two tags, with or without the leading `v`.
63///
64/// Numeric components compare as numbers, a release outranks its own
65/// prerelease, and prerelease identifiers compare the way semver says.
66/// Anything the grammar cannot read falls back to text order.
67#[must_use]
68pub fn version_order(left: &str, right: &str) -> Ordering {
69    let (left_core, left_pre) = split_version(left);
70    let (right_core, right_pre) = split_version(right);
71    let core = left_core
72        .iter()
73        .zip(right_core.iter())
74        .map(|(a, b)| a.cmp(b))
75        .find(|order| order.is_ne())
76        .unwrap_or_else(|| left_core.len().cmp(&right_core.len()));
77    if core.is_ne() {
78        return core;
79    }
80    match (left_pre, right_pre) {
81        (None, None) => Ordering::Equal,
82        (None, Some(_)) => Ordering::Greater,
83        (Some(_), None) => Ordering::Less,
84        (Some(a), Some(b)) => prerelease_order(a, b),
85    }
86}
87
88/// One component: a number, or an identifier that sorts after every number.
89#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
90enum Component {
91    Number(u64),
92    Text(String),
93}
94
95/// The core components and the prerelease suffix of a tag.
96fn split_version(tag: &str) -> (Vec<Component>, Option<&str>) {
97    let trimmed = tag.trim();
98    let bare = trimmed.strip_prefix('v').unwrap_or(trimmed);
99    let bare = bare.split('+').next().unwrap_or(bare);
100    let (core, pre) = bare
101        .split_once('-')
102        .map_or((bare, None), |(core, pre)| (core, Some(pre)));
103    (core.split('.').map(component).collect(), pre)
104}
105
106fn component(text: &str) -> Component {
107    text.parse()
108        .map_or_else(|_| Component::Text(text.to_owned()), Component::Number)
109}
110
111/// Prerelease order: identifier by identifier, numbers before text,
112/// and the shorter list first where every shared identifier ties.
113fn prerelease_order(left: &str, right: &str) -> Ordering {
114    let a: Vec<Component> = left.split('.').map(component).collect();
115    let b: Vec<Component> = right.split('.').map(component).collect();
116    a.iter()
117        .zip(b.iter())
118        .map(|(x, y)| x.cmp(y))
119        .find(|order| order.is_ne())
120        .unwrap_or_else(|| a.len().cmp(&b.len()))
121}
122
123#[cfg(test)]
124mod tests {
125    use std::cmp::Ordering;
126
127    use super::{latest_url, version_order};
128
129    #[test]
130    fn the_version_order_is_semantic_not_textual() {
131        assert_eq!(version_order("v0.2.16", "v0.2.16"), Ordering::Equal);
132        assert_eq!(version_order("0.2.16", "v0.2.16"), Ordering::Equal);
133        assert_eq!(version_order("v0.2.9", "v0.2.16"), Ordering::Less);
134        assert_eq!(version_order("v0.10.0", "v0.9.9"), Ordering::Greater);
135        assert_eq!(version_order("v1.0.0", "v1.0.0-rc.1"), Ordering::Greater);
136        assert_eq!(version_order("v1.0.0-rc.1", "v1.0.0-rc.2"), Ordering::Less);
137        assert_eq!(
138            version_order("v1.0.0-alpha", "v1.0.0-alpha.1"),
139            Ordering::Less
140        );
141        assert_eq!(version_order("v1.0.0-1", "v1.0.0-beta"), Ordering::Less);
142        assert_eq!(version_order("v1.0.0+build", "v1.0.0"), Ordering::Equal);
143        assert_eq!(version_order("v1.0", "v1.0.0"), Ordering::Less);
144    }
145
146    #[test]
147    fn the_latest_url_derives_from_the_pin_grammar() {
148        assert_eq!(
149            latest_url(),
150            "https://github.com/gubasso/release-kit/releases/latest"
151        );
152    }
153}