use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, channel};
use std::time::Duration;
use crate::update_watch::UpdateEvent;
pub const RELEASES_LATEST_URL: &str = "https://api.github.com/repos/vitali87/croft/releases/latest";
pub const CRATE_NAME: &str = "croft-software";
pub const CHECK_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
const CACHE_FILE: &str = "update-check.json";
const STAGE_DIR: &str = "staged";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstallSource {
Homebrew,
SelfManaged,
}
pub const BREW_UPGRADE: &str = "brew upgrade croft";
pub fn install_source(exe: &Path) -> InstallSource {
let parts: Vec<_> = exe.components().map(|c| c.as_os_str()).collect();
let owned = parts.len() >= 5
&& parts[parts.len() - 5] == "Cellar"
&& parts[parts.len() - 4] == "croft"
&& parts[parts.len() - 2] == "bin"
&& parts[parts.len() - 1] == "croft";
if owned {
InstallSource::Homebrew
} else {
InstallSource::SelfManaged
}
}
pub fn current_install_source() -> InstallSource {
std::env::current_exe()
.and_then(|p| p.canonicalize())
.map(|p| install_source(&p))
.unwrap_or(InstallSource::SelfManaged)
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CheckCache {
#[serde(default)]
pub checked_at: u64,
#[serde(default)]
pub latest: Option<String>,
#[serde(default)]
pub dismissed: Option<String>,
}
impl CheckCache {
pub fn load(cache_dir: &Path) -> Self {
std::fs::read_to_string(cache_dir.join(CACHE_FILE))
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default()
}
pub fn save(&self, cache_dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(cache_dir)?;
let text = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
std::fs::write(cache_dir.join(CACHE_FILE), text)
}
}
pub fn parse_version(s: &str) -> Option<(u64, u64, u64)> {
let s = s.trim().trim_start_matches('v');
let mut it = s.split('.');
let major = it.next()?.parse().ok()?;
let minor = it.next()?.parse().ok()?;
let patch = it.next()?.parse().ok()?;
if it.next().is_some() {
return None;
}
Some((major, minor, patch))
}
pub fn is_newer(candidate: &str, current: &str) -> bool {
match (parse_version(candidate), parse_version(current)) {
(Some(c), Some(cur)) => c > cur,
_ => false,
}
}
pub fn latest_from_release_json(json: &str) -> Option<String> {
let v: serde_json::Value = serde_json::from_str(json).ok()?;
let tag = v.get("tag_name")?.as_str()?.trim();
let version = tag.trim_start_matches('v');
parse_version(version).map(|_| version.to_string())
}
pub fn should_query(cache: &CheckCache, now_secs: u64) -> bool {
now_secs < cache.checked_at || now_secs - cache.checked_at >= CHECK_INTERVAL.as_secs()
}
pub fn offer_from(cache: &CheckCache, current: &str) -> Option<String> {
let latest = cache.latest.as_deref()?;
if !is_newer(latest, current) {
return None;
}
if cache.dismissed.as_deref() == Some(latest) {
return None;
}
Some(latest.to_string())
}
fn now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn fetch_latest() -> Option<String> {
let resp = ureq::AgentBuilder::new()
.timeout(REQUEST_TIMEOUT)
.build()
.get(RELEASES_LATEST_URL)
.set("Accept", "application/vnd.github+json")
.set("User-Agent", concat!("croft/", env!("CARGO_PKG_VERSION")))
.call()
.ok()?;
let body = resp.into_string().ok()?;
latest_from_release_json(&body)
}
pub struct UpdateCheck {
rx: Receiver<Option<String>>,
}
impl UpdateCheck {
pub fn start(cache_dir: PathBuf, current_version: String) -> Self {
Self::start_with(cache_dir, current_version, fetch_latest)
}
pub fn start_with(
cache_dir: PathBuf,
current_version: String,
fetch: impl FnOnce() -> Option<String> + Send + 'static,
) -> Self {
let (tx, rx) = channel();
std::thread::spawn(move || {
let mut cache = CheckCache::load(&cache_dir);
if should_query(&cache, now_secs()) {
if let Some(latest) = fetch() {
cache.latest = Some(latest);
}
cache.checked_at = now_secs();
let _ = cache.save(&cache_dir);
}
let _ = tx.send(offer_from(&cache, ¤t_version));
});
Self { rx }
}
#[cfg(test)]
pub fn wait(&self) -> Option<String> {
self.rx
.recv_timeout(Duration::from_secs(10))
.expect("the check answers")
}
pub fn take(&self) -> Option<Option<String>> {
self.rx.try_recv().ok()
}
#[cfg(test)]
pub fn preloaded(offer: Option<String>) -> Self {
let (tx, rx) = channel();
let _ = tx.send(offer);
Self { rx }
}
}
pub fn dismiss(cache_dir: &Path, version: &str) -> std::io::Result<()> {
let mut cache = CheckCache::load(cache_dir);
cache.dismissed = Some(version.to_string());
cache.save(cache_dir)
}
pub fn staged_binary_path(cache_dir: &Path) -> PathBuf {
cache_dir.join(STAGE_DIR).join("bin").join("croft")
}
pub fn stage_command(cargo: PathBuf, version: &str, stage_root: &Path) -> std::process::Command {
let mut cmd = std::process::Command::new(cargo);
cmd.args([
"install",
CRATE_NAME,
"--version",
version,
"--locked",
"--root",
])
.arg(stage_root);
cmd
}
pub fn prebuilt_triple() -> Option<&'static str> {
if cfg!(target_os = "linux") {
crate::remote::arch_to_musl_triple(std::env::consts::ARCH)
} else {
None
}
}
pub type PrepareRelease<'a> =
dyn Fn(&str, &str) -> anyhow::Result<(PathBuf, crate::remote_prebuilt::Signature)> + 'a;
pub fn stage_update(
version: &str,
binary: &Path,
prebuilt: Option<(&str, &PrepareRelease<'_>)>,
build: &dyn Fn() -> std::io::Result<std::process::Output>,
) -> (UpdateEvent, String) {
let mut log = String::new();
if let Some((triple, prepare)) = prebuilt {
match prepare(version, triple) {
Ok((path, signature)) => {
let copied = binary
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::copy(&path, binary).map(|_| ()));
match copied {
Ok(()) => {
log.push_str(&format!(
"Staged the v{version} release binary for {triple} (signature {})\n",
match signature {
crate::remote_prebuilt::Signature::Verified => "verified",
crate::remote_prebuilt::Signature::Unchecked =>
"NOT checked: cosign is not installed",
}
));
return (UpdateEvent::Ready, log);
}
Err(e) => log.push_str(&format!(
"Could not stage the release binary ({e}); building instead\n"
)),
}
}
Err(e) if crate::remote_prebuilt::is_not_published(&e) => log.push_str(&format!(
"v{version} has no release binary for {triple}; building instead\n"
)),
Err(e) => log.push_str(&format!(
"The v{version} release binary was refused ({e:#}); building instead\n"
)),
}
}
match build() {
Ok(out) => {
log.push_str(&String::from_utf8_lossy(&out.stdout));
log.push_str(&String::from_utf8_lossy(&out.stderr));
let event = if out.status.success() {
UpdateEvent::Ready
} else {
UpdateEvent::Failed
};
(event, log)
}
Err(err) => {
log.push_str(&format!("failed to run cargo: {err}"));
(UpdateEvent::Failed, log)
}
}
}
pub struct StagedInstall {
rx: Receiver<UpdateEvent>,
binary: PathBuf,
pub version: String,
}
impl StagedInstall {
pub fn start(cache_dir: PathBuf, version: String, log_path: PathBuf) -> Self {
let (tx, rx) = channel();
let binary = staged_binary_path(&cache_dir);
let stage_root = cache_dir.join(STAGE_DIR);
let ver = version.clone();
std::thread::spawn(move || {
let _ = tx.send(UpdateEvent::InProgress);
if let Some(dir) = log_path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let build = || {
stage_command(
crate::widgets::dependencies::cargo_binary(),
&ver,
&stage_root,
)
.output()
};
let cache = crate::session_state::dirs_cache_croft().join("prebuilt");
let prepare = |version: &str, triple: &str| {
crate::remote_prebuilt::prepare(
version,
triple,
&cache,
&crate::remote_prebuilt::http_get,
&crate::remote_prebuilt::cosign_verify,
)
};
let prebuilt = prebuilt_triple()
.filter(|_| crate::remote_prebuilt::eligible(env!("CARGO_MANIFEST_DIR")))
.map(|t| (t, &prepare as &PrepareRelease<'_>));
let staged = staged_binary_path(&cache_dir);
let (event, log) = stage_update(&ver, &staged, prebuilt, &build);
let _ = std::fs::write(&log_path, log);
let _ = tx.send(event);
});
Self {
rx,
binary,
version,
}
}
pub fn binary(&self) -> &Path {
&self.binary
}
pub fn drain(&self) -> Vec<UpdateEvent> {
let mut out = Vec::new();
while let Ok(ev) = self.rx.try_recv() {
out.push(ev);
}
out
}
#[cfg(test)]
pub fn preloaded(events: &[UpdateEvent], binary: PathBuf, version: &str) -> Self {
let (tx, rx) = channel();
for ev in events {
let _ = tx.send(*ev);
}
Self {
rx,
binary,
version: version.to_string(),
}
}
}
pub fn apply_staged(staged: &Path, target: &Path) -> std::io::Result<()> {
let Some(dir) = target.parent() else {
return Err(std::io::Error::other(
"install target has no parent directory",
));
};
std::fs::create_dir_all(dir)?;
let tmp = temp_name(dir);
apply_staged_at(staged, target, &tmp)
}
fn temp_name(dir: &Path) -> PathBuf {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
dir.join(format!(".croft-update-{}-{nonce}", std::process::id()))
}
fn apply_staged_at(staged: &Path, target: &Path, tmp: &Path) -> std::io::Result<()> {
let result = (|| {
let mut src = std::fs::File::open(staged)?;
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o755);
}
let mut dst = opts.open(tmp)?;
std::io::copy(&mut src, &mut dst)?;
dst.sync_all()?;
drop(dst);
std::fs::rename(tmp, target)
})();
if result.is_err() {
let _ = std::fs::remove_file(tmp);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_binary_in_a_homebrew_cellar_is_homebrew_owned() {
for p in [
"/opt/homebrew/Cellar/croft/0.1.961/bin/croft",
"/usr/local/Cellar/croft/0.1.961/bin/croft",
"/home/linuxbrew/.linuxbrew/Cellar/croft/0.1.961/bin/croft",
] {
assert_eq!(install_source(Path::new(p)), InstallSource::Homebrew, "{p}");
}
}
#[test]
fn other_installs_are_self_managed() {
for p in [
"/Users/me/.cargo/bin/croft",
"/usr/local/bin/croft",
"/opt/homebrew/Cellar/other/1.0/bin/croft",
"/Users/me/Cellar/notes/croft",
"/Users/me/Cellar/croft/target/release/croft",
"/Users/me/code/croft/target/release/croft",
] {
assert_eq!(
install_source(Path::new(p)),
InstallSource::SelfManaged,
"{p}"
);
}
}
#[test]
fn versions_parse_with_or_without_the_v_and_compare_numerically() {
assert_eq!(parse_version("v0.1.800"), Some((0, 1, 800)));
assert_eq!(parse_version("0.1.9"), Some((0, 1, 9)));
assert_eq!(parse_version("0.1"), None);
assert_eq!(parse_version("0.1.9-dirty"), None);
assert!(is_newer("0.1.800", "0.1.799"));
assert!(is_newer("0.2.0", "0.1.999"), "numeric, not lexical");
assert!(!is_newer("0.1.799", "0.1.799"));
assert!(!is_newer("garbage", "0.1.799"), "unparseable never nags");
}
#[test]
fn the_release_tag_is_read_from_github_json() {
let json = r#"{"tag_name":"v0.1.900","name":"croft v0.1.900","assets":[]}"#;
assert_eq!(latest_from_release_json(json).as_deref(), Some("0.1.900"));
assert_eq!(latest_from_release_json(r#"{"message":"Not Found"}"#), None);
assert_eq!(latest_from_release_json("not json"), None);
}
#[test]
fn the_network_is_asked_once_a_day() {
let fresh = CheckCache {
checked_at: 1_000_000,
latest: Some("0.1.5".into()),
dismissed: None,
};
assert!(!should_query(&fresh, 1_000_000 + 3600));
assert!(should_query(&fresh, 1_000_000 + CHECK_INTERVAL.as_secs()));
assert!(
should_query(&CheckCache::default(), 1_700_000_000),
"a never-stamped cache asks"
);
assert!(
should_query(&fresh, 1_000_000 - 60),
"a stamp from the future is stale, not a gag"
);
}
#[test]
fn an_offer_needs_a_newer_undismissed_release() {
let mut cache = CheckCache {
checked_at: 1,
latest: Some("0.1.5".into()),
dismissed: None,
};
assert_eq!(offer_from(&cache, "0.1.4").as_deref(), Some("0.1.5"));
assert_eq!(offer_from(&cache, "0.1.5"), None, "already current");
assert_eq!(offer_from(&cache, "0.1.6"), None, "ahead of the release");
cache.dismissed = Some("0.1.5".into());
assert_eq!(offer_from(&cache, "0.1.4"), None, "Later means not again");
cache.latest = Some("0.1.6".into());
assert_eq!(
offer_from(&cache, "0.1.4").as_deref(),
Some("0.1.6"),
"a newer release than the dismissed one is offered"
);
}
#[test]
fn dismiss_persists_through_the_cache_file() {
let dir = tempfile::tempdir().unwrap();
CheckCache {
checked_at: 7,
latest: Some("0.1.5".into()),
dismissed: None,
}
.save(dir.path())
.unwrap();
dismiss(dir.path(), "0.1.5").unwrap();
let cache = CheckCache::load(dir.path());
assert_eq!(cache.dismissed.as_deref(), Some("0.1.5"));
assert_eq!(
cache.latest.as_deref(),
Some("0.1.5"),
"dismiss keeps the rest"
);
assert_eq!(cache.checked_at, 7);
assert_eq!(
CheckCache::load(&dir.path().join("nowhere")),
CheckCache::default(),
"a missing file is an empty cache"
);
}
#[test]
fn a_failed_check_is_stamped_and_not_retried_until_the_interval() {
let dir = tempfile::tempdir().unwrap();
let check = UpdateCheck::start_with(dir.path().to_path_buf(), "0.1.0".into(), || None);
assert_eq!(check.wait(), None);
let cache = CheckCache::load(dir.path());
assert!(cache.checked_at > 0, "the failed attempt is stamped");
assert_eq!(cache.latest, None);
assert!(
!should_query(&cache, cache.checked_at + 60),
"not asked again for a day"
);
let check = UpdateCheck::start_with(dir.path().to_path_buf(), "0.1.0".into(), || {
Some("0.2.0".into())
});
assert_eq!(
check.wait(),
None,
"inside the interval the cache answers, and it is empty"
);
}
#[test]
fn apply_refuses_a_planted_symlink_at_the_temp_name() {
let dir = tempfile::tempdir().unwrap();
let staged = dir.path().join("staged");
std::fs::write(&staged, b"new").unwrap();
let target = dir.path().join("bin").join("croft");
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(&target, b"old").unwrap();
let victim = dir.path().join("victim");
std::fs::write(&victim, b"precious").unwrap();
let tmp = temp_name(target.parent().unwrap());
std::os::unix::fs::symlink(&victim, &tmp).unwrap();
assert!(
apply_staged_at(&staged, &target, &tmp).is_err(),
"an existing entry is refused"
);
assert_eq!(
std::fs::read(&victim).unwrap(),
b"precious",
"the symlink target is untouched"
);
assert_eq!(std::fs::read(&target).unwrap(), b"old");
}
#[test]
fn staging_builds_the_published_crate_into_the_cache_root() {
let cmd = stage_command(PathBuf::from("/x/cargo"), "0.1.900", Path::new("/c/staged"));
assert_eq!(cmd.get_program(), "/x/cargo");
let args: Vec<String> = cmd
.get_args()
.map(|a| a.to_string_lossy().into_owned())
.collect();
assert_eq!(
args,
[
"install",
"croft-software",
"--version",
"0.1.900",
"--locked",
"--root",
"/c/staged"
]
);
assert_eq!(
staged_binary_path(Path::new("/c")),
PathBuf::from("/c/staged/bin/croft")
);
}
#[test]
fn apply_copies_the_staged_binary_over_the_target_executably() {
let dir = tempfile::tempdir().unwrap();
let staged = dir.path().join("staged").join("bin").join("croft");
std::fs::create_dir_all(staged.parent().unwrap()).unwrap();
std::fs::write(&staged, b"#!/bin/sh\necho new\n").unwrap();
let target = dir.path().join("bin").join("croft");
std::fs::create_dir_all(target.parent().unwrap()).unwrap();
std::fs::write(&target, b"old").unwrap();
apply_staged(&staged, &target).unwrap();
assert_eq!(std::fs::read(&target).unwrap(), b"#!/bin/sh\necho new\n");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&target).unwrap().permissions().mode();
assert_eq!(mode & 0o111, 0o111, "executable by everyone: {mode:o}");
}
let leftovers: Vec<_> = std::fs::read_dir(target.parent().unwrap())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| {
e.file_name()
.to_string_lossy()
.starts_with(".croft-update-")
})
.collect();
assert!(
leftovers.is_empty(),
"no temp file survives a successful swap"
);
assert!(
apply_staged(&dir.path().join("missing"), &target).is_err(),
"a missing staged binary is an error, not a silent no-op"
);
assert_eq!(
std::fs::read(&target).unwrap(),
b"#!/bin/sh\necho new\n",
"the failed apply left the target alone"
);
}
#[test]
fn a_release_binary_is_staged_without_building() {
use crate::remote_prebuilt::{NotPublished, Signature};
let tmp = tempfile::tempdir().unwrap();
let release = tmp.path().join("release-croft");
std::fs::write(&release, b"release bytes").unwrap();
let staged = tmp.path().join("staged/bin/croft");
let built = std::cell::Cell::new(0);
let build = || {
built.set(built.get() + 1);
std::process::Command::new("sh")
.args(["-c", "echo compiled; exit 0"])
.output()
};
let asked = std::cell::RefCell::new(Vec::new());
let found = |v: &str, t: &str| {
asked.borrow_mut().push(format!("{v} {t}"));
Ok((release.clone(), Signature::Verified))
};
let (event, log) = stage_update(
"0.2.0",
&staged,
Some(("x86_64-unknown-linux-musl", &found)),
&build,
);
assert_eq!(event, UpdateEvent::Ready);
assert_eq!(std::fs::read(&staged).unwrap(), b"release bytes");
assert_eq!(built.get(), 0, "no compile");
assert_eq!(*asked.borrow(), ["0.2.0 x86_64-unknown-linux-musl"]);
assert!(log.contains("signature verified"), "{log}");
let missing = |_: &str, _: &str| -> anyhow::Result<(PathBuf, Signature)> {
Err(anyhow::Error::new(NotPublished(String::from("x"))))
};
let (event, log) = stage_update("0.2.1", &staged, Some(("t", &missing)), &build);
assert_eq!((event, built.get()), (UpdateEvent::Ready, 1));
assert!(
log.contains("v0.2.1 has no release binary for t; building instead"),
"{log}"
);
assert!(log.contains("compiled"), "{log}");
let forged = |_: &str, _: &str| -> anyhow::Result<(PathBuf, Signature)> {
anyhow::bail!("does not match SHA256SUMS")
};
let (_, log) = stage_update("0.2.2", &staged, Some(("t", &forged)), &build);
assert!(log.contains("refused (does not match SHA256SUMS)"), "{log}");
assert_eq!(built.get(), 2);
let failing = || {
std::process::Command::new("sh")
.args(["-c", "echo broken >&2; exit 1"])
.output()
};
let (event, log) = stage_update("0.2.3", &staged, None, &failing);
assert_eq!(event, UpdateEvent::Failed);
assert!(log.contains("broken"), "{log}");
}
}