Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c12232cf3 | ||
|
|
59b3e94021 |
No files matched your search
@@ -28,4 +28,6 @@ pub const RTK_META_COMMANDS: &[&str] = &[
|
||||
"smart",
|
||||
"deps",
|
||||
"json",
|
||||
"update",
|
||||
"uninstall",
|
||||
];
|
||||
@@ -0,0 +1,217 @@
|
||||
//! Release source: rtk's GitHub releases.
|
||||
//!
|
||||
//! The latest version is read from the `releases/latest` 302 redirect
|
||||
//! (no API rate limit) and checksums from the release's `checksums.txt`.
|
||||
//!
|
||||
//! Env overrides: `RTK_OSS_BASE` (also how tests point at a fixture
|
||||
//! server), `RTK_VERSION` (pin an exact version).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
|
||||
use super::platform::Target;
|
||||
|
||||
pub const DEFAULT_OSS_BASE: &str = "https://github.com/rtk-ai/rtk";
|
||||
|
||||
const FETCH_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Release {
|
||||
pub version: String,
|
||||
pub sha256: Option<String>,
|
||||
pub tarball_url: String,
|
||||
}
|
||||
|
||||
/// Resolve the latest published release for this platform.
|
||||
pub fn latest(target: &Target) -> Result<Release> {
|
||||
let base = std::env::var("RTK_OSS_BASE").unwrap_or_else(|_| DEFAULT_OSS_BASE.to_string());
|
||||
let pinned = std::env::var("RTK_VERSION").ok();
|
||||
github_latest(&base, pinned.as_deref(), target.triple)
|
||||
}
|
||||
|
||||
fn github_latest(base: &str, pinned: Option<&str>, triple: &str) -> Result<Release> {
|
||||
let tag = match pinned {
|
||||
Some(pin) => format!("v{}", super::version::numeric(pin)),
|
||||
None => {
|
||||
let url = format!("{}/releases/latest", base);
|
||||
resolve_latest_tag(&url)
|
||||
.with_context(|| format!("Failed to resolve latest release ({})", url))?
|
||||
}
|
||||
};
|
||||
let version = super::version::numeric(&tag);
|
||||
if version.is_empty() {
|
||||
bail!("Could not parse a version from release tag '{}'", tag);
|
||||
}
|
||||
|
||||
let tarball_name = format!("rtk-{}.tar.gz", triple);
|
||||
let checksums_url = format!("{}/releases/download/{}/checksums.txt", base, tag);
|
||||
let sha256 = match http_get_string(&checksums_url) {
|
||||
Ok(body) => parse_checksums(&body, &tarball_name),
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"rtk: warning: could not fetch checksums.txt ({:#}) — proceeding without verification",
|
||||
e
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let tarball_url = format!("{}/releases/download/{}/{}", base, tag, tarball_name);
|
||||
Ok(Release {
|
||||
version,
|
||||
sha256,
|
||||
tarball_url,
|
||||
})
|
||||
}
|
||||
|
||||
/// GitHub answers `releases/latest` with a 302 whose Location ends in
|
||||
/// `/tag/<tag>`; fixture servers may answer 200 with the tag as body.
|
||||
fn resolve_latest_tag(url: &str) -> Result<String> {
|
||||
let agent = ureq::builder().redirects(0).build();
|
||||
let response = match agent.get(url).timeout(FETCH_TIMEOUT).call() {
|
||||
Ok(resp) => resp,
|
||||
Err(ureq::Error::Status(_, resp)) => resp,
|
||||
Err(e) => return Err(e).context("Request failed"),
|
||||
};
|
||||
|
||||
if (300..400).contains(&response.status()) {
|
||||
let location = response
|
||||
.header("location")
|
||||
.ok_or_else(|| anyhow!("Redirect without Location header"))?;
|
||||
return tag_from_location(location)
|
||||
.ok_or_else(|| anyhow!("Could not parse tag from redirect '{}'", location));
|
||||
}
|
||||
if response.status() == 200 {
|
||||
let tag = response
|
||||
.into_string()
|
||||
.context("Failed to read response body")?
|
||||
.trim()
|
||||
.to_string();
|
||||
if tag.is_empty() {
|
||||
bail!("Empty response for latest release tag");
|
||||
}
|
||||
return Ok(tag);
|
||||
}
|
||||
bail!("Unexpected HTTP status {}", response.status());
|
||||
}
|
||||
|
||||
fn tag_from_location(location: &str) -> Option<String> {
|
||||
let tag = location.rsplit("/tag/").next()?;
|
||||
let tag = tag.split(['?', '#']).next().unwrap_or(tag).trim();
|
||||
if tag.is_empty() || tag == location {
|
||||
None
|
||||
} else {
|
||||
Some(tag.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_checksums(body: &str, file_name: &str) -> Option<String> {
|
||||
body.lines().find_map(|line| {
|
||||
let mut parts = line.split_whitespace();
|
||||
let hash = parts.next()?;
|
||||
let name = parts.next()?;
|
||||
// sha256sum prefixes binary-mode entries with '*'.
|
||||
if name.trim_start_matches('*') == file_name && hash.len() == 64 {
|
||||
Some(hash.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn http_get_string(url: &str) -> Result<String> {
|
||||
let response = ureq::get(url)
|
||||
.set("Cache-Control", "no-cache")
|
||||
.set("User-Agent", "rtk-distribution")
|
||||
.timeout(FETCH_TIMEOUT)
|
||||
.call()
|
||||
.with_context(|| format!("GET {} failed", url))?;
|
||||
response.into_string().context("Failed to read response")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_tag_from_location() {
|
||||
assert_eq!(
|
||||
tag_from_location("https://github.com/rtk-ai/rtk/releases/tag/v0.43.0").as_deref(),
|
||||
Some("v0.43.0")
|
||||
);
|
||||
assert_eq!(
|
||||
tag_from_location("/rtk-ai/rtk/releases/tag/v1.0.0?foo=1").as_deref(),
|
||||
Some("v1.0.0")
|
||||
);
|
||||
assert!(tag_from_location("https://github.com/").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_checksums() {
|
||||
let body = "abc\n\
|
||||
56a49da54b9a4f3f75779656d40f1f53647052becb70415143158c8672895634 rtk-x86_64-unknown-linux-musl.tar.gz\n\
|
||||
17ddd8217957d1423463d754f406b07b244c690435f3c2d88a6df9c5451cdf82 *rtk-aarch64-unknown-linux-gnu.tar.gz\n";
|
||||
assert_eq!(
|
||||
parse_checksums(body, "rtk-x86_64-unknown-linux-musl.tar.gz").as_deref(),
|
||||
Some("56a49da54b9a4f3f75779656d40f1f53647052becb70415143158c8672895634")
|
||||
);
|
||||
assert_eq!(
|
||||
parse_checksums(body, "rtk-aarch64-unknown-linux-gnu.tar.gz").as_deref(),
|
||||
Some("17ddd8217957d1423463d754f406b07b244c690435f3c2d88a6df9c5451cdf82")
|
||||
);
|
||||
assert!(parse_checksums(body, "rtk-missing.tar.gz").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_latest_via_fixture_200_body() {
|
||||
let checksums =
|
||||
"aaaa000000000000000000000000000000000000000000000000000000000000 rtk-x86_64-unknown-linux-musl.tar.gz\n";
|
||||
let base = super::super::test_http::serve(vec![
|
||||
("/releases/latest".to_string(), 200, b"v9.9.9".to_vec()),
|
||||
(
|
||||
"/releases/download/v9.9.9/checksums.txt".to_string(),
|
||||
200,
|
||||
checksums.as_bytes().to_vec(),
|
||||
),
|
||||
]);
|
||||
let release = github_latest(&base, None, "x86_64-unknown-linux-musl").unwrap();
|
||||
assert_eq!(release.version, "9.9.9");
|
||||
assert_eq!(
|
||||
release.sha256.as_deref(),
|
||||
Some("aaaa000000000000000000000000000000000000000000000000000000000000")
|
||||
);
|
||||
assert_eq!(
|
||||
release.tarball_url,
|
||||
format!(
|
||||
"{}/releases/download/v9.9.9/rtk-x86_64-unknown-linux-musl.tar.gz",
|
||||
base
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_latest_via_fixture_302_redirect() {
|
||||
let base = super::super::test_http::serve_with_headers(vec![(
|
||||
"/releases/latest".to_string(),
|
||||
302,
|
||||
vec![(
|
||||
"Location".to_string(),
|
||||
"https://example.com/rtk-ai/rtk/releases/tag/v1.2.3".to_string(),
|
||||
)],
|
||||
Vec::new(),
|
||||
)]);
|
||||
let release = github_latest(&base, None, "x86_64-unknown-linux-musl").unwrap();
|
||||
assert_eq!(release.version, "1.2.3");
|
||||
assert!(release.sha256.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_latest_pinned_version() {
|
||||
let base = super::super::test_http::serve(Vec::new());
|
||||
let release = github_latest(&base, Some("v1.5.0"), "x86_64-unknown-linux-musl").unwrap();
|
||||
assert_eq!(release.version, "1.5.0");
|
||||
assert!(release.sha256.is_none());
|
||||
assert!(release.tarball_url.contains("/releases/download/v1.5.0/"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Install-method detection: who owns the binary we are running from?
|
||||
//!
|
||||
//! The self-managed engine only ever mutates `SelfManaged` installs.
|
||||
//! Brew-managed and system-package binaries are detected so every
|
||||
//! mutating verb refuses cleanly instead of creating a second `rtk`
|
||||
//! copy on PATH (the silent-shadowing bug this feature exists to prevent).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &[
|
||||
"/usr/bin/",
|
||||
"/usr/sbin/",
|
||||
"/bin/",
|
||||
"/sbin/",
|
||||
"/usr/local/sbin/",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum InstallMethod {
|
||||
BrewManaged { path: PathBuf },
|
||||
SelfManaged { path: PathBuf },
|
||||
SystemPackage { path: PathBuf },
|
||||
}
|
||||
|
||||
impl InstallMethod {
|
||||
pub fn path(&self) -> &Path {
|
||||
match self {
|
||||
InstallMethod::BrewManaged { path }
|
||||
| InstallMethod::SelfManaged { path }
|
||||
| InstallMethod::SystemPackage { path } => path,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn describe(&self) -> &'static str {
|
||||
match self {
|
||||
InstallMethod::BrewManaged { .. } => "brew-managed",
|
||||
InstallMethod::SelfManaged { .. } => "self-managed",
|
||||
InstallMethod::SystemPackage { .. } => "system package",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detect() -> Result<InstallMethod> {
|
||||
let exe = std::env::current_exe().context("Failed to resolve own executable path")?;
|
||||
// A brew-linked bin/rtk canonicalizes into the Cellar.
|
||||
let real = exe.canonicalize().unwrap_or(exe);
|
||||
let writable = real.parent().is_some_and(dir_writable);
|
||||
Ok(classify(
|
||||
&real,
|
||||
std::env::var("HOMEBREW_PREFIX").ok().as_deref(),
|
||||
writable,
|
||||
))
|
||||
}
|
||||
|
||||
fn classify(real: &Path, homebrew_prefix: Option<&str>, dir_writable: bool) -> InstallMethod {
|
||||
let s = real.to_string_lossy();
|
||||
let path = real.to_path_buf();
|
||||
|
||||
let brew = s.contains("/Cellar/")
|
||||
|| s.starts_with("/opt/homebrew/")
|
||||
|| s.starts_with("/home/linuxbrew/.linuxbrew/")
|
||||
|| homebrew_prefix.is_some_and(|p| !p.is_empty() && s.starts_with(p));
|
||||
if brew {
|
||||
return InstallMethod::BrewManaged { path };
|
||||
}
|
||||
|
||||
// The swap engine needs a writable parent dir (temp file + rename);
|
||||
// an unwritable one means a package-manager or root install.
|
||||
if SYSTEM_DIRS.iter().any(|p| s.starts_with(p)) || !dir_writable {
|
||||
return InstallMethod::SystemPackage { path };
|
||||
}
|
||||
|
||||
InstallMethod::SelfManaged { path }
|
||||
}
|
||||
|
||||
fn dir_writable(dir: &Path) -> bool {
|
||||
let probe = dir.join(format!(".rtk-write-probe-{}", std::process::id()));
|
||||
match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&probe)
|
||||
{
|
||||
Ok(_) => {
|
||||
let _ = std::fs::remove_file(&probe);
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_classify_self_managed_home() {
|
||||
let m = classify(Path::new("/home/dev/.local/bin/rtk"), None, true);
|
||||
assert!(matches!(m, InstallMethod::SelfManaged { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_brew_cellar() {
|
||||
for path in [
|
||||
"/opt/homebrew/Cellar/rtk/0.43.0/bin/rtk",
|
||||
"/usr/local/Cellar/rtk/0.43.0/bin/rtk",
|
||||
"/home/linuxbrew/.linuxbrew/Cellar/rtk/0.43.0/bin/rtk",
|
||||
] {
|
||||
let m = classify(Path::new(path), None, true);
|
||||
assert!(matches!(m, InstallMethod::BrewManaged { .. }), "{}", path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_homebrew_prefix_env() {
|
||||
let m = classify(
|
||||
Path::new("/custom/brew/bin/rtk"),
|
||||
Some("/custom/brew"),
|
||||
true,
|
||||
);
|
||||
assert!(matches!(m, InstallMethod::BrewManaged { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_empty_homebrew_prefix_ignored() {
|
||||
let m = classify(Path::new("/home/dev/.local/bin/rtk"), Some(""), true);
|
||||
assert!(matches!(m, InstallMethod::SelfManaged { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_system_dir() {
|
||||
let m = classify(Path::new("/usr/bin/rtk"), None, false);
|
||||
assert!(matches!(m, InstallMethod::SystemPackage { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_unwritable_dir_is_system() {
|
||||
let m = classify(Path::new("/opt/tools/rtk"), None, false);
|
||||
assert!(matches!(m, InstallMethod::SystemPackage { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dir_writable_probe() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(dir_writable(tmp.path()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Self-managed install lifecycle: `rtk update` / `rtk uninstall`.
|
||||
//!
|
||||
//! One engine drives both flows: resolve the latest GitHub release, verify
|
||||
//! its checksum, atomically swap the binary at its own path. The `rtk` name
|
||||
//! always has exactly one owner — mutating verbs refuse on brew-managed or
|
||||
//! system-package installs instead of creating a second copy on PATH
|
||||
//! (Homebrew-aware flows arrive in a later phase).
|
||||
|
||||
pub mod channel;
|
||||
pub mod detect;
|
||||
pub mod platform;
|
||||
pub mod swap;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_http;
|
||||
pub mod version;
|
||||
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
use detect::InstallMethod;
|
||||
|
||||
pub fn update(current_version: &str, check: bool, rollback: bool, yes: bool) -> Result<i32> {
|
||||
if check {
|
||||
return status_check(current_version);
|
||||
}
|
||||
if rollback {
|
||||
let target = require_self_managed(&detect::detect()?, "rollback")?;
|
||||
confirm(
|
||||
&format!("Restore the previous binary at {}?", target.display()),
|
||||
yes,
|
||||
)?;
|
||||
swap::restore_backup(&target)?;
|
||||
println!("Previous binary restored. Verify with: rtk --version");
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let target = require_self_managed(&detect::detect()?, "update")?;
|
||||
let release = channel::latest(&platform::detect()?)?;
|
||||
if !version::is_newer(&release.version, current_version) {
|
||||
println!(
|
||||
"Already up to date (v{})",
|
||||
version::numeric(current_version)
|
||||
);
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
confirm(
|
||||
&format!(
|
||||
"Update rtk v{} → v{}?",
|
||||
version::numeric(current_version),
|
||||
release.version
|
||||
),
|
||||
yes,
|
||||
)?;
|
||||
swap::download_and_swap(&release.tarball_url, release.sha256.as_deref(), &target)?;
|
||||
println!(
|
||||
"Updated to rtk v{} (previous binary kept at {})",
|
||||
release.version,
|
||||
swap::backup_path(&target).display()
|
||||
);
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub fn uninstall(yes: bool, purge: bool) -> Result<i32> {
|
||||
let target = require_self_managed(&detect::detect()?, "uninstall")?;
|
||||
confirm(
|
||||
&format!(
|
||||
"Remove rtk from {}?{}",
|
||||
target.display(),
|
||||
if purge {
|
||||
" Config and data directories will also be removed."
|
||||
} else {
|
||||
""
|
||||
}
|
||||
),
|
||||
yes,
|
||||
)?;
|
||||
|
||||
std::fs::remove_file(&target)
|
||||
.with_context(|| format!("Failed to remove '{}'", target.display()))?;
|
||||
let _ = std::fs::remove_file(swap::backup_path(&target));
|
||||
println!("Removed {}", target.display());
|
||||
|
||||
if purge {
|
||||
purge_user_dirs();
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn status_check(current_version: &str) -> Result<i32> {
|
||||
let method = detect::detect()?;
|
||||
let target = platform::detect()?;
|
||||
println!("version: {}", current_version);
|
||||
println!(
|
||||
"binary: {} ({})",
|
||||
method.path().display(),
|
||||
method.describe()
|
||||
);
|
||||
println!(
|
||||
"backup: {}",
|
||||
if swap::backup_path(method.path()).exists() {
|
||||
"present (rtk update --rollback)"
|
||||
} else {
|
||||
"none"
|
||||
}
|
||||
);
|
||||
match channel::latest(&target) {
|
||||
Ok(release) => {
|
||||
println!("latest: {}", release.version);
|
||||
if version::is_newer(&release.version, current_version) {
|
||||
println!("update available: v{} — run 'rtk update'", release.version);
|
||||
}
|
||||
}
|
||||
Err(e) => println!("latest: unavailable ({:#})", e),
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn require_self_managed(method: &InstallMethod, verb: &str) -> Result<PathBuf> {
|
||||
match method {
|
||||
InstallMethod::SelfManaged { path } => Ok(path.clone()),
|
||||
InstallMethod::BrewManaged { path } => bail!(
|
||||
"This rtk is managed by Homebrew ({}) — '{}' only operates on self-managed installs.\n\
|
||||
Use 'brew upgrade rtk' / 'brew uninstall rtk'. Homebrew-aware flows arrive in a later version.",
|
||||
path.display(),
|
||||
verb
|
||||
),
|
||||
InstallMethod::SystemPackage { path } => bail!(
|
||||
"This rtk is managed by a system package manager ({}) — '{}' only operates on self-managed installs.\n\
|
||||
Use 'apt upgrade rtk' / 'dnf upgrade rtk' or your package tool.",
|
||||
path.display(),
|
||||
verb
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(prompt: &str, yes: bool) -> Result<()> {
|
||||
if yes {
|
||||
return Ok(());
|
||||
}
|
||||
if !std::io::stdin().is_terminal() {
|
||||
bail!("Confirmation required — re-run with --yes in non-interactive contexts");
|
||||
}
|
||||
eprint!("{} [y/N] ", prompt);
|
||||
let mut answer = String::new();
|
||||
std::io::stdin()
|
||||
.read_line(&mut answer)
|
||||
.context("Failed to read confirmation")?;
|
||||
if matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("Aborted");
|
||||
}
|
||||
}
|
||||
|
||||
fn purge_user_dirs() {
|
||||
let dirs = [
|
||||
dirs::config_dir().map(|d| d.join("rtk")),
|
||||
dirs::data_local_dir().map(|d| d.join("rtk")),
|
||||
];
|
||||
for dir in dirs.into_iter().flatten() {
|
||||
if dir.exists() {
|
||||
match std::fs::remove_dir_all(&dir) {
|
||||
Ok(()) => println!("Removed {}", dir.display()),
|
||||
Err(e) => eprintln!("rtk: warning: could not remove {}: {}", dir.display(), e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_require_self_managed() {
|
||||
let ok = require_self_managed(
|
||||
&InstallMethod::SelfManaged {
|
||||
path: PathBuf::from("/home/dev/.local/bin/rtk"),
|
||||
},
|
||||
"update",
|
||||
);
|
||||
assert!(ok.is_ok());
|
||||
|
||||
let brew = require_self_managed(
|
||||
&InstallMethod::BrewManaged {
|
||||
path: PathBuf::from("/opt/homebrew/Cellar/rtk/0.43.0/bin/rtk"),
|
||||
},
|
||||
"update",
|
||||
);
|
||||
assert!(brew.unwrap_err().to_string().contains("Homebrew"));
|
||||
|
||||
let system = require_self_managed(
|
||||
&InstallMethod::SystemPackage {
|
||||
path: PathBuf::from("/usr/bin/rtk"),
|
||||
},
|
||||
"update",
|
||||
);
|
||||
assert!(system.unwrap_err().to_string().contains("package manager"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_confirm_yes_flag_skips_prompt() {
|
||||
assert!(confirm("proceed?", true).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Maps the running build to its release triple
|
||||
//! (`x86_64-unknown-linux-musl`) used in release asset names.
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
pub struct Target {
|
||||
pub triple: &'static str,
|
||||
}
|
||||
|
||||
pub fn detect() -> Result<Target> {
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
return Ok(Target {
|
||||
triple: "x86_64-unknown-linux-musl",
|
||||
});
|
||||
|
||||
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
|
||||
return Ok(Target {
|
||||
triple: "aarch64-unknown-linux-gnu",
|
||||
});
|
||||
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
return Ok(Target {
|
||||
triple: "x86_64-apple-darwin",
|
||||
});
|
||||
|
||||
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
|
||||
return Ok(Target {
|
||||
triple: "aarch64-apple-darwin",
|
||||
});
|
||||
|
||||
#[allow(unreachable_code)]
|
||||
{
|
||||
bail!(
|
||||
"unsupported platform for self-managed install flows ({}-{})",
|
||||
std::env::consts::OS,
|
||||
std::env::consts::ARCH
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_detect_current_platform() {
|
||||
let target = detect().expect("supported platform");
|
||||
assert!(target.triple.contains('-'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! Atomic binary replacement engine for self-managed installs.
|
||||
//!
|
||||
//! Verify-before-touch: the tarball is downloaded to a temp file in the
|
||||
//! target's own directory (same filesystem → atomic `rename`), its sha256
|
||||
//! checked against the channel's expected value, and only then is the live
|
||||
//! binary stashed to `<target>.bak` and replaced. Any failure leaves the
|
||||
//! live binary untouched.
|
||||
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::core::utils::resolved_command;
|
||||
|
||||
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
const BINARY_NAMES: &[&str] = &["rtk"];
|
||||
|
||||
pub fn backup_path(target: &Path) -> PathBuf {
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "rtk".to_string());
|
||||
target.with_file_name(format!("{}.bak", name))
|
||||
}
|
||||
|
||||
/// Download, verify and atomically install a release tarball over `target`.
|
||||
pub fn download_and_swap(url: &str, expected_sha256: Option<&str>, target: &Path) -> Result<()> {
|
||||
let dir = target
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("Target path '{}' has no parent directory", target.display()))?;
|
||||
fs::create_dir_all(dir)
|
||||
.with_context(|| format!("Failed to create install directory '{}'", dir.display()))?;
|
||||
|
||||
let staging = Staging::new(dir)?;
|
||||
download(url, &staging.tarball)?;
|
||||
|
||||
match expected_sha256 {
|
||||
Some(expected) => {
|
||||
let actual = sha256_file(&staging.tarball)?;
|
||||
if actual != expected.to_lowercase() {
|
||||
bail!(
|
||||
"Checksum mismatch for {} (expected {}, got {}) — a proxy may have served a stale file; retry",
|
||||
url,
|
||||
expected,
|
||||
actual
|
||||
);
|
||||
}
|
||||
}
|
||||
None => eprintln!("rtk: warning: no checksum available — installing unverified download"),
|
||||
}
|
||||
|
||||
let binary = extract_binary(&staging)?;
|
||||
swap_file(&binary, target)
|
||||
}
|
||||
|
||||
/// Restore the previous binary stashed by the last swap.
|
||||
pub fn restore_backup(target: &Path) -> Result<()> {
|
||||
let bak = backup_path(target);
|
||||
if !bak.exists() {
|
||||
bail!("No backup found at '{}'", bak.display());
|
||||
}
|
||||
fs::rename(&bak, target)
|
||||
.with_context(|| format!("Failed to restore '{}' from backup", target.display()))
|
||||
}
|
||||
|
||||
fn swap_file(new_binary: &Path, target: &Path) -> Result<()> {
|
||||
set_executable(new_binary)?;
|
||||
if target.exists() {
|
||||
fs::copy(target, backup_path(target))
|
||||
.with_context(|| format!("Failed to back up '{}'", target.display()))?;
|
||||
}
|
||||
fs::rename(new_binary, target)
|
||||
.with_context(|| format!("Failed to install to '{}'", target.display()))
|
||||
}
|
||||
|
||||
fn download(url: &str, dest: &Path) -> Result<()> {
|
||||
let response = ureq::get(url)
|
||||
.set("Cache-Control", "no-cache")
|
||||
.set("User-Agent", "rtk-distribution")
|
||||
.timeout(DOWNLOAD_TIMEOUT)
|
||||
.call()
|
||||
.with_context(|| format!("Download failed: {}", url))?;
|
||||
let mut file = fs::File::create(dest)
|
||||
.with_context(|| format!("Failed to create temp file '{}'", dest.display()))?;
|
||||
std::io::copy(&mut response.into_reader(), &mut file)
|
||||
.with_context(|| format!("Failed to write download to '{}'", dest.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sha256_file(path: &Path) -> Result<String> {
|
||||
let mut file =
|
||||
fs::File::open(path).with_context(|| format!("Failed to open '{}'", path.display()))?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = [0u8; 64 * 1024];
|
||||
loop {
|
||||
let n = file.read(&mut buf).context("Read failed during hashing")?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buf[..n]);
|
||||
}
|
||||
Ok(hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|b| format!("{:02x}", b))
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn extract_binary(staging: &Staging) -> Result<PathBuf> {
|
||||
let status = resolved_command("tar")
|
||||
.arg("-xzf")
|
||||
.arg(&staging.tarball)
|
||||
.arg("-C")
|
||||
.arg(&staging.extract_dir)
|
||||
.status()
|
||||
.context("Failed to run tar")?;
|
||||
if !status.success() {
|
||||
bail!("tar extraction failed (corrupt archive?)");
|
||||
}
|
||||
find_binary(&staging.extract_dir)
|
||||
.ok_or_else(|| anyhow!("No rtk binary found in downloaded archive"))
|
||||
}
|
||||
|
||||
fn find_binary(dir: &Path) -> Option<PathBuf> {
|
||||
let entries = fs::read_dir(dir).ok()?;
|
||||
let mut subdirs = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
let name = entry.file_name();
|
||||
if BINARY_NAMES.iter().any(|b| name == *b) {
|
||||
return Some(path);
|
||||
}
|
||||
} else if path.is_dir() {
|
||||
subdirs.push(path);
|
||||
}
|
||||
}
|
||||
subdirs.iter().find_map(|sub| find_binary(sub))
|
||||
}
|
||||
|
||||
fn set_executable(path: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o755))
|
||||
.with_context(|| format!("Failed to chmod '{}'", path.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Temp paths inside the target directory, removed on drop so failures
|
||||
/// never leave half-written files next to the live binary.
|
||||
struct Staging {
|
||||
tarball: PathBuf,
|
||||
extract_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Staging {
|
||||
fn new(dir: &Path) -> Result<Self> {
|
||||
let pid = std::process::id();
|
||||
let extract_dir = dir.join(format!(".rtk-dist-{}", pid));
|
||||
fs::create_dir_all(&extract_dir)
|
||||
.with_context(|| format!("Failed to create staging dir in '{}'", dir.display()))?;
|
||||
Ok(Self {
|
||||
tarball: dir.join(format!(".rtk-dist-{}.tar.gz", pid)),
|
||||
extract_dir,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Staging {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(&self.tarball);
|
||||
let _ = fs::remove_dir_all(&self.extract_dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
fn make_tarball(dir: &Path, binary_name: &str, content: &str) -> PathBuf {
|
||||
let src = dir.join("pack");
|
||||
fs::create_dir_all(&src).unwrap();
|
||||
fs::write(src.join(binary_name), content).unwrap();
|
||||
let tar = dir.join("release.tar.gz");
|
||||
let status = Command::new("tar")
|
||||
.arg("-czf")
|
||||
.arg(&tar)
|
||||
.arg("-C")
|
||||
.arg(&src)
|
||||
.arg(binary_name)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
tar
|
||||
}
|
||||
|
||||
fn serve_tarball(tar: &Path) -> (String, String) {
|
||||
let bytes = fs::read(tar).unwrap();
|
||||
let sha = sha256_file(tar).unwrap();
|
||||
let base =
|
||||
super::super::test_http::serve(vec![("/release.tar.gz".to_string(), 200, bytes)]);
|
||||
(format!("{}/release.tar.gz", base), sha)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_download_and_swap_success_with_backup() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("bin").join("rtk");
|
||||
fs::create_dir_all(target.parent().unwrap()).unwrap();
|
||||
fs::write(&target, "old-binary").unwrap();
|
||||
|
||||
let tar = make_tarball(tmp.path(), "rtk", "new-binary");
|
||||
let (url, sha) = serve_tarball(&tar);
|
||||
|
||||
download_and_swap(&url, Some(&sha), &target).unwrap();
|
||||
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), "new-binary");
|
||||
assert_eq!(
|
||||
fs::read_to_string(backup_path(&target)).unwrap(),
|
||||
"old-binary"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(&target).unwrap().permissions().mode();
|
||||
assert_eq!(mode & 0o777, 0o755);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_checksum_mismatch_leaves_target_untouched() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("rtk");
|
||||
fs::write(&target, "old-binary").unwrap();
|
||||
|
||||
let tar = make_tarball(tmp.path(), "rtk", "evil-binary");
|
||||
let (url, _) = serve_tarball(&tar);
|
||||
|
||||
let err = download_and_swap(&url, Some(&"0".repeat(64)), &target).unwrap_err();
|
||||
assert!(err.to_string().contains("Checksum mismatch"));
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), "old-binary");
|
||||
assert!(!backup_path(&target).exists());
|
||||
// Staging temp files must be cleaned up.
|
||||
let leftovers: Vec<_> = fs::read_dir(tmp.path())
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.filter(|e| e.file_name().to_string_lossy().starts_with(".rtk-dist"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_swap_rejects_unknown_binary_name() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("rtk");
|
||||
fs::write(&target, "old-binary").unwrap();
|
||||
let tar = make_tarball(tmp.path(), "other-tool", "other-binary");
|
||||
let (url, sha) = serve_tarball(&tar);
|
||||
|
||||
assert!(download_and_swap(&url, Some(&sha), &target).is_err());
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), "old-binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_corrupt_archive_fails_cleanly() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("rtk");
|
||||
fs::write(&target, "old-binary").unwrap();
|
||||
|
||||
let base = super::super::test_http::serve(vec![(
|
||||
"/release.tar.gz".to_string(),
|
||||
200,
|
||||
b"not a tarball".to_vec(),
|
||||
)]);
|
||||
let url = format!("{}/release.tar.gz", base);
|
||||
|
||||
assert!(download_and_swap(&url, None, &target).is_err());
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), "old-binary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_backup_roundtrip() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("rtk");
|
||||
fs::write(&target, "current").unwrap();
|
||||
fs::write(backup_path(&target), "previous").unwrap();
|
||||
|
||||
restore_backup(&target).unwrap();
|
||||
assert_eq!(fs::read_to_string(&target).unwrap(), "previous");
|
||||
assert!(!backup_path(&target).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_restore_backup_missing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let target = tmp.path().join("rtk");
|
||||
assert!(restore_backup(&target).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! Minimal in-process HTTP fixture server for distribution tests.
|
||||
//! Serves canned responses on an ephemeral port; the daemon thread dies
|
||||
//! with the test process.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
type Route = (String, u16, Vec<(String, String)>, Vec<u8>);
|
||||
|
||||
pub fn serve(routes: Vec<(String, u16, Vec<u8>)>) -> String {
|
||||
serve_with_headers(
|
||||
routes
|
||||
.into_iter()
|
||||
.map(|(path, status, body)| (path, status, Vec::new(), body))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn serve_with_headers(routes: Vec<Route>) -> String {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind fixture server");
|
||||
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
handle(stream, &routes);
|
||||
}
|
||||
});
|
||||
base
|
||||
}
|
||||
|
||||
fn handle(stream: std::net::TcpStream, routes: &[Route]) {
|
||||
let mut reader = BufReader::new(stream);
|
||||
let mut request_line = String::new();
|
||||
if reader.read_line(&mut request_line).is_err() {
|
||||
return;
|
||||
}
|
||||
// Drain headers so the client sees a well-behaved server.
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).is_ok() && line.trim() != "" {
|
||||
line.clear();
|
||||
}
|
||||
|
||||
let path = request_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("/")
|
||||
.split('?')
|
||||
.next()
|
||||
.unwrap_or("/")
|
||||
.to_string();
|
||||
|
||||
let mut stream = reader.into_inner();
|
||||
match routes.iter().find(|(p, ..)| *p == path) {
|
||||
Some((_, status, headers, body)) => {
|
||||
let mut response = format!(
|
||||
"HTTP/1.1 {} X\r\nContent-Length: {}\r\n",
|
||||
status,
|
||||
body.len()
|
||||
);
|
||||
for (k, v) in headers {
|
||||
response.push_str(&format!("{}: {}\r\n", k, v));
|
||||
}
|
||||
response.push_str("Connection: close\r\n\r\n");
|
||||
let _ = stream.write_all(response.as_bytes());
|
||||
let _ = stream.write_all(body);
|
||||
}
|
||||
None => {
|
||||
let _ = stream.write_all(
|
||||
b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Version parsing and comparison for self-update.
|
||||
//!
|
||||
//! Compares versions without a semver dependency: release tags (`v0.42.4`)
|
||||
//! and pre-releases (`dev-0.44.0-rc.3`). Only the numeric dotted core is
|
||||
//! compared; any suffix is ignored.
|
||||
|
||||
pub fn parse(version: &str) -> Vec<u64> {
|
||||
let start = match version.find(|c: char| c.is_ascii_digit()) {
|
||||
Some(i) => i,
|
||||
None => return Vec::new(),
|
||||
};
|
||||
version[start..]
|
||||
.split(|c: char| !c.is_ascii_digit() && c != '.')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.split('.')
|
||||
.filter_map(|part| part.parse::<u64>().ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn is_newer(remote: &str, local: &str) -> bool {
|
||||
let r = parse(remote);
|
||||
let l = parse(local);
|
||||
if r.is_empty() || l.is_empty() {
|
||||
// Unparseable versions must never trigger a self-replace.
|
||||
return false;
|
||||
}
|
||||
r > l
|
||||
}
|
||||
|
||||
/// Plain `X.Y.Z` form as used in download URLs.
|
||||
pub fn numeric(version: &str) -> String {
|
||||
parse(version)
|
||||
.iter()
|
||||
.map(|n| n.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(".")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_forms() {
|
||||
assert_eq!(parse("0.42.4"), vec![0, 42, 4]);
|
||||
assert_eq!(parse("v0.42.4"), vec![0, 42, 4]);
|
||||
assert_eq!(parse("1.2.3-rc.4"), vec![1, 2, 3]);
|
||||
assert_eq!(parse("dev-0.44.0-rc.309"), vec![0, 44, 0]);
|
||||
assert!(parse("not-a-version").is_empty());
|
||||
assert!(parse("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_newer() {
|
||||
assert!(is_newer("0.43.0", "0.42.4"));
|
||||
assert!(!is_newer("0.42.4", "0.43.0"));
|
||||
assert!(!is_newer("0.42.4", "0.42.4"));
|
||||
assert!(is_newer("0.100.0", "0.99.9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_newer_ignores_suffix() {
|
||||
assert!(is_newer("0.42.4", "0.40.0-rc.1"));
|
||||
assert!(!is_newer("0.40.0-rc.1", "0.42.4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_newer_unparseable_never_updates() {
|
||||
assert!(!is_newer("garbage", "0.42.4"));
|
||||
assert!(!is_newer("0.43.0", "garbage"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_numeric() {
|
||||
assert_eq!(numeric("v0.43.0"), "0.43.0");
|
||||
assert_eq!(numeric("1.2.3-rc.4"), "1.2.3");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ pub mod args_utils;
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
pub mod display_helpers;
|
||||
pub mod distribution;
|
||||
pub mod filter;
|
||||
pub mod guard;
|
||||
pub mod runner;
|
||||
|
||||
+32
-1
@@ -55,7 +55,7 @@ pub enum AgentTarget {
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "rtk",
|
||||
version,
|
||||
version = concat!(env!("CARGO_PKG_VERSION"), " (OSS)"),
|
||||
about = "Rust Token Killer - Minimize LLM token consumption",
|
||||
long_about = "A high-performance CLI proxy designed to filter and summarize system outputs before they reach your LLM context."
|
||||
)]
|
||||
@@ -841,6 +841,29 @@ enum Commands {
|
||||
#[command(subcommand)]
|
||||
command: HookCommands,
|
||||
},
|
||||
|
||||
/// Update rtk to the latest release
|
||||
Update {
|
||||
/// Show install method and available version without changing anything
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
/// Restore the previous binary kept by the last update
|
||||
#[arg(long)]
|
||||
rollback: bool,
|
||||
/// Skip confirmation prompts
|
||||
#[arg(short, long)]
|
||||
yes: bool,
|
||||
},
|
||||
|
||||
/// Uninstall rtk from this machine
|
||||
Uninstall {
|
||||
/// Skip confirmation prompts
|
||||
#[arg(short, long)]
|
||||
yes: bool,
|
||||
/// Also remove rtk config and data directories
|
||||
#[arg(long)]
|
||||
purge: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
@@ -2625,6 +2648,14 @@ fn run_cli() -> Result<i32> {
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
Commands::Update {
|
||||
check,
|
||||
rollback,
|
||||
yes,
|
||||
} => core::distribution::update(env!("CARGO_PKG_VERSION"), check, rollback, yes)?,
|
||||
|
||||
Commands::Uninstall { yes, purge } => core::distribution::uninstall(yes, purge)?,
|
||||
};
|
||||
|
||||
Ok(code)
|
||||
|
||||
Reference in new issue
Block a user