BlueGit

ict rusty-teams

Files

rusty-teams / crates / kvt-update / src / lib.rs

lib.rs

lib.rs 12.4 KiB Download Raw
1//! KVT fork only: the release feed of `ict/rusty-teams` on git.kvt.nl (BlueGit).
2//!
3//! Upstream's updater (`app-base/src/release_feed.rs`) reads GitHub releases. This
4//! fork reads BlueGit instead and turns its answer into the GitHub shape that
5//! `release_feed::Release` already parses, so the download, verification, swap and
6//! dialogs stay upstream's code. Keeping this in its own crate, without GPUI, keeps
7//! the weekly upstream merge small and lets CI test it in seconds.
8//!
9//! BlueGit lists a release as `{"tag", "name", "assets": [{"name", "size"}]}`. There
10//! is no download URL and no digest in that list: an asset downloads from
11//! `/api/v1/projects/<owner>/<repo>/releases/<tag>/assets/<name>`, and the sha256 of
12//! each file is in the `SHA256SUMS` asset that the release job publishes.
13
14use std::collections::HashMap;
15use std::path::Path;
16
17use serde::{Deserialize, Serialize};
18
19/// The BlueGit server and project this fork publishes to.
20pub const SERVER: &str = "https://git.kvt.nl";
21pub const PROJECT: &str = "ict/rusty-teams";
22/// The file in every release with `sha256 name` lines.
23pub const CHECKSUMS_ASSET: &str = "SHA256SUMS";
24/// Set (to anything but empty or `0`) by a package manager: no update checks at all.
25pub const PACKAGE_MANAGED_ENV: &str = "RUSTY_TEAMS_PACKAGE_MANAGED";
26/// Installed by the AUR package `kvt-rusty-teams-bin` (and any other system package).
27pub const PACKAGE_MANAGED_MARKER: &str = "/usr/lib/rusty-teams/package-managed";
28
29/// The public JSON list of releases (newest first).
30pub fn releases_url() -> String {
31 format!("{SERVER}/api/v1/projects/{PROJECT}/releases")
32}
33
34/// The page that lists the releases; installs that must not replace themselves open it.
35pub fn release_page_url(tag: &str) -> String {
36 format!("{SERVER}/{PROJECT}/-/releases#{tag}")
37}
38
39/// Download URL of one release asset.
40pub fn asset_url(tag: &str, name: &str) -> String {
41 format!(
42 "{SERVER}/api/v1/projects/{PROJECT}/releases/{}/assets/{}",
43 encode_segment(tag),
44 encode_segment(name)
45 )
46}
47
48/// BlueGit allows `A-Za-z0-9._-` in a tag and a basename for an asset. Anything else
49/// is percent-encoded so a strange name can never change the path.
50fn encode_segment(segment: &str) -> String {
51 let mut out = String::with_capacity(segment.len());
52 for byte in segment.bytes() {
53 if byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'~') {
54 out.push(byte as char);
55 } else {
56 out.push_str(&format!("%{byte:02X}"));
57 }
58 }
59 out
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
63pub struct BlueGitRelease {
64 pub tag: String,
65 #[serde(default)]
66 pub assets: Vec<BlueGitAsset>,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
70pub struct BlueGitAsset {
71 pub name: String,
72 #[serde(default)]
73 pub size: u64,
74}
75
76impl BlueGitRelease {
77 pub fn has_checksums(&self) -> bool {
78 self.assets
79 .iter()
80 .any(|asset| asset.name == CHECKSUMS_ASSET)
81 }
82
83 pub fn checksums_url(&self) -> String {
84 asset_url(&self.tag, CHECKSUMS_ASSET)
85 }
86}
87
88/// Parses the BlueGit release list.
89pub fn parse_releases(json: &[u8]) -> Result<Vec<BlueGitRelease>, String> {
90 serde_json::from_slice(json).map_err(|error| format!("release list: {error}"))
91}
92
93/// Parses `sha256sum` output: `<64 hex> <name>` (or `<hex> *<name>`) per line.
94/// Lines that do not look like that are skipped.
95pub fn parse_checksums(text: &str) -> HashMap<String, String> {
96 text.lines()
97 .filter_map(|line| {
98 let (hash, name) = line.trim().split_once(char::is_whitespace)?;
99 let name = name.trim_start().trim_start_matches('*').trim();
100 let valid = hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit());
101 (valid && !name.is_empty()).then(|| (name.to_owned(), hash.to_ascii_lowercase()))
102 })
103 .collect()
104}
105
106/// One release in the GitHub shape upstream's `release_feed::Release` reads.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
108pub struct GitHubRelease {
109 pub tag_name: String,
110 pub draft: bool,
111 pub prerelease: bool,
112 pub assets: Vec<GitHubAsset>,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
116pub struct GitHubAsset {
117 pub name: String,
118 pub browser_download_url: String,
119 pub size: u64,
120 /// `sha256:<hex>`, or `None` when the release has no line for this file. Upstream
121 /// refuses to install an asset without a digest, so a missing checksum is safe.
122 pub digest: Option<String>,
123}
124
125/// Converts one BlueGit release. `checksums` is the parsed `SHA256SUMS` of this
126/// release, or empty when it was not fetched.
127pub fn to_github(release: &BlueGitRelease, checksums: &HashMap<String, String>) -> GitHubRelease {
128 GitHubRelease {
129 tag_name: release.tag.clone(),
130 draft: false,
131 // BlueGit has no pre-release flag. Upstream treats a tag with `-` as a
132 // pre-release by version order already, and offers it only to a build that
133 // runs a pre-release itself (our `-kvt.N` tags do).
134 prerelease: false,
135 assets: release
136 .assets
137 .iter()
138 .filter(|asset| asset.name != CHECKSUMS_ASSET)
139 .map(|asset| GitHubAsset {
140 name: asset.name.clone(),
141 browser_download_url: asset_url(&release.tag, &asset.name),
142 size: asset.size,
143 digest: checksums
144 .get(&asset.name)
145 .map(|hash| format!("sha256:{hash}")),
146 })
147 .collect(),
148 }
149}
150
151/// The GitHub-shaped JSON for a list of converted releases.
152pub fn to_github_json(releases: &[GitHubRelease]) -> Vec<u8> {
153 serde_json::to_vec(releases).unwrap_or_else(|_| b"[]".to_vec())
154}
155
156/// Whether a package manager owns this install, so the app must not look for
157/// updates (not even a notice): the AUR package and any other system package.
158pub fn package_managed() -> bool {
159 package_managed_from(
160 std::env::var(PACKAGE_MANAGED_ENV).ok().as_deref(),
161 option_env!("RUSTY_TEAMS_PACKAGE_MANAGED"),
162 Path::new(PACKAGE_MANAGED_MARKER).exists(),
163 )
164}
165
166fn flag(value: Option<&str>) -> bool {
167 value.is_some_and(|value| {
168 let value = value.trim();
169 !value.is_empty() && value != "0" && !value.eq_ignore_ascii_case("false")
170 })
171}
172
173/// `runtime` is the environment, `compile_time` the same variable during the build
174/// (a source package sets it), `marker_exists` the file the binary package installs.
175pub fn package_managed_from(
176 runtime: Option<&str>,
177 compile_time: Option<&str>,
178 marker_exists: bool,
179) -> bool {
180 flag(runtime) || flag(compile_time) || marker_exists
181}
182
183/// The release asset names CI publishes for `version` (the tag without `v`). The
184/// suffixes must match upstream's `ASSET_SUFFIX` per platform in `release_feed.rs`;
185/// a test there and one here keep both sides in step.
186pub fn release_asset_names(version: &str) -> Vec<String> {
187 ["-linux-amd64", "-linux-amd64.tar.gz", "-windows-amd64.exe"]
188 .iter()
189 .map(|suffix| format!("rusty-teams-{version}{suffix}"))
190 .collect()
191}
192
193#[cfg(test)]
194mod tests {
195 use super::*;
196
197 const LIST: &str = r#"[
198 {"assets":[{"name":"SHA256SUMS","size":200},
199 {"name":"rusty-teams-0.6.1-kvt.2-linux-amd64","size":1234},
200 {"name":"rusty-teams-0.6.1-kvt.2-windows-amd64.exe","size":4321}],
201 "body":"Rusty Teams v0.6.1-kvt.2","commit":"0123456789abcdef0123456789abcdef01234567",
202 "created_at":"2026-11-27T11:53:43Z","id":7,"name":"v0.6.1-kvt.2","tag":"v0.6.1-kvt.2"},
203 {"assets":[],"name":"v0.6.1-kvt.1","tag":"v0.6.1-kvt.1"}
204 ]"#;
205
206 fn hex(byte: char) -> String {
207 std::iter::repeat_n(byte, 64).collect()
208 }
209
210 #[test]
211 fn parses_the_bluegit_list_and_ignores_extra_fields() {
212 let releases = parse_releases(LIST.as_bytes()).unwrap();
213 assert_eq!(releases.len(), 2);
214 assert_eq!(releases[0].tag, "v0.6.1-kvt.2");
215 assert_eq!(releases[0].assets.len(), 3);
216 assert!(releases[0].has_checksums());
217 assert!(!releases[1].has_checksums());
218 assert!(parse_releases(b"[]").unwrap().is_empty());
219 assert!(parse_releases(b"<html>").is_err());
220 assert!(parse_releases(b"").is_err());
221 }
222
223 #[test]
224 fn urls_point_at_git_kvt_nl() {
225 assert_eq!(
226 releases_url(),
227 "https://git.kvt.nl/api/v1/projects/ict/rusty-teams/releases"
228 );
229 assert_eq!(
230 asset_url("v0.6.1-kvt.2", "rusty-teams-0.6.1-kvt.2-windows-amd64.exe"),
231 "https://git.kvt.nl/api/v1/projects/ict/rusty-teams/releases/v0.6.1-kvt.2/assets/rusty-teams-0.6.1-kvt.2-windows-amd64.exe"
232 );
233 assert_eq!(
234 release_page_url("v0.6.1-kvt.2"),
235 "https://git.kvt.nl/ict/rusty-teams/-/releases#v0.6.1-kvt.2"
236 );
237 }
238
239 #[test]
240 fn a_strange_name_cannot_escape_the_asset_path() {
241 assert_eq!(
242 asset_url("v1/../x", "a b?c#d"),
243 "https://git.kvt.nl/api/v1/projects/ict/rusty-teams/releases/v1%2F..%2Fx/assets/a%20b%3Fc%23d"
244 );
245 }
246
247 #[test]
248 fn checksums_parse_like_sha256sum_output() {
249 let text = format!(
250 "{} rusty-teams-0.6.1-linux-amd64\n{} *rusty-teams-0.6.1-windows-amd64.exe\r\nnot a line\n{} short\n\n",
251 hex('a'),
252 hex('B'),
253 "abc"
254 );
255 let sums = parse_checksums(&text);
256 assert_eq!(sums.len(), 2);
257 assert_eq!(sums["rusty-teams-0.6.1-linux-amd64"], hex('a'));
258 assert_eq!(sums["rusty-teams-0.6.1-windows-amd64.exe"], hex('b'));
259 }
260
261 #[test]
262 fn conversion_fills_url_size_and_digest_and_drops_the_checksum_file() {
263 let releases = parse_releases(LIST.as_bytes()).unwrap();
264 let mut sums = HashMap::new();
265 sums.insert("rusty-teams-0.6.1-kvt.2-linux-amd64".to_owned(), hex('c'));
266 let converted = to_github(&releases[0], &sums);
267 assert_eq!(converted.tag_name, "v0.6.1-kvt.2");
268 assert!(!converted.draft && !converted.prerelease);
269 assert_eq!(converted.assets.len(), 2);
270 let linux = &converted.assets[0];
271 assert_eq!(linux.size, 1234);
272 assert_eq!(
273 linux.digest.as_deref(),
274 Some(format!("sha256:{}", hex('c')).as_str())
275 );
276 assert!(
277 linux
278 .browser_download_url
279 .ends_with("/assets/rusty-teams-0.6.1-kvt.2-linux-amd64")
280 );
281 // No checksum line: no digest, and upstream then refuses the download.
282 assert_eq!(converted.assets[1].digest, None);
283 }
284
285 #[test]
286 fn the_json_reads_back_in_the_github_shape() {
287 let releases = parse_releases(LIST.as_bytes()).unwrap();
288 let converted: Vec<_> = releases
289 .iter()
290 .map(|r| to_github(r, &HashMap::new()))
291 .collect();
292 let value: serde_json::Value = serde_json::from_slice(&to_github_json(&converted)).unwrap();
293 assert_eq!(value[0]["tag_name"], "v0.6.1-kvt.2");
294 assert!(
295 !value[0]["assets"][0]["browser_download_url"]
296 .as_str()
297 .unwrap()
298 .is_empty()
299 );
300 assert_eq!(value[0]["assets"][0]["size"], 1234);
301 assert!(value[0]["assets"][0]["digest"].is_null());
302 assert_eq!(value[1]["assets"].as_array().unwrap().len(), 0);
303 }
304
305 #[test]
306 fn package_managed_installs_never_check() {
307 assert!(!package_managed_from(None, None, false));
308 assert!(!package_managed_from(Some(""), Some("0"), false));
309 assert!(!package_managed_from(Some("false"), None, false));
310 assert!(package_managed_from(Some("1"), None, false));
311 assert!(package_managed_from(None, Some("aur"), false));
312 assert!(package_managed_from(None, None, true));
313 }
314
315 #[test]
316 fn published_names_end_with_the_suffix_each_platform_installs() {
317 let names = release_asset_names("0.6.1-kvt.2");
318 // Upstream release_feed.rs: ASSET_SUFFIX for Linux and Windows x86_64.
319 for suffix in ["-linux-amd64", "-windows-amd64.exe"] {
320 let matching: Vec<_> = names.iter().filter(|name| name.ends_with(suffix)).collect();
321 assert_eq!(matching.len(), 1, "{suffix}");
322 }
323 assert!(names.contains(&"rusty-teams-0.6.1-kvt.2-linux-amd64".to_owned()));
324 // The tarball must not be taken for the bare Linux binary.
325 assert!(!"rusty-teams-0.6.1-kvt.2-linux-amd64.tar.gz".ends_with("-linux-amd64"));
326 }
327}