Files
bytesize/src-tauri/src/updates.rs
T

245 lines
6.9 KiB
Rust

use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
const GITEA_LATEST: &str =
"https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest";
#[derive(Debug, Clone, Serialize)]
pub struct UpdateInfo {
pub version: String,
pub current_version: String,
pub release_url: String,
pub body: String,
pub download_url: Option<String>,
}
#[derive(Debug, Deserialize)]
struct GiteaRelease {
tag_name: String,
body: Option<String>,
html_url: String,
#[serde(default)]
assets: Vec<GiteaAsset>,
}
#[derive(Debug, Deserialize)]
struct GiteaAsset {
name: String,
browser_download_url: String,
}
pub async fn check_for_update() -> Result<Option<UpdateInfo>> {
let client = reqwest::Client::builder()
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
.build()?;
let resp = client.get(GITEA_LATEST).send().await?;
if !resp.status().is_success() {
tracing::debug!("update check returned status {}", resp.status());
return Ok(None);
}
let body = resp.text().await?;
let release: GiteaRelease = serde_json::from_str(&body)?;
let latest = release.tag_name.trim_start_matches('v').to_string();
let current = env!("CARGO_PKG_VERSION").to_string();
if is_newer(&latest, &current) {
let download_url = release
.assets
.iter()
.find(|a| a.name.eq_ignore_ascii_case("ByteSize.exe"))
.or_else(|| release.assets.iter().find(|a| a.name.to_lowercase().ends_with(".exe")))
.map(|a| a.browser_download_url.clone());
Ok(Some(UpdateInfo {
version: latest,
current_version: current,
release_url: release.html_url,
body: release.body.unwrap_or_default(),
download_url,
}))
} else {
Ok(None)
}
}
pub async fn download_to<F>(url: &str, dest: &Path, mut on_progress: F) -> Result<()>
where
F: FnMut(u64, Option<u64>) + Send,
{
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).context("creating update parent dir")?;
}
let client = reqwest::Client::builder()
.user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
.build()?;
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
let mut downloaded = 0u64;
let mut stream = resp.bytes_stream();
let mut file = std::fs::File::create(dest).context("creating update file")?;
use std::io::Write;
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
file.write_all(&chunk)?;
downloaded += chunk.len() as u64;
on_progress(downloaded, total);
}
file.flush()?;
Ok(())
}
pub fn pending_update_path(app_dir: &Path) -> PathBuf {
app_dir.join("ByteSize.new.exe")
}
fn last_check_path(app_dir: &Path) -> PathBuf {
app_dir.join("temp").join("last-update-check")
}
/// Returns true if the last successful update check happened more than `ttl`
/// ago, or never. The stamp file's mtime is the source of truth.
pub fn should_check(app_dir: &Path, ttl: std::time::Duration) -> bool {
let path = last_check_path(app_dir);
let Ok(meta) = std::fs::metadata(&path) else {
return true;
};
let Ok(modified) = meta.modified() else {
return true;
};
let Ok(elapsed) = modified.elapsed() else {
return true;
};
elapsed > ttl
}
pub fn stamp_check(app_dir: &Path) {
let path = last_check_path(app_dir);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(&path, b"");
}
pub fn has_pending_update(app_dir: &Path) -> bool {
pending_update_path(app_dir).is_file()
}
pub fn write_apply_script(app_dir: &Path) -> Result<PathBuf> {
let bat_path = app_dir.join("bytesize-apply-update.bat");
let exe_name = std::env::current_exe()
.ok()
.and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned()))
.unwrap_or_else(|| "ByteSize.exe".to_string());
let body = format!(
"@echo off\r\n\
timeout /t 3 /nobreak >nul\r\n\
:retry\r\n\
del \"%~dp0{exe}\" 2>nul\r\n\
if exist \"%~dp0{exe}\" (\r\n\
timeout /t 2 /nobreak >nul\r\n\
goto retry\r\n\
)\r\n\
move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\
if errorlevel 1 (\r\n\
echo Failed to replace executable\r\n\
pause\r\n\
del \"%~f0\"\r\n\
exit /b 1\r\n\
)\r\n\
start \"\" \"%~dp0{exe}\"\r\n\
del \"%~f0\"\r\n",
exe = exe_name
);
std::fs::write(&bat_path, body).context("writing apply script")?;
Ok(bat_path)
}
#[derive(Debug, PartialEq, Eq)]
struct VersionParts {
nums: Vec<u32>,
pre: Option<String>,
}
fn parse_version(v: &str) -> VersionParts {
let trimmed = v.trim().trim_start_matches('v');
let (core, pre) = trimmed
.split_once('-')
.map(|(core, pre)| (core, Some(pre.to_ascii_lowercase())))
.unwrap_or((trimmed, None));
let nums = core
.split('.')
.map(|s| s.parse::<u32>().unwrap_or(0))
.collect();
VersionParts { nums, pre }
}
fn is_newer(latest: &str, current: &str) -> bool {
let mut l = parse_version(latest);
let mut c = parse_version(current);
let max = l.nums.len().max(c.nums.len());
l.nums.resize(max, 0);
c.nums.resize(max, 0);
if l.nums != c.nums {
return l.nums > c.nums;
}
match (&l.pre, &c.pre) {
(None, Some(_)) => true,
(Some(_), None) => false,
(Some(a), Some(b)) => a > b,
(None, None) => false,
}
}
#[cfg(test)]
mod tests {
use super::is_newer;
#[test]
fn version_major_bump() {
assert!(is_newer("2.0.0", "1.9.9"));
assert!(!is_newer("1.9.9", "2.0.0"));
}
#[test]
fn version_minor_bump() {
assert!(is_newer("1.1.0", "1.0.0"));
assert!(!is_newer("1.0.0", "1.1.0"));
}
#[test]
fn version_patch_bump() {
assert!(is_newer("1.0.1", "1.0.0"));
assert!(!is_newer("1.0.0", "1.0.1"));
}
#[test]
fn version_equal() {
assert!(!is_newer("1.0.0", "1.0.0"));
}
#[test]
fn version_different_lengths() {
assert!(is_newer("1.0.1", "1.0"));
assert!(!is_newer("1.0", "1.0.1"));
assert!(is_newer("1.1", "1.0.9"));
}
#[test]
fn version_ignores_extra_text() {
assert!(is_newer("1.0.0-beta", "0.9.0"));
}
#[test]
fn stable_is_newer_than_matching_prerelease() {
assert!(is_newer("1.0.0", "1.0.0-beta"));
assert!(!is_newer("1.0.0-beta", "1.0.0"));
}
#[test]
fn prerelease_compares_when_core_matches() {
assert!(is_newer("1.0.0-rc", "1.0.0-beta"));
assert!(!is_newer("1.0.0-beta", "1.0.0-rc"));
}
}