diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 7fad59726..31f7def7c 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -60,6 +60,56 @@ dependencies = [ "equator", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -842,6 +892,46 @@ dependencies = [ "libloading", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + [[package]] name = "cocoa" version = "0.25.0" @@ -919,6 +1009,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "command-fds" version = "0.3.3" @@ -2471,10 +2567,12 @@ dependencies = [ name = "horizon-launcher" version = "0.1.0" dependencies = [ + "clap", "dirs 5.0.1", "flate2", "gpui", "pulldown-cmark", + "self-replace", "serde", "serde_json", "tar", @@ -2826,6 +2924,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itertools" version = "0.13.0" @@ -3586,6 +3690,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "oo7" version = "0.5.0" @@ -4706,6 +4816,17 @@ dependencies = [ "libc", ] +[[package]] +name = "self-replace" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03ec815b5eab420ab893f63393878d89c90fdd94c0bcc44c07abb8ad95552fb7" +dependencies = [ + "fastrand 2.5.0", + "tempfile", + "windows-sys 0.52.0", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -5060,6 +5181,12 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.26.3" @@ -5893,6 +6020,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "uuid" version = "1.28.0" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index b8432b31c..d2f3f020a 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -17,6 +17,8 @@ flate2 = "1" tar = { version = "0.4", default-features = false } zip = { version = "2", default-features = false, features = ["deflate"] } dirs = "5" +self-replace = "1" +clap = { version = "4", features = ["derive"] } [profile.release] strip = true diff --git a/launcher/assets/fonts/Inter-Medium.ttf b/launcher/assets/fonts/Inter-Medium.ttf deleted file mode 100644 index 458cd0601..000000000 Binary files a/launcher/assets/fonts/Inter-Medium.ttf and /dev/null differ diff --git a/launcher/assets/fonts/Inter-Regular.ttf b/launcher/assets/fonts/Inter-Regular.ttf deleted file mode 100644 index b7aaca8de..000000000 Binary files a/launcher/assets/fonts/Inter-Regular.ttf and /dev/null differ diff --git a/launcher/assets/fonts/Inter-SemiBold.ttf b/launcher/assets/fonts/Inter-SemiBold.ttf deleted file mode 100644 index 47f8ab1d6..000000000 Binary files a/launcher/assets/fonts/Inter-SemiBold.ttf and /dev/null differ diff --git a/launcher/assets/fonts/LICENSE.txt b/launcher/assets/fonts/LICENSE.txt deleted file mode 100644 index 9b2ca37b3..000000000 --- a/launcher/assets/fonts/LICENSE.txt +++ /dev/null @@ -1,92 +0,0 @@ -Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION AND CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index b589775e2..c91d49b9f 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -93,13 +93,18 @@ pub fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering { .unwrap_or(std::cmp::Ordering::Equal) } -/// Every published release of the repository, both kinds, with the asset named `asset`. -fn all_releases(asset: Option<&str>) -> Result, String> { +/// Every published release of the repository, both kinds, as GitHub's JSON. +fn release_list() -> Result { let url = format!("https://api.github.com/repos/{REPO}/releases?per_page=100"); - let list: serde_json::Value = get(&url)?.into_json().map_err(|e| e.to_string())?; + get(&url)?.into_json().map_err(|e| e.to_string()) +} + +/// The releases in `list` whose tag passes `keep`, newest first, with the asset named `asset`. +fn parse_releases(list: &serde_json::Value, asset: Option<&str>, keep: fn(&str) -> bool) -> Vec { let mut out = Vec::new(); for r in list.as_array().into_iter().flatten() { - if r["draft"].as_bool().unwrap_or(false) { + let tag = r["tag_name"].as_str().unwrap_or_default(); + if r["draft"].as_bool().unwrap_or(false) || !keep(tag) { continue; } let found = r["assets"].as_array().into_iter().flatten().find_map(|a| { @@ -107,30 +112,30 @@ fn all_releases(asset: Option<&str>) -> Result, String> { .then(|| Some((a["browser_download_url"].as_str()?.to_string(), a["size"].as_u64()?)))? }); out.push(Release { - tag: r["tag_name"].as_str().unwrap_or_default().into(), + tag: tag.into(), name: r["name"].as_str().unwrap_or_default().into(), body: r["body"].as_str().unwrap_or_default().replace("\r\n", "\n"), date: r["published_at"].as_str().unwrap_or_default().chars().take(10).collect(), asset: found, }); } - Ok(out) + out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); + out +} + +fn is_launcher_tag(tag: &str) -> bool { + launcher_version(tag).is_some() } /// Published Horizon releases, newest first. Drafts never reach the anonymous API, and launcher /// releases are left out. pub fn releases() -> Result, String> { - let mut out: Vec = all_releases(ASSET)?.into_iter().filter(|r| is_game_tag(&r.tag)).collect(); - out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); - Ok(out) + Ok(parse_releases(&release_list()?, ASSET, is_game_tag)) } /// Published launcher releases (`launcher-v…`), newest first, with this platform's archive. pub fn launcher_releases() -> Result, String> { - let mut out: Vec = - all_releases(LAUNCHER_ASSET)?.into_iter().filter(|r| launcher_version(&r.tag).is_some()).collect(); - out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); - Ok(out) + Ok(parse_releases(&release_list()?, LAUNCHER_ASSET, is_launcher_tag)) } /// The newest Horizon release that has a build for this platform. @@ -189,34 +194,43 @@ pub fn installed() -> Vec { tags } +fn download(url: &str, size: u64, to: &Path, progress: &impl Fn(f32)) -> Result<(), String> { + let mut reader = get(url)?.into_reader(); + let mut file = fs::File::create(to).map_err(|e| e.to_string())?; + let (mut done, mut buf) = (0u64, vec![0u8; 1 << 16]); + loop { + let n = reader.read(&mut buf).map_err(|e| format!("Download interrupted: {e}"))?; + if n == 0 { + return Ok(()); + } + file.write_all(&buf[..n]).map_err(|e| e.to_string())?; + done += n as u64; + progress((done as f32 / size.max(1) as f32).min(1.0) * 0.9); + } +} + +fn unpack(archive: &Path, url: &str, to: &Path) -> Result<(), String> { + let file = fs::File::open(archive).map_err(|e| e.to_string())?; + if url.ends_with(".tar.gz") { + tar::Archive::new(flate2::read::GzDecoder::new(file)).unpack(to).map_err(|e| e.to_string()) + } else { + zip::ZipArchive::new(file).and_then(|mut z| z.extract(to)).map_err(|e| e.to_string()) + } +} + /// Downloads and unpacks one release; `progress` gets the fraction done. pub fn install(tag: &str, url: &str, size: u64, progress: impl Fn(f32)) -> Result<(), String> { + if !is_game_tag(tag) { + return Err(format!("{tag} is not a Horizon release.")); + } let root = versions_dir(); let partial = root.join(format!(".{tag}.partial")); let _ = fs::remove_dir_all(&partial); fs::create_dir_all(&partial).map_err(|e| e.to_string())?; let archive = partial.join("download"); - { - let mut reader = get(url)?.into_reader(); - let mut file = fs::File::create(&archive).map_err(|e| e.to_string())?; - let (mut done, mut buf) = (0u64, vec![0u8; 1 << 16]); - loop { - let n = reader.read(&mut buf).map_err(|e| format!("Download interrupted: {e}"))?; - if n == 0 { - break; - } - file.write_all(&buf[..n]).map_err(|e| e.to_string())?; - done += n as u64; - progress((done as f32 / size.max(1) as f32).min(1.0) * 0.9); - } - } + download(url, size, &archive, &progress)?; let unpacked = partial.join("unpacked"); - let file = fs::File::open(&archive).map_err(|e| e.to_string())?; - if url.ends_with(".tar.gz") { - tar::Archive::new(flate2::read::GzDecoder::new(file)).unpack(&unpacked).map_err(|e| e.to_string())?; - } else { - zip::ZipArchive::new(file).and_then(|mut z| z.extract(&unpacked)).map_err(|e| e.to_string())?; - } + unpack(&archive, url, &unpacked)?; progress(0.97); // The archives hold one top folder (horizon-linux-x86_64/...); the version folder is its contents. let entries: Vec<_> = fs::read_dir(&unpacked).map_err(|e| e.to_string())?.flatten().collect(); @@ -345,6 +359,185 @@ pub fn agree_eula(folder: &Path) -> Result<(), String> { fs::write(folder.join("eula.txt"), text).map_err(|e| e.to_string()) } +// ----- Updates ----------------------------------------------------------------------------------- + +/// What a check found: a Horizon build newer than every installed one, and a newer launcher. +#[derive(Clone, Debug, Default, serde::Serialize)] +pub struct Updates { + pub horizon: Option, + pub launcher: Option, +} + +/// The newest Horizon release with a build here, if it is newer than every installed version. +pub fn horizon_update(releases: &[Release], installed: &[String]) -> Option { + let newest = latest(releases)?; + let newer = installed.iter().all(|t| compare_versions(&newest.tag, t).is_gt()); + newer.then(|| newest.clone()) +} + +/// The newest launcher release with an archive for this platform, if newer than this launcher. +pub fn launcher_update(releases: &[Release]) -> Option { + releases + .iter() + .find(|r| r.asset.is_some()) + .filter(|r| compare_versions(launcher_version(&r.tag).unwrap_or("0"), VERSION).is_gt()) + .cloned() +} + +/// One request to GitHub, both kinds of update. +pub fn check_updates() -> Result { + let list = release_list()?; + Ok(Updates { + horizon: horizon_update(&parse_releases(&list, ASSET, is_game_tag), &installed()), + launcher: launcher_update(&parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag)), + }) +} + +/// Whether a version installed as an update becomes the selected one: only when the player was +/// on the newest installed version before (or had none). +pub fn select_after_update(selected: Option<&str>, installed_before: &[String]) -> bool { + match selected { + None => true, + Some(s) => installed_before.first().is_none_or(|newest| newest == s), + } +} + +/// Installs `tag` (or the newest release with "latest"), then updates the selection as +/// `select_after_update` says when `as_update`, or always selects it otherwise. +pub fn install_tag(tag: &str, as_update: bool, progress: impl Fn(f32)) -> Result { + let releases = releases()?; + let release = if tag == "latest" { + latest(&releases).ok_or("No release has a build for this platform yet.")? + } else { + releases.iter().find(|r| r.tag == tag).ok_or_else(|| format!("No Horizon release is tagged {tag}."))? + }; + let (url, size) = release.asset.clone().ok_or_else(|| format!("{} has no build for this platform.", release.tag))?; + let before = installed(); + install(&release.tag, &url, size, progress)?; + let mut settings = Settings::load(); + if !as_update || select_after_update(settings.selected.as_deref(), &before) { + settings.selected = Some(release.tag.clone()); + settings.save(); + } + Ok(release.tag.clone()) +} + +/// The launcher's own path, read once at start: after a self-update the running file is gone. +pub fn exe_path() -> &'static Path { + static EXE: std::sync::OnceLock = std::sync::OnceLock::new(); + EXE.get_or_init(|| std::env::current_exe().unwrap_or_else(|_| PathBuf::from(LAUNCHER_BINARY))) +} + +/// Development builds and `HORIZON_LAUNCHER_NO_SELF_UPDATE` never replace themselves. +pub fn self_update_allowed() -> bool { + !cfg!(debug_assertions) && std::env::var_os("HORIZON_LAUNCHER_NO_SELF_UPDATE").is_none() +} + +/// Downloads a launcher release and puts its binary in place of this one. The running process +/// keeps working; `restart` starts the new one. +pub fn self_update(release: &Release, progress: impl Fn(f32)) -> Result<(), String> { + let (url, size) = release.asset.clone().ok_or("This launcher release has no build for this platform.")?; + let work = data_dir().join(".launcher-update"); + let _ = fs::remove_dir_all(&work); + fs::create_dir_all(&work).map_err(|e| e.to_string())?; + let archive = work.join("download"); + download(&url, size, &archive, &progress)?; + let unpacked = work.join("unpacked"); + unpack(&archive, &url, &unpacked)?; + let binary = find_file(&unpacked, LAUNCHER_BINARY).ok_or("The download has no launcher binary.")?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&binary, fs::Permissions::from_mode(0o755)); + } + self_replace::self_replace(&binary).map_err(|e| format!("Could not replace the launcher: {e}"))?; + let _ = fs::remove_dir_all(&work); + progress(1.0); + Ok(()) +} + +fn find_file(dir: &Path, name: &str) -> Option { + for entry in fs::read_dir(dir).ok()?.flatten() { + let path = entry.path(); + if path.is_dir() { + if let Some(found) = find_file(&path, name) { + return Some(found); + } + } else if entry.file_name() == name { + return Some(path); + } + } + None +} + +/// Starts the launcher again (the updated binary) with the same arguments, and exits. +pub fn restart() -> ! { + let _ = Command::new(exe_path()).args(std::env::args_os().skip(1)).spawn(); + std::process::exit(0) +} + +/// Plain text from markdown, for terminals: headings on their own lines, bullets as "- ", +/// links followed by their address. +pub fn markdown_to_text(md: &str) -> String { + use pulldown_cmark::{Event, Parser, Tag, TagEnd}; + let mut out = String::new(); + let mut links = Vec::new(); + let mut lists: Vec> = Vec::new(); + for event in Parser::new(md) { + match event { + Event::Start(Tag::Item) => { + let depth = lists.len().saturating_sub(1); + out.push_str(&" ".repeat(depth)); + match lists.last_mut() { + Some(Some(n)) => { + out.push_str(&format!("{n}. ")); + *n += 1; + } + _ => out.push_str("- "), + } + } + Event::Start(Tag::List(start)) => { + if !out.ends_with('\n') && !out.is_empty() { + out.push('\n'); + } + lists.push(start) + } + Event::End(TagEnd::List(_)) => { + lists.pop(); + if lists.is_empty() { + out.push('\n'); + } + } + Event::Start(Tag::Link { dest_url, .. }) => links.push(dest_url.to_string()), + Event::End(TagEnd::Link) => { + if let Some(url) = links.pop() { + out.push_str(&format!(" ({url})")); + } + } + Event::End(TagEnd::Heading(_)) => out.push_str("\n\n"), + Event::End(TagEnd::Paragraph) => out.push_str(if lists.is_empty() { "\n\n" } else { "\n" }), + Event::End(TagEnd::Item) if !out.ends_with('\n') => out.push('\n'), + Event::End(TagEnd::CodeBlock) => out.push('\n'), + Event::Text(t) | Event::Code(t) => out.push_str(&t), + Event::SoftBreak | Event::HardBreak => out.push('\n'), + Event::Rule => out.push_str("---\n\n"), + _ => {} + } + } + out.trim_end().to_string() + "\n" +} + +/// The first sentence-like line of a release's notes, for a one-line summary. +pub fn notes_summary(body: &str) -> Option { + let text = markdown_to_text(body); + let line = text.lines().map(str::trim).find(|l| l.len() > 24 && !l.starts_with("---"))?; + let line = line.trim_start_matches("- "); + Some(match line.char_indices().nth(140) { + Some((i, _)) => format!("{}…", line[..i].trim_end()), + None => line.to_string(), + }) +} + #[derive(Clone, Copy, PartialEq, Debug)] pub enum Job { Prepare, @@ -425,6 +618,8 @@ pub struct Settings { pub selected: Option, pub minecraft_dir: Option, pub server_dir: Option, + #[serde(default)] + pub auto_install: bool, } impl Settings { @@ -439,3 +634,59 @@ impl Settings { let _ = fs::write(data_dir().join("settings.json"), serde_json::to_string_pretty(self).unwrap()); } } + +#[cfg(test)] +mod tests { + use super::*; + use std::cmp::Ordering::*; + + #[test] + fn tags_never_mix() { + assert!(is_game_tag("v2026.10.13")); + assert!(!is_game_tag("launcher-v0.2.0")); + assert!(!is_game_tag("vnext")); + assert_eq!(launcher_version("launcher-v0.2.0"), Some("0.2.0")); + assert_eq!(launcher_version("v2026.10.13"), None); + assert_eq!(launcher_version("launcher-vx"), None); + let list = serde_json::json!([ + {"tag_name": "v2026.10.12", "assets": [{"name": "horizon-linux-x86_64.tar.gz", "browser_download_url": "u", "size": 1}]}, + {"tag_name": "launcher-v9.0.0", "assets": [{"name": "horizon-launcher-linux-x86_64.tar.gz", "browser_download_url": "u", "size": 1}]}, + {"tag_name": "v2026.10.13", "assets": []}, + {"tag_name": "launcher-v0.0.1", "draft": true, "assets": []}, + ]); + let game: Vec<_> = parse_releases(&list, ASSET, is_game_tag).into_iter().map(|r| r.tag).collect(); + assert_eq!(game, ["v2026.10.13", "v2026.10.12"]); + let launcher: Vec<_> = parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag).into_iter().map(|r| r.tag).collect(); + assert_eq!(launcher, ["launcher-v9.0.0"]); + } + + #[test] + fn versions_compare_by_number() { + assert_eq!(compare_versions("v2026.10.13", "v2026.10.12"), Greater); + assert_eq!(compare_versions("v2026.9.30", "v2026.10.1"), Less); + assert_eq!(compare_versions("v2026.10.13.1", "v2026.10.13"), Greater); + assert_eq!(compare_versions("0.10.0", "0.9.9"), Greater); + assert_eq!(compare_versions("launcher-v1.2", "1.2.0"), Equal); + assert_eq!(compare_versions("1.0.0-rc1", "1.0.0"), Equal); + } + + #[test] + fn updates() { + let r = |tag: &str| Release { tag: tag.into(), name: String::new(), body: String::new(), date: String::new(), asset: Some(("u".into(), 1)) }; + let releases = [r("v2026.10.13"), r("v2026.10.12")]; + assert_eq!(horizon_update(&releases, &["v2026.10.12".into()]).map(|r| r.tag), Some("v2026.10.13".into())); + assert!(horizon_update(&releases, &["v2026.10.13".into()]).is_none()); + assert!(launcher_update(&[r("launcher-v0.0.1")]).is_none()); + assert!(launcher_update(&[r("launcher-v99.0.0")]).is_some()); + let installed = ["v2026.10.12".to_string(), "v2026.10.1".to_string()]; + assert!(select_after_update(Some("v2026.10.12"), &installed)); + assert!(!select_after_update(Some("v2026.10.1"), &installed)); + assert!(select_after_update(None, &installed)); + } + + #[test] + fn plain_notes() { + let text = markdown_to_text("# Title\n\nSome *words* and [a link](https://x.y).\n\n- one\n- two\n"); + assert_eq!(text, "Title\n\nSome words and a link (https://x.y).\n\n- one\n- two\n"); + } +}