Skip to main content

cosmic_applet_avestruz/
update_check.rs

1// SPDX-License-Identifier: MIT
2
3//! Whether a release newer than the one running is out.
4//!
5//! Asked once each time Avestruz runs, when it starts, and only if the
6//! settings say so: the project's latest release on GitHub, which is
7//! never a draft nor a pre-release, against the version this was built
8//! as. The one thing sent is the request itself, which says which version
9//! asks; nothing of the account, and nothing that was read.
10//!
11//! A check that fails is no news, and shows nothing: there is another
12//! the next time Avestruz starts.
13//!
14//! ```mermaid
15//! flowchart TD
16//!     start["Avestruz starts, or the setting is turned on"] --> asked{"Was it asked already, this run?"}
17//!     asked -->|"yes"| nothing["Nothing"]
18//!     asked -->|"no"| github["GitHub is asked for the project's latest release"]
19//!     github --> newer{"Is its version higher than the one running?"}
20//!     newer -->|"yes"| banner["A line over what the popup shows says so, with a link to what is new, until it is dismissed"]
21//!     newer -->|"no, or it could not be asked, or its tag is no version"| nothing
22//!     off["The setting is turned off"] --> gone["The line goes, and nothing is asked"]
23//! ```
24//!
25//! Where it is asked from, and what the answer does, is in
26//! [`crate::handlers::settings`].
27
28use serde::Deserialize;
29
30use crate::http;
31
32/// How much of GitHub's answer is read at the most: a release with all
33/// its files and notes is a fraction of this.
34const ANSWER_MAX_BYTES: usize = 512 * 1024;
35
36/// A release newer than the one running.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct AvailableUpdate {
39    /// Its version, without the `v` its tag starts with: `0.2.0`.
40    pub version: String,
41    /// Its page, where what is new in it is said.
42    pub url: String,
43}
44
45/// What is read of how GitHub describes a release.
46#[derive(Debug, Deserialize)]
47struct Release {
48    /// Its tag: `v1.2.3`.
49    tag_name: String,
50    /// Its page on GitHub.
51    html_url: String,
52}
53
54/// Where GitHub says what the latest release is of the project whose
55/// source is at `repository`. `None` if that is not on GitHub.
56fn latest_release_url(repository: &str) -> Option<String> {
57    let project = repository.strip_prefix("https://github.com/")?.trim_end_matches('/');
58    (!project.is_empty()).then(|| format!("https://api.github.com/repos/{project}/releases/latest"))
59}
60
61/// A version as its three numbers, with or without a leading `v`.
62/// Anything else is no version to compare: two numbers, four, or one
63/// with something after it, as a pre-release has.
64fn version_numbers(version: &str) -> Option<[u64; 3]> {
65    let mut numbers = version.strip_prefix('v').unwrap_or(version).split('.').map(|number| number.parse::<u64>().ok());
66    let read = [numbers.next()??, numbers.next()??, numbers.next()??];
67    numbers.next().is_none().then_some(read)
68}
69
70/// `release`, if its version is higher than `running`, each number
71/// compared as a number. `None` if either is no version to compare.
72fn newer_than(running: &str, release: Release) -> Option<AvailableUpdate> {
73    let newer = version_numbers(&release.tag_name)? > version_numbers(running)?;
74    newer.then(|| AvailableUpdate {
75        version: release.tag_name.strip_prefix('v').unwrap_or(&release.tag_name).to_string(),
76        url: release.html_url,
77    })
78}
79
80/// The project's latest release, if it is newer than what is running.
81pub async fn check(http: reqwest::Client) -> Result<Option<AvailableUpdate>, String> {
82    let url = latest_release_url(env!("CARGO_PKG_REPOSITORY")).ok_or("the project is not on GitHub")?;
83    let answer = http::get_as(&http, &url, "application/vnd.github+json", ANSWER_MAX_BYTES).await?;
84    let release: Release = serde_json::from_slice(&answer).map_err(|e| e.to_string())?;
85    // Its page is opened in the browser: only one on GitHub, wherever
86    // there the project is by then.
87    if !release.html_url.starts_with("https://github.com/") {
88        return Err(format!("the release's page is not on GitHub: {}", release.html_url));
89    }
90    Ok(newer_than(env!("CARGO_PKG_VERSION"), release))
91}
92
93#[cfg(test)]
94mod tests {
95    use super::{AvailableUpdate, Release, latest_release_url, newer_than, version_numbers};
96
97    fn release(tag: &str) -> Release {
98        Release { tag_name: tag.to_string(), html_url: format!("https://github.com/glima/avestruz/releases/tag/{tag}") }
99    }
100
101    #[test]
102    fn the_latest_release_is_asked_of_where_the_source_is() {
103        assert_eq!(
104            latest_release_url("https://github.com/glima/avestruz").as_deref(),
105            Some("https://api.github.com/repos/glima/avestruz/releases/latest")
106        );
107        assert_eq!(
108            latest_release_url("https://github.com/glima/avestruz/").as_deref(),
109            Some("https://api.github.com/repos/glima/avestruz/releases/latest")
110        );
111        // What the crate says of itself is such an address.
112        assert!(latest_release_url(env!("CARGO_PKG_REPOSITORY")).is_some());
113        // Anywhere else has no such thing to ask.
114        assert_eq!(latest_release_url("https://codeberg.org/someone/thing"), None);
115        assert_eq!(latest_release_url("https://github.com/"), None);
116        assert_eq!(latest_release_url(""), None);
117    }
118
119    #[test]
120    fn a_version_is_three_numbers() {
121        assert_eq!(version_numbers("v1.2.3"), Some([1, 2, 3]));
122        assert_eq!(version_numbers("1.2.3"), Some([1, 2, 3]));
123        assert_eq!(version_numbers("0.10.0"), Some([0, 10, 0]));
124        for not_one in ["1.2", "1.2.3.4", "1.2.3-rc1", "v1.2.x", "nightly", "", "vv1.2.3", "1..3"] {
125            assert_eq!(version_numbers(not_one), None, "{not_one}");
126        }
127        // The version this is built as is one, or nothing would ever be
128        // found to be newer.
129        assert!(version_numbers(env!("CARGO_PKG_VERSION")).is_some());
130    }
131
132    #[test]
133    fn only_a_higher_version_is_news() {
134        let found = newer_than("0.1.9", release("v0.1.10"));
135        let news = AvailableUpdate {
136            version: "0.1.10".to_string(),
137            url: "https://github.com/glima/avestruz/releases/tag/v0.1.10".to_string(),
138        };
139        assert_eq!(found, Some(news), "ten is more than nine: numbers, not letters");
140        assert!(newer_than("0.1.9", release("v0.2.0")).is_some());
141        assert!(newer_than("0.1.9", release("1.0.0")).is_some());
142        // The same, or an older one, is none.
143        assert_eq!(newer_than("0.1.9", release("v0.1.9")), None);
144        assert_eq!(newer_than("0.1.10", release("v0.1.9")), None);
145        assert_eq!(newer_than("1.0.0", release("v0.9.9")), None);
146        // Nor is what can't be compared, on either side.
147        assert_eq!(newer_than("0.1.9", release("nightly")), None);
148        assert_eq!(newer_than("0.2.0-rc1", release("v0.2.0")), None);
149    }
150
151    #[test]
152    fn what_github_says_of_a_release_is_read() {
153        // As it answers, less what is not read.
154        let answer = r#"{"url":"https://api.github.com/repos/glima/avestruz/releases/1","html_url":"https://github.com/glima/avestruz/releases/tag/v9.9.9","id":1,"tag_name":"v9.9.9","name":"v9.9.9","draft":false,"prerelease":false,"assets":[],"body":"notes"}"#;
155        let release: Release = serde_json::from_str(answer).unwrap();
156        let found = newer_than(env!("CARGO_PKG_VERSION"), release).unwrap();
157        assert_eq!(found.version, "9.9.9");
158        assert!(found.url.starts_with(env!("CARGO_PKG_REPOSITORY")));
159        // An answer that is not a release is an error, not a release.
160        assert!(serde_json::from_str::<Release>(r#"{"message":"Not Found"}"#).is_err());
161    }
162
163    #[test]
164    fn it_is_asked_unless_it_was_turned_off() {
165        assert!(crate::config::Config::default().check_for_updates);
166    }
167}