use crate::ui::Style;
use anyhow::{bail, Result};
use eclipse_core::config::{Track, UpdateConfig};
use eclipse_core::session::{held_locks, HeldLock};
use eclipse_core::update::{Channel, InstallMarker};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub const LOG_CAP: usize = 20;
#[derive(Debug, Clone, Copy, Default)]
pub struct Opts {
pub check: bool,
pub dry_run: bool,
pub no_restart: bool,
}
pub struct Setup {
pub marker: PathBuf,
pub session_dirs: Vec<PathBuf>,
pub update: UpdateConfig,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
Current,
Behind,
Upgraded,
Planned,
}
#[derive(Debug, Clone)]
pub struct Cmd {
pub program: String,
pub args: Vec<String>,
pub dir: Option<PathBuf>,
pub stream: bool,
pub no_prompt: bool,
}
impl Cmd {
fn git(ws: &Path, args: &[&str]) -> Cmd {
let mut full = vec!["-C".to_string(), ws.display().to_string()];
full.extend(args.iter().map(|a| a.to_string()));
Cmd {
program: "git".into(),
args: full,
dir: None,
stream: false,
no_prompt: false,
}
}
pub fn display(&self) -> String {
std::iter::once(self.program.as_str())
.chain(self.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ")
}
}
#[derive(Debug, Clone, Default)]
pub struct Out {
pub success: bool,
pub stdout: String,
pub stderr: String,
}
pub trait Runner {
fn run(&self, cmd: &Cmd) -> std::io::Result<Out>;
}
pub struct SystemRunner;
impl Runner for SystemRunner {
fn run(&self, cmd: &Cmd) -> std::io::Result<Out> {
let mut c = Command::new(&cmd.program);
c.args(&cmd.args).stdin(Stdio::null());
if let Some(dir) = &cmd.dir {
c.current_dir(dir);
}
if cmd.no_prompt {
c.env("GIT_TERMINAL_PROMPT", "0");
}
if cmd.stream {
let status = c.status()?;
return Ok(Out {
success: status.success(),
..Out::default()
});
}
let out = c.output()?;
Ok(Out {
success: out.status.success(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
})
}
}
pub fn session_dirs(root: &Path, configured: Option<PathBuf>) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = configured.into_iter().collect();
dirs.push(root.join("state").join("sessions"));
if let Ok(profiles) = std::fs::read_dir(root.join("profiles")) {
let mut found: Vec<PathBuf> = profiles
.flatten()
.map(|p| p.path().join("state").join("sessions"))
.collect();
found.sort();
dirs.extend(found);
}
let mut seen = Vec::new();
dirs.retain(|d| {
let new = !seen.contains(d);
seen.push(d.clone());
new
});
dirs
}
pub struct Term<'a> {
pub out: &'a mut dyn Write,
pub err: &'a mut dyn Write,
pub style: Style,
pub err_style: Style,
}
fn short(id: &str) -> &str {
id.get(..7).unwrap_or(id)
}
struct Repo<'a> {
runner: &'a dyn Runner,
ws: &'a Path,
no_prompt: bool,
}
impl Repo<'_> {
fn cmd(&self, args: &[&str]) -> Cmd {
let mut c = Cmd::git(self.ws, args);
c.no_prompt = self.no_prompt;
c
}
fn output(&self, args: &[&str]) -> Result<Out> {
let cmd = self.cmd(args);
self.runner
.run(&cmd)
.map_err(|e| anyhow::anyhow!("could not run `{}`: {e}", cmd.display()))
}
fn capture_raw(&self, args: &[&str]) -> Result<String> {
let out = self.output(args)?;
if !out.success {
bail!("`git {}` failed: {}", args.join(" "), out.stderr.trim());
}
Ok(out.stdout)
}
fn capture(&self, args: &[&str]) -> Result<String> {
Ok(self.capture_raw(args)?.trim().to_string())
}
fn count(&self, range: &str) -> Result<usize> {
let text = self.capture(&["rev-list", "--count", range])?;
text.parse()
.map_err(|_| anyhow::anyhow!("`git rev-list --count {range}` printed {text:?}"))
}
}
fn dirty_files(repo: &Repo) -> Result<Vec<String>> {
let out = repo.capture_raw(&["status", "--porcelain", "-z", "--untracked-files=no"])?;
let mut files = Vec::new();
let mut entries = out.split('\0').filter(|e| !e.is_empty());
while let Some(entry) = entries.next() {
let (code, path) = entry.split_at(entry.len().min(2));
files.push(format!("{code} {}", path.trim_start()));
if code.contains('R') || code.contains('C') {
entries.next();
}
}
Ok(files)
}
fn load_marker(setup: &Setup) -> Result<InstallMarker> {
match InstallMarker::load(&setup.marker)? {
Some(m) => Ok(m),
None => bail!(
"no install record at {}: `eclipse upgrade` only upgrades an install made by \
install.sh, which writes that file. Run install.sh once from your checkout (with \
--prefix DIR if you used one) and try again",
setup.marker.display()
),
}
}
fn locate_checkout(setup: &Setup, marker: &InstallMarker) -> Result<PathBuf> {
let Some(workspace) = marker.workspace.clone() else {
bail!(
"{} does not say which checkout the install was built from (it was written by an \
older install.sh). Run install.sh once from your checkout to record it",
setup.marker.display()
);
};
if !workspace.join("install.sh").is_file() {
bail!(
"{} says the install was built from {}, but there is no install.sh there any more. \
Run install.sh from the checkout you use now to record it",
setup.marker.display(),
workspace.display()
);
}
Ok(workspace)
}
pub(crate) fn no_run_in_progress(setup: &Setup) -> Result<()> {
let runs: Vec<HeldLock> = setup
.session_dirs
.iter()
.flat_map(|d| held_locks(d))
.collect();
if let Some(first) = runs.first() {
bail!(
"a run is in progress (session {} is held by {}): replacing the binary under it \
could lose the session. Wait for it to finish, or stop it, then run \
`eclipse upgrade` again",
first.id,
first.holder
);
}
Ok(())
}
fn followed_branch(repo: &Repo, workspace: &Path, track: Track) -> Result<String> {
let wanted = track.branch();
let out = repo.output(&["rev-parse", "--abbrev-ref", "HEAD"])?;
let found = out.stdout.trim();
if !out.success || found.is_empty() {
bail!(
"could not tell which branch the checkout at {} is on ({}). `eclipse upgrade` \
follows `{wanted}`, and it will not pull into a checkout it cannot identify",
workspace.display(),
out.stderr.trim()
);
}
if found != wanted {
let on = if found == "HEAD" {
"a detached HEAD (not on a branch)".to_string()
} else {
format!("`{found}`")
};
bail!(
"the checkout at {} is on {on}, and `[update] track = \"{}\"` follows `{wanted}`. \
Nothing was fetched: an upgrade only ever pulls the track's branch. Check the \
checkout out onto it (`git -C {} switch {wanted}`), or set the track to the branch \
you are on (`eclipse config set update.track {}`)",
workspace.display(),
track.label(),
workspace.display(),
track.label()
);
}
Ok(found.to_string())
}
pub fn run(opts: &Opts, setup: &Setup, runner: &dyn Runner, term: &mut Term) -> Result<Verdict> {
let marker = load_marker(setup)?;
let binary = marker.prefix.join("bin").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, run install.sh again (with --prefix DIR for the new place) to record it",
setup.marker.display(),
marker.prefix.display(),
binary.display()
);
}
if marker.channel == Channel::Release {
if setup.update.track == Track::Develop {
bail!(
"this is a release install, and `[update] track = \"develop\"` has nothing to \
follow: the release workflow builds tags only, so there is no develop build to \
download. Set the track back with `eclipse config set update.track release`, or \
install from a clone of the repository (install.sh --track develop) to follow \
develop"
);
}
return crate::release::run(opts, setup, &marker, runner, term);
}
let workspace = locate_checkout(setup, &marker)?;
let repo = Repo {
runner,
ws: &workspace,
no_prompt: opts.check,
};
let inside = repo.output(&["rev-parse", "--is-inside-work-tree"])?;
if !inside.success {
bail!(
"{} is not a git checkout ({}), so there is nothing to fetch. Run install.sh from \
a clone of github.com/mmhorda/eclipse to record one",
workspace.display(),
inside.stderr.trim()
);
}
let dirty = dirty_files(&repo)?;
if !dirty.is_empty() {
let list = dirty
.iter()
.map(|f| format!(" {f}"))
.collect::<Vec<_>>()
.join("\n");
if !opts.check {
bail!(
"{} has local changes, and an upgrade will not stash, reset or check out over \
them. Commit or discard these, then run it again:\n{list}",
workspace.display()
);
}
writeln!(
term.err,
"{} {} has local changes ({} file(s)); `eclipse upgrade` would refuse until they are \
committed or discarded:\n{list}",
term.err_style.yellow("warning:"),
workspace.display(),
dirty.len()
)?;
}
if !opts.check {
no_run_in_progress(setup)?;
}
let branch = followed_branch(&repo, &workspace, setup.update.track)?;
let target = format!("origin/{branch}");
let mut install = vec![
workspace.join("install.sh").display().to_string(),
"--upgrade".to_string(),
"--prefix".to_string(),
marker.prefix.display().to_string(),
];
if marker.build.as_deref() == Some("debug") {
install.push("--debug".to_string());
}
let install_cmd = Cmd {
program: install.remove(0),
args: install,
dir: Some(workspace.clone()),
stream: true,
no_prompt: false,
};
let head_range = format!("HEAD..{target}");
let log_cmd = repo.cmd(&["log", "--oneline", "-n", &LOG_CAP.to_string(), &head_range]);
if opts.dry_run {
let mut plan = vec![
repo.cmd(&["fetch"]),
log_cmd,
repo.cmd(&["merge", "--ff-only", &target]),
install_cmd,
];
if !opts.no_restart && crate::gateway_cli::installed_unit().is_some() {
plan.push(systemctl(&["restart", crate::gateway_cli::SERVICE_NAME]));
}
writeln!(
term.out,
"dry run: nothing below is run. An upgrade would run:"
)?;
for c in &plan {
writeln!(term.out, " {}", c.display())?;
}
writeln!(
term.out,
"Sessions are never touched. The config's values are not changed either: \
`config migrate` runs afterwards to add a setting this build reads, and \
`eclipse config migrate --dry-run` shows that list before you upgrade."
)?;
return Ok(Verdict::Planned);
}
let fetch = repo.output(&["fetch"])?;
if !fetch.success {
bail!(
"could not fetch {} for the checkout at {}: {}. The remote may be unreachable; \
nothing was changed",
target,
workspace.display(),
fetch.stderr.trim()
);
}
if !repo
.output(&[
"rev-parse",
"--verify",
"--quiet",
&format!("{target}^{{commit}}"),
])?
.success
{
bail!(
"the checkout at {} has no `{target}` after `git fetch`, so there is nothing on the \
`{}` track to follow. Its remote may carry no {branch}, or may not be called \
`origin`; `git -C {} fetch origin {branch}` creates it",
workspace.display(),
setup.update.track.label(),
workspace.display()
);
}
let head = repo.capture(&["rev-parse", "HEAD"])?;
let installed = marker.commit.clone().filter(|c| !c.is_empty());
let stale = installed.as_deref().is_some_and(|c| c != head);
let base = installed
.as_deref()
.filter(|c| {
repo.output(&["cat-file", "-e", &format!("{c}^{{commit}}")])
.is_ok_and(|o| o.success)
})
.unwrap_or("HEAD")
.to_string();
let range = format!("{base}..{target}");
let incoming = repo.count(&range)?;
let to_pull = repo.count(&head_range)?;
if to_pull == 0 && !stale {
writeln!(
term.out,
"{} {} on {target}",
term.style.green("already up to date:"),
short(&head)
)?;
if !opts.check {
migrate_config(term, &marker.prefix)?;
}
return Ok(Verdict::Current);
}
if incoming > 0 {
writeln!(
term.out,
"{incoming} new commit{} on {target}:",
if incoming == 1 { "" } else { "s" }
)?;
let log = repo.capture(&["log", "--oneline", "-n", &LOG_CAP.to_string(), &range])?;
for line in log.lines() {
writeln!(term.out, " {line}")?;
}
if incoming > LOG_CAP {
writeln!(
term.out,
" \u{2026} and {} more (`git -C {} log --oneline {range}`)",
incoming - LOG_CAP,
workspace.display()
)?;
}
}
if stale {
writeln!(
term.out,
"the installed build ({}) is not the checkout ({}); `eclipse upgrade` rebuilds it",
short(installed.as_deref().unwrap_or("?")),
short(&head)
)?;
}
if opts.check {
return Ok(Verdict::Behind);
}
writeln!(
term.out,
"{}",
term.style.dim(
"Sessions are never touched. The config's values are not changed either: \
`config migrate` runs afterwards to add a setting this build reads, and \
`eclipse config migrate --dry-run` shows that list before you upgrade."
)
)?;
if to_pull > 0 {
let pull = repo.output(&["merge", "--ff-only", &target])?;
if !pull.success {
bail!(
"`git merge --ff-only {target}` failed in {}: {}. An upgrade only ever \
fast-forwards: it will not merge or rebase your commits. Nothing was installed; \
resolve the checkout by hand and run `eclipse upgrade` again",
workspace.display(),
pull.stderr.trim()
);
}
}
let now = repo.capture(&["rev-parse", "HEAD"])?;
writeln!(
term.out,
"checkout at {}; rebuilding and reinstalling",
short(&now)
)?;
term.out.flush()?;
let built = runner
.run(&install_cmd)
.map_err(|e| anyhow::anyhow!("could not run `{}`: {e}", install_cmd.display()))?;
if !built.success {
bail!(
"`{}` failed (its output is above). The checkout is at {} but the installed \
binaries are still the old ones; fix the build and run `eclipse upgrade` again, \
which rebuilds from the checkout",
install_cmd.display(),
short(&now)
);
}
writeln!(
term.out,
"{} {} \u{2192} {}.",
term.style.green("upgraded:"),
short(installed.as_deref().unwrap_or(&head)),
short(&now)
)?;
if let Err(e) = after_the_binaries(term, runner, opts) {
writeln!(
term.out,
"{}",
term.style
.dim(&format!("the gateway was not restarted ({e})"))
)?;
}
migrate_config(term, &marker.prefix)?;
refresh_manual(term)?;
Ok(Verdict::Upgraded)
}
pub(crate) fn migrate_config(term: &mut Term, prefix: &std::path::Path) -> Result<()> {
let binary = prefix.join("bin").join("eclipse");
if !binary.is_file() {
return Ok(());
}
let output = std::process::Command::new(&binary)
.arg("config")
.arg("migrate")
.output();
match output {
Ok(out) if out.status.success() => {
let text = String::from_utf8_lossy(&out.stdout);
if text.contains("migrated:") {
for line in text.lines().filter(|l| !l.trim().is_empty()) {
writeln!(term.out, " {line}")?;
}
}
}
Ok(out) => writeln!(
term.out,
"{} `config migrate` failed ({}); the config is unchanged and still loads: {}",
term.style.yellow("warning:"),
out.status,
String::from_utf8_lossy(&out.stderr).trim()
)?,
Err(e) => writeln!(
term.out,
"{} could not run {} config migrate: {e}",
term.style.yellow("warning:"),
binary.display()
)?,
}
Ok(())
}
fn refresh_manual(term: &mut Term) -> Result<()> {
let env = |key: &str| std::env::var(key).ok().filter(|v| !v.is_empty());
let Some(config_path) = eclipse_core::config::config_path(&env) else {
return Ok(());
};
let page = crate::docs_cli::page_path(&config_path);
let Ok(cfg) = eclipse_core::config::Config::load_with(Some(&config_path), &env) else {
return Ok(());
};
match crate::docs_cli::write_page(&config_path, &cfg, env!("CARGO_PKG_VERSION")) {
Ok(_) => writeln!(term.out, "{} {}", term.style.dim("manual:"), page.display())?,
Err(e) => writeln!(
term.out,
"{} could not rewrite {}: {e}",
term.style.yellow("warning:"),
page.display()
)?,
}
Ok(())
}
pub(crate) fn systemctl(args: &[&str]) -> Cmd {
let mut full: Vec<String> = vec!["--user".to_string()];
full.extend(args.iter().map(|a| a.to_string()));
Cmd {
program: "systemctl".into(),
args: full,
dir: None,
stream: false,
no_prompt: false,
}
}
pub(crate) fn after_the_binaries(term: &mut Term, runner: &dyn Runner, opts: &Opts) -> Result<()> {
if crate::gateway_cli::installed_unit().is_none() {
return Ok(());
}
if opts.no_restart {
writeln!(
term.out,
"{}",
term.style.dim(
"--no-restart: the gateway still holds the old build; `eclipse gateway restart` \
when you want it on the new one"
)
)?;
return Ok(());
}
let active = runner.run(&systemctl(&["is-active", crate::gateway_cli::SERVICE_NAME]))?;
if !(active.success && crate::gateway_cli::is_active_text(&active.stdout)) {
writeln!(
term.out,
"{}",
term.style.dim(
"the gateway is installed but not running; `eclipse gateway start` brings up the \
new build"
)
)?;
return Ok(());
}
let restarted = runner.run(&systemctl(&["restart", crate::gateway_cli::SERVICE_NAME]))?;
if !restarted.success {
writeln!(
term.err,
"{} the gateway did not restart ({}). It is still serving the old build; \
`eclipse gateway restart` says why",
term.err_style.yellow("warning:"),
restarted.stderr.trim()
)?;
return Ok(());
}
writeln!(
term.out,
"{} the new binary is the one serving now",
term.style.green("gateway restarted:")
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
struct Recording {
calls: RefCell<Vec<String>>,
}
impl Recording {
fn new() -> Self {
Recording {
calls: RefCell::new(Vec::new()),
}
}
fn ran(&self, needle: &str) -> bool {
self.calls.borrow().iter().any(|c| c.contains(needle))
}
}
impl Runner for Recording {
fn run(&self, cmd: &Cmd) -> std::io::Result<Out> {
self.calls.borrow_mut().push(cmd.display());
SystemRunner.run(cmd)
}
}
fn sh(dir: &Path, program: &str, args: &[&str]) -> String {
let out = Command::new(program)
.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(), "{program} {args:?}: {out:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
struct Fixture {
_root: tempfile::TempDir,
_serial: std::sync::MutexGuard<'static, ()>,
origin: PathBuf,
ws: PathBuf,
prefix: PathBuf,
marker: PathBuf,
state: PathBuf,
root: PathBuf,
}
impl Fixture {
fn new() -> Fixture {
let serial = crate::repl::serial();
let root = tempfile::tempdir().unwrap();
let base = root.path().to_path_buf();
let origin = base.join("origin.git");
let seed = base.join("seed");
let ws = base.join("checkout");
let prefix = base.join("prefix");
let state = base.join("state");
std::fs::create_dir_all(&origin).unwrap();
std::fs::create_dir_all(&seed).unwrap();
std::fs::create_dir_all(prefix.join("bin")).unwrap();
std::fs::create_dir_all(&state).unwrap();
std::fs::write(prefix.join("bin/eclipse"), "old binary").unwrap();
sh(&origin, "git", &["init", "-q", "--bare", "-b", "main"]);
sh(&seed, "git", &["init", "-q", "-b", "main"]);
std::fs::write(
seed.join("install.sh"),
"#!/bin/sh\ncd \"$(dirname \"$0\")\"\n\
[ ! -e fail-build ] || { echo 'cargo exploded' >&2; exit 1; }\n\
echo \"$@\" >> install-calls\n",
)
.unwrap();
std::fs::write(seed.join("README"), "one\n").unwrap();
sh(&seed, "chmod", &["+x", "install.sh"]);
sh(&seed, "git", &["add", "."]);
sh(&seed, "git", &["commit", "-q", "-m", "first"]);
sh(
&seed,
"git",
&["remote", "add", "origin", origin.to_str().unwrap()],
);
sh(&seed, "git", &["push", "-q", "origin", "main"]);
sh(
&base,
"git",
&["clone", "-q", origin.to_str().unwrap(), "checkout"],
);
let f = Fixture {
_root: root,
_serial: serial,
origin,
ws,
prefix,
marker: state.join("install.json"),
state,
root: base.clone(),
};
f.write_marker("source", Some(&f.head()), None);
f
}
fn head(&self) -> String {
sh(&self.ws, "git", &["rev-parse", "HEAD"])
}
fn write_marker(&self, channel: &str, commit: Option<&str>, build: Option<&str>) {
let json = serde_json::json!({
"channel": channel,
"prefix": self.prefix,
"workspace": self.ws,
"commit": commit,
"installed_at": "2026-01-01T00:00:00Z",
"build": build,
});
std::fs::write(&self.marker, json.to_string()).unwrap();
}
fn publish(&self, subject: &str) {
let seed = self.ws.parent().unwrap().join("seed");
sh(
&seed,
"git",
&["commit", "-q", "--allow-empty", "-m", subject],
);
sh(&seed, "git", &["push", "-q", "origin", "main"]);
}
fn publish_to(&self, branch: &str, subject: &str) {
let seed = self.ws.parent().unwrap().join("seed");
let at = format!("origin/{branch}");
sh(&seed, "git", &["fetch", "-q", "origin", branch]);
sh(&seed, "git", &["checkout", "-q", "--detach", &at]);
sh(
&seed,
"git",
&["commit", "-q", "--allow-empty", "-m", subject],
);
sh(
&seed,
"git",
&["push", "-q", "origin", &format!("HEAD:refs/heads/{branch}")],
);
sh(&seed, "git", &["checkout", "-q", "main"]);
}
fn follow_develop(&self) {
let seed = self.ws.parent().unwrap().join("seed");
sh(&seed, "git", &["branch", "-f", "develop", "main"]);
sh(&seed, "git", &["push", "-q", "origin", "develop"]);
sh(&self.ws, "git", &["fetch", "-q", "origin"]);
sh(
&self.ws,
"git",
&[
"checkout",
"-q",
"-b",
"develop",
"--track",
"origin/develop",
],
);
}
fn setup_on(&self, track: Track) -> Setup {
Setup {
marker: self.marker.clone(),
session_dirs: session_dirs(&self.root, None),
update: UpdateConfig {
track,
..UpdateConfig::default()
},
}
}
fn go(&self, opts: Opts, runner: &dyn Runner) -> (Result<Verdict>, String, String) {
self.go_on(opts, runner, Track::Release)
}
fn go_on(
&self,
opts: Opts,
runner: &dyn Runner,
track: Track,
) -> (Result<Verdict>, String, String) {
let (mut out, mut err) = (Vec::new(), Vec::new());
let verdict = run(
&opts,
&self.setup_on(track),
runner,
&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(),
)
}
}
const UPGRADE: Opts = Opts {
check: false,
dry_run: false,
no_restart: false,
};
const CHECK: Opts = Opts {
check: true,
dry_run: false,
no_restart: false,
};
fn refusal(r: Result<Verdict>) -> String {
format!("{:#}", r.expect_err("expected a refusal"))
}
#[test]
fn a_missing_marker_is_refused_naming_the_path_it_looked_for() {
let f = Fixture::new();
std::fs::remove_file(&f.marker).unwrap();
let run = Recording::new();
let msg = refusal(f.go(UPGRADE, &run).0);
assert!(msg.contains(f.marker.to_str().unwrap()), "{msg}");
assert!(
msg.contains("install.sh") && msg.contains("--prefix"),
"{msg}"
);
assert!(run.calls.borrow().is_empty(), "nothing ran");
}
#[test]
fn a_release_marker_is_never_upgraded_from_its_checkout_and_says_what_recorded_it() {
let f = Fixture::new();
f.write_marker("release", None, None);
let run = Recording::new();
let msg = refusal(f.go(UPGRADE, &run).0);
assert!(msg.contains("does not say which version"), "{msg}");
assert!(
msg.contains("install.sh"),
"the refusal says what records it: {msg}"
);
assert!(
run.calls.borrow().is_empty(),
"a release install runs no git and no build: {:?}",
run.calls.borrow()
);
}
#[test]
fn a_prefix_with_no_binary_is_refused_rather_than_installed_somewhere_new() {
let f = Fixture::new();
std::fs::remove_file(f.prefix.join("bin/eclipse")).unwrap();
let run = Recording::new();
let msg = refusal(f.go(UPGRADE, &run).0);
let bin = f.prefix.join("bin/eclipse");
assert!(msg.contains(bin.to_str().unwrap()), "{msg}");
assert!(
msg.contains("nothing will be installed anywhere new"),
"{msg}"
);
assert!(run.calls.borrow().is_empty(), "nothing ran");
}
#[test]
fn a_dirty_tree_is_refused_naming_the_files_and_nothing_is_fetched_or_changed() {
let f = Fixture::new();
f.publish("second");
std::fs::write(f.ws.join("README"), "my local edit\n").unwrap();
let before = f.head();
let run = Recording::new();
let msg = refusal(f.go(UPGRADE, &run).0);
assert!(
msg.contains("README") && msg.contains("local changes"),
"{msg}"
);
assert!(!run.ran(" fetch") && !run.ran(" pull") && !run.ran("install.sh"));
assert_eq!(f.head(), before);
assert_eq!(
std::fs::read_to_string(f.ws.join("README")).unwrap(),
"my local edit\n",
"the edit survives"
);
assert!(!f.ws.join("install-calls").exists());
}
#[test]
fn check_is_current_when_nothing_is_new_and_prints_one_line() {
let f = Fixture::new();
let (verdict, out, err) = f.go(CHECK, &SystemRunner);
assert_eq!(verdict.unwrap(), Verdict::Current);
assert_eq!(out.lines().count(), 1, "{out}");
assert!(
out.contains("already up to date") && err.is_empty(),
"{out} / {err}"
);
}
#[test]
fn check_is_behind_and_lists_the_commits_when_the_remote_has_a_new_one() {
let f = Fixture::new();
f.publish("teach the agent to sing");
let (verdict, out, _) = f.go(CHECK, &SystemRunner);
assert_eq!(verdict.unwrap(), Verdict::Behind);
assert!(
out.contains("1 new commit") && out.contains("teach the agent to sing"),
"{out}"
);
assert_eq!(
sh(&f.ws, "git", &["log", "--oneline"]).lines().count(),
1,
"check fetches but never pulls"
);
}
#[test]
fn check_reports_an_unreachable_remote_as_an_error() {
let f = Fixture::new();
std::fs::remove_dir_all(&f.origin).unwrap();
let msg = refusal(f.go(CHECK, &SystemRunner).0);
assert!(
msg.contains("could not fetch") && msg.contains("nothing was changed"),
"{msg}"
);
}
#[test]
fn check_on_a_dirty_tree_warns_on_stderr_and_still_reports_what_is_behind() {
let f = Fixture::new();
f.publish("second");
std::fs::write(f.ws.join("README"), "edited\n").unwrap();
let (verdict, out, err) = f.go(CHECK, &SystemRunner);
assert_eq!(
verdict.unwrap(),
Verdict::Behind,
"a dirty tree is not an error here"
);
assert!(
err.contains("README") && err.contains("local changes"),
"{err}"
);
assert!(out.contains("second"), "{out}");
}
#[test]
fn check_caps_a_long_list_and_still_prints_the_true_count() {
let f = Fixture::new();
for i in 0..(LOG_CAP + 5) {
f.publish(&format!("change {i}"));
}
let (verdict, out, _) = f.go(CHECK, &SystemRunner);
assert_eq!(verdict.unwrap(), Verdict::Behind);
assert!(
out.contains(&format!("{} new commits", LOG_CAP + 5)),
"{out}"
);
assert!(out.contains("and 5 more"), "{out}");
assert_eq!(out.matches("change ").count(), LOG_CAP);
}
#[test]
fn dry_run_prints_every_command_and_runs_nothing_that_changes_anything() {
let f = Fixture::new();
f.publish("second");
let before = f.head();
let run = Recording::new();
let opts = Opts {
check: false,
dry_run: true,
no_restart: false,
};
let (verdict, out, _) = f.go(opts, &run);
assert_eq!(verdict.unwrap(), Verdict::Planned);
for needle in [
" fetch",
"log --oneline",
"merge --ff-only origin/main",
"install.sh --upgrade --prefix",
] {
assert!(
out.contains(needle),
"{needle} missing from the plan:\n{out}"
);
}
for mutating in [" fetch", " pull", "install.sh", "cargo"] {
assert!(
!run.ran(mutating),
"dry run ran {mutating}: {:?}",
run.calls.borrow()
);
}
assert_eq!(f.head(), before);
assert!(!f.ws.join("install-calls").exists());
let tracking = sh(&f.ws, "git", &["rev-parse", "origin/main"]);
assert_eq!(tracking, before, "nothing was fetched");
}
#[test]
fn an_upgrade_takes_the_commits_rebuilds_through_install_sh_and_says_config_is_untouched() {
let f = Fixture::new();
f.publish("add the thing");
let old = f.head();
let (verdict, out, _) = f.go(UPGRADE, &SystemRunner);
assert_eq!(verdict.unwrap(), Verdict::Upgraded, "{out}");
assert!(
out.contains("1 new commit") && out.contains("add the thing"),
"{out}"
);
assert_eq!(
out.matches("Sessions are never touched").count(),
1,
"{out}"
);
assert!(out.contains("config migrate --dry-run"), "{out}");
assert_ne!(f.head(), old, "the checkout moved");
let calls = std::fs::read_to_string(f.ws.join("install-calls")).unwrap();
assert_eq!(calls.lines().count(), 1, "{calls}");
assert!(
calls.contains(&format!("--upgrade --prefix {}", f.prefix.display())),
"{calls}"
);
assert!(
!calls.contains("--no-build"),
"--no-build would install the OLD build: {calls}"
);
}
#[test]
fn a_second_upgrade_has_nothing_to_do() {
let f = Fixture::new();
f.publish("add the thing");
assert_eq!(f.go(UPGRADE, &SystemRunner).0.unwrap(), Verdict::Upgraded);
f.write_marker("source", Some(&f.head()), None);
let (verdict, out, _) = f.go(UPGRADE, &SystemRunner);
assert_eq!(verdict.unwrap(), Verdict::Current);
assert!(out.contains("already up to date"), "{out}");
let calls = std::fs::read_to_string(f.ws.join("install-calls")).unwrap();
assert_eq!(calls.lines().count(), 1, "no second rebuild: {calls}");
}
#[test]
fn a_debug_install_is_rebuilt_as_a_debug_install() {
let f = Fixture::new();
f.write_marker("source", Some(&f.head()), Some("debug"));
f.publish("x");
assert_eq!(f.go(UPGRADE, &SystemRunner).0.unwrap(), Verdict::Upgraded);
let calls = std::fs::read_to_string(f.ws.join("install-calls")).unwrap();
assert!(calls.contains("--debug"), "{calls}");
}
#[test]
fn a_failed_build_is_reported_and_the_next_upgrade_rebuilds_even_though_the_checkout_is_current(
) {
let f = Fixture::new();
f.publish("breaks the build");
std::fs::write(f.ws.join("fail-build"), "").unwrap();
let msg = refusal(f.go(UPGRADE, &SystemRunner).0);
assert!(
msg.contains("still the old ones") && msg.contains("run `eclipse upgrade` again"),
"{msg}"
);
std::fs::remove_file(f.ws.join("fail-build")).unwrap();
let (verdict, out, _) = f.go(UPGRADE, &SystemRunner);
assert_eq!(verdict.unwrap(), Verdict::Upgraded, "{out}");
assert!(out.contains("installed build"), "{out}");
assert!(f.ws.join("install-calls").exists());
}
#[test]
fn a_checkout_that_cannot_fast_forward_is_refused_without_merging() {
let f = Fixture::new();
sh(
&f.ws,
"git",
&["commit", "-q", "--allow-empty", "-m", "mine"],
);
f.write_marker("source", Some(&f.head()), None);
f.publish("theirs");
let mine = f.head();
let msg = refusal(f.go(UPGRADE, &SystemRunner).0);
assert!(msg.contains("will not merge or rebase"), "{msg}");
assert_eq!(f.head(), mine, "the checkout is where it was");
assert!(!f.ws.join("install-calls").exists());
}
#[cfg(unix)]
#[test]
fn an_upgrade_inside_a_run_is_refused_and_names_the_session() {
use std::os::unix::io::AsRawFd;
let f = Fixture::new();
f.publish("second");
let sessions = f.state.join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
let lock = std::fs::File::create(sessions.join("busy-1.lock")).unwrap();
assert_eq!(unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) }, 0);
let run = Recording::new();
let msg = refusal(f.go(UPGRADE, &run).0);
assert!(
msg.contains("a run is in progress") && msg.contains("busy-1"),
"{msg}"
);
assert!(!run.ran(" fetch") && !run.ran("install.sh"));
assert_eq!(f.go(CHECK, &SystemRunner).0.unwrap(), Verdict::Behind);
drop(lock);
}
#[test]
fn profiles_sessions_are_searched_for_runs_too() {
let _serial = crate::repl::serial();
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("profiles/work/state/sessions")).unwrap();
let dirs = session_dirs(tmp.path(), None);
assert!(
dirs.contains(&tmp.path().join("profiles/work/state/sessions")),
"{dirs:?}"
);
assert!(
dirs.contains(&tmp.path().join("state/sessions")),
"{dirs:?}"
);
assert!(
!dirs.contains(&tmp.path().join("profiles/work/sessions")),
"the pre-0.9 shape is not a place to look: {dirs:?}"
);
let dirs = session_dirs(Path::new("/s"), Some(PathBuf::from("/s/state/sessions")));
assert_eq!(dirs, [PathBuf::from("/s/state/sessions")], "{dirs:?}");
}
#[test]
fn the_develop_track_follows_develop_and_never_main() {
let f = Fixture::new();
f.follow_develop();
f.publish_to("develop", "tomorrow's commit");
f.publish_to("main", "a release that is already out");
let before = f.head();
let (verdict, out, _) = f.go_on(CHECK, &SystemRunner, Track::Develop);
assert_eq!(verdict.unwrap(), Verdict::Behind, "{out}");
assert!(out.contains("origin/develop"), "{out}");
assert!(out.contains("tomorrow's commit"), "{out}");
assert!(
!out.contains("a release that is already out"),
"main's commits are not this install's news: {out}"
);
assert_eq!(f.head(), before, "--check pulls nothing");
}
#[test]
fn an_upgrade_on_the_develop_track_fast_forwards_to_develop() {
let f = Fixture::new();
f.follow_develop();
f.publish_to("develop", "tomorrow's commit");
f.publish_to("main", "a release that is already out");
let old = f.head();
let (verdict, out, _) = f.go_on(UPGRADE, &SystemRunner, Track::Develop);
assert_eq!(verdict.unwrap(), Verdict::Upgraded, "{out}");
assert!(out.contains("origin/develop"), "{out}");
assert_ne!(f.head(), old, "the checkout moved");
assert_eq!(
sh(&f.ws, "git", &["log", "-1", "--pretty=%s"]),
"tomorrow's commit",
"it moved to develop, not to main"
);
assert!(f.ws.join("install-calls").exists(), "it rebuilt");
}
#[test]
fn a_checkout_on_another_branch_is_refused_instead_of_being_pulled() {
let f = Fixture::new();
f.follow_develop();
f.publish_to("develop", "tomorrow's commit");
sh(&f.ws, "git", &["fetch", "-q", "origin"]);
sh(&f.ws, "git", &["checkout", "-q", "-b", "feat/whatever"]);
sh(
&f.ws,
"git",
&["branch", "--set-upstream-to=origin/develop"],
);
let before = f.head();
let run = Recording::new();
let msg = refusal(f.go_on(UPGRADE, &run, Track::Develop).0);
assert!(msg.contains("feat/whatever"), "{msg}");
assert!(
msg.contains("`develop`") && msg.contains("switch develop"),
"the refusal names the track's branch and the command: {msg}"
);
assert!(
!run.ran(" fetch") && !run.ran(" merge") && !run.ran("install.sh"),
"nothing was fetched, merged or built: {:?}",
run.calls.borrow()
);
assert_eq!(f.head(), before);
}
#[test]
fn the_release_track_refuses_a_checkout_that_is_on_develop() {
let f = Fixture::new();
f.follow_develop();
f.publish_to("develop", "tomorrow's commit");
let run = Recording::new();
let msg = refusal(f.go_on(UPGRADE, &run, Track::Release).0);
assert!(msg.contains("on `develop`"), "{msg}");
assert!(msg.contains("follows `main`"), "{msg}");
assert!(
!run.ran(" fetch") && !run.ran(" merge") && !run.ran("install.sh"),
"{:?}",
run.calls.borrow()
);
}
#[test]
fn a_release_install_asked_for_the_develop_track_refuses_and_says_why() {
let f = Fixture::new();
f.write_marker("release", None, None);
let run = Recording::new();
let msg = refusal(f.go_on(UPGRADE, &run, Track::Develop).0);
assert!(msg.contains("track = \"develop\""), "{msg}");
assert!(
msg.contains("tags only"),
"the refusal says why there is nothing to download: {msg}"
);
assert!(
msg.contains("update.track release"),
"and how to put it back: {msg}"
);
assert!(run.calls.borrow().is_empty(), "nothing ran");
}
#[test]
fn the_develop_track_with_no_origin_develop_names_the_ref_it_could_not_find() {
let f = Fixture::new();
sh(&f.ws, "git", &["checkout", "-q", "-b", "develop"]);
let run = Recording::new();
let msg = refusal(f.go_on(CHECK, &run, Track::Develop).0);
assert!(msg.contains("origin/develop"), "{msg}");
assert!(msg.contains("track"), "{msg}");
assert!(!run.ran(" merge") && !run.ran("install.sh"));
}
}