#![cfg(unix)]
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(dir)
.args(args)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@t")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@t")
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}: {out:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn text(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).into_owned()
}
fn eclipse(home: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(args)
.current_dir(home)
.env_clear()
.env("HOME", home)
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.env("NO_COLOR", "1")
.stdin(Stdio::null())
.output()
.unwrap()
}
struct Install {
_root: tempfile::TempDir,
home: PathBuf,
seed: PathBuf,
ws: PathBuf,
prefix: PathBuf,
}
impl Install {
fn new() -> Install {
let root = tempfile::tempdir().unwrap();
let base = root.path().to_path_buf();
let (home, origin, seed) = (
base.join("home"),
base.join("origin.git"),
base.join("seed"),
);
let (ws, prefix) = (base.join("checkout"), base.join("prefix"));
for d in [&home, &origin, &seed, &prefix.join("bin")] {
std::fs::create_dir_all(d).unwrap();
}
std::fs::write(prefix.join("bin/eclipse"), "old binary").unwrap();
git(&origin, &["init", "-q", "--bare", "-b", "main"]);
git(&seed, &["init", "-q", "-b", "main"]);
std::fs::write(
seed.join("install.sh"),
"#!/bin/sh\ncd \"$(dirname \"$0\")\"\necho \"$@\" >> install-calls\n",
)
.unwrap();
std::fs::write(seed.join("README"), "one\n").unwrap();
Command::new("chmod")
.arg("+x")
.arg(seed.join("install.sh"))
.status()
.unwrap();
git(&seed, &["add", "."]);
git(&seed, &["commit", "-q", "-m", "first"]);
git(
&seed,
&["remote", "add", "origin", origin.to_str().unwrap()],
);
git(&seed, &["push", "-q", "origin", "main"]);
git(
&base,
&["clone", "-q", origin.to_str().unwrap(), "checkout"],
);
let i = Install {
_root: root,
home,
seed,
ws,
prefix,
};
let head = git(&i.ws, &["rev-parse", "HEAD"]);
i.write_marker("source", Some(&head));
i
}
fn marker_path(&self) -> PathBuf {
self.home.join(".eclipse/state/install.json")
}
fn write_marker(&self, channel: &str, commit: Option<&str>) {
let path = self.marker_path();
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let json = serde_json::json!({
"channel": channel,
"prefix": self.prefix,
"workspace": self.ws,
"commit": commit,
"installed_at": "2026-01-01T00:00:00Z",
});
std::fs::write(path, json.to_string()).unwrap();
}
fn publish(&self, subject: &str) {
std::fs::write(self.seed.join("README"), format!("{subject}\n")).unwrap();
git(&self.seed, &["commit", "-q", "-am", subject]);
git(&self.seed, &["push", "-q", "origin", "main"]);
}
fn head(&self) -> String {
git(&self.ws, &["rev-parse", "HEAD"])
}
fn upgrade(&self, args: &[&str]) -> Output {
let mut all = vec!["upgrade"];
all.extend_from_slice(args);
eclipse(&self.home, &all)
}
fn install_calls(&self) -> String {
std::fs::read_to_string(self.ws.join("install-calls")).unwrap_or_default()
}
}
#[test]
fn an_upgrade_writes_the_manual_an_older_install_never_had() {
let i = Install::new();
let config_dir = i.home.join(".eclipse");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::write(
config_dir.join("config.toml"),
"version = 1\n[provider]\nmodel = \"stub\"\n",
)
.unwrap();
let page = config_dir.join("docs/configuration.html");
let twin = config_dir.join("docs/configuration.txt");
assert!(
!page.exists(),
"starts as an install that predates the manual"
);
i.publish("second");
let out = i.upgrade(&["--no-restart"]);
assert!(out.status.success(), "{out:?}");
assert!(page.exists(), "the upgrade wrote the page: {out:?}");
let text = std::fs::read_to_string(&twin).expect("and its text twin");
assert!(text.contains("memory_budget_chars"), "{text:.2000}");
assert!(
String::from_utf8_lossy(&out.stdout).contains("manual:"),
"and says so: {out:?}"
);
}
#[test]
fn upgrade_without_a_marker_is_refused_naming_the_path_it_looked_for() {
let home = tempfile::tempdir().unwrap();
let out = eclipse(home.path(), &["upgrade"]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
let err = text(&out.stderr);
let looked = home.path().join(".eclipse/state/install.json");
assert!(err.contains(looked.to_str().unwrap()), "{err}");
assert!(err.contains("install.sh"), "{err}");
assert!(err.contains("--prefix"), "{err}");
}
#[test]
fn check_without_a_marker_is_an_error_exit_two() {
let home = tempfile::tempdir().unwrap();
let out = eclipse(home.path(), &["upgrade", "--check"]);
assert_eq!(out.status.code(), Some(2), "{out:?}");
assert!(text(&out.stderr).contains("install.json"));
assert!(out.stdout.is_empty(), "stdout stays empty on an error");
}
#[test]
fn a_release_marker_without_a_version_is_refused_naming_what_records_one() {
let i = Install::new();
i.write_marker("release", None);
i.publish("second");
let out = i.upgrade(&[]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
let err = text(&out.stderr);
assert!(err.contains("does not say which version"), "{err}");
assert!(
err.contains("install.sh"),
"the message says what records it: {err}"
);
assert_eq!(
i.install_calls(),
"",
"a release install is never rebuilt from a checkout"
);
assert_eq!(
git(&i.ws, &["rev-parse", "origin/main"]),
git(&i.ws, &["rev-parse", "HEAD"]),
"and nothing was fetched either"
);
}
#[test]
fn a_marker_whose_prefix_has_no_binary_is_refused_instead_of_installing_somewhere_new() {
let i = Install::new();
std::fs::remove_file(i.prefix.join("bin/eclipse")).unwrap();
i.publish("second");
let before = i.head();
let out = i.upgrade(&[]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
let err = text(&out.stderr);
assert!(err.contains(i.prefix.to_str().unwrap()), "{err}");
assert!(err.contains("does not exist"), "{err}");
assert_eq!(i.head(), before);
assert_eq!(i.install_calls(), "");
}
#[test]
fn a_dirty_tree_is_refused_naming_the_files_and_nothing_is_fetched_or_changed() {
let i = Install::new();
i.publish("second");
std::fs::write(i.ws.join("README"), "my edit\n").unwrap();
let before = i.head();
let remote_before = git(&i.ws, &["rev-parse", "origin/main"]);
let out = i.upgrade(&[]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
assert!(text(&out.stderr).contains("README"), "{out:?}");
assert_eq!(i.head(), before);
assert_eq!(git(&i.ws, &["rev-parse", "origin/main"]), remote_before);
assert_eq!(
std::fs::read_to_string(i.ws.join("README")).unwrap(),
"my edit\n",
"local edits are left alone"
);
assert_eq!(i.install_calls(), "");
assert_eq!(git(&i.ws, &["stash", "list"]), "", "nothing was stashed");
}
#[test]
fn the_develop_track_reaches_the_binary_and_another_branch_is_refused() {
let i = Install::new();
git(&i.seed, &["branch", "-f", "develop", "main"]);
git(&i.seed, &["push", "-q", "origin", "develop"]);
git(&i.ws, &["fetch", "-q", "origin"]);
git(
&i.ws,
&[
"checkout",
"-q",
"-b",
"develop",
"--track",
"origin/develop",
],
);
git(&i.seed, &["checkout", "-q", "develop"]);
std::fs::write(i.seed.join("README"), "tomorrow\n").unwrap();
git(&i.seed, &["commit", "-q", "-am", "tomorrow's commit"]);
git(&i.seed, &["push", "-q", "origin", "develop"]);
git(&i.seed, &["checkout", "-q", "main"]);
i.publish("a release that is already out");
i.write_marker("source", Some(&git(&i.ws, &["rev-parse", "HEAD"])));
std::fs::create_dir_all(i.home.join(".eclipse")).unwrap();
std::fs::write(
i.home.join(".eclipse/config.toml"),
"[update]\ntrack = \"develop\"\n",
)
.unwrap();
let behind = i.upgrade(&["--check"]);
assert_eq!(behind.status.code(), Some(1), "{behind:?}");
let out = text(&behind.stdout);
assert!(out.contains("origin/develop"), "{out}");
assert!(out.contains("tomorrow's commit"), "{out}");
assert!(!out.contains("a release that is already out"), "{out}");
git(&i.ws, &["checkout", "-q", "-b", "feat/whatever"]);
let refused = i.upgrade(&["--check"]);
assert_eq!(refused.status.code(), Some(2), "{refused:?}");
let err = text(&refused.stderr);
assert!(
err.contains("feat/whatever") && err.contains("develop"),
"the refusal names the branch it found and the one it follows: {err}"
);
}
#[test]
fn check_exits_zero_with_one_line_when_current_and_one_with_the_commits_when_behind() {
let i = Install::new();
let current = i.upgrade(&["--check"]);
assert_eq!(current.status.code(), Some(0), "{current:?}");
assert_eq!(text(¤t.stdout).lines().count(), 1, "{current:?}");
assert!(current.stderr.is_empty(), "{current:?}");
i.publish("add the thing");
let behind = i.upgrade(&["--check"]);
assert_eq!(behind.status.code(), Some(1), "{behind:?}");
let out = text(&behind.stdout);
assert!(out.contains("add the thing"), "{out}");
assert!(out.contains("1 new commit"), "{out}");
assert_eq!(i.install_calls(), "", "--check installs nothing");
assert_eq!(
git(&i.ws, &["rev-list", "--count", "HEAD"]),
"1",
"--check does not pull"
);
}
#[test]
fn check_with_a_dirty_tree_still_reports_what_is_behind_and_says_so_on_stderr() {
let i = Install::new();
i.publish("second");
std::fs::write(i.ws.join("README"), "my edit\n").unwrap();
let out = i.upgrade(&["--check"]);
assert_eq!(out.status.code(), Some(1), "{out:?}");
assert!(text(&out.stdout).contains("second"));
assert!(text(&out.stderr).contains("README"));
}
#[test]
fn check_with_an_unreachable_remote_is_an_error_exit_two() {
let i = Install::new();
git(
&i.ws,
&[
"remote",
"set-url",
"origin",
i.home.join("gone.git").to_str().unwrap(),
],
);
let out = i.upgrade(&["--check"]);
assert_eq!(out.status.code(), Some(2), "{out:?}");
assert!(text(&out.stderr).contains("error"), "{out:?}");
}
#[test]
fn dry_run_prints_every_command_and_changes_nothing() {
let i = Install::new();
i.publish("second");
let before = i.head();
let out = i.upgrade(&["--dry-run"]);
assert_eq!(out.status.code(), Some(0), "{out:?}");
let shown = text(&out.stdout);
for needle in [
" fetch",
"HEAD..origin/main",
" merge --ff-only origin/main",
"install.sh --upgrade",
] {
assert!(shown.contains(needle), "{needle} missing from:\n{shown}");
}
assert!(shown.contains(i.prefix.to_str().unwrap()), "{shown}");
assert_eq!(i.head(), before, "nothing was pulled");
assert_eq!(i.install_calls(), "", "install.sh was not run");
assert_eq!(
std::fs::read_to_string(i.prefix.join("bin/eclipse")).unwrap(),
"old binary"
);
}
#[test]
fn an_upgrade_pulls_reinstalls_and_leaves_the_config_and_sessions_alone() {
let i = Install::new();
let config = i.home.join(".eclipse/config.toml");
let session = i.home.join(".eclipse/state/sessions/s1.jsonl");
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::create_dir_all(session.parent().unwrap()).unwrap();
std::fs::write(&config, "model = \"mine\"\n").unwrap();
std::fs::write(&session, "{}\n").unwrap();
i.publish("second");
let out = i.upgrade(&[]);
assert_eq!(out.status.code(), Some(0), "{out:?}");
let shown = text(&out.stdout);
assert!(shown.contains("second"), "{shown}");
assert_eq!(
shown.matches("Sessions are never touched").count(),
1,
"said once: {shown}"
);
assert!(
shown.contains("eclipse config migrate --dry-run"),
"the promise names the command that previews it: {shown}"
);
assert_eq!(i.head(), git(&i.seed, &["rev-parse", "HEAD"]));
let calls = i.install_calls();
assert!(calls.contains("--upgrade"), "{calls}");
assert!(calls.contains(i.prefix.to_str().unwrap()), "{calls}");
assert!(
!calls.contains("--no-build"),
"--no-build would reinstall the old build: {calls}"
);
assert_eq!(
std::fs::read_to_string(&config).unwrap(),
"model = \"mine\"\n"
);
assert_eq!(std::fs::read_to_string(&session).unwrap(), "{}\n");
i.write_marker("source", Some(&i.head()));
let again = i.upgrade(&[]);
assert_eq!(again.status.code(), Some(0), "{again:?}");
assert!(
text(&again.stdout).contains("already up to date"),
"{again:?}"
);
assert_eq!(i.install_calls().lines().count(), 1, "nothing ran twice");
}
struct Script {
_root: tempfile::TempDir,
home: PathBuf,
ws: PathBuf,
prefix: PathBuf,
}
impl Script {
fn new() -> Script {
let root = tempfile::tempdir().unwrap();
let base = root.path().to_path_buf();
let (home, ws, prefix) = (base.join("home"), base.join("src"), base.join("prefix"));
let release = ws.join("target/release");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(&release).unwrap();
std::fs::copy(
concat!(env!("CARGO_MANIFEST_DIR"), "/../../install.sh"),
ws.join("install.sh"),
)
.unwrap();
std::fs::write(
ws.join("Cargo.toml"),
"[workspace.package]\nversion = \"9.9.9\"\n",
)
.unwrap();
for bin in ["eclipse", "eclipse-web", "eclipse-gateway"] {
let path = release.join(bin);
std::fs::write(&path, "#!/bin/sh\nexit 0\n").unwrap();
Command::new("chmod").arg("+x").arg(&path).status().unwrap();
}
Script {
_root: root,
home,
ws,
prefix,
}
}
fn install(&self, args: &[&str]) -> Output {
self.install_at(&self.prefix, args)
}
fn install_at(&self, prefix: &std::path::Path, args: &[&str]) -> Output {
Command::new("bash")
.arg(self.ws.join("install.sh"))
.args(["--prefix", prefix.to_str().unwrap()])
.args(args)
.current_dir(&self.ws)
.env_clear()
.env("HOME", &self.home)
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.env("NO_COLOR", "1")
.output()
.unwrap()
}
fn marker(&self) -> serde_json::Value {
let path = self.prefix.join("state/install.json");
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
}
}
#[test]
fn install_sh_upgrade_leaves_the_context_files_byte_for_byte() {
let s = Script::new();
let memory = s.prefix.join("memory");
std::fs::create_dir_all(&memory).unwrap();
let written = [
(
"AGENT.md",
"run make, never cargo test\n\nWe do not use the network in tests.\n",
),
(
"USER.md",
"I am the operator. Direct answers, no preamble.\n",
),
(
"MEMORY.md",
"- the fleet is two NUCs\n- releases are cut on main\n",
),
];
for (name, body) in written {
std::fs::write(memory.join(name), body).unwrap();
}
std::fs::write(s.prefix.join("config.toml"), "model = \"mine\"\n").unwrap();
let out = s.install(&["--no-build", "--upgrade"]);
assert!(out.status.success(), "{out:?}");
assert_eq!(
s.marker()["version"].as_str(),
Some("9.9.9"),
"the upgrade recorded the install it made"
);
for (name, body) in written {
assert_eq!(
std::fs::read_to_string(memory.join(name)).unwrap(),
body,
"{name} was rewritten by an upgrade"
);
}
assert_eq!(
std::fs::read_to_string(s.prefix.join("config.toml")).unwrap(),
"model = \"mine\"\n",
"and the config with it"
);
}
#[test]
fn install_sh_writes_the_shipped_skills_and_keeps_an_edited_one() {
let s = Script::new();
let shipped = s.ws.join("skills");
for (name, body) in [
(
"orientation",
"---\nname: orientation\ndescription: where things live\n---\n\nbody\n",
),
(
"prove-it",
"---\nname: prove-it\ndescription: how to be sure\n---\n\nbody\n",
),
] {
std::fs::create_dir_all(shipped.join(name)).unwrap();
std::fs::write(shipped.join(name).join("SKILL.md"), body).unwrap();
}
let mine = s.prefix.join("skills/prove-it/SKILL.md");
std::fs::create_dir_all(mine.parent().unwrap()).unwrap();
std::fs::write(
&mine,
"---\nname: prove-it\ndescription: mine\n---\n\nedited\n",
)
.unwrap();
let out = s.install(&["--no-build"]);
assert!(out.status.success(), "{out:?}");
assert_eq!(
std::fs::read_to_string(s.prefix.join("skills/orientation/SKILL.md")).unwrap(),
"---\nname: orientation\ndescription: where things live\n---\n\nbody\n",
"a shipped skill that was absent is written"
);
assert_eq!(
std::fs::read_to_string(&mine).unwrap(),
"---\nname: prove-it\ndescription: mine\n---\n\nedited\n",
"an edited skill is never overwritten"
);
}
#[test]
fn install_sh_records_a_marker_with_no_commit_when_the_source_is_not_a_checkout() {
let s = Script::new();
let out = s.install(&["--no-build"]);
assert!(out.status.success(), "{out:?}");
let m = s.marker();
assert_eq!(m["channel"], "source");
assert_eq!(m["prefix"], s.prefix.to_str().unwrap());
assert_eq!(m["workspace"], s.ws.to_str().unwrap());
assert!(m["commit"].is_null(), "{m}");
let at = m["installed_at"].as_str().unwrap();
assert!(at.ends_with('Z') && at.len() == 20, "RFC 3339 UTC: {at}");
}
#[test]
fn install_sh_records_the_commit_of_the_checkout_and_uninstall_removes_the_marker() {
let s = Script::new();
git(&s.ws, &["init", "-q", "-b", "main"]);
git(&s.ws, &["add", "Cargo.toml", "install.sh"]);
git(&s.ws, &["commit", "-q", "-m", "first"]);
let head = git(&s.ws, &["rev-parse", "HEAD"]);
let out = s.install(&["--no-build"]);
assert!(out.status.success(), "{out:?}");
assert_eq!(s.marker()["commit"], head.as_str());
assert!(s.prefix.join("bin/eclipse").exists());
let out = s.install(&["--uninstall"]);
assert!(out.status.success(), "{out:?}");
assert!(!s.home.join(".eclipse/state/install.json").exists());
assert!(!s.prefix.join("bin/eclipse").exists());
}
#[test]
fn install_sh_purge_refuses_a_directory_that_is_not_an_eclipse_root() {
let s = Script::new();
std::fs::create_dir_all(&s.prefix).unwrap();
std::fs::write(s.prefix.join("something-else.txt"), "not ours\n").unwrap();
let out = s.install(&["--uninstall", "--purge", "--force"]);
assert!(!out.status.success(), "the purge was refused: {out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(
err.contains("does not look like an Eclipse install"),
"{err}"
);
assert!(
s.prefix.join("something-else.txt").exists(),
"and nothing was deleted"
);
}
#[test]
fn install_sh_purge_refuses_a_prefix_that_contains_home() {
let s = Script::new();
let base = s.prefix.parent().unwrap().to_path_buf();
let out = s.install_at(&base, &["--uninstall", "--purge", "--force"]);
assert!(!out.status.success(), "the purge was refused: {out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("contains $HOME"), "{err}");
assert!(s.home.exists(), "the home directory is still there");
}
#[test]
fn install_sh_purge_refuses_a_system_directory() {
let s = Script::new();
let out = s.install_at(
std::path::Path::new("/usr/local"),
&["--uninstall", "--purge", "--force", "--dry-run"],
);
assert!(!out.status.success(), "the purge was refused: {out:?}");
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("system directory"), "{err}");
}
#[test]
fn install_sh_purge_deletes_the_root_it_installed() {
let s = Script::new();
let out = s.install(&["--no-build"]);
assert!(out.status.success(), "{out:?}");
std::fs::create_dir_all(s.prefix.join("memory")).unwrap();
std::fs::write(s.prefix.join("memory/MEMORY.md"), "- something\n").unwrap();
let out = s.install(&["--uninstall", "--purge", "--force"]);
assert!(out.status.success(), "{out:?}");
assert!(!s.prefix.exists(), "the whole prefix is gone");
}
fn serve_forever(body: &'static str) -> (String, Arc<AtomicUsize>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/latest", listener.local_addr().unwrap());
let hits = Arc::new(AtomicUsize::new(0));
let counted = hits.clone();
std::thread::spawn(move || {
while let Ok((mut s, _)) = listener.accept() {
counted.fetch_add(1, Ordering::SeqCst);
let mut buf = [0u8; 2048];
let _ = s.read(&mut buf);
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
});
(url, hits)
}
fn model_server() -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let body = serde_json::json!({
"choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}]
})
.to_string();
std::thread::spawn(move || {
while let Ok((mut s, _)) = listener.accept() {
let mut req = Vec::new();
let mut chunk = [0u8; 4096];
while !req.windows(4).any(|w| w == b"\r\n\r\n") {
match s.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => req.extend_from_slice(&chunk[..n]),
}
}
std::thread::sleep(std::time::Duration::from_millis(100));
let _ = write!(
s,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
});
base
}
fn run_with_notice(i: &Install, remote: &str, model: &str) -> Output {
let cfg = i.home.join("c.toml");
std::fs::write(
&cfg,
format!("[update]\ncheck = \"daily\"\nremote = \"{remote}\"\n"),
)
.unwrap();
Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap(), "run", "hi"])
.current_dir(&i.home)
.env_clear()
.env("HOME", &i.home)
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.env("NO_COLOR", "1")
.env("ECLIPSE_BASE_URL", model)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.output()
.unwrap()
}
#[test]
fn the_notice_asks_once_across_two_runs_and_prints_one_line_once() {
let i = Install::new();
let (remote, hits) = serve_forever("2222222222222222222222222222222222222222");
let model = model_server();
let first = run_with_notice(&i, &remote, &model);
assert!(first.status.success(), "{first:?}");
assert!(
!text(&first.stderr).contains("newer eclipse"),
"the first run only learns: {first:?}"
);
let second = run_with_notice(&i, &remote, &model);
assert!(second.status.success(), "{second:?}");
let err = text(&second.stderr);
assert_eq!(err.matches("newer eclipse").count(), 1, "{err}");
assert!(
err.contains("eclipse upgrade"),
"says how to upgrade: {err}"
);
assert_eq!(text(&second.stdout), "ok\n", "stdout stays the reply");
let third = run_with_notice(&i, &remote, &model);
assert!(!text(&third.stderr).contains("newer eclipse"), "{third:?}");
assert_eq!(hits.load(Ordering::SeqCst), 1, "one request for three runs");
}
#[test]
fn the_notice_is_silent_and_never_blocks_a_run_when_the_server_is_down() {
let i = Install::new();
let closed = {
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
format!("http://{}/latest", l.local_addr().unwrap())
};
let model = model_server();
for _ in 0..2 {
let out = run_with_notice(&i, &closed, &model);
assert!(out.status.success(), "{out:?}");
assert_eq!(text(&out.stdout), "ok\n");
assert!(!text(&out.stderr).contains("eclipse upgrade"), "{out:?}");
}
}
#[test]
fn the_notice_makes_no_request_when_it_is_turned_off() {
let i = Install::new();
let (remote, hits) = serve_forever("2222222222222222222222222222222222222222");
let model = model_server();
let cfg = i.home.join("c.toml");
std::fs::write(
&cfg,
format!("[update]\ncheck = \"off\"\nremote = \"{remote}\"\n"),
)
.unwrap();
for _ in 0..2 {
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["--config", cfg.to_str().unwrap(), "run", "hi"])
.current_dir(&i.home)
.env_clear()
.env("HOME", &i.home)
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.env("ECLIPSE_BASE_URL", &model)
.env("ECLIPSE_MODEL", "m")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
}
assert_eq!(hits.load(Ordering::SeqCst), 0);
}
#[test]
fn config_show_prints_the_update_section_and_config_init_writes_it() {
let home = tempfile::tempdir().unwrap();
let shown = text(&eclipse(home.path(), &["config", "show"]).stdout);
assert!(shown.contains("[update]"), "{shown}");
assert!(shown.contains("check = \"daily\""), "{shown}");
assert!(eclipse(home.path(), &["config", "init"]).status.success());
let written = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
assert!(written.contains("[update]"), "{written}");
}
fn home_with_gateway(i: &Install) -> (tempfile::TempDir, String) {
let unit = i.home.join(".config/systemd/user/eclipse-gateway.service");
std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
let bin = tempfile::tempdir().unwrap();
let log = bin.path().join("calls.txt");
std::fs::write(
bin.path().join("systemctl"),
format!(
"#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
case \"$*\" in\n *is-active*) echo active; exit 0;;\nesac\nexit 0\n",
log = log.display()
),
)
.unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(
bin.path().join("systemctl"),
std::fs::Permissions::from_mode(0o755),
)
.unwrap();
let path = format!(
"{}:{}",
bin.path().display(),
std::env::var("PATH").unwrap_or_default()
);
(bin, path)
}
#[test]
fn an_upgrade_restarts_the_gateway_that_is_running_the_old_build() {
let i = Install::new();
i.publish("second");
let (_bin, path) = home_with_gateway(&i);
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["upgrade"])
.current_dir(&i.home)
.env_clear()
.env("HOME", &i.home)
.env("PATH", &path)
.env("NO_COLOR", "1")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
let shown = text(&out.stdout);
assert!(shown.contains("gateway restarted"), "{shown}");
let calls = std::fs::read_to_string(_bin.path().join("calls.txt")).unwrap_or_default();
assert!(
calls.contains("--user restart eclipse-gateway.service"),
"the upgrade restarts it rather than telling the reader to: {calls}"
);
assert!(
!calls.contains("enable"),
"and does not change enablement: {calls}"
);
}
#[test]
fn a_no_restart_upgrade_says_what_it_left_running() {
let i = Install::new();
i.publish("second");
let (_bin, path) = home_with_gateway(&i);
let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
.args(["upgrade", "--no-restart"])
.current_dir(&i.home)
.env_clear()
.env("HOME", &i.home)
.env("PATH", &path)
.env("NO_COLOR", "1")
.stdin(Stdio::null())
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
let shown = text(&out.stdout);
assert!(shown.contains("--no-restart"), "{shown}");
assert!(shown.contains("eclipse gateway restart"), "{shown}");
let calls = std::fs::read_to_string(_bin.path().join("calls.txt")).unwrap_or_default();
assert!(!calls.contains("restart"), "nothing restarted: {calls}");
}
#[test]
fn a_machine_with_no_gateway_unit_is_not_told_about_one() {
let i = Install::new();
i.publish("second");
let out = i.upgrade(&[]);
assert!(out.status.success(), "{out:?}");
let shown = text(&out.stdout);
assert!(!shown.contains("gateway"), "{shown}");
}
#[test]
fn an_upgrade_runs_the_migration_through_the_binary_it_just_installed() {
let i = Install::new();
let calls = i.prefix.join("migrate-calls");
std::fs::write(
i.prefix.join("bin/eclipse"),
format!(
"#!/bin/sh\necho \"$@\" >> {}\necho \"{}: config_version 0 -> 1\"\necho \" added provider.max_retries = 3\"\necho \"migrated: wrote something\"\n",
calls.display(),
i.prefix.join("config.toml").display()
),
)
.unwrap();
Command::new("chmod")
.arg("+x")
.arg(i.prefix.join("bin/eclipse"))
.status()
.unwrap();
i.publish("second");
let out = i.upgrade(&[]);
assert!(out.status.success(), "{out:?}");
assert_eq!(
std::fs::read_to_string(&calls).unwrap_or_default().trim(),
"config migrate",
"the prefix binary is called with `config migrate`"
);
let shown = text(&out.stdout);
assert!(shown.contains("config_version 0 -> 1"), "{shown}");
assert!(shown.contains("added provider.max_retries"), "{shown}");
}
#[test]
fn a_failed_migration_warns_and_leaves_the_upgrade_successful() {
let i = Install::new();
std::fs::write(
i.prefix.join("bin/eclipse"),
"#!/bin/sh\necho 'the file does not load' >&2\nexit 1\n",
)
.unwrap();
Command::new("chmod")
.arg("+x")
.arg(i.prefix.join("bin/eclipse"))
.status()
.unwrap();
i.publish("second");
let out = i.upgrade(&[]);
assert!(out.status.success(), "{out:?}");
let shown = text(&out.stdout);
assert!(shown.contains("config migrate"), "{shown}");
assert!(shown.contains("the file does not load"), "{shown}");
}
#[test]
fn an_upgrade_with_nothing_to_install_still_migrates_the_config() {
let i = Install::new();
let calls = i.prefix.join("migrate-calls");
std::fs::write(
i.prefix.join("bin/eclipse"),
format!(
"#!/bin/sh\necho \"$@\" >> {}\necho \"migrated: wrote something\"\n",
calls.display()
),
)
.unwrap();
Command::new("chmod")
.arg("+x")
.arg(i.prefix.join("bin/eclipse"))
.status()
.unwrap();
let head = i.head();
i.write_marker("source", Some(&head));
let out = i.upgrade(&[]);
assert!(out.status.success(), "{out:?}");
assert!(text(&out.stdout).contains("already up to date"), "{out:?}");
assert_eq!(
std::fs::read_to_string(&calls).unwrap_or_default().trim(),
"config migrate",
"the config catches up even when no binary moved"
);
std::fs::remove_file(&calls).unwrap();
let checked = i.upgrade(&["--check"]);
assert!(checked.status.success(), "{checked:?}");
assert!(
!calls.exists(),
"--check is a question: {} was written",
calls.display()
);
}