Skip to main content

sapphire_framework_update/
release.rs

1//! Where a binary's releases are, and which is the newest.
2
3use std::time::Duration;
4
5use serde::Deserialize;
6
7use crate::{Error, Result};
8
9/// How long one request may take before it counts as failed. Downloads have their own,
10/// longer budget.
11const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
12
13/// Where a binary's releases are published: a GitHub repository whose releases are tagged
14/// `<prefix><version>`, and — for the `update` command — the file in them.
15#[derive(Clone, Debug)]
16pub struct ReleaseSource {
17    owner: String,
18    repo: String,
19    tag_prefix: String,
20    api_base: String,
21    asset: Option<String>,
22    cargo_crate: Option<String>,
23}
24
25impl ReleaseSource {
26    /// The releases of `github.com/<owner>/<repo>`, tagged `v<version>`.
27    pub fn github(owner: impl Into<String>, repo: impl Into<String>) -> ReleaseSource {
28        ReleaseSource {
29            owner: owner.into(),
30            repo: repo.into(),
31            tag_prefix: "v".to_owned(),
32            api_base: "https://api.github.com".to_owned(),
33            asset: None,
34            cargo_crate: None,
35        }
36    }
37
38    /// Release tags are `<prefix><version>` rather than `v<version>`, e.g. `cli-v` in a
39    /// repository that also tags a desktop app.
40    pub fn tag_prefix(mut self, prefix: impl Into<String>) -> ReleaseSource {
41        self.tag_prefix = prefix.into();
42        self
43    }
44
45    /// Ask another GitHub API root than `https://api.github.com`: for fixtures.
46    pub fn api_base(mut self, base: impl Into<String>) -> ReleaseSource {
47        self.api_base = base.into();
48        self
49    }
50
51    /// The binary is published as `<name>-<os>-<arch>` (`.exe` on Windows): what `update`
52    /// downloads. Without it, `update` only reports.
53    pub fn asset(mut self, name: impl Into<String>) -> ReleaseSource {
54        self.asset = Some(name.into());
55        self
56    }
57
58    /// The crate `cargo install` installs this binary from, for the advice `update` gives
59    /// a binary it will not replace.
60    pub fn cargo_crate(mut self, name: impl Into<String>) -> ReleaseSource {
61        self.cargo_crate = Some(name.into());
62        self
63    }
64
65    /// `<owner>/<repo>`.
66    pub fn repository(&self) -> String {
67        format!("{}/{}", self.owner, self.repo)
68    }
69
70    pub(crate) fn asset_base(&self) -> Option<&str> {
71        self.asset.as_deref()
72    }
73
74    pub(crate) fn crate_name(&self) -> Option<&str> {
75        self.cargo_crate.as_deref()
76    }
77
78    /// The repository's newest releases. Not `releases/latest`: a repository that tags
79    /// several binaries (`cli-v…`, `desktop-v…`) has one "latest" among all of them.
80    fn releases_url(&self) -> String {
81        format!(
82            "{}/repos/{}/{}/releases?per_page=100",
83            self.api_base.trim_end_matches('/'),
84            self.owner,
85            self.repo
86        )
87    }
88}
89
90/// One published release.
91#[derive(Clone, Debug, PartialEq, Eq)]
92pub struct Release {
93    /// Its version, the tag without its prefix.
94    pub version: semver::Version,
95    /// Its web page, where its notes are.
96    pub url: String,
97    /// Its files.
98    pub assets: Vec<Asset>,
99}
100
101/// One file of a release.
102#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
103pub struct Asset {
104    /// The file's name.
105    pub name: String,
106    /// Where it downloads from.
107    #[serde(rename = "browser_download_url")]
108    pub download_url: String,
109}
110
111/// The part of GitHub's release object this reads.
112#[derive(Debug, Deserialize)]
113pub(crate) struct GithubRelease {
114    pub(crate) tag_name: String,
115    pub(crate) html_url: String,
116    #[serde(default)]
117    pub(crate) draft: bool,
118    #[serde(default)]
119    pub(crate) prerelease: bool,
120    #[serde(default)]
121    pub(crate) assets: Vec<Asset>,
122}
123
124/// An HTTP client that names itself `user_agent` (GitHub refuses requests without one).
125pub fn client(user_agent: &str) -> Result<reqwest::Client> {
126    reqwest::Client::builder()
127        .user_agent(user_agent)
128        .timeout(REQUEST_TIMEOUT)
129        .build()
130        .map_err(|e| Error::Http(format!("no HTTP client: {e}")))
131}
132
133/// Ask GitHub for `source`'s newest release.
134pub async fn latest_release(client: &reqwest::Client, source: &ReleaseSource) -> Result<Release> {
135    let url = source.releases_url();
136    let releases: Vec<GithubRelease> = client
137        .get(&url)
138        .header(reqwest::header::ACCEPT, "application/vnd.github+json")
139        .send()
140        .await
141        .and_then(reqwest::Response::error_for_status)
142        .map_err(|e| Error::Http(format!("asking {url}: {e}")))?
143        .json()
144        .await
145        .map_err(|e| Error::Http(format!("reading the releases: {e}")))?;
146    newest(releases, &source.tag_prefix).ok_or_else(|| {
147        Error::NoRelease(format!(
148            "{} has no published release tagged {}<version>",
149            source.repository(),
150            source.tag_prefix
151        ))
152    })
153}
154
155/// The newest published, non-prerelease release tagged `<prefix><semver>`. Tags of the
156/// repository's other binaries, drafts, prereleases and tags that are not versions are
157/// skipped.
158pub(crate) fn newest(
159    releases: impl IntoIterator<Item = GithubRelease>,
160    prefix: &str,
161) -> Option<Release> {
162    releases
163        .into_iter()
164        .filter(|r| !r.draft && !r.prerelease)
165        .filter_map(|r| {
166            let version = semver::Version::parse(r.tag_name.strip_prefix(prefix)?).ok()?;
167            version.pre.is_empty().then_some(Release {
168                version,
169                url: r.html_url,
170                assets: r.assets,
171            })
172        })
173        .max_by(|a, b| a.version.cmp(&b.version))
174}
175
176#[cfg(test)]
177pub(crate) mod tests {
178    use super::*;
179
180    pub(crate) fn release(tag: &str) -> GithubRelease {
181        GithubRelease {
182            tag_name: tag.to_owned(),
183            html_url: format!("https://example.invalid/{tag}"),
184            draft: false,
185            prerelease: false,
186            assets: Vec::new(),
187        }
188    }
189
190    #[test]
191    fn the_newest_release_is_the_highest_version_with_the_prefix() {
192        // sapphire-journal tags its CLI and its desktop app in one repository, and the
193        // desktop app's release can be the newest of all.
194        let releases = || {
195            [
196                release("desktop-v0.1.0"),
197                release("cli-v0.12.0"),
198                release("cli-v0.9.3"),
199                release("cli-v0.11.0"),
200            ]
201        };
202        let info = newest(releases(), "cli-v").unwrap();
203        assert_eq!(info.version.to_string(), "0.12.0");
204        assert_eq!(info.url, "https://example.invalid/cli-v0.12.0");
205        assert_eq!(
206            newest(releases(), "desktop-v").unwrap().version.to_string(),
207            "0.1.0"
208        );
209        // `v` does not reach into `desktop-v…`, nor `cli-v` into `sapphire-agent-cli-v…`.
210        assert_eq!(newest(releases(), "v"), None);
211        assert_eq!(
212            newest([release("sapphire-agent-cli-v0.8.0")], "cli-v"),
213            None
214        );
215    }
216
217    #[test]
218    fn drafts_prereleases_and_tags_that_are_not_versions_are_skipped() {
219        let mut draft = release("v0.22.0");
220        draft.draft = true;
221        let mut flagged = release("v0.21.0");
222        flagged.prerelease = true;
223        let releases = [
224            draft,
225            flagged,
226            release("v0.21.0-rc.1"),
227            release("vnext"),
228            release("v0.20.0"),
229        ];
230        assert_eq!(newest(releases, "v").unwrap().version.to_string(), "0.20.0");
231    }
232}