Updates: opt-in launch check, Check for Updates…, install after a normal quit, from the Gitea release; dmgs carry an Applications link (UPD-1, REL-1)

This commit is contained in:
ZacharyZhang-NY committed 2026-10-09 16:34:32 -04:00
1 parent fa273aff13
commit b03c9f2853
28 files changed
+896 -16

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
//! Puts a downloaded release in place of the running app.
use std::{
io,
path::{Path, PathBuf},
process::{Command, Stdio},
};
/// The `.app` running this process; none in dev builds.
pub fn running_bundle() -> io::Result<Option<PathBuf>> {
let exe = std::env::current_exe()?;
Ok(bundle_of(&exe).map(Path::to_path_buf))
}
fn bundle_of(exe: &Path) -> Option<&Path> {
exe.ancestors().find(|dir| dir.extension().is_some_and(|ext| ext == "app"))
}
/// Replaces `bundle` with the same-named app inside `dmg`.
#[cfg(target_os = "macos")]
pub fn install(dmg: &Path, bundle: &Path) -> io::Result<()> {
let name = bundle.file_name().ok_or_else(|| io::Error::other("the app has no name"))?;
let parent = bundle.parent().ok_or_else(|| io::Error::other("the app has no folder"))?;
let mount = tempfile::tempdir()?;
run(Command::new("hdiutil").args(["attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint"]).arg(mount.path()).arg(dmg))?;
let copied = stage(&mount.path().join(name), parent, name);
let detached = run(Command::new("hdiutil").args(["detach", "-force"]).arg(mount.path()));
let staged = copied?;
detached?;
swap(&staged, bundle)
}
#[cfg(not(target_os = "macos"))]
pub fn install(_dmg: &Path, _bundle: &Path) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "installing updates is not built for this platform"))
}
/// Copies the new app beside the old, hidden.
#[cfg(target_os = "macos")]
fn stage(from: &Path, parent: &Path, name: &std::ffi::OsStr) -> io::Result<PathBuf> {
if !from.is_dir() {
return Err(io::Error::new(io::ErrorKind::NotFound, format!("the download holds no {}", name.to_string_lossy())));
}
let staged = parent.join(format!(".{}.new", name.to_string_lossy()));
if staged.exists() {
std::fs::remove_dir_all(&staged)?;
}
run(Command::new("ditto").arg(from).arg(&staged))?;
Ok(staged)
}
/// Puts `staged` at `bundle`; on failure the old returns.
fn swap(staged: &Path, bundle: &Path) -> io::Result<()> {
let name = bundle.file_name().ok_or_else(|| io::Error::other("the app has no name"))?;
let old = bundle.with_file_name(format!(".{}.old", name.to_string_lossy()));
if old.exists() {
std::fs::remove_dir_all(&old)?;
}
std::fs::rename(bundle, &old)?;
if let Err(error) = std::fs::rename(staged, bundle) {
std::fs::rename(&old, bundle)?;
return Err(error);
}
log::info!("install: {} replaced", bundle.display());
// Installed: an old copy left behind is only untidy.
if let Err(error) = std::fs::remove_dir_all(&old) {
log::warn!("install: the old copy at {} stays: {error}", old.display());
}
Ok(())
}
/// Returns once process `pid` has ended.
#[cfg(unix)]
pub fn wait_for_exit(pid: u32) {
while unsafe { libc::kill(pid as libc::pid_t, 0) } == 0 {
std::thread::sleep(std::time::Duration::from_millis(200));
}
}
#[cfg(not(unix))]
pub fn wait_for_exit(_pid: u32) {}
/// Opens `bundle` as a fresh launch.
#[cfg(target_os = "macos")]
pub fn reopen(bundle: &Path) -> io::Result<()> {
run(Command::new("open").arg(bundle))
}
#[cfg(not(target_os = "macos"))]
pub fn reopen(_bundle: &Path) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "reopening after an update is not built for this platform"))
}
/// Runs `command`; a failure carries what it said.
#[cfg(target_os = "macos")]
fn run(command: &mut Command) -> io::Result<()> {
let out = command.stdin(Stdio::null()).output()?;
if out.status.success() {
return Ok(());
}
let said = String::from_utf8_lossy(&out.stderr);
Err(io::Error::other(format!("{:?} failed ({}): {}", command.get_program(), out.status, said.trim())))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_bundle_is_the_nearest_app_folder() {
let exe = Path::new("/Applications/ElyDoc.app/Contents/MacOS/ely-doc");
assert_eq!(bundle_of(exe), Some(Path::new("/Applications/ElyDoc.app")));
assert_eq!(bundle_of(Path::new("/repo/target/debug/ely-doc")), None);
}
#[test]
fn a_swap_replaces_the_app_and_leaves_no_copy() {
let dir = tempfile::tempdir().expect("a temp dir");
let (bundle, staged) = (dir.path().join("ElyDoc.app"), dir.path().join(".ElyDoc.app.new"));
std::fs::create_dir_all(bundle.join("old")).expect("the old app");
std::fs::create_dir_all(staged.join("new")).expect("the new app");
swap(&staged, &bundle).expect("swaps");
assert!(bundle.join("new").exists() && !bundle.join("old").exists());
assert_eq!(std::fs::read_dir(dir.path()).expect("lists").count(), 1, "nothing else is left");
}
#[cfg(target_os = "macos")]
#[test]
fn an_old_copy_that_will_not_go_leaves_the_install_done() {
let dir = tempfile::tempdir().expect("a temp dir");
let (bundle, staged) = (dir.path().join("ElyDoc.app"), dir.path().join(".ElyDoc.app.new"));
std::fs::create_dir_all(&bundle).expect("the old app");
std::fs::write(bundle.join("version"), "old").expect("marks it");
std::fs::create_dir_all(&staged).expect("the new app");
std::fs::write(staged.join("version"), "new").expect("marks it");
run(Command::new("chflags").arg("uchg").arg(bundle.join("version"))).expect("locks a file");
swap(&staged, &bundle).expect("installed although the old copy stays");
assert_eq!(std::fs::read_to_string(bundle.join("version")).expect("reads"), "new");
let old = dir.path().join(".ElyDoc.app.old");
run(Command::new("chflags").arg("nouchg").arg(old.join("version"))).expect("unlocks");
}
#[cfg(target_os = "macos")]
#[test]
fn a_dmg_installs_over_the_app() {
let dir = tempfile::tempdir().expect("a temp dir");
let source = dir.path().join("src");
std::fs::create_dir_all(source.join("ElyDoc.app/Contents")).expect("the new app");
std::fs::write(source.join("ElyDoc.app/Contents/version"), "new").expect("marks it");
let dmg = dir.path().join("ElyDoc.dmg");
run(Command::new("hdiutil").args(["create", "-quiet", "-fs", "HFS+", "-srcfolder"]).arg(&source).arg(&dmg)).expect("a dmg");
let bundle = dir.path().join("Applications/ElyDoc.app");
std::fs::create_dir_all(bundle.join("Contents")).expect("the old app");
std::fs::write(bundle.join("Contents/version"), "old").expect("marks it");
install(&dmg, &bundle).expect("installs");
assert_eq!(std::fs::read_to_string(bundle.join("Contents/version")).expect("reads"), "new");
let empty = dir.path().join("Applications/Other.app");
assert!(install(&dmg, &empty).is_err(), "a dmg without that app is refused");
}
}
+2
View File
@@ -7,12 +7,14 @@ mod dirs;
pub mod env;
pub mod git;
pub mod graphics;
pub mod install;
pub mod instance;
pub mod locale;
pub mod lock;
pub mod logging;
pub mod media;
pub mod print;
pub mod release;
pub mod settings;
pub mod startup;
pub mod storage;
+46
View File
@@ -0,0 +1,46 @@
//! The newest release's files, as the release server lists them.
use anyhow::{Context, Result, bail};
use serde::Deserialize;
#[derive(Deserialize)]
struct Latest {
tag_name: String,
assets: Vec<Asset>,
}
#[derive(Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
/// Where the latest release at `api` keeps the file `name`.
pub fn asset_url(api: &str, name: &str) -> Result<String> {
let text = crate::update::fetch(&crate::update::manifest_agent(), api)?
.body_mut()
.with_config()
.limit(1 << 20)
.read_to_string()
.context("cannot read the latest release")?;
asset_in(&text, name)
}
fn asset_in(text: &str, name: &str) -> Result<String> {
let latest: Latest = serde_json::from_str(text).context("the latest release is not valid")?;
match latest.assets.into_iter().find(|asset| asset.name == name) {
Some(asset) => Ok(asset.browser_download_url),
None => bail!("release {} has no {name}", latest.tag_name),
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_named_file_is_found_or_said_missing() {
let text = r#"{"tag_name":"v0.1.2","assets":[{"name":"ely-doc.json","browser_download_url":"https://h/d.json"}]}"#;
assert_eq!(super::asset_in(text, "ely-doc.json").unwrap(), "https://h/d.json");
let missing = super::asset_in(text, "ely-tree.json").unwrap_err().to_string();
assert_eq!(missing, "release v0.1.2 has no ely-tree.json");
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use serde_json::{Map, Value};
use crate::{AppId, lock::FileLock};
mod shared;
pub use shared::{APPEARANCE, AUTHOR, Appearance, LANGUAGE, Language, MOTION, Motion, OMARCHY_SYNC, Shared, word};
pub use shared::{APPEARANCE, AUTHOR, Appearance, CHECK_UPDATES, LANGUAGE, Language, MOTION, Motion, OMARCHY_SYNC, Shared, word};
/// The layout this build reads and writes.
pub const VERSION: u64 = 1;
@@ -38,6 +38,7 @@ pub const LANGUAGE: &str = "language";
pub const MOTION: &str = "motion";
pub const OMARCHY_SYNC: &str = "omarchy_sync";
pub const AUTHOR: &str = "author";
pub const CHECK_UPDATES: &str = "check_updates";
/// The shared settings; absent fields take their defaults.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -48,6 +49,8 @@ pub struct Shared {
pub omarchy_sync: bool,
/// Signs comments and changes; empty means the account name.
pub author: String,
/// Asks for a newer release at launch; off unless chosen.
pub check_updates: bool,
}
impl Default for Shared {
@@ -58,6 +61,7 @@ impl Default for Shared {
motion: Motion::System,
omarchy_sync: true,
author: String::new(),
check_updates: false,
}
}
}
@@ -92,6 +96,11 @@ impl Shared {
appearance: pick(fields, APPEARANCE, &Appearance::ALL)?.unwrap_or(defaults.appearance),
language: pick(fields, LANGUAGE, &Language::ALL)?.unwrap_or(defaults.language),
motion: pick(fields, MOTION, &Motion::ALL)?.unwrap_or(defaults.motion),
check_updates: match fields.get(CHECK_UPDATES) {
None => defaults.check_updates,
Some(Value::Bool(on)) => *on,
Some(other) => return Err(wrong(CHECK_UPDATES, other)),
},
omarchy_sync: match fields.get(OMARCHY_SYNC) {
None => defaults.omarchy_sync,
Some(Value::Bool(on)) => *on,
+3 -2
View File
@@ -63,14 +63,15 @@ fn shared_fields_type_strictly_and_default_when_absent() {
let fields = |text: &str| serde_json::from_str::<serde_json::Map<_, _>>(text).unwrap();
assert_eq!(Shared::from_fields(&fields("{}")).unwrap(), Shared::default());
let read = Shared::from_fields(&fields(
r#"{"appearance":"dark","language":"zh-CN","motion":"reduce","omarchy_sync":false,"author":" Ana "}"#,
r#"{"appearance":"dark","language":"zh-CN","motion":"reduce","omarchy_sync":false,"author":" Ana ","check_updates":true}"#,
))
.unwrap();
assert!(read.check_updates && !Shared::default().check_updates, "asked for, never by default");
assert_eq!(
(read.appearance, read.language, read.motion, read.omarchy_sync, read.author.as_str()),
(Appearance::Dark, Language::Chinese, Motion::Reduced, false, "Ana")
);
for bad in [r#"{"appearance":"blue"}"#, r#"{"omarchy_sync":"yes"}"#, r#"{"author":3}"#] {
for bad in [r#"{"appearance":"blue"}"#, r#"{"omarchy_sync":"yes"}"#, r#"{"author":3}"#, r#"{"check_updates":1}"#] {
assert!(Shared::from_fields(&fields(bad)).is_err(), "{bad}");
}
}
+2 -2
View File
@@ -305,7 +305,7 @@ fn secure_host(url: &str) -> Result<String> {
}
/// GETs `url`, following redirects only to places `secure_host` accepts.
fn fetch(agent: &Agent, url: &str) -> Result<Response<Body>> {
pub(crate) fn fetch(agent: &Agent, url: &str) -> Result<Response<Body>> {
let mut url = url.to_string();
for _ in 0..=MAX_REDIRECTS {
secure_host(&url)?;
@@ -335,7 +335,7 @@ fn fetch(agent: &Agent, url: &str) -> Result<Response<Body>> {
bail!("too many redirects")
}
fn manifest_agent() -> Agent {
pub(crate) fn manifest_agent() -> Agent {
Agent::config_builder()
.timeout_global(Some(MANIFEST_TIMEOUT))
.max_redirects(0)