use crate::{kill, process_scan};
use anyhow::{Context, Result};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;
const BUILT_COMMIT: &str = env!("LARUST_GIT_COMMIT");
const CHECKOUT_ROOT: &str = env!("LARUST_CHECKOUT_ROOT");
pub fn version_string() -> String {
format_version(env!("CARGO_PKG_VERSION"), BUILT_COMMIT)
}
fn format_version(pkg_version: &str, built_commit: &str) -> String {
if built_commit == "unknown" {
pkg_version.to_string()
} else {
format!("{pkg_version} ({built_commit})")
}
}
pub fn leaked_version_string() -> &'static str {
Box::leak(version_string().into_boxed_str())
}
pub fn run(force: bool, legacy: bool, stop_running: bool, fix: bool) -> Result<()> {
if legacy {
run_legacy(force, stop_running, fix)
} else {
run_from_crates_io(force, stop_running, fix)
}
}
fn ensure_binary_not_locked(stop_running: bool) -> Result<()> {
let other_pids = process_scan::other_running_xr_pids();
if other_pids.is_empty() {
return Ok(());
}
if stop_running {
println!(
"xr upgrade: stopping {} other running `xr` process(es) first...",
other_pids.len()
);
return kill::kill_all();
}
anyhow::bail!(
"{} other `xr` process(es) are still running (pid(s): {}) - one of them is almost \
certainly holding the installed `xr` binary open, which is what actually fails \
`cargo install`'s own last step (moving the new binary into place) on Windows. \
Re-run with `--stop-running` to stop them first, or run `xr kill --all` yourself, \
then retry.",
other_pids.len(),
other_pids
.iter()
.map(|pid| pid.to_string())
.collect::<Vec<_>>()
.join(", "),
);
}
fn run_from_crates_io(force: bool, stop_running: bool, fix: bool) -> Result<()> {
ensure_binary_not_locked(stop_running)?;
println!("xr upgrade: reinstalling larust-cli from crates.io...");
let mut args = vec!["install", "larust-cli", "--color=always"];
if force {
args.push("--force");
}
run_cargo_install(&args, None, fix)?;
println!("xr upgrade: done - `xr --version` will show the new version on next run");
Ok(())
}
const INSTALL_LOCK_RETRY_ATTEMPTS: u32 = 5;
const INSTALL_LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(400);
fn run_cargo_install(args: &[&str], current_dir: Option<&Path>, fix: bool) -> Result<()> {
let aside = move_self_aside_if_about_to_be_replaced()
.context("failed to check whether the running xr needs to move itself aside first")?;
let result = run_cargo_install_retrying(args, current_dir, fix);
let Some((destination, aside)) = aside else {
return result;
};
if result.is_ok() {
let _ = std::fs::remove_file(&aside);
return result;
}
if let Err(restore_err) = std::fs::rename(&aside, &destination) {
let original = result.unwrap_err();
return Err(original).context(format!(
"additionally failed to restore the original xr.exe from {} back to {} - xr may not \
run until you fix this yourself: {restore_err}",
aside.display(),
destination.display()
));
}
result
}
#[cfg_attr(not(windows), allow(dead_code))]
fn aside_path_for(destination: &Path) -> PathBuf {
let mut aside = destination.as_os_str().to_os_string();
aside.push(".old");
PathBuf::from(aside)
}
fn move_self_aside_if_about_to_be_replaced() -> Result<Option<(PathBuf, PathBuf)>> {
#[cfg(windows)]
{
let destination = cargo_bin_dir().join("xr.exe");
let Ok(current) = std::env::current_exe() else {
return Ok(None);
};
let Ok(current) = current.canonicalize() else {
return Ok(None);
};
let Ok(destination_canon) = destination.canonicalize() else {
return Ok(None);
};
if current != destination_canon {
return Ok(None);
}
let aside = aside_path_for(&destination);
std::fs::rename(&destination, &aside).with_context(|| {
format!(
"failed to move the running xr.exe aside (to {}) before reinstalling",
aside.display()
)
})?;
println!(
"xr upgrade: {} is the binary currently running this command - moved it aside first \
(Windows can rename a running executable but never overwrite one in place, which is \
what cargo install's own replace step would otherwise always fail doing here)",
destination.display()
);
Ok(Some((destination, aside)))
}
#[cfg(not(windows))]
{
Ok(None)
}
}
fn run_cargo_install_retrying(args: &[&str], current_dir: Option<&Path>, fix: bool) -> Result<()> {
let mut attempt = 0;
let mut applied_fix = false;
loop {
let mut command = Command::new("cargo");
command
.args(args)
.stdout(Stdio::inherit())
.stderr(Stdio::piped());
if let Some(dir) = current_dir {
command.current_dir(dir);
}
let mut child = command.spawn().context("failed to run cargo install")?;
let stderr = child.stderr.take().expect("stderr was piped");
let relay = std::thread::spawn(move || {
let mut captured = String::new();
for line in BufReader::new(stderr).lines() {
let Ok(line) = line else { break };
eprintln!("{line}");
captured.push_str(&line);
captured.push('\n');
}
captured
});
let status = child.wait().context("waiting for cargo install")?;
let captured = relay.join().unwrap_or_default();
if status.success() {
return Ok(());
}
if !cfg!(windows) || !process_scan::looks_like_a_transient_windows_file_lock(&captured) {
anyhow::bail!("cargo install failed - see the output above");
}
attempt += 1;
if attempt <= INSTALL_LOCK_RETRY_ATTEMPTS {
std::thread::sleep(INSTALL_LOCK_RETRY_INTERVAL);
continue;
}
if fix && !applied_fix {
applied_fix = true;
apply_windows_defender_fix()?;
attempt = 0;
continue;
}
anyhow::bail!(
"cargo install failed - see the output above. This looks like Windows Defender (or \
another antivirus/EDR product) briefly locking the freshly-built binary - re-run \
with `xr upgrade --fix` to have `xr` exclude `.cargo\\bin` from real-time scanning \
automatically, or add that exclusion yourself."
);
}
}
#[cfg(windows)]
fn cargo_bin_dir() -> PathBuf {
resolve_cargo_bin_dir(
std::env::var_os("CARGO_HOME"),
std::env::var_os("USERPROFILE"),
)
}
#[cfg_attr(not(windows), allow(dead_code))]
fn resolve_cargo_bin_dir(
cargo_home: Option<std::ffi::OsString>,
user_profile: Option<std::ffi::OsString>,
) -> PathBuf {
let cargo_home = cargo_home
.map(PathBuf::from)
.or_else(|| user_profile.map(|home| PathBuf::from(home).join(".cargo")))
.unwrap_or_else(|| PathBuf::from(".cargo"));
cargo_home.join("bin")
}
#[cfg(windows)]
fn apply_windows_defender_fix() -> Result<()> {
let bin_dir = cargo_bin_dir();
println!(
"xr upgrade: cargo install kept failing with Windows' \"Access is denied\" moving the \
freshly-built binary into place - attempting to exclude {} from Windows Defender \
real-time scanning...",
bin_dir.display()
);
let status = Command::new("powershell")
.args([
"-NoProfile",
"-Command",
&format!("Add-MpPreference -ExclusionPath '{}'", bin_dir.display()),
])
.status()
.context("failed to run powershell to add a Windows Defender exclusion")?;
anyhow::ensure!(
status.success(),
"couldn't add a Windows Defender exclusion for {0} - this needs an elevated \
(Administrator) PowerShell. Run this yourself from one, then re-run `xr upgrade`:\n\n \
Add-MpPreference -ExclusionPath '{0}'",
bin_dir.display()
);
println!("xr upgrade: excluded {} - retrying...", bin_dir.display());
Ok(())
}
#[cfg(not(windows))]
fn apply_windows_defender_fix() -> Result<()> {
unreachable!("run_cargo_install only calls this when cfg!(windows) already matched")
}
fn run_legacy(force: bool, stop_running: bool, fix: bool) -> Result<()> {
dotenvy::from_filename(".env").ok();
let checkout = checkout_root()?;
if force {
println!("xr upgrade: reinstalling from {} ...", checkout.display());
return reinstall(&checkout, stop_running, fix);
}
println!("xr upgrade: checking {} for updates...", checkout.display());
run_git(&checkout, &["fetch"])?;
let local_head = run_git_output(&checkout, &["rev-parse", "HEAD"])?;
let upstream = run_git_output(&checkout, &["rev-parse", "@{u}"]).context(
"the current branch in that checkout has no upstream tracking branch configured - \
set one (e.g. `git branch --set-upstream-to=origin/main`) or use `xr upgrade --legacy \
--force` to reinstall from the checkout's current state without checking",
)?;
match plan(&local_head, &upstream, BUILT_COMMIT) {
Plan::UpToDate => {
println!(
"xr upgrade: already up to date (built from commit {})",
short(BUILT_COMMIT)
);
Ok(())
}
Plan::ReinstallOnly => {
println!(
"xr upgrade: the checkout is already at {} but the installed xr was built from \
{} - reinstalling...",
short(&local_head),
short(BUILT_COMMIT)
);
reinstall(&checkout, stop_running, fix)
}
Plan::PullAndReinstall => {
println!(
"xr upgrade: new commits available ({} -> {}) - pulling...",
short(&local_head),
short(&upstream)
);
let status = Command::new("git")
.args(["merge", "--ff-only", "@{u}"])
.current_dir(&checkout)
.status()
.context("failed to run git merge --ff-only")?;
anyhow::ensure!(
status.success(),
"git merge --ff-only failed - the checkout at {} likely has local changes or \
diverged history; resolve that yourself, then re-run `xr upgrade`",
checkout.display()
);
reinstall(&checkout, stop_running, fix)
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum Plan {
UpToDate,
ReinstallOnly,
PullAndReinstall,
}
fn plan(local_head: &str, upstream: &str, built_commit: &str) -> Plan {
if local_head != upstream {
Plan::PullAndReinstall
} else if local_head != built_commit {
Plan::ReinstallOnly
} else {
Plan::UpToDate
}
}
fn reinstall(checkout: &Path, stop_running: bool, fix: bool) -> Result<()> {
ensure_binary_not_locked(stop_running)?;
println!("xr upgrade: rebuilding and reinstalling xr...");
run_cargo_install(
&[
"install",
"--path",
"crates/larust-cli",
"--force",
"--color=always",
],
Some(checkout),
fix,
)?;
println!("xr upgrade: done - `xr --version` will show the new commit on next run");
Ok(())
}
fn checkout_root() -> Result<PathBuf> {
let (root, source) = resolve_checkout_root(std::env::var("LARUST_CHECKOUT_ROOT").ok());
anyhow::ensure!(
root.join("Cargo.toml").is_file() && root.join(".git").exists(),
"{source} ({}) no longer looks like a Larust git checkout - cd there yourself and run \
`git pull && cargo install --path crates/larust-cli --force` (or re-clone and re-run \
install.sh/install.ps1), or fix/unset LARUST_CHECKOUT_ROOT if it's pointing at the \
wrong place",
root.display()
);
Ok(root)
}
fn resolve_checkout_root(env_override: Option<String>) -> (PathBuf, &'static str) {
match env_override {
Some(value) if !value.is_empty() => (PathBuf::from(value), "LARUST_CHECKOUT_ROOT"),
_ => (
PathBuf::from(CHECKOUT_ROOT),
"the checkout this `xr` was built from",
),
}
}
fn run_git(dir: &Path, args: &[&str]) -> Result<()> {
let status = Command::new("git")
.args(args)
.current_dir(dir)
.status()
.with_context(|| format!("failed to run git {}", args.join(" ")))?;
anyhow::ensure!(status.success(), "git {} failed", args.join(" "));
Ok(())
}
fn run_git_output(dir: &Path, args: &[&str]) -> Result<String> {
let output = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.with_context(|| format!("failed to run git {}", args.join(" ")))?;
anyhow::ensure!(output.status.success(), "git {} failed", args.join(" "));
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
fn short(commit: &str) -> &str {
&commit[..commit.len().min(12)]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_version_omits_the_suffix_when_no_real_commit_was_embedded() {
assert_eq!(format_version("0.9.0", "unknown"), "0.9.0");
}
#[test]
fn format_version_includes_the_commit_when_a_real_one_was_embedded() {
assert_eq!(format_version("0.9.0", "abc123"), "0.9.0 (abc123)");
}
#[test]
fn plan_pulls_and_reinstalls_when_the_checkout_is_behind_its_upstream() {
assert_eq!(plan("aaa", "bbb", "aaa"), Plan::PullAndReinstall);
}
#[test]
fn plan_reinstalls_only_when_the_checkout_matches_upstream_but_not_the_installed_binary() {
assert_eq!(plan("ccc", "ccc", "aaa"), Plan::ReinstallOnly);
}
#[test]
fn plan_reports_up_to_date_only_when_all_three_commits_match() {
assert_eq!(plan("aaa", "aaa", "aaa"), Plan::UpToDate);
}
#[test]
fn resolve_checkout_root_uses_the_override_when_set() {
let (root, source) = resolve_checkout_root(Some("/somewhere/else".to_string()));
assert_eq!(root, PathBuf::from("/somewhere/else"));
assert_eq!(source, "LARUST_CHECKOUT_ROOT");
}
#[test]
fn resolve_checkout_root_falls_back_to_the_baked_in_default_when_unset() {
let (root, source) = resolve_checkout_root(None);
assert_eq!(root, PathBuf::from(CHECKOUT_ROOT));
assert_eq!(source, "the checkout this `xr` was built from");
}
#[test]
fn resolve_checkout_root_treats_an_empty_override_the_same_as_unset() {
let (root, source) = resolve_checkout_root(Some(String::new()));
assert_eq!(root, PathBuf::from(CHECKOUT_ROOT));
assert_eq!(source, "the checkout this `xr` was built from");
}
#[test]
fn resolve_cargo_bin_dir_prefers_cargo_home_when_set() {
let dir = resolve_cargo_bin_dir(
Some(std::ffi::OsString::from("D:\\custom-cargo-home")),
Some(std::ffi::OsString::from("C:\\Users\\someone")),
);
assert_eq!(dir, PathBuf::from("D:\\custom-cargo-home").join("bin"));
}
#[test]
fn resolve_cargo_bin_dir_falls_back_to_user_profile_dot_cargo() {
let dir = resolve_cargo_bin_dir(None, Some(std::ffi::OsString::from("C:\\Users\\someone")));
assert_eq!(
dir,
PathBuf::from("C:\\Users\\someone")
.join(".cargo")
.join("bin")
);
}
#[test]
fn resolve_cargo_bin_dir_falls_back_to_a_relative_path_when_neither_is_set() {
let dir = resolve_cargo_bin_dir(None, None);
assert_eq!(dir, PathBuf::from(".cargo").join("bin"));
}
#[test]
fn aside_path_for_appends_old_to_the_full_name_not_replace_the_extension() {
assert_eq!(
aside_path_for(&PathBuf::from("C:\\Users\\someone\\.cargo\\bin\\xr.exe")),
PathBuf::from("C:\\Users\\someone\\.cargo\\bin\\xr.exe.old")
);
}
#[test]
fn aside_path_for_works_on_a_path_with_no_extension_too() {
assert_eq!(
aside_path_for(&PathBuf::from("xr")),
PathBuf::from("xr.old")
);
}
#[test]
fn short_truncates_a_full_hash_to_twelve_characters() {
let full = "a1b2c3d4e5f60789abcdef0123456789abcdef0";
assert_eq!(short(full).len(), 12);
assert_eq!(short(full), "a1b2c3d4e5f6");
}
#[test]
fn short_leaves_a_shorter_string_untouched() {
assert_eq!(short("unknown"), "unknown");
assert_eq!(short(""), "");
}
}