use std::io::Read;
use std::path::Path;
use std::sync::mpsc;
use anyhow::{Context, Result};
use log::{debug, info, warn};
use crate::event::AppEvent;
pub fn current_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
const HEADLINE_MAX_BYTES: usize = 200;
fn extract_headline(notes: &str) -> Option<String> {
let line = notes
.lines()
.map(|l| l.trim())
.find(|l| !l.is_empty() && !l.starts_with('#'))?;
let trimmed = line.strip_prefix("- ").unwrap_or(line);
if trimmed.len() <= HEADLINE_MAX_BYTES {
return Some(trimmed.to_string());
}
let mut cut = HEADLINE_MAX_BYTES;
while cut > 0 && !trimmed.is_char_boundary(cut) {
cut -= 1;
}
Some(trimmed[..cut].to_string())
}
fn parse_version(v: &str) -> Option<(u32, u32, u32)> {
let mut parts = v.splitn(3, '.');
let major = parts.next()?.parse().ok()?;
let minor = parts.next()?.parse().ok()?;
let patch = parts.next()?.parse().ok()?;
Some((major, minor, patch))
}
fn is_newer(current: &str, latest: &str) -> bool {
match (parse_version(current), parse_version(latest)) {
(Some(c), Some(l)) => l > c,
_ => false,
}
}
struct ReleaseInfo {
version: String,
notes: String,
}
fn extract_release_info(json: &serde_json::Value) -> Result<ReleaseInfo> {
let tag = json["tag_name"]
.as_str()
.context("Missing tag_name in release")?;
let version = tag.strip_prefix('v').unwrap_or(tag);
if parse_version(version).is_none() {
anyhow::bail!("Invalid version format: {}", version);
}
let notes = json["body"].as_str().unwrap_or("").to_string();
Ok(ReleaseInfo {
version: version.to_string(),
notes,
})
}
fn check_latest_release(agent: &ureq::Agent) -> Result<ReleaseInfo> {
let mut resp = agent
.get("https://api.github.com/repos/erickochen/purple/releases/latest")
.header("Accept", "application/vnd.github+json")
.header("User-Agent", &format!("purple-ssh/{}", current_version()))
.call()
.context("Failed to fetch latest release. GitHub may be rate-limited.")?;
let mut body = Vec::new();
resp.body_mut()
.as_reader()
.take(1_048_576) .read_to_end(&mut body)
.context("Failed to read release JSON")?;
let json: serde_json::Value =
serde_json::from_slice(&body).context("Failed to parse release JSON")?;
extract_release_info(&json)
}
const VERSION_CHECK_TTL: std::time::Duration = std::time::Duration::from_secs(60 * 60);
#[derive(Debug, PartialEq)]
struct CachedVersion {
version: String,
headline: Option<String>,
}
fn parse_version_cache(
content: &str,
now_secs: u64,
current: &str,
) -> Option<Option<CachedVersion>> {
let mut lines = content.lines();
let timestamp: u64 = lines.next()?.parse().ok()?;
let version = lines.next()?.to_string();
let headline = lines
.next()
.map(|s| s.to_string())
.filter(|s| !s.is_empty());
if version.is_empty() || parse_version(&version).is_none() {
return None; }
if now_secs.saturating_sub(timestamp) > VERSION_CHECK_TTL.as_secs() {
return None; }
if is_newer(current, &version) {
Some(Some(CachedVersion { version, headline }))
} else {
Some(None) }
}
fn read_cached_version() -> Option<Option<CachedVersion>> {
let path = dirs::home_dir()?.join(".purple").join("last_version_check");
let content = std::fs::read_to_string(&path).ok()?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_secs();
parse_version_cache(&content, now, current_version())
}
fn write_version_cache(version: &str, headline: Option<&str>) {
let Some(dir) = dirs::home_dir().map(|h| h.join(".purple")) else {
return;
};
if let Err(e) = std::fs::create_dir_all(&dir) {
debug!("[config] Failed to create version cache directory: {e}");
return;
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let hl = headline.unwrap_or("");
let content = format!("{}\n{}\n{}\n", now, version, hl);
if let Err(e) =
crate::fs_util::atomic_write(&dir.join("last_version_check"), content.as_bytes())
{
debug!("[config] Failed to write version cache: {e}");
}
}
pub fn spawn_version_check(tx: mpsc::Sender<AppEvent>) {
let _ = std::thread::Builder::new()
.name("version-check".to_string())
.spawn(move || {
debug!("Version check started");
match read_cached_version() {
Some(Some(cached)) => {
debug!(
"Version check: current={} latest={}",
current_version(),
cached.version
);
let _ = tx.send(AppEvent::UpdateAvailable {
version: cached.version,
headline: cached.headline,
});
return;
}
Some(None) => return, None => {} }
let agent = ureq::Agent::config_builder()
.timeout_global(Some(std::time::Duration::from_secs(5)))
.build()
.new_agent();
match check_latest_release(&agent) {
Ok(info) => {
let current = current_version();
debug!("Version check: current={current} latest={}", info.version);
let headline = extract_headline(&info.notes);
write_version_cache(&info.version, headline.as_deref());
if is_newer(current, &info.version) {
let _ = tx.send(AppEvent::UpdateAvailable {
version: info.version,
headline,
});
}
}
Err(err) => {
warn!("[external] Version check failed: {err}");
}
}
});
}
fn bold(text: &str) -> String {
if std::env::var_os("NO_COLOR").is_some() {
text.to_string()
} else {
format!("\x1b[1m{}\x1b[0m", text)
}
}
fn bold_purple(text: &str) -> String {
if std::env::var_os("NO_COLOR").is_some() {
text.to_string()
} else {
format!("\x1b[1;35m{}\x1b[0m", text)
}
}
enum InstallMethod {
Homebrew,
Cargo,
CurlOrManual,
}
fn is_homebrew_path(exe_path: &Path, cellar: &Path) -> bool {
if cellar.file_name().and_then(|n| n.to_str()) != Some("Cellar") {
return false;
}
if !exe_path.starts_with(cellar) {
return false;
}
exe_path
.strip_prefix(cellar)
.is_ok_and(|rest| rest.components().count() >= 1)
}
fn is_cargo_path(exe_path: &Path, cargo_home: &Path) -> bool {
let cargo_bin = cargo_home.join("bin");
exe_path.parent() == Some(cargo_bin.as_path())
}
fn detect_install_method(exe_path: &Path) -> InstallMethod {
if let Ok(cellar) = std::env::var("HOMEBREW_CELLAR") {
if is_homebrew_path(exe_path, Path::new(&cellar)) {
return InstallMethod::Homebrew;
}
}
if let Ok(prefix) = std::env::var("HOMEBREW_PREFIX") {
let cellar = std::path::PathBuf::from(&prefix).join("Cellar");
if is_homebrew_path(exe_path, &cellar) {
return InstallMethod::Homebrew;
}
}
for cellar in [
"/opt/homebrew/Cellar",
"/usr/local/Cellar",
"/home/linuxbrew/.linuxbrew/Cellar",
] {
if is_homebrew_path(exe_path, Path::new(cellar)) {
return InstallMethod::Homebrew;
}
}
if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
if is_cargo_path(exe_path, Path::new(&cargo_home)) {
return InstallMethod::Cargo;
}
}
if let Some(parent) = exe_path.parent() {
if parent.file_name().and_then(|n| n.to_str()) == Some("bin") {
if let Some(grandparent) = parent.parent() {
if grandparent.file_name().and_then(|n| n.to_str()) == Some(".cargo") {
return InstallMethod::Cargo;
}
}
}
}
InstallMethod::CurlOrManual
}
pub fn update_hint() -> &'static str {
if !matches!(std::env::consts::OS, "macos" | "linux") {
return "cargo install purple-ssh";
}
if let Ok(exe) = std::env::current_exe() {
let path = std::fs::canonicalize(&exe).unwrap_or(exe);
return match detect_install_method(&path) {
InstallMethod::Homebrew => "brew upgrade erickochen/purple/purple",
InstallMethod::Cargo => "cargo install purple-ssh",
InstallMethod::CurlOrManual => "purple update",
};
}
"purple update"
}
pub fn self_update() -> Result<()> {
if !matches!(std::env::consts::OS, "macos" | "linux") {
anyhow::bail!(
"Self-update is available on macOS and Linux only.\n \
Update via: cargo install purple-ssh"
);
}
println!("{}", crate::messages::update::header(&bold("purple.")));
let exe_path = std::env::current_exe().context("Failed to detect binary path")?;
let exe_path = std::fs::canonicalize(&exe_path).unwrap_or(exe_path);
println!("{}", crate::messages::update::binary_path(&exe_path));
match detect_install_method(&exe_path) {
InstallMethod::Homebrew => {
anyhow::bail!(
"purple appears to be installed via Homebrew.\n \
Update with: brew upgrade erickochen/purple/purple"
);
}
InstallMethod::Cargo => {
anyhow::bail!(
"purple appears to be installed via cargo.\n \
Update with: cargo install purple-ssh"
);
}
InstallMethod::CurlOrManual => {}
}
print!(" Checking for updates... ");
let agent = ureq::Agent::config_builder()
.timeout_global(Some(std::time::Duration::from_secs(30)))
.build()
.new_agent();
let info = check_latest_release(&agent)?;
let latest = info.version;
let current = current_version();
if !is_newer(current, &latest) {
println!("{}", crate::messages::update::already_on(current));
return Ok(());
}
println!("{}", crate::messages::update::available(&latest, current));
info!("[purple] Update started: {current} -> {latest}");
let target = match (std::env::consts::ARCH, std::env::consts::OS) {
("aarch64", "macos") => "aarch64-apple-darwin",
("x86_64", "macos") => "x86_64-apple-darwin",
("aarch64", "linux") => "aarch64-unknown-linux-gnu",
("x86_64", "linux") => "x86_64-unknown-linux-gnu",
(arch, os) => anyhow::bail!("Unsupported platform: {}-{}", arch, os),
};
let parent = exe_path
.parent()
.context("Binary has no parent directory")?;
if std::env::var_os("SUDO_USER").is_some() {
eprintln!(" {} {}", bold("!"), crate::messages::update::SUDO_WARNING,);
}
if !is_writable(parent) {
anyhow::bail!(
"No write permission to {}.\n Check directory permissions or run with elevated privileges.",
parent.display()
);
}
clean_stale_staged(parent);
let tmp_dir = std::env::temp_dir().join(format!(
"purple_update_{}_{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
));
std::fs::create_dir(&tmp_dir).context("Failed to create temp directory")?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp_dir, std::fs::Permissions::from_mode(0o700))
.context("Failed to set temp directory permissions")?;
}
let _cleanup = TempCleanup(&tmp_dir);
let tarball_name = format!("purple-{}-{}.tar.gz", latest, target);
let base_url = format!(
"https://github.com/erickochen/purple/releases/download/v{}",
latest
);
print!(" Downloading v{}... ", latest);
let tarball_path = tmp_dir.join(&tarball_name);
download_file(
&agent,
&format!("{}/{}", base_url, tarball_name),
&tarball_path,
)?;
let sha_path = tmp_dir.join(format!("{}.sha256", tarball_name));
download_file(
&agent,
&format!("{}/{}.sha256", base_url, tarball_name),
&sha_path,
)?;
println!("{}", crate::messages::update::DONE);
print!(" Verifying checksum... ");
verify_checksum(&tarball_path, &sha_path)?;
println!("{}", crate::messages::update::CHECKSUM_OK);
print!(" Installing... ");
let status = std::process::Command::new("tar")
.arg("-xzf")
.arg(&tarball_path)
.arg("-C")
.arg(&tmp_dir)
.status()
.context("Failed to run tar")?;
if !status.success() {
anyhow::bail!("tar extraction failed");
}
let new_binary = tmp_dir.join("purple");
if !new_binary.exists() {
anyhow::bail!("Binary not found in archive");
}
let staged_path = parent.join(format!(".purple_new_{}", std::process::id()));
{
use std::io::Write;
let source = std::fs::read(&new_binary).context("Failed to read new binary")?;
let mut dest = std::fs::OpenOptions::new()
.write(true)
.create_new(true) .open(&staged_path)
.context("Failed to create staged binary")?;
dest.write_all(&source)
.context("Failed to write staged binary")?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&staged_path, std::fs::Permissions::from_mode(0o755))
.context("Failed to set permissions")?;
}
if let Err(e) = std::fs::rename(&staged_path, &exe_path) {
let _ = std::fs::remove_file(&staged_path);
return Err(e).context("Failed to replace binary");
}
println!("{}", crate::messages::update::DONE);
info!("[purple] Update completed: {latest}");
println!(
"{}",
crate::messages::update::installed_at(
&bold_purple(&format!("purple v{}", latest)),
&exe_path,
)
);
println!("{}", crate::messages::update::whats_new_hint_indented());
println!();
Ok(())
}
fn download_file(agent: &ureq::Agent, url: &str, dest: &Path) -> Result<()> {
let mut resp = agent
.get(url)
.call()
.with_context(|| format!("Failed to download {}", url))?;
let mut bytes = Vec::new();
resp.body_mut()
.as_reader()
.take(100 * 1024 * 1024) .read_to_end(&mut bytes)
.context("Failed to read download")?;
if bytes.is_empty() {
anyhow::bail!("Empty response from {}", url);
}
std::fs::write(dest, bytes).context("Failed to write file")?;
Ok(())
}
fn verify_checksum(file: &Path, sha_file: &Path) -> Result<()> {
let expected = std::fs::read_to_string(sha_file).context("Failed to read checksum file")?;
let expected = expected
.split_whitespace()
.next()
.context("Empty checksum file")?;
use sha2::{Digest, Sha256};
let bytes = std::fs::read(file).context("Failed to read file for checksum")?;
let actual = format!("{:x}", Sha256::digest(&bytes));
if expected != actual {
anyhow::bail!(
"Checksum mismatch.\n Expected: {}\n Got: {}",
expected,
actual
);
}
Ok(())
}
fn clean_stale_staged(dir: &Path) {
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if name.starts_with(".purple_new_") {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
}
fn is_writable(path: &Path) -> bool {
let probe = path.join(format!(".purple_write_test_{}", std::process::id()));
if std::fs::File::create(&probe).is_ok() {
let _ = std::fs::remove_file(&probe);
true
} else {
false
}
}
struct TempCleanup<'a>(&'a Path);
impl Drop for TempCleanup<'_> {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(self.0);
}
}
#[cfg(test)]
#[path = "update_tests.rs"]
mod tests;