use crate::upgrade::{no_run_in_progress, Cmd, Opts, Runner, Setup, Term, Verdict};
use anyhow::{anyhow, bail, Context, Result};
use eclipse_core::config::UpdateConfig;
use eclipse_core::http;
use eclipse_core::update::{self, Channel, InstallMarker, Release, Version};
use std::io::IsTerminal;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::Duration;
const MAX_TARBALL_BYTES: u64 = 128 * 1024 * 1024;
const MAX_SUMS_BYTES: u64 = 64 * 1024;
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
const BINARIES: [&str; 3] = ["eclipse", "eclipse-web", "eclipse-gateway"];
pub fn run(
opts: &Opts,
setup: &Setup,
marker: &InstallMarker,
runner: &dyn Runner,
term: &mut Term,
) -> Result<Verdict> {
let bin_dir = marker.prefix.join("bin");
let binary = bin_dir.join("eclipse");
if !binary.is_file() {
bail!(
"{} says eclipse was installed under {}, but {} does not exist. Nothing was \
changed, and nothing will be installed anywhere new: if the install was moved or \
removed, install from the release tarball again to record it",
setup.marker.display(),
marker.prefix.display(),
binary.display()
);
}
if !opts.check {
no_run_in_progress(setup)?;
}
let Some(installed) = marker.version.as_deref().and_then(Version::parse) else {
bail!(
"{} does not say which version is installed, so there is nothing to compare a newer \
tag with. Re-run install.sh from the tarball you installed (that is what records \
it); nothing was changed",
setup.marker.display()
);
};
let asked = setup
.update
.releases
.as_deref()
.unwrap_or(update::DEFAULT_RELEASES_URL);
let latest = fetch(asked, &setup.update).map_err(|e| {
anyhow!("could not ask {asked} for the newest release: {e}. Nothing was changed")
})?;
if latest.version <= installed {
writeln!(
term.out,
"{} {installed} on the {} release",
term.style.green("already up to date:"),
latest.tag
)?;
if !opts.check && !opts.dry_run {
crate::upgrade::migrate_config(term, &marker.prefix)?;
}
return Ok(Verdict::Current);
}
writeln!(
term.out,
"{installed} installed; {} is the newest release",
latest.tag
)?;
if opts.check {
return Ok(Verdict::Behind);
}
if opts.dry_run {
writeln!(term.out, "dry run: nothing below is fetched or run.")?;
writeln!(term.out, " GET {}", latest.tarball_url)?;
writeln!(term.out, " GET {}", latest.sums_url)?;
writeln!(
term.out,
" sha256sum {} (must equal the digest in SHA256SUMS)",
latest.tarball_name
)?;
writeln!(
term.out,
" tar -xzf {} (must hold eclipse, eclipse-web and eclipse-gateway)",
latest.tarball_name
)?;
writeln!(
term.out,
" <unpacked>/eclipse --version (must say `eclipse {}`)",
latest.version
)?;
for name in BINARIES {
writeln!(
term.out,
" install <unpacked>/{name} -> {} (the old one kept as {name}.old)",
bin_dir.join(name).display()
)?;
}
if !opts.no_restart && crate::gateway_cli::installed_unit().is_some() {
writeln!(
term.out,
" systemctl --user restart {} (it is serving the old build until it does)",
crate::gateway_cli::SERVICE_NAME
)?;
}
writeln!(
term.out,
"Config and sessions are not touched: an upgrade replaces the binaries and the install record."
)?;
return Ok(Verdict::Planned);
}
if latest.version.major != installed.major {
major_gate(term, installed, &latest)?;
}
let state = setup
.marker
.parent()
.context("the install record has no directory")?;
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let work = state.join(format!("upgrade-{}-{stamp}", std::process::id()));
std::fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
let done = perform(runner, &latest, &bin_dir, &work, setup, marker, term);
if matches!(done, Ok(Verdict::Upgraded)) {
if let Err(e) = crate::upgrade::after_the_binaries(term, runner, opts) {
writeln!(
term.out,
"{}",
term.style.dim(&format!(
"the gateway was not restarted ({e}); `eclipse gateway restart` when you are ready"
))
)?;
}
crate::upgrade::migrate_config(term, &marker.prefix)?;
}
let _ = std::fs::remove_dir_all(&work);
done
}
fn perform(
runner: &dyn Runner,
latest: &Release,
bin_dir: &Path,
work: &Path,
setup: &Setup,
marker: &InstallMarker,
term: &mut Term,
) -> Result<Verdict> {
writeln!(term.out, "downloading {} ...", latest.tarball_name)?;
term.out.flush()?;
let (tarball, sums) = download(latest, work)?;
let expected = expected_digest(&sums, &latest.tarball_name)?;
let actual = sha256_of(runner, &tarball)?;
if actual != expected {
bail!(
"the downloaded {} has SHA256 {actual}, and {} says it should be {expected}. The \
download is corrupt or not what the release published; it was not installed, \
nothing was replaced, and the download was discarded",
latest.tarball_name,
update::SUMS_NAME
);
}
let unpacked = unpack(runner, &tarball, work)?;
the_binary_says_its_version(runner, latest, &unpacked)?;
let kept_marker = keep_the_marker(setup)?;
let swapped = swap(bin_dir, &unpacked)?;
if let Err(e) = write_marker(setup, marker, latest) {
return Err(roll_back(bin_dir, &swapped, e));
}
writeln!(
term.out,
"{} {} \u{2192} {} ({}).",
term.style.green("upgraded:"),
marker.version.as_deref().unwrap_or("?"),
latest.version,
latest.tag
)?;
writeln!(
term.out,
"{} rename each {}/<name>.old back over <name>, then restore {} from {} — without the \
record the next upgrade thinks it is already on {}.",
term.style.dim("to roll back:"),
bin_dir.display(),
setup.marker.display(),
kept_marker.display(),
latest.version
)?;
Ok(Verdict::Upgraded)
}
fn fetch(asked: &str, cfg: &UpdateConfig) -> std::result::Result<Release, String> {
let cfg = cfg.clone();
let result = std::thread::scope(|scope| {
scope
.spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(update::fetch_release(&cfg))
})
.join()
});
match result {
Ok(r) => r,
Err(_) => Err(format!("the request to {asked} could not be run")),
}
}
fn download(latest: &Release, work: &Path) -> Result<(PathBuf, PathBuf)> {
let tarball = work.join(&latest.tarball_name);
let sums = work.join(update::SUMS_NAME);
let (want_tar, want_sums) = (tarball.clone(), sums.clone());
let (tar_url, sums_url) = (latest.tarball_url.clone(), latest.sums_url.clone());
let result = std::thread::scope(|scope| {
scope
.spawn(move || {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(async move {
http::download(&tar_url, DOWNLOAD_TIMEOUT, MAX_TARBALL_BYTES, &want_tar)
.await?;
http::download(&sums_url, DOWNLOAD_TIMEOUT, MAX_SUMS_BYTES, &want_sums).await?;
Ok::<(), String>(())
})
})
.join()
});
match result {
Ok(Ok(())) => Ok((tarball, sums)),
Ok(Err(e)) => {
let _ = std::fs::remove_file(&tarball);
let _ = std::fs::remove_file(&sums);
bail!(
"could not download {}: {e}. Nothing was replaced",
latest.tarball_name
)
}
Err(_) => {
let _ = std::fs::remove_file(&tarball);
let _ = std::fs::remove_file(&sums);
bail!(
"could not download {}: the download could not be run. Nothing was replaced",
latest.tarball_name
)
}
}
}
fn expected_digest(sums: &Path, name: &str) -> Result<String> {
let text =
std::fs::read_to_string(sums).with_context(|| format!("reading {}", sums.display()))?;
for line in text.lines() {
let mut parts = line.split_whitespace();
let (Some(digest), Some(file)) = (parts.next(), parts.next()) else {
continue;
};
if file.trim_start_matches('*') != name {
continue;
}
if digest.len() == 64 && digest.bytes().all(|b| b.is_ascii_hexdigit()) {
return Ok(digest.to_ascii_lowercase());
}
}
bail!(
"{} names no SHA256 for {name}, so the download cannot be checked. Nothing was \
replaced",
sums.display()
)
}
fn sha256_of(runner: &dyn Runner, path: &Path) -> Result<String> {
let cmd = Cmd {
program: "sha256sum".into(),
args: vec![path.display().to_string()],
dir: None,
stream: false,
no_prompt: false,
};
let out = runner.run(&cmd).map_err(|e| {
anyhow!(
"could not run `{}`: {e}. An upgrade of a release install needs sha256sum \
(coreutils) to verify the download",
cmd.display()
)
})?;
if !out.success {
bail!("`{}` failed: {}", cmd.display(), out.stderr.trim());
}
let digest = out
.stdout
.split_whitespace()
.next()
.unwrap_or("")
.to_ascii_lowercase();
if digest.len() != 64 || !digest.bytes().all(|b| b.is_ascii_hexdigit()) {
bail!(
"`{}` printed something that is not a SHA256: {:?}",
cmd.display(),
out.stdout.trim()
);
}
Ok(digest)
}
fn unpack(runner: &dyn Runner, tarball: &Path, into: &Path) -> Result<PathBuf> {
let cmd = Cmd {
program: "tar".into(),
args: vec![
"--no-same-owner".into(),
"--no-same-permissions".into(),
"-xzf".into(),
tarball.display().to_string(),
"-C".into(),
into.display().to_string(),
],
dir: None,
stream: false,
no_prompt: false,
};
let out = runner.run(&cmd).map_err(|e| {
anyhow!(
"could not run `{}`: {e}. An upgrade of a release install needs tar.",
cmd.display()
)
})?;
if !out.success {
bail!(
"`{}` failed: {}. Nothing was replaced",
cmd.display(),
out.stderr.trim()
);
}
let dirs: Vec<PathBuf> = std::fs::read_dir(into)
.with_context(|| format!("reading {}", into.display()))?
.flatten()
.map(|e| e.path())
.filter(|p| {
std::fs::symlink_metadata(p)
.map(|m| m.file_type().is_dir())
.unwrap_or(false)
})
.collect();
match dirs.as_slice() {
[one] => Ok(one.clone()),
_ => bail!(
"the tarball did not unpack to one directory ({} found). Nothing was replaced",
dirs.len()
),
}
}
fn the_binary_says_its_version(runner: &dyn Runner, latest: &Release, dir: &Path) -> Result<()> {
let binary = dir.join("eclipse");
let missing: Vec<&str> = BINARIES
.iter()
.copied()
.filter(|name| !dir.join(name).is_file())
.collect();
if !missing.is_empty() {
bail!(
"the tarball for {} has no {} at its top level. Nothing was replaced",
latest.tag,
missing.join(" or ")
);
}
let cmd = Cmd {
program: binary.display().to_string(),
args: vec!["--version".into()],
dir: None,
stream: false,
no_prompt: false,
};
let out = runner
.run(&cmd)
.map_err(|e| anyhow!("could not run `{}`: {e}", cmd.display()))?;
let said = out.stdout.trim();
let want = format!("eclipse {}", latest.version);
if !out.success || said != want {
bail!(
"the tarball for {} unpacks to a binary that says {said:?}, not {want:?}. That is \
not the release it claims to be; nothing was replaced",
latest.tag
);
}
Ok(())
}
#[derive(Debug)]
struct Moved {
name: &'static str,
existed: bool,
}
#[derive(Debug, Default)]
struct Swap {
moved: Vec<Moved>,
}
fn swap(bin_dir: &Path, from: &Path) -> Result<Swap> {
let result = stage_and_swap(bin_dir, from);
if result.is_err() {
for name in BINARIES {
let _ = std::fs::remove_file(bin_dir.join(format!(".{name}.new")));
}
}
result
}
fn stage_and_swap(bin_dir: &Path, from: &Path) -> Result<Swap> {
let mut staged = Vec::new();
for name in BINARIES {
let source = from.join(name);
let new = bin_dir.join(format!(".{name}.new"));
std::fs::copy(&source, &new)
.with_context(|| format!("staging {} from {}", new.display(), source.display()))?;
std::fs::set_permissions(&new, std::fs::Permissions::from_mode(0o755))
.with_context(|| format!("making {} executable", new.display()))?;
staged.push((name, new));
}
let mut plan = Vec::new();
for (name, new) in staged {
let target = bin_dir.join(name);
let existed = target.is_file();
if existed {
let old = bin_dir.join(format!("{name}.old"));
std::fs::copy(&target, &old).with_context(|| {
format!(
"keeping {} as {}; nothing was replaced",
target.display(),
old.display()
)
})?;
}
plan.push((name, new, existed));
}
let mut swap = Swap::default();
for (name, new, existed) in plan {
let target = bin_dir.join(name);
if let Err(e) = std::fs::rename(&new, &target) {
return Err(roll_back(
bin_dir,
&swap,
anyhow!("replacing {}: {e}", target.display()),
));
}
swap.moved.push(Moved { name, existed });
}
Ok(swap)
}
fn roll_back(bin_dir: &Path, swapped: &Swap, cause: anyhow::Error) -> anyhow::Error {
let mut stuck = Vec::new();
for moved in swapped.moved.iter().rev() {
let target = bin_dir.join(moved.name);
if !moved.existed {
if let Err(e) = std::fs::remove_file(&target) {
stuck.push(format!("{} ({e})", moved.name));
}
continue;
}
let old = bin_dir.join(format!("{}.old", moved.name));
if !old.is_file() {
stuck.push(format!("{} ({} is missing)", moved.name, old.display()));
continue;
}
if let Err(e) = std::fs::rename(&old, &target) {
stuck.push(format!("{} ({e})", moved.name));
}
}
if stuck.is_empty() {
cause.context("the swap was undone; the install still runs what it ran before")
} else {
cause.context(format!(
"the swap could not be undone for {}: that binary is the new one and this install is \
mixed — reinstall from a tarball by hand",
stuck.join(", ")
))
}
}
fn keep_the_marker(setup: &Setup) -> Result<PathBuf> {
let kept = setup.marker.with_extension("json.old");
std::fs::copy(&setup.marker, &kept).with_context(|| {
format!(
"keeping {} as {}; nothing was replaced",
setup.marker.display(),
kept.display()
)
})?;
Ok(kept)
}
fn write_marker(setup: &Setup, old: &InstallMarker, latest: &Release) -> Result<()> {
let marker = InstallMarker {
channel: Channel::Release,
prefix: old.prefix.clone(),
workspace: None,
commit: None,
installed_at: update::rfc3339_utc(eclipse_core::session::now_ms()),
build: old.build.clone(),
version: Some(latest.version.to_string()),
};
let text =
serde_json::to_string_pretty(&marker).context("writing the install record as JSON")? + "\n";
let tmp = setup
.marker
.with_extension(format!("json.{}.tmp", std::process::id()));
std::fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
std::fs::rename(&tmp, &setup.marker)
.inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})
.with_context(|| format!("replacing {}", setup.marker.display()))?;
Ok(())
}
fn major_gate(term: &mut Term, installed: Version, latest: &Release) -> Result<()> {
writeln!(
term.out,
"{} {installed} to {} crosses a major version, and a major release may change \
behaviour or configuration. Nothing has been replaced yet.",
term.style.yellow("major version:"),
latest.version
)?;
match &latest.page {
Some(page) => writeln!(term.out, " what changed: {page}")?,
None => writeln!(term.out, " the release is {}", latest.tag)?,
}
term.out.flush()?;
if !std::io::stdin().is_terminal() {
bail!(
"{} crosses a major version and this run has no terminal to ask in. Run `eclipse \
upgrade` from an interactive shell to confirm it. Nothing was changed",
latest.tag
);
}
let ok = crate::setup::confirm(
&format!("Upgrade to {} across a major version?", latest.tag),
false,
)?
.unwrap_or(false);
if !ok {
bail!("nothing was changed: {} was not confirmed", latest.tag);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ui::Style;
use crate::upgrade::SystemRunner;
use std::io::{Read, Write};
use std::sync::{Arc, Mutex};
fn chmod_x(path: &Path) {
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
fn build_tarball(dir: &Path, name: &str, says: &str) -> PathBuf {
let staging = dir.join("staging");
let inside = staging.join(name);
std::fs::create_dir_all(&inside).unwrap();
for (file, body) in [
(
"eclipse",
format!("#!/bin/sh\necho \"$@\" >> \"${{0%/*}}/calls\"\necho \"eclipse {says}\"\n"),
),
("eclipse-web", "#!/bin/sh\nexit 0\n".to_string()),
("eclipse-gateway", "#!/bin/sh\nexit 0\n".to_string()),
] {
let path = inside.join(file);
std::fs::write(&path, body).unwrap();
chmod_x(&path);
}
std::fs::write(inside.join("VERSION"), format!("{says}\n")).unwrap();
let tarball = dir.join(format!("{name}.tar.gz"));
let out = std::process::Command::new("tar")
.current_dir(&staging)
.args(["-czf", tarball.to_str().unwrap(), name])
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
tarball
}
fn digest(path: &Path) -> String {
let out = std::process::Command::new("sha256sum")
.arg(path)
.output()
.unwrap();
assert!(out.status.success());
String::from_utf8_lossy(&out.stdout)
.split_whitespace()
.next()
.unwrap()
.to_string()
}
fn release_json(port: u16, tag: &str, name: &str) -> Vec<u8> {
format!(
r#"{{"tag_name":"{tag}","html_url":"http://127.0.0.1:{port}/page",
"assets":[
{{"name":"{name}.tar.gz","browser_download_url":"http://127.0.0.1:{port}/dl/{name}.tar.gz"}},
{{"name":"SHA256SUMS","browser_download_url":"http://127.0.0.1:{port}/dl/SHA256SUMS"}}
]}}"#
)
.into_bytes()
}
fn serve(
dir: PathBuf,
tag: &'static str,
name: &'static str,
) -> (String, Arc<Mutex<Vec<String>>>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let hits = Arc::new(Mutex::new(Vec::new()));
let counted = hits.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut s) = stream else { break };
let mut buf = [0u8; 4096];
let n = s.read(&mut buf).unwrap_or(0);
let request = String::from_utf8_lossy(&buf[..n]).to_string();
let path = request.split_whitespace().nth(1).unwrap_or("/").to_string();
counted.lock().unwrap().push(path.clone());
let (status, body): (&str, Vec<u8>) = if path == "/latest" {
("200 OK", release_json(port, tag, name))
} else if let Some(file) = path.strip_prefix("/dl/") {
match std::fs::read(dir.join(file)) {
Ok(bytes) => ("200 OK", bytes),
Err(_) => ("404 Not Found", b"no such asset".to_vec()),
}
} else {
("404 Not Found", b"nothing here".to_vec())
};
let head = format!(
"HTTP/1.1 {status}\r\ncontent-length: {}\r\ncontent-type: application/octet-stream\r\nconnection: close\r\n\r\n",
body.len()
);
let _ = s.write_all(head.as_bytes());
let _ = s.write_all(&body);
}
});
(format!("http://127.0.0.1:{port}/latest"), hits)
}
struct Install {
_root: tempfile::TempDir,
_serial: std::sync::MutexGuard<'static, ()>,
prefix: PathBuf,
marker: PathBuf,
state: PathBuf,
url: String,
hits: Arc<Mutex<Vec<String>>>,
}
impl Install {
fn new(installed: &str, tag: &'static str, says: &str) -> Install {
Self::with_digest_of(installed, tag, says, None)
}
fn with_digest_of(
installed: &str,
tag: &'static str,
says: &str,
corrupt_sums: Option<String>,
) -> Install {
let serial = crate::repl::serial();
let root = tempfile::tempdir().unwrap();
let base = root.path().to_path_buf();
let (prefix, state, assets) =
(base.join("prefix"), base.join("state"), base.join("assets"));
for d in [prefix.join("bin"), state.clone(), assets.clone()] {
std::fs::create_dir_all(d).unwrap();
}
std::fs::write(prefix.join("bin/eclipse"), "old eclipse\n").unwrap();
std::fs::write(prefix.join("bin/eclipse-web"), "old web\n").unwrap();
let name = format!("eclipse-{tag}-x86_64-unknown-linux-gnu");
let tarball = build_tarball(&assets, &name, says);
let digest = corrupt_sums.unwrap_or_else(|| digest(&tarball));
std::fs::write(
assets.join("SHA256SUMS"),
format!("{digest} {name}.tar.gz\n"),
)
.unwrap();
let name_static: &'static str = Box::leak(name.clone().into_boxed_str());
let (url, hits) = serve(assets, tag, name_static);
let marker = state.join("install.json");
std::fs::write(
&marker,
format!(
r#"{{"channel":"release","prefix":{},"workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z","build":"release","version":"{installed}"}}"#,
serde_json::to_string(&prefix).unwrap()
),
)
.unwrap();
Install {
_root: root,
_serial: serial,
prefix,
marker,
state,
url,
hits,
}
}
fn calls(&self) -> String {
std::fs::read_to_string(self.prefix.join("bin/calls")).unwrap_or_default()
}
fn setup(&self) -> Setup {
Setup {
marker: self.marker.clone(),
session_dirs: Vec::new(),
update: UpdateConfig {
check: eclipse_core::config::UpdateCheck::Off,
track: eclipse_core::config::Track::Release,
remote: None,
releases: Some(self.url.clone()),
},
}
}
fn go(&self, opts: Opts) -> (Result<Verdict>, String, String) {
let setup = self.setup();
let marker = InstallMarker::load(&setup.marker).unwrap().unwrap();
let (mut out, mut err) = (Vec::new(), Vec::new());
let verdict = run(
&opts,
&setup,
&marker,
&SystemRunner,
&mut Term {
out: &mut out,
err: &mut err,
style: Style::plain(),
err_style: Style::plain(),
},
);
(
verdict,
String::from_utf8_lossy(&out).into_owned(),
String::from_utf8_lossy(&err).into_owned(),
)
}
fn binary(&self) -> String {
std::fs::read_to_string(self.prefix.join("bin/eclipse")).unwrap()
}
fn marker_json(&self) -> serde_json::Value {
serde_json::from_str(&std::fs::read_to_string(&self.marker).unwrap()).unwrap()
}
fn asked_for(&self, needle: &str) -> usize {
self.hits
.lock()
.unwrap()
.iter()
.filter(|p| p.contains(needle))
.count()
}
}
const UPGRADE: Opts = Opts {
check: false,
dry_run: false,
no_restart: false,
};
const CHECK: Opts = Opts {
check: true,
dry_run: false,
no_restart: false,
};
const PLAN: Opts = Opts {
check: false,
dry_run: true,
no_restart: false,
};
fn refusal(r: Result<Verdict>) -> String {
format!("{:#}", r.expect_err("expected a refusal"))
}
#[test]
fn a_tarball_missing_one_binary_names_the_one_it_is_missing() {
let dir = tempfile::tempdir().unwrap();
let latest = Release {
tag: "v0.12.3".into(),
version: Version::parse("v0.12.3").unwrap(),
tarball_url: "https://example.invalid/t.tgz".into(),
tarball_name: "t.tar.gz".into(),
sums_url: "https://example.invalid/t.tgz.sha256".into(),
page: None,
};
for name in BINARIES {
if name == "eclipse-gateway" {
continue;
}
std::fs::write(dir.path().join(name), "#!/bin/sh\nexit 0\n").unwrap();
}
let msg = format!(
"{:#}",
the_binary_says_its_version(&SystemRunner, &latest, dir.path())
.expect_err("a tarball with two of three binaries is refused")
);
assert!(
msg.contains("eclipse-gateway"),
"the message names the one that is missing: {msg}"
);
assert!(
!msg.contains("does not hold eclipse and"),
"and does not blame the two that are there: {msg}"
);
}
#[test]
fn a_swap_that_stops_half_way_puts_back_what_it_already_replaced() {
let dir = tempfile::tempdir().unwrap();
let bin_dir = dir.path().join("bin");
let from = dir.path().join("unpacked");
std::fs::create_dir_all(&bin_dir).unwrap();
std::fs::create_dir_all(&from).unwrap();
for (name, body) in [
("eclipse", "old eclipse\n"),
("eclipse-web", "old web\n"),
("eclipse-gateway", "old gateway\n"),
] {
std::fs::write(bin_dir.join(name), body).unwrap();
std::fs::write(from.join(name), body.replace("old", "new")).unwrap();
}
std::fs::remove_file(bin_dir.join("eclipse-web")).unwrap();
std::fs::create_dir(bin_dir.join("eclipse-web")).unwrap();
std::fs::write(bin_dir.join("eclipse-web/keep"), "x").unwrap();
let err = swap(&bin_dir, &from).unwrap_err();
let msg = format!("{err:#}");
assert!(
msg.contains("eclipse-web"),
"the error names the binary: {msg}"
);
assert!(
msg.contains("undone"),
"and says the install was put back: {msg}"
);
assert_eq!(
std::fs::read_to_string(bin_dir.join("eclipse")).unwrap(),
"old eclipse\n",
"the binary that was already swapped is the old one again"
);
assert_eq!(
std::fs::read_to_string(bin_dir.join("eclipse-gateway")).unwrap(),
"old gateway\n",
"and the one that was never reached is untouched"
);
assert!(
!bin_dir.join(".eclipse.new").exists(),
"no staging copy is left behind"
);
assert!(
!bin_dir.join("eclipse.old").exists(),
"the .old was consumed by the rollback, so nothing points at a binary that is now the target"
);
}
#[test]
fn a_marker_that_cannot_be_written_takes_the_new_binaries_back_with_it() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
let blocked = i
.marker
.with_extension(format!("json.{}.tmp", std::process::id()));
std::fs::create_dir(&blocked).unwrap();
let (verdict, _out, _err) = i.go(UPGRADE);
let msg = refusal(verdict);
assert!(
msg.contains("install.json"),
"the failure names the record: {msg}"
);
assert!(msg.contains("undone"), "and says the swap went back: {msg}");
assert_eq!(
i.binary(),
"old eclipse\n",
"the binary that ran before is the one in place"
);
assert_eq!(
std::fs::read_to_string(i.prefix.join("bin/eclipse-web")).unwrap(),
"old web\n"
);
assert!(
!i.prefix.join("bin/eclipse-gateway").exists(),
"the binary the swap introduced is gone again — this install had two, not three"
);
assert_eq!(
i.marker_json()["version"],
"0.2.0",
"and the record still names the version that is running"
);
assert!(
!i.prefix.join("bin/eclipse.old").exists(),
"the rollback consumed the copy it made, so nothing points at a binary that is now the target"
);
}
#[test]
fn a_backup_that_cannot_be_kept_refuses_before_any_binary_is_replaced() {
let dir = tempfile::tempdir().unwrap();
let (bin_dir, from) = (dir.path().join("bin"), dir.path().join("unpacked"));
std::fs::create_dir_all(&bin_dir).unwrap();
std::fs::create_dir_all(&from).unwrap();
for name in BINARIES {
std::fs::write(bin_dir.join(name), format!("old {name}\n")).unwrap();
std::fs::write(from.join(name), format!("new {name}\n")).unwrap();
}
std::fs::create_dir(bin_dir.join("eclipse-gateway.old")).unwrap();
let err = swap(&bin_dir, &from).unwrap_err();
let msg = format!("{err:#}");
assert!(
msg.contains("nothing was replaced"),
"the refusal says the install is whole: {msg}"
);
for name in BINARIES {
assert_eq!(
std::fs::read_to_string(bin_dir.join(name)).unwrap(),
format!("old {name}\n"),
"{name} is the one that was there"
);
}
assert!(
!bin_dir.join(".eclipse.new").exists(),
"no staging copy is left behind"
);
}
#[test]
fn a_dry_run_of_an_up_to_date_install_migrates_nothing() {
let i = Install::new("0.3.0", "v0.3.0", "0.3.0");
let script = i.prefix.join("bin/eclipse");
std::fs::write(
&script,
format!(
"#!/bin/sh\necho \"$@\" >> {}\n",
i.prefix.join("bin/calls").display()
),
)
.unwrap();
chmod_x(&script);
let (verdict, out, err) = i.go(PLAN);
assert_eq!(verdict.unwrap(), Verdict::Current, "err: {err}");
assert!(out.contains("already up to date"), "{out}");
assert!(
!i.prefix.join("bin/calls").exists(),
"a dry run ran the migration: {}",
i.calls()
);
}
#[test]
fn the_printed_rollback_restores_the_record_too_so_the_release_is_offered_again() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
let (verdict, out, err) = i.go(UPGRADE);
assert_eq!(verdict.unwrap(), Verdict::Upgraded, "err: {err}");
assert!(i.binary().contains("eclipse 0.3.0"), "{:?}", i.binary());
let kept = i.state.join("install.json.old");
assert!(
kept.is_file(),
"the record the upgrade replaced is kept beside it: {out}"
);
assert!(
out.contains("install.json.old") && out.contains("rename each"),
"the recipe names both halves: {out}"
);
for name in BINARIES {
let old = i.prefix.join("bin").join(format!("{name}.old"));
if old.is_file() {
std::fs::rename(&old, i.prefix.join("bin").join(name)).unwrap();
}
}
std::fs::rename(&kept, &i.marker).unwrap();
assert_eq!(
i.binary(),
"old eclipse\n",
"the rollback puts the old binary back"
);
assert_eq!(i.marker_json()["version"], "0.2.0");
let (verdict, out, err) = i.go(CHECK);
assert_eq!(verdict.unwrap(), Verdict::Behind, "err: {err}");
assert!(out.contains("v0.3.0"), "{out}");
}
#[test]
fn an_upgrade_installs_the_tag_keeps_the_old_binary_and_records_the_new_version() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
let (verdict, out, err) = i.go(UPGRADE);
assert_eq!(verdict.unwrap(), Verdict::Upgraded, "err: {err}");
assert!(out.contains("upgraded:"), "{out}");
assert!(
i.binary().contains("eclipse 0.3.0"),
"the new binary is in place: {:?}",
i.binary()
);
assert_eq!(
std::fs::read_to_string(i.prefix.join("bin/eclipse.old")).unwrap(),
"old eclipse\n",
"the old one is kept for a rollback"
);
assert_ne!(i.state.join("upgrade-0"), i.prefix, "nothing else moved");
let marker = i.marker_json();
assert_eq!(marker["channel"], "release");
assert_eq!(marker["version"], "0.3.0");
assert!(marker["commit"].is_null());
assert!(marker["workspace"].is_null());
let at = marker["installed_at"].as_str().unwrap();
assert_eq!(at.len(), 20, "RFC 3339 UTC: {at}");
assert_eq!(i.asked_for("SHA256SUMS"), 1, "the digests were fetched");
let leftovers: Vec<_> = std::fs::read_dir(&i.state)
.unwrap()
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
assert!(
leftovers.iter().all(|n| !n.starts_with("upgrade-")),
"{leftovers:?}"
);
}
#[test]
fn a_checksum_that_does_not_match_is_refused_and_nothing_is_replaced() {
let wrong = "0".repeat(64);
let i = Install::with_digest_of("0.2.0", "v0.3.0", "0.3.0", Some(wrong.clone()));
let msg = refusal(i.go(UPGRADE).0);
assert!(msg.contains(&wrong), "it prints what the file said: {msg}");
assert!(msg.contains("0000") || msg.contains("SHA256"), "{msg}");
assert_eq!(i.binary(), "old eclipse\n", "the binary is untouched");
assert!(
!i.prefix.join("bin/eclipse.old").exists(),
"and there is nothing to roll back from"
);
assert_eq!(
i.marker_json()["version"],
"0.2.0",
"the record is untouched"
);
}
#[test]
fn an_upgrade_with_nothing_to_install_migrates_the_config_on_the_release_channel() {
let i = Install::new("0.3.0", "v0.3.0", "0.3.0");
let script = i.prefix.join("bin/eclipse");
std::fs::write(
&script,
format!(
"#!/bin/sh\necho \"$@\" >> {}\necho 'migrated: wrote something'\n",
i.prefix.join("bin/calls").display()
),
)
.unwrap();
chmod_x(&script);
let (verdict, out, err) = i.go(UPGRADE);
assert_eq!(verdict.unwrap(), Verdict::Current, "err: {err}");
assert!(out.contains("already up to date"), "{out}");
assert_eq!(
i.calls().trim(),
"config migrate",
"the config catches up even when no binary moved"
);
std::fs::remove_file(i.prefix.join("bin/calls")).unwrap();
let (verdict, _out, err) = i.go(CHECK);
assert_eq!(verdict.unwrap(), Verdict::Current, "err: {err}");
assert!(
!i.prefix.join("bin/calls").exists(),
"--check must not run the migration"
);
}
#[test]
fn a_release_upgrade_migrates_the_config_after_the_swap() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
let (verdict, out, err) = i.go(UPGRADE);
assert_eq!(verdict.unwrap(), Verdict::Upgraded, "out: {out} err: {err}");
assert_eq!(
i.calls().trim(),
"config migrate",
"the binary that was just installed is asked to bring the file forward: {out}"
);
}
#[test]
fn a_tarball_whose_binary_does_not_name_the_tag_is_refused_before_the_swap() {
let i = Install::new("0.2.0", "v0.3.0", "9.9.9");
let msg = refusal(i.go(UPGRADE).0);
assert!(msg.contains("9.9.9") && msg.contains("0.3.0"), "{msg}");
assert_eq!(i.binary(), "old eclipse\n");
assert_eq!(i.marker_json()["version"], "0.2.0");
}
#[test]
fn check_names_the_newer_tag_and_downloads_nothing() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
let (verdict, out, err) = i.go(CHECK);
assert_eq!(verdict.unwrap(), Verdict::Behind, "err: {err}");
assert!(out.contains("v0.3.0") && out.contains("0.2.0"), "{out}");
assert_eq!(i.asked_for("/dl/"), 0, "only the question, no assets");
assert_eq!(i.binary(), "old eclipse\n");
}
#[test]
fn a_current_install_says_so_and_downloads_nothing() {
let i = Install::new("0.3.0", "v0.3.0", "0.3.0");
for opts in [UPGRADE, CHECK] {
let (verdict, out, _err) = i.go(opts);
assert_eq!(verdict.unwrap(), Verdict::Current);
assert!(out.contains("already up to date"), "{out}");
}
assert_eq!(i.asked_for("/dl/"), 0);
assert_eq!(i.binary(), "old eclipse\n");
}
#[test]
fn a_dry_run_prints_the_plan_and_downloads_nothing() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
let (verdict, out, _err) = i.go(PLAN);
assert_eq!(verdict.unwrap(), Verdict::Planned);
for needle in ["sha256sum", "tar -xzf", "--version", "eclipse.old"] {
assert!(out.contains(needle), "plan names {needle}: {out}");
}
assert_eq!(i.asked_for("/dl/"), 0);
assert_eq!(i.binary(), "old eclipse\n");
}
#[test]
fn a_major_jump_with_nobody_to_ask_is_refused_rather_than_assumed() {
let i = Install::new("0.9.0", "v1.0.0", "1.0.0");
let msg = refusal(i.go(UPGRADE).0);
assert!(msg.contains("major"), "{msg}");
assert!(msg.contains("v1.0.0"), "{msg}");
assert_eq!(i.binary(), "old eclipse\n");
assert_eq!(
i.asked_for("/dl/"),
0,
"nothing is downloaded to ask a question"
);
}
#[test]
fn a_marker_from_before_versions_were_recorded_is_refused_naming_the_fix() {
let i = Install::new("0.2.0", "v0.3.0", "0.3.0");
std::fs::write(
&i.marker,
format!(
r#"{{"channel":"release","prefix":{},"installed_at":"t"}}"#,
serde_json::to_string(&i.prefix).unwrap()
),
)
.unwrap();
let msg = refusal(i.go(UPGRADE).0);
assert!(msg.contains("does not say which version"), "{msg}");
assert!(msg.contains("install.sh"), "{msg}");
assert_eq!(i.asked_for("/latest"), 0, "a refusal costs no request");
}
#[test]
fn a_checksum_file_is_read_by_name_and_nothing_unparsable_is_believed() {
let dir = tempfile::tempdir().unwrap();
let sums = dir.path().join(update::SUMS_NAME);
let hex = "a".repeat(64);
let other = "b".repeat(64);
std::fs::write(
&sums,
format!(
"{hex} eclipse-v0.2.0-x86_64-unknown-linux-gnu.tar.gz\n{other} *eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz\n"
),
)
.unwrap();
assert_eq!(
expected_digest(&sums, "eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz").unwrap(),
other,
"the binary-mode marker is not part of the name"
);
let missing = expected_digest(&sums, "eclipse-v0.9.0-x86_64-unknown-linux-gnu.tar.gz")
.unwrap_err()
.to_string();
assert!(missing.contains("no SHA256"), "{missing}");
std::fs::write(&sums, "deadbeef eclipse.tar.gz\n").unwrap();
assert!(expected_digest(&sums, "eclipse.tar.gz").is_err());
}
}