BlueGit

ict rusty-teams

Files

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

lib.rs

lib.rs 12.5 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 [
188 "-linux-amd64",
189 "-linux-amd64.tar.gz",
190 "-windows-amd64.exe",
191 "-windows-arm64.exe",
192 ]
193 .iter()
194 .map(|suffix| format!("rusty-teams-{version}{suffix}"))
195 .collect()
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 const LIST: &str = r#"[
203 {"assets":[{"name":"SHA256SUMS","size":200},
204 {"name":"rusty-teams-0.6.1-kvt.2-linux-amd64","size":1234},
205 {"name":"rusty-teams-0.6.1-kvt.2-windows-amd64.exe","size":4321}],
206 "body":"Rusty Teams v0.6.1-kvt.2","commit":"0123456789abcdef0123456789abcdef01234567",
207 "created_at":"2026-11-27T11:53:43Z","id":7,"name":"v0.6.1-kvt.2","tag":"v0.6.1-kvt.2"},
208 {"assets":[],"name":"v0.6.1-kvt.1","tag":"v0.6.1-kvt.1"}
209 ]"#;
210
211 fn hex(byte: char) -> String {
212 std::iter::repeat_n(byte, 64).collect()
213 }
214
215 #[test]
216 fn parses_the_bluegit_list_and_ignores_extra_fields() {
217 let releases = parse_releases(LIST.as_bytes()).unwrap();
218 assert_eq!(releases.len(), 2);
219 assert_eq!(releases[0].tag, "v0.6.1-kvt.2");
220 assert_eq!(releases[0].assets.len(), 3);
221 assert!(releases[0].has_checksums());
222 assert!(!releases[1].has_checksums());
223 assert!(parse_releases(b"[]").unwrap().is_empty());
224 assert!(parse_releases(b"<html>").is_err());
225 assert!(parse_releases(b"").is_err());
226 }
227
228 #[test]
229 fn urls_point_at_git_kvt_nl() {
230 assert_eq!(
231 releases_url(),
232 "https://git.kvt.nl/api/v1/projects/ict/rusty-teams/releases"
233 );
234 assert_eq!(
235 asset_url("v0.6.1-kvt.2", "rusty-teams-0.6.1-kvt.2-windows-amd64.exe"),
236 "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"
237 );
238 assert_eq!(
239 release_page_url("v0.6.1-kvt.2"),
240 "https://git.kvt.nl/ict/rusty-teams/-/releases#v0.6.1-kvt.2"
241 );
242 }
243
244 #[test]
245 fn a_strange_name_cannot_escape_the_asset_path() {
246 assert_eq!(
247 asset_url("v1/../x", "a b?c#d"),
248 "https://git.kvt.nl/api/v1/projects/ict/rusty-teams/releases/v1%2F..%2Fx/assets/a%20b%3Fc%23d"
249 );
250 }
251
252 #[test]
253 fn checksums_parse_like_sha256sum_output() {
254 let text = format!(
255 "{} rusty-teams-0.6.1-linux-amd64\n{} *rusty-teams-0.6.1-windows-amd64.exe\r\nnot a line\n{} short\n\n",
256 hex('a'),
257 hex('B'),
258 "abc"
259 );
260 let sums = parse_checksums(&text);
261 assert_eq!(sums.len(), 2);
262 assert_eq!(sums["rusty-teams-0.6.1-linux-amd64"], hex('a'));
263 assert_eq!(sums["rusty-teams-0.6.1-windows-amd64.exe"], hex('b'));
264 }
265
266 #[test]
267 fn conversion_fills_url_size_and_digest_and_drops_the_checksum_file() {
268 let releases = parse_releases(LIST.as_bytes()).unwrap();
269 let mut sums = HashMap::new();
270 sums.insert("rusty-teams-0.6.1-kvt.2-linux-amd64".to_owned(), hex('c'));
271 let converted = to_github(&releases[0], &sums);
272 assert_eq!(converted.tag_name, "v0.6.1-kvt.2");
273 assert!(!converted.draft && !converted.prerelease);
274 assert_eq!(converted.assets.len(), 2);
275 let linux = &converted.assets[0];
276 assert_eq!(linux.size, 1234);
277 assert_eq!(
278 linux.digest.as_deref(),
279 Some(format!("sha256:{}", hex('c')).as_str())
280 );
281 assert!(
282 linux
283 .browser_download_url
284 .ends_with("/assets/rusty-teams-0.6.1-kvt.2-linux-amd64")
285 );
286 // No checksum line: no digest, and upstream then refuses the download.
287 assert_eq!(converted.assets[1].digest, None);
288 }
289
290 #[test]
291 fn the_json_reads_back_in_the_github_shape() {
292 let releases = parse_releases(LIST.as_bytes()).unwrap();
293 let converted: Vec<_> = releases
294 .iter()
295 .map(|r| to_github(r, &HashMap::new()))
296 .collect();
297 let value: serde_json::Value = serde_json::from_slice(&to_github_json(&converted)).unwrap();
298 assert_eq!(value[0]["tag_name"], "v0.6.1-kvt.2");
299 assert!(
300 !value[0]["assets"][0]["browser_download_url"]
301 .as_str()
302 .unwrap()
303 .is_empty()
304 );
305 assert_eq!(value[0]["assets"][0]["size"], 1234);
306 assert!(value[0]["assets"][0]["digest"].is_null());
307 assert_eq!(value[1]["assets"].as_array().unwrap().len(), 0);
308 }
309
310 #[test]
311 fn package_managed_installs_never_check() {
312 assert!(!package_managed_from(None, None, false));
313 assert!(!package_managed_from(Some(""), Some("0"), false));
314 assert!(!package_managed_from(Some("false"), None, false));
315 assert!(package_managed_from(Some("1"), None, false));
316 assert!(package_managed_from(None, Some("aur"), false));
317 assert!(package_managed_from(None, None, true));
318 }
319
320 #[test]
321 fn published_names_end_with_the_suffix_each_platform_installs() {
322 let names = release_asset_names("0.6.1-kvt.2");
323 // Upstream release_feed.rs: ASSET_SUFFIX for Linux, Windows x86_64 and Windows ARM64.
324 for suffix in ["-linux-amd64", "-windows-amd64.exe", "-windows-arm64.exe"] {
325 let matching: Vec<_> = names.iter().filter(|name| name.ends_with(suffix)).collect();
326 assert_eq!(matching.len(), 1, "{suffix}");
327 }
328 assert!(names.contains(&"rusty-teams-0.6.1-kvt.2-linux-amd64".to_owned()));
329 // The tarball must not be taken for the bare Linux binary.
330 assert!(!"rusty-teams-0.6.1-kvt.2-linux-amd64.tar.gz".ends_with("-linux-amd64"));
331 }
332}