use crate::errors::*;
use std::convert::Infallible;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
static REPLACED_EXE: OnceLock<PathBuf> = OnceLock::new();
pub(crate) fn record_replaced_exe(exe: &Path) {
let _ = REPLACED_EXE.set(exe.to_path_buf());
}
fn restart_exe(recorded: Option<&Path>) -> Result<PathBuf> {
match recorded {
Some(exe) => Ok(exe.to_path_buf()),
None => Ok(strip_deleted_suffix(std::env::current_exe()?)),
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn strip_deleted_suffix(exe: PathBuf) -> PathBuf {
use std::os::unix::ffi::OsStrExt;
const SUFFIX: &[u8] = b" (deleted)";
if exe.exists() {
return exe;
}
match exe.as_os_str().as_bytes().strip_suffix(SUFFIX) {
Some(stripped) => {
let stripped = PathBuf::from(OsStr::from_bytes(stripped));
if stripped.exists() { stripped } else { exe }
}
None => exe,
}
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn strip_deleted_suffix(exe: PathBuf) -> PathBuf {
exe
}
fn restart_command<I, S>(args: I) -> Result<Command>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let exe = restart_exe(REPLACED_EXE.get().map(PathBuf::as_path))?;
let mut cmd = Command::new(exe);
cmd.args(args);
Ok(cmd)
}
pub fn restart() -> Result<Infallible> {
restart_with(std::env::args_os().skip(1))
}
#[cfg(unix)]
pub fn restart_with<I, S>(args: I) -> Result<Infallible>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
use std::os::unix::process::CommandExt;
let mut cmd = restart_command(args)?;
Err(Error::Io(cmd.exec()))
}
#[cfg(windows)]
pub fn restart_with<I, S>(args: I) -> Result<Infallible>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut cmd = restart_command(args)?;
cmd.spawn()?;
std::process::exit(0);
}
#[cfg(test)]
mod tests {
use super::{restart_command, restart_exe};
use std::ffi::OsStr;
use std::path::Path;
#[test]
fn restart_command_targets_current_exe_with_given_args() {
let cmd = restart_command(["run", "--quiet"]).unwrap();
assert_eq!(cmd.get_program(), std::env::current_exe().unwrap());
let args: Vec<&OsStr> = cmd.get_args().collect();
assert_eq!(args, ["run", "--quiet"]);
}
#[test]
fn restart_command_with_no_args_forwards_none() {
let cmd = restart_command(std::iter::empty::<&OsStr>()).unwrap();
assert_eq!(cmd.get_args().count(), 0);
}
#[test]
fn restart_exe_prefers_recorded_path() {
let recorded = Path::new("/recorded/before/replace");
assert_eq!(restart_exe(Some(recorded)).unwrap(), recorded);
assert_eq!(restart_exe(None).unwrap(), std::env::current_exe().unwrap());
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod deleted_suffix {
use super::super::strip_deleted_suffix;
use std::path::PathBuf;
fn deleted(path: &std::path::Path) -> PathBuf {
let mut s = path.as_os_str().to_owned();
s.push(" (deleted)");
PathBuf::from(s)
}
#[test]
fn strips_suffix_when_only_the_stripped_path_exists() {
let dir = tempfile::TempDir::new().unwrap();
let exe = dir.path().join("app");
std::fs::write(&exe, b"").unwrap();
assert_eq!(strip_deleted_suffix(deleted(&exe)), exe);
}
#[test]
fn keeps_suffix_when_the_suffixed_path_exists() {
let dir = tempfile::TempDir::new().unwrap();
let exe = dir.path().join("app");
std::fs::write(&exe, b"").unwrap();
std::fs::write(deleted(&exe), b"").unwrap();
assert_eq!(strip_deleted_suffix(deleted(&exe)), deleted(&exe));
}
#[test]
fn keeps_path_when_neither_exists() {
let dir = tempfile::TempDir::new().unwrap();
let exe = dir.path().join("app");
assert_eq!(strip_deleted_suffix(deleted(&exe)), deleted(&exe));
assert_eq!(strip_deleted_suffix(exe.clone()), exe);
}
}
}