aKode: comando akode update e avviso di nuova versione
- Nuovo crate akode-update: legge l'ultima release dal repository Gitea configurato ([update] repo_url, predefinito git.difonzo.net/andrea/aKode; 404 = nessun aggiornamento), confronta la semver, scarica akode-<versione>-<target>.tar.gz solo dallo stesso host, verifica lo SHA-256 e sostituisce il binario in modo atomico tenendo akode.old (nel layout a pacchetto aggiorna anche akode-package.json o l'intero pacchetto). - `akode update [--check]` con messaggi in italiano; mai installazioni automatiche. - TUI: controllo in background all'avvio al massimo ogni 24 h (update-check.json in AKODE_HOME), avviso su una riga, disattivabile con [update] check_on_startup = false. - Rimossi il prompt di aggiornamento e le azioni npm/brew/installer di OpenAI ormai inutilizzati; il doctor mostra sorgente e ultimo controllo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
601
akode-rs/update/src/lib.rs
Normal file
601
akode-rs/update/src/lib.rs
Normal file
@@ -0,0 +1,601 @@
|
||||
//! aKode self-update.
|
||||
//!
|
||||
//! Releases are read from the configured Gitea repository only (`[update] repo_url`): the
|
||||
//! latest-release API, then the release's own assets, which must live on the same host.
|
||||
//! Nothing is ever installed automatically: callers decide when to call [`install_release`].
|
||||
//! There is no telemetry; the only request is the release lookup and the asset downloads.
|
||||
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use anyhow::bail;
|
||||
use anyhow::ensure;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use semver::Version;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
/// The startup check contacts the repository at most once per interval.
|
||||
pub const CHECK_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
/// Timeout for the non-blocking startup check.
|
||||
pub const STARTUP_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Timeout for the explicit `akode update` requests (asset downloads included).
|
||||
pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
const STATE_FILE_NAME: &str = "update-check.json";
|
||||
const PACKAGE_MANIFEST_FILE_NAME: &str = "akode-package.json";
|
||||
const USER_AGENT: &str = concat!("akode/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
/// A downloadable file attached to a release.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct ReleaseAsset {
|
||||
pub name: String,
|
||||
pub browser_download_url: String,
|
||||
}
|
||||
|
||||
/// The latest published release of the repository.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Release {
|
||||
pub version: Version,
|
||||
pub tag: String,
|
||||
pub assets: Vec<ReleaseAsset>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GiteaRelease {
|
||||
tag_name: String,
|
||||
#[serde(default)]
|
||||
assets: Vec<ReleaseAsset>,
|
||||
}
|
||||
|
||||
/// Result of comparing the running version with the latest release.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CheckResult {
|
||||
/// No release is published, or none is newer than the running version.
|
||||
UpToDate {
|
||||
latest: Option<Version>,
|
||||
},
|
||||
Available(Release),
|
||||
}
|
||||
|
||||
/// Where the running installation lives.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct InstallTarget {
|
||||
/// The binary to replace.
|
||||
pub exe: PathBuf,
|
||||
/// Package directory (with `akode-package.json`) when the binary belongs to a package layout.
|
||||
pub package_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// What [`install_release`] replaced, and where the previous version was kept.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum InstallOutcome {
|
||||
Binary { backup: PathBuf },
|
||||
Package { backup: PathBuf },
|
||||
}
|
||||
|
||||
/// HTTP client for update requests. Honors the standard proxy environment variables.
|
||||
pub fn http_client(timeout: Duration) -> Result<reqwest::Client> {
|
||||
akode_utils_rustls_provider::ensure_rustls_crypto_provider();
|
||||
reqwest::Client::builder()
|
||||
.use_rustls_tls()
|
||||
.user_agent(USER_AGENT)
|
||||
.connect_timeout(timeout.min(Duration::from_secs(10)))
|
||||
.timeout(timeout)
|
||||
.build()
|
||||
.context("impossibile creare il client HTTP per gli aggiornamenti")
|
||||
}
|
||||
|
||||
/// Gitea API URL for the latest release of `repo_url` (`https://host/owner/repo`).
|
||||
pub fn latest_release_api_url(repo_url: &str) -> Result<reqwest::Url> {
|
||||
let repo = parse_repo_url(repo_url)?;
|
||||
let segments: Vec<&str> = repo
|
||||
.path_segments()
|
||||
.map(|segments| segments.filter(|segment| !segment.is_empty()).collect())
|
||||
.unwrap_or_default();
|
||||
let [prefix @ .., owner, name] = segments.as_slice() else {
|
||||
bail!(
|
||||
"[update] repo_url deve avere la forma https://host/proprietario/repository: {repo_url}"
|
||||
);
|
||||
};
|
||||
let name = name.strip_suffix(".git").unwrap_or(name);
|
||||
let prefix: String = prefix.iter().map(|segment| format!("/{segment}")).collect();
|
||||
let mut api = repo.clone();
|
||||
api.set_path(&format!(
|
||||
"{prefix}/api/v1/repos/{owner}/{name}/releases/latest"
|
||||
));
|
||||
api.set_query(None);
|
||||
api.set_fragment(None);
|
||||
Ok(api)
|
||||
}
|
||||
|
||||
fn parse_repo_url(repo_url: &str) -> Result<reqwest::Url> {
|
||||
let url = reqwest::Url::parse(repo_url.trim().trim_end_matches('/'))
|
||||
.with_context(|| format!("[update] repo_url non valido: {repo_url}"))?;
|
||||
ensure!(
|
||||
matches!(url.scheme(), "https" | "http") && url.host_str().is_some(),
|
||||
"[update] repo_url deve essere un URL http(s): {repo_url}"
|
||||
);
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
/// Reads the latest release. A repository without releases (HTTP 404) yields `None`.
|
||||
pub async fn fetch_latest_release(
|
||||
client: &reqwest::Client,
|
||||
repo_url: &str,
|
||||
) -> Result<Option<Release>> {
|
||||
let url = latest_release_api_url(repo_url)?;
|
||||
let response = client
|
||||
.get(url.clone())
|
||||
.header(reqwest::header::ACCEPT, "application/json")
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"impossibile contattare {}",
|
||||
url.origin().ascii_serialization()
|
||||
)
|
||||
})?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(None);
|
||||
}
|
||||
ensure!(
|
||||
response.status().is_success(),
|
||||
"il server delle release ha risposto {}",
|
||||
response.status()
|
||||
);
|
||||
let release: GiteaRelease = response
|
||||
.json()
|
||||
.await
|
||||
.context("risposta non valida dal server delle release")?;
|
||||
let version = parse_version(&release.tag_name).with_context(|| {
|
||||
format!(
|
||||
"il tag della release {} non è una versione valida",
|
||||
release.tag_name
|
||||
)
|
||||
})?;
|
||||
Ok(Some(Release {
|
||||
version,
|
||||
tag: release.tag_name,
|
||||
assets: release.assets,
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_version(tag: &str) -> Result<Version> {
|
||||
let trimmed = tag.trim();
|
||||
let trimmed = trimmed
|
||||
.strip_prefix('v')
|
||||
.or_else(|| trimmed.strip_prefix('V'))
|
||||
.unwrap_or(trimmed);
|
||||
Ok(Version::parse(trimmed)?)
|
||||
}
|
||||
|
||||
/// Whether `latest` is newer than the running `current` version.
|
||||
/// Unparseable current versions never report an update.
|
||||
pub fn is_newer(current: &str, latest: &Version) -> bool {
|
||||
Version::parse(current.trim()).is_ok_and(|current| *latest > current)
|
||||
}
|
||||
|
||||
/// [`is_newer`] for a version string; unparseable versions are never newer.
|
||||
pub fn is_newer_str(current: &str, latest: &str) -> bool {
|
||||
Version::parse(latest.trim()).is_ok_and(|latest| is_newer(current, &latest))
|
||||
}
|
||||
|
||||
/// Compares the latest release with `current_version`.
|
||||
pub async fn check(
|
||||
client: &reqwest::Client,
|
||||
repo_url: &str,
|
||||
current_version: &str,
|
||||
) -> Result<CheckResult> {
|
||||
Ok(match fetch_latest_release(client, repo_url).await? {
|
||||
Some(release) if is_newer(current_version, &release.version) => {
|
||||
CheckResult::Available(release)
|
||||
}
|
||||
Some(release) => CheckResult::UpToDate {
|
||||
latest: Some(release.version),
|
||||
},
|
||||
None => CheckResult::UpToDate { latest: None },
|
||||
})
|
||||
}
|
||||
|
||||
/// Target triple used in release asset names, for the platforms aKode publishes.
|
||||
pub fn current_target() -> Option<&'static str> {
|
||||
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
|
||||
Some("aarch64-apple-darwin")
|
||||
} else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
|
||||
Some("x86_64-apple-darwin")
|
||||
} else if cfg!(all(
|
||||
target_os = "linux",
|
||||
target_arch = "x86_64",
|
||||
target_env = "musl"
|
||||
)) {
|
||||
Some("x86_64-unknown-linux-musl")
|
||||
} else if cfg!(all(
|
||||
target_os = "linux",
|
||||
target_arch = "aarch64",
|
||||
target_env = "musl"
|
||||
)) {
|
||||
Some("aarch64-unknown-linux-musl")
|
||||
} else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
|
||||
Some("x86_64-unknown-linux-gnu")
|
||||
} else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
|
||||
Some("aarch64-unknown-linux-gnu")
|
||||
} else if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
|
||||
Some("x86_64-pc-windows-msvc")
|
||||
} else if cfg!(all(target_os = "windows", target_arch = "aarch64")) {
|
||||
Some("aarch64-pc-windows-msvc")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Name of the archive asset for `version` on `target`.
|
||||
pub fn archive_asset_name(version: &Version, target: &str) -> String {
|
||||
format!("akode-{version}-{target}.tar.gz")
|
||||
}
|
||||
|
||||
/// Downloads the release archive for `target` and verifies it against its `.sha256` asset.
|
||||
pub async fn download_verified_archive(
|
||||
client: &reqwest::Client,
|
||||
repo_url: &str,
|
||||
release: &Release,
|
||||
target: &str,
|
||||
) -> Result<Vec<u8>> {
|
||||
let archive_name = archive_asset_name(&release.version, target);
|
||||
let checksum_name = format!("{archive_name}.sha256");
|
||||
let find = |name: &str| {
|
||||
release
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.name == name)
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"la release {} non contiene {name} per questa piattaforma",
|
||||
release.tag
|
||||
)
|
||||
})
|
||||
};
|
||||
let archive_asset = find(&archive_name)?;
|
||||
let checksum_asset = find(&checksum_name)?;
|
||||
let repo = parse_repo_url(repo_url)?;
|
||||
|
||||
let checksum_text = download(client, &repo, checksum_asset).await?;
|
||||
let checksum_text =
|
||||
String::from_utf8(checksum_text).context("il file .sha256 non è testo UTF-8")?;
|
||||
let expected = parse_sha256(&checksum_text, &archive_name)?;
|
||||
let archive = download(client, &repo, archive_asset).await?;
|
||||
let actual = hex(&Sha256::digest(&archive));
|
||||
ensure!(
|
||||
actual == expected,
|
||||
"checksum SHA-256 non corrispondente per {archive_name} (atteso {expected}, ottenuto {actual}): aggiornamento annullato"
|
||||
);
|
||||
Ok(archive)
|
||||
}
|
||||
|
||||
async fn download(
|
||||
client: &reqwest::Client,
|
||||
repo: &reqwest::Url,
|
||||
asset: &ReleaseAsset,
|
||||
) -> Result<Vec<u8>> {
|
||||
let url = reqwest::Url::parse(&asset.browser_download_url)
|
||||
.with_context(|| format!("URL non valido per {}", asset.name))?;
|
||||
// Downloads stay on the configured repository's origin.
|
||||
ensure!(
|
||||
url.origin() == repo.origin(),
|
||||
"{} è ospitato fuori dal repository configurato ({}): download rifiutato",
|
||||
asset.name,
|
||||
url.origin().ascii_serialization()
|
||||
);
|
||||
let response = client
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("download di {} non riuscito", asset.name))?;
|
||||
ensure!(
|
||||
response.status().is_success(),
|
||||
"download di {} non riuscito: HTTP {}",
|
||||
asset.name,
|
||||
response.status()
|
||||
);
|
||||
Ok(response
|
||||
.bytes()
|
||||
.await
|
||||
.with_context(|| format!("download di {} interrotto", asset.name))?
|
||||
.to_vec())
|
||||
}
|
||||
|
||||
/// Accepts `<hex>` or `sha256sum` output (`<hex> <file>`), possibly listing several files.
|
||||
fn parse_sha256(text: &str, archive_name: &str) -> Result<String> {
|
||||
let lines: Vec<Vec<&str>> = text
|
||||
.lines()
|
||||
.map(|line| line.split_whitespace().collect::<Vec<_>>())
|
||||
.filter(|tokens| !tokens.is_empty())
|
||||
.collect();
|
||||
let line = match lines.as_slice() {
|
||||
[only] => only,
|
||||
many => many
|
||||
.iter()
|
||||
.find(|tokens| {
|
||||
tokens
|
||||
.get(1)
|
||||
.is_some_and(|file| file.trim_start_matches('*') == archive_name)
|
||||
})
|
||||
.ok_or_else(|| anyhow!("il file .sha256 non elenca {archive_name}"))?,
|
||||
};
|
||||
let digest = line[0].to_ascii_lowercase();
|
||||
ensure!(
|
||||
digest.len() == 64 && digest.bytes().all(|byte| byte.is_ascii_hexdigit()),
|
||||
"il file .sha256 di {archive_name} non contiene un hash SHA-256 valido"
|
||||
);
|
||||
Ok(digest)
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
/// Downloads, verifies and installs `release`. Nothing on disk changes unless the
|
||||
/// archive matches its published checksum.
|
||||
pub async fn install_release(
|
||||
client: &reqwest::Client,
|
||||
repo_url: &str,
|
||||
release: &Release,
|
||||
target: &str,
|
||||
install: &InstallTarget,
|
||||
) -> Result<InstallOutcome> {
|
||||
let archive = download_verified_archive(client, repo_url, release, target).await?;
|
||||
install_archive(&archive, install, &release.version)
|
||||
}
|
||||
|
||||
/// Extracts a verified `.tar.gz` and swaps it in. The previous binary (or package) is kept
|
||||
/// as `*.old` and restored if the swap fails.
|
||||
pub fn install_archive(
|
||||
archive: &[u8],
|
||||
install: &InstallTarget,
|
||||
version: &Version,
|
||||
) -> Result<InstallOutcome> {
|
||||
let exe_dir = install
|
||||
.exe
|
||||
.parent()
|
||||
.context("il binario installato non ha una cartella")?;
|
||||
// Stage next to the destination so the final renames never cross file systems.
|
||||
let staging_parent = match &install.package_dir {
|
||||
Some(package_dir) => package_dir
|
||||
.parent()
|
||||
.context("il pacchetto installato non ha una cartella")?,
|
||||
None => exe_dir,
|
||||
};
|
||||
let staging = tempfile::Builder::new()
|
||||
.prefix(".akode-update-")
|
||||
.tempdir_in(staging_parent)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"impossibile scrivere in {} (servono i permessi di scrittura)",
|
||||
staging_parent.display()
|
||||
)
|
||||
})?;
|
||||
let extract_dir = staging.path().join("extract");
|
||||
std::fs::create_dir(&extract_dir)?;
|
||||
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(archive));
|
||||
tar.set_preserve_permissions(true);
|
||||
tar.unpack(&extract_dir)
|
||||
.context("l'archivio della release non è un .tar.gz valido")?;
|
||||
let root = archive_root(&extract_dir)?;
|
||||
|
||||
if let Some(package_dir) = &install.package_dir
|
||||
&& root.join(PACKAGE_MANIFEST_FILE_NAME).is_file()
|
||||
{
|
||||
let backup = replace_package_dir(&root, package_dir)?;
|
||||
return Ok(InstallOutcome::Package { backup });
|
||||
}
|
||||
|
||||
let new_binary = find_binary(&root)?;
|
||||
let staged_manifest = match &install.package_dir {
|
||||
Some(package_dir) => Some(stage_manifest_version(
|
||||
package_dir,
|
||||
version,
|
||||
staging.path(),
|
||||
)?),
|
||||
None => None,
|
||||
};
|
||||
let backup = replace_binary(&new_binary, &install.exe)?;
|
||||
if let (Some(staged), Some(package_dir)) = (staged_manifest, &install.package_dir)
|
||||
&& let Err(err) = std::fs::rename(&staged, package_dir.join(PACKAGE_MANIFEST_FILE_NAME))
|
||||
{
|
||||
restore_binary(&backup, &install.exe);
|
||||
return Err(err).context("impossibile aggiornare akode-package.json; binario ripristinato");
|
||||
}
|
||||
Ok(InstallOutcome::Binary { backup })
|
||||
}
|
||||
|
||||
/// Archives may wrap their content in a single top-level directory.
|
||||
fn archive_root(extract_dir: &Path) -> Result<PathBuf> {
|
||||
let entries: Vec<_> = std::fs::read_dir(extract_dir)?.collect::<std::io::Result<_>>()?;
|
||||
match entries.as_slice() {
|
||||
[] => bail!("l'archivio della release è vuoto"),
|
||||
[single] if single.file_type()?.is_dir() => Ok(single.path()),
|
||||
_ => Ok(extract_dir.to_path_buf()),
|
||||
}
|
||||
}
|
||||
|
||||
fn binary_file_name() -> &'static str {
|
||||
if cfg!(windows) { "akode.exe" } else { "akode" }
|
||||
}
|
||||
|
||||
fn find_binary(root: &Path) -> Result<PathBuf> {
|
||||
let name = binary_file_name();
|
||||
[root.join(name), root.join("bin").join(name)]
|
||||
.into_iter()
|
||||
.find(|candidate| candidate.is_file())
|
||||
.ok_or_else(|| anyhow!("l'archivio della release non contiene {name}"))
|
||||
}
|
||||
|
||||
fn backup_path(exe: &Path) -> PathBuf {
|
||||
let stem = exe
|
||||
.file_stem()
|
||||
.and_then(|stem| stem.to_str())
|
||||
.unwrap_or("akode");
|
||||
exe.with_file_name(format!("{stem}.old"))
|
||||
}
|
||||
|
||||
/// Puts `new_binary` at `exe`. On Unix the final rename atomically replaces the binary; on
|
||||
/// Windows a running executable cannot be overwritten, so it is moved aside first.
|
||||
fn replace_binary(new_binary: &Path, exe: &Path) -> Result<PathBuf> {
|
||||
let file_name = exe
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("akode");
|
||||
let staged = exe.with_file_name(format!(".{file_name}.new-{}", std::process::id()));
|
||||
std::fs::copy(new_binary, &staged)
|
||||
.with_context(|| format!("impossibile scrivere {}", staged.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755))?;
|
||||
}
|
||||
let backup = backup_path(exe);
|
||||
let result = swap_into_place(&staged, exe, &backup);
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&staged);
|
||||
}
|
||||
result.map(|()| backup)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn swap_into_place(staged: &Path, exe: &Path, backup: &Path) -> Result<()> {
|
||||
if backup.exists() {
|
||||
std::fs::remove_file(backup)?;
|
||||
}
|
||||
std::fs::copy(exe, backup)
|
||||
.with_context(|| format!("impossibile creare la copia {}", backup.display()))?;
|
||||
std::fs::rename(staged, exe)
|
||||
.with_context(|| format!("impossibile sostituire {}", exe.display()))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn swap_into_place(staged: &Path, exe: &Path, backup: &Path) -> Result<()> {
|
||||
if backup.exists() {
|
||||
std::fs::remove_file(backup)?;
|
||||
}
|
||||
std::fs::rename(exe, backup)
|
||||
.with_context(|| format!("impossibile spostare {}", exe.display()))?;
|
||||
if let Err(err) = std::fs::rename(staged, exe) {
|
||||
restore_binary(backup, exe);
|
||||
return Err(err).with_context(|| format!("impossibile sostituire {}", exe.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_binary(backup: &Path, exe: &Path) {
|
||||
if cfg!(windows) {
|
||||
let _ = std::fs::rename(backup, exe);
|
||||
} else {
|
||||
let _ = std::fs::copy(backup, exe);
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_manifest_version(
|
||||
package_dir: &Path,
|
||||
version: &Version,
|
||||
staging: &Path,
|
||||
) -> Result<PathBuf> {
|
||||
let path = package_dir.join(PACKAGE_MANIFEST_FILE_NAME);
|
||||
let mut manifest: serde_json::Value = serde_json::from_slice(
|
||||
&std::fs::read(&path).with_context(|| format!("impossibile leggere {}", path.display()))?,
|
||||
)
|
||||
.with_context(|| format!("{} non è JSON valido", path.display()))?;
|
||||
let object = manifest
|
||||
.as_object_mut()
|
||||
.with_context(|| format!("{} non è un oggetto JSON", path.display()))?;
|
||||
object.insert(
|
||||
"version".to_string(),
|
||||
serde_json::Value::String(version.to_string()),
|
||||
);
|
||||
// Same file system as the package directory, so the later rename is atomic.
|
||||
let staged = staging.join(PACKAGE_MANIFEST_FILE_NAME);
|
||||
std::fs::write(&staged, serde_json::to_vec_pretty(&manifest)?)?;
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn replace_package_dir(new_package: &Path, package_dir: &Path) -> Result<PathBuf> {
|
||||
let name = package_dir
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.context("cartella del pacchetto non valida")?;
|
||||
let backup = package_dir.with_file_name(format!("{name}.old"));
|
||||
if backup.exists() {
|
||||
std::fs::remove_dir_all(&backup)?;
|
||||
}
|
||||
std::fs::rename(package_dir, &backup)
|
||||
.with_context(|| format!("impossibile spostare {}", package_dir.display()))?;
|
||||
if let Err(err) = std::fs::rename(new_package, package_dir) {
|
||||
let _ = std::fs::rename(&backup, package_dir);
|
||||
return Err(err)
|
||||
.with_context(|| format!("impossibile sostituire {}", package_dir.display()));
|
||||
}
|
||||
Ok(backup)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct CheckState {
|
||||
last_checked_at: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
latest_version: Option<String>,
|
||||
}
|
||||
|
||||
/// Startup check: contacts the repository at most once per [`CHECK_INTERVAL`] and returns a
|
||||
/// newer version to announce, if any. Never installs anything.
|
||||
pub struct StartupCheck<'a> {
|
||||
pub akode_home: &'a Path,
|
||||
pub repo_url: &'a str,
|
||||
pub enabled: bool,
|
||||
pub current_version: &'a str,
|
||||
}
|
||||
|
||||
impl StartupCheck<'_> {
|
||||
pub async fn run(&self, client: &reqwest::Client, now: DateTime<Utc>) -> Option<Version> {
|
||||
if !self.enabled {
|
||||
return None;
|
||||
}
|
||||
let state_path = self.akode_home.join(STATE_FILE_NAME);
|
||||
let previous: Option<CheckState> = std::fs::read(&state_path)
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok());
|
||||
let interval = chrono::Duration::from_std(CHECK_INTERVAL).ok()?;
|
||||
let latest = match &previous {
|
||||
Some(state)
|
||||
if state.last_checked_at <= now && now - state.last_checked_at < interval =>
|
||||
{
|
||||
state.latest_version.clone()
|
||||
}
|
||||
_ => {
|
||||
let latest = match fetch_latest_release(client, self.repo_url).await {
|
||||
Ok(release) => release.map(|release| release.version.to_string()),
|
||||
Err(_) => previous.and_then(|state| state.latest_version),
|
||||
};
|
||||
let state = CheckState {
|
||||
last_checked_at: now,
|
||||
latest_version: latest.clone(),
|
||||
};
|
||||
if let Ok(bytes) = serde_json::to_vec(&state) {
|
||||
let _ = std::fs::create_dir_all(self.akode_home);
|
||||
let _ = std::fs::write(&state_path, bytes);
|
||||
}
|
||||
latest
|
||||
}
|
||||
};
|
||||
let latest = Version::parse(&latest?).ok()?;
|
||||
is_newer(self.current_version, &latest).then_some(latest)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
472
akode-rs/update/src/lib_tests.rs
Normal file
472
akode-rs/update/src/lib_tests.rs
Normal file
@@ -0,0 +1,472 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const TARGET: &str = "aarch64-apple-darwin";
|
||||
const LATEST_PATH: &str = "/api/v1/repos/andrea/aKode/releases/latest";
|
||||
|
||||
fn repo_url(server: &MockServer) -> String {
|
||||
format!("{}/andrea/aKode", server.uri())
|
||||
}
|
||||
|
||||
fn client() -> reqwest::Client {
|
||||
http_client(Duration::from_secs(5)).expect("client")
|
||||
}
|
||||
|
||||
fn tarball(files: &[(&str, &[u8])]) -> Vec<u8> {
|
||||
let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
|
||||
let mut builder = tar::Builder::new(encoder);
|
||||
for (name, contents) in files {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(contents.len() as u64);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
builder
|
||||
.append_data(&mut header, name, *contents)
|
||||
.expect("append");
|
||||
}
|
||||
builder.into_inner().expect("tar").finish().expect("gzip")
|
||||
}
|
||||
|
||||
async fn mount_release(server: &MockServer, archive: &[u8], checksum: &str) {
|
||||
let archive_name = format!("akode-1.2.3-{TARGET}.tar.gz");
|
||||
let base = server.uri();
|
||||
Mock::given(method("GET"))
|
||||
.and(path(LATEST_PATH))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"tag_name": "v1.2.3",
|
||||
"assets": [
|
||||
{"name": archive_name, "browser_download_url": format!("{base}/dl/{archive_name}")},
|
||||
{"name": format!("{archive_name}.sha256"), "browser_download_url": format!("{base}/dl/{archive_name}.sha256")},
|
||||
],
|
||||
})))
|
||||
.mount(server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/dl/{archive_name}")))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(archive.to_vec()))
|
||||
.mount(server)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(format!("/dl/{archive_name}.sha256")))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_string(format!("{checksum} {archive_name}\n")),
|
||||
)
|
||||
.mount(server)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn installed_binary(dir: &Path) -> PathBuf {
|
||||
let exe = dir.join(binary_file_name());
|
||||
std::fs::write(&exe, b"old binary").expect("write exe");
|
||||
exe
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn api_url_is_derived_from_repo_url() {
|
||||
for (repo, expected) in [
|
||||
(
|
||||
"https://git.difonzo.net/andrea/aKode",
|
||||
"https://git.difonzo.net/api/v1/repos/andrea/aKode/releases/latest",
|
||||
),
|
||||
(
|
||||
"https://git.difonzo.net/andrea/aKode.git/",
|
||||
"https://git.difonzo.net/api/v1/repos/andrea/aKode/releases/latest",
|
||||
),
|
||||
(
|
||||
"https://example.com/gitea/andrea/aKode",
|
||||
"https://example.com/gitea/api/v1/repos/andrea/aKode/releases/latest",
|
||||
),
|
||||
] {
|
||||
assert_eq!(latest_release_api_url(repo).unwrap().as_str(), expected);
|
||||
}
|
||||
assert!(latest_release_api_url("https://git.difonzo.net/andrea").is_err());
|
||||
assert!(latest_release_api_url("ftp://git.difonzo.net/andrea/aKode").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_comparison() {
|
||||
let latest = Version::parse("1.2.3").unwrap();
|
||||
assert!(is_newer("1.2.2", &latest));
|
||||
assert!(is_newer("0.1.0", &latest));
|
||||
assert!(is_newer("1.2.3-alpha.1", &latest));
|
||||
assert!(!is_newer("1.2.3", &latest));
|
||||
assert!(!is_newer("1.3.0", &latest));
|
||||
assert!(!is_newer("not-a-version", &latest));
|
||||
assert_eq!(parse_version("v1.2.3").unwrap(), latest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sha256_file_formats() {
|
||||
let digest = "a".repeat(64);
|
||||
assert_eq!(parse_sha256(&digest, "x.tar.gz").unwrap(), digest);
|
||||
assert_eq!(
|
||||
parse_sha256(&format!("{digest} *x.tar.gz\n"), "x.tar.gz").unwrap(),
|
||||
digest
|
||||
);
|
||||
let other = "b".repeat(64);
|
||||
assert_eq!(
|
||||
parse_sha256(
|
||||
&format!("{other} y.tar.gz\n{digest} x.tar.gz\n"),
|
||||
"x.tar.gz"
|
||||
)
|
||||
.unwrap(),
|
||||
digest
|
||||
);
|
||||
assert!(parse_sha256("not-a-hash", "x.tar.gz").is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parses_latest_release() {
|
||||
let server = MockServer::start().await;
|
||||
mount_release(&server, b"irrelevant", &"0".repeat(64)).await;
|
||||
|
||||
let release = fetch_latest_release(&client(), &repo_url(&server))
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("release");
|
||||
|
||||
assert_eq!(release.version, Version::parse("1.2.3").unwrap());
|
||||
assert_eq!(release.tag, "v1.2.3");
|
||||
assert_eq!(release.assets.len(), 2);
|
||||
assert!(matches!(
|
||||
check(&client(), &repo_url(&server), "1.0.0").await.unwrap(),
|
||||
CheckResult::Available(_)
|
||||
));
|
||||
assert_eq!(
|
||||
check(&client(), &repo_url(&server), "1.2.3").await.unwrap(),
|
||||
CheckResult::UpToDate {
|
||||
latest: Some(Version::parse("1.2.3").unwrap())
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_release_means_no_update() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(LATEST_PATH))
|
||||
.respond_with(ResponseTemplate::new(404))
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
check(&client(), &repo_url(&server), "0.1.0").await.unwrap(),
|
||||
CheckResult::UpToDate { latest: None }
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installs_verified_archive_and_keeps_backup() {
|
||||
let server = MockServer::start().await;
|
||||
let archive = tarball(&[(binary_file_name(), b"new binary")]);
|
||||
mount_release(&server, &archive, &hex(&Sha256::digest(&archive))).await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = installed_binary(dir.path());
|
||||
let release = fetch_latest_release(&client(), &repo_url(&server))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let outcome = install_release(
|
||||
&client(),
|
||||
&repo_url(&server),
|
||||
&release,
|
||||
TARGET,
|
||||
&InstallTarget {
|
||||
exe: exe.clone(),
|
||||
package_dir: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let backup = dir.path().join("akode.old");
|
||||
assert_eq!(
|
||||
outcome,
|
||||
InstallOutcome::Binary {
|
||||
backup: backup.clone()
|
||||
}
|
||||
);
|
||||
assert_eq!(std::fs::read(&exe).unwrap(), b"new binary");
|
||||
assert_eq!(std::fs::read(&backup).unwrap(), b"old binary");
|
||||
let leftovers: Vec<_> = std::fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
|
||||
.filter(|name| name.starts_with('.'))
|
||||
.collect();
|
||||
assert!(
|
||||
leftovers.is_empty(),
|
||||
"staging files left behind: {leftovers:?}"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(
|
||||
std::fs::metadata(&exe).unwrap().permissions().mode() & 0o777,
|
||||
0o755
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn checksum_mismatch_leaves_binary_untouched() {
|
||||
let server = MockServer::start().await;
|
||||
let archive = tarball(&[(binary_file_name(), b"tampered binary")]);
|
||||
mount_release(&server, &archive, &"0".repeat(64)).await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = installed_binary(dir.path());
|
||||
let release = fetch_latest_release(&client(), &repo_url(&server))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let err = install_release(
|
||||
&client(),
|
||||
&repo_url(&server),
|
||||
&release,
|
||||
TARGET,
|
||||
&InstallTarget {
|
||||
exe: exe.clone(),
|
||||
package_dir: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains("SHA-256"), "{err:#}");
|
||||
assert_eq!(std::fs::read(&exe).unwrap(), b"old binary");
|
||||
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn assets_outside_the_repository_are_refused() {
|
||||
let server = MockServer::start().await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = installed_binary(dir.path());
|
||||
let archive_name = format!("akode-1.2.3-{TARGET}.tar.gz");
|
||||
let release = Release {
|
||||
version: Version::parse("1.2.3").unwrap(),
|
||||
tag: "v1.2.3".to_string(),
|
||||
assets: vec![
|
||||
ReleaseAsset {
|
||||
name: archive_name.clone(),
|
||||
browser_download_url: format!("https://elsewhere.invalid/{archive_name}"),
|
||||
},
|
||||
ReleaseAsset {
|
||||
name: format!("{archive_name}.sha256"),
|
||||
browser_download_url: format!("https://elsewhere.invalid/{archive_name}.sha256"),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let err = install_release(
|
||||
&client(),
|
||||
&repo_url(&server),
|
||||
&release,
|
||||
TARGET,
|
||||
&InstallTarget {
|
||||
exe: exe.clone(),
|
||||
package_dir: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains("fuori dal repository"), "{err:#}");
|
||||
assert_eq!(std::fs::read(&exe).unwrap(), b"old binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_only_archive_updates_package_manifest() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let package_dir = dir.path().join("package");
|
||||
std::fs::create_dir_all(package_dir.join("bin")).unwrap();
|
||||
std::fs::write(
|
||||
package_dir.join(PACKAGE_MANIFEST_FILE_NAME),
|
||||
r#"{"version":"0.1.0","layoutVersion":1}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let exe = installed_binary(&package_dir.join("bin"));
|
||||
let archive = tarball(&[(
|
||||
&format!("akode-1.2.3/{}", binary_file_name()),
|
||||
b"new binary",
|
||||
)]);
|
||||
|
||||
install_archive(
|
||||
&archive,
|
||||
&InstallTarget {
|
||||
exe: exe.clone(),
|
||||
package_dir: Some(package_dir.clone()),
|
||||
},
|
||||
&Version::parse("1.2.3").unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(std::fs::read(&exe).unwrap(), b"new binary");
|
||||
let manifest: serde_json::Value = serde_json::from_slice(
|
||||
&std::fs::read(package_dir.join(PACKAGE_MANIFEST_FILE_NAME)).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
manifest,
|
||||
serde_json::json!({"version": "1.2.3", "layoutVersion": 1})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_archive_replaces_package_directory() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let package_dir = dir.path().join("package");
|
||||
std::fs::create_dir_all(package_dir.join("bin")).unwrap();
|
||||
std::fs::write(
|
||||
package_dir.join(PACKAGE_MANIFEST_FILE_NAME),
|
||||
r#"{"version":"0.1.0"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let exe = installed_binary(&package_dir.join("bin"));
|
||||
let archive = tarball(&[
|
||||
(PACKAGE_MANIFEST_FILE_NAME, br#"{"version":"1.2.3"}"#),
|
||||
(&format!("bin/{}", binary_file_name()), b"new binary"),
|
||||
]);
|
||||
|
||||
let outcome = install_archive(
|
||||
&archive,
|
||||
&InstallTarget {
|
||||
exe: exe.clone(),
|
||||
package_dir: Some(package_dir.clone()),
|
||||
},
|
||||
&Version::parse("1.2.3").unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let backup = dir.path().join("package.old");
|
||||
assert_eq!(
|
||||
outcome,
|
||||
InstallOutcome::Package {
|
||||
backup: backup.clone()
|
||||
}
|
||||
);
|
||||
assert_eq!(std::fs::read(&exe).unwrap(), b"new binary");
|
||||
assert_eq!(
|
||||
std::fs::read(backup.join("bin").join(binary_file_name())).unwrap(),
|
||||
b"old binary"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archive_without_binary_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = installed_binary(dir.path());
|
||||
let archive = tarball(&[("README.md", b"hello")]);
|
||||
|
||||
assert!(
|
||||
install_archive(
|
||||
&archive,
|
||||
&InstallTarget {
|
||||
exe: exe.clone(),
|
||||
package_dir: None,
|
||||
},
|
||||
&Version::parse("1.2.3").unwrap(),
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(std::fs::read(&exe).unwrap(), b"old binary");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_check_contacts_repository_once_per_day() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(LATEST_PATH))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"tag_name": "v1.2.3",
|
||||
"assets": [],
|
||||
})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let repo = repo_url(&server);
|
||||
let check = StartupCheck {
|
||||
akode_home: home.path(),
|
||||
repo_url: &repo,
|
||||
enabled: true,
|
||||
current_version: "0.1.0",
|
||||
};
|
||||
let now = Utc::now();
|
||||
let expected = Some(Version::parse("1.2.3").unwrap());
|
||||
|
||||
assert_eq!(check.run(&client(), now).await, expected);
|
||||
// Within 24 h the cached result is reused without a request.
|
||||
assert_eq!(
|
||||
check
|
||||
.run(&client(), now + chrono::Duration::hours(23))
|
||||
.await,
|
||||
expected
|
||||
);
|
||||
assert_eq!(
|
||||
check
|
||||
.run(&client(), now + chrono::Duration::hours(25))
|
||||
.await,
|
||||
expected
|
||||
);
|
||||
let up_to_date = StartupCheck {
|
||||
current_version: "1.2.3",
|
||||
..check
|
||||
};
|
||||
assert_eq!(
|
||||
up_to_date
|
||||
.run(&client(), now + chrono::Duration::hours(26))
|
||||
.await,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_check_records_missing_release() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path(LATEST_PATH))
|
||||
.respond_with(ResponseTemplate::new(404))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let repo = repo_url(&server);
|
||||
let check = StartupCheck {
|
||||
akode_home: home.path(),
|
||||
repo_url: &repo,
|
||||
enabled: true,
|
||||
current_version: "0.1.0",
|
||||
};
|
||||
|
||||
assert_eq!(check.run(&client(), Utc::now()).await, None);
|
||||
assert_eq!(check.run(&client(), Utc::now()).await, None);
|
||||
assert!(home.path().join(STATE_FILE_NAME).is_file());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_check_opt_out_makes_no_request() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(0)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let repo = repo_url(&server);
|
||||
let check = StartupCheck {
|
||||
akode_home: home.path(),
|
||||
repo_url: &repo,
|
||||
enabled: false,
|
||||
current_version: "0.1.0",
|
||||
};
|
||||
|
||||
assert_eq!(check.run(&client(), Utc::now()).await, None);
|
||||
assert!(!home.path().join(STATE_FILE_NAME).exists());
|
||||
}
|
||||
Reference in New Issue
Block a user