use std::path::{Path, PathBuf};
use cuno_core::{CunoError, Env, Shell};
use cuno_self::SelfError;
use cuno_self::fetch::{Curl, Fetch};
use cuno_self::install::{self, Method};
use cuno_self::release::{self, Version};
use cuno_self::uninstall::{self, RegistryPath, UserPath};
use cuno_self::update::{self, Check};
use crate::Input;
fn current() -> Version {
Version::parse(env!("CARGO_PKG_VERSION")).expect("cuno's own version is x.y.z or x.y.z-rc.n")
}
fn system_tar(env: &Env) -> PathBuf {
let root = env
.set_value("SystemRoot")
.map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from);
root.join(r"System32\tar.exe")
}
fn method_of(exe: &Path, env: &Env) -> Result<Method, Box<dyn CunoError>> {
let home = cuno_core::cuno_home(env).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
let cargo = install::cargo_home(env);
Ok(install::method(exe, &home, cargo.as_deref(), env.case()))
}
pub fn update(
exe: &Result<PathBuf, String>,
env: &Env,
temp: &Path,
shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
let exe = exe.clone().map_err(|e| boxed(SelfError::Exe(e)))?;
let method = method_of(&exe, env)?;
update::refuse(method, &exe).map_err(boxed)?;
let curl = Curl::find(env).map_err(boxed)?;
updated(&exe, &curl, current(), temp, &system_tar(env), shell)
}
fn boxed(e: SelfError) -> Box<dyn CunoError> {
Box::new(e)
}
fn updated(
exe: &Path,
fetch: &dyn Fetch,
current: Version,
temp: &Path,
tar: &Path,
shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
update::remove_renamed(exe);
match update::check(Method::Installer, exe, current, fetch, release::RELEASES).map_err(boxed)? {
Check::Unchanged { latest } if latest == current => {
shell.status("Unchanged", format!("cuno {current} is the latest release"));
}
Check::Unchanged { latest } => {
shell.status(
"Unchanged",
format!("cuno {current} is newer than the latest release, {latest}"),
);
}
Check::Newer { latest } => {
shell.status("Downloading", format!("cuno {latest}"));
update::install(exe, latest, fetch, release::RELEASES, temp, tar).map_err(boxed)?;
shell.status("Updated", format!("cuno {current} -> {latest}"));
}
}
Ok(0)
}
pub fn uninstall(
exe: &Result<PathBuf, String>,
env: &Env,
yes: bool,
input: Input<'_>,
shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
let remove_rest = |home: &Path| uninstall::remove_after_exit(home, std::process::id(), env);
uninstall_with(
exe,
env,
yes,
input,
&RegistryPath { env: env.clone() },
&remove_rest,
shell,
)
}
fn uninstall_with(
exe: &Result<PathBuf, String>,
env: &Env,
yes: bool,
input: Input<'_>,
path: &dyn UserPath,
remove_rest: &dyn Fn(&Path) -> Result<(), SelfError>,
shell: &mut Shell,
) -> Result<i32, Box<dyn CunoError>> {
let exe = exe.clone().map_err(|e| boxed(SelfError::Exe(e)))?;
let home = cuno_core::cuno_home(env).map_err(|e| Box::new(e) as Box<dyn CunoError>)?;
let method = method_of(&exe, env)?;
if !home.exists() {
shell.warning(format!(
"nothing to remove: {} does not exist",
home.display()
));
return Ok(0);
}
uninstall::guard(&home, env).map_err(boxed)?;
let bin = home.join("bin");
if !yes {
if !input.is_terminal {
return Err(boxed(SelfError::NoAnswer));
}
let mut question = format!("This removes:\n {}\n", home.display());
if method == Method::Installer {
question += &format!(" {} from PATH\n", bin.display());
}
question += "Continue? [y/N] ";
shell.raw(question.as_bytes());
let mut answer = String::new();
let _ = input.stdin.read_line(&mut answer);
let answer = answer.trim();
if !(answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes")) {
return Ok(0);
}
}
let report = uninstall::uninstall(&home, &exe, method, path, env.case()).map_err(boxed)?;
if report.path_removed {
shell.status("Removed", format!("{} from PATH", bin.display()));
}
if report.exe_left {
remove_rest(&home).map_err(boxed)?;
}
shell.status("Removed", home.display());
match method {
Method::Installer => {}
Method::Cargo => shell.help(
"cuno itself was installed by cargo install; run cargo uninstall cuno to remove it",
),
Method::Other => shell.help(format!(
"cuno itself is at {}; remove it yourself",
exe.display()
)),
}
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
use cuno_core::NameCase;
fn env(pairs: &[(&str, &str)]) -> Env {
Env::from_pairs(
pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())),
NameCase::Insensitive,
)
}
#[test]
fn the_homes_come_from_the_environment() {
let given = env(&[
("CUNO_HOME", r"D:\c"),
("CARGO_HOME", r"D:\r"),
("USERPROFILE", r"C:\u"),
]);
let of = |exe: &str| method_of(Path::new(exe), &given).ok();
assert_eq!(of(r"D:\c\bin\cuno.exe"), Some(Method::Installer));
assert_eq!(of(r"D:\r\bin\cuno.exe"), Some(Method::Cargo));
assert_eq!(of(r"C:\u\.cuno\bin\cuno.exe"), Some(Method::Other));
}
#[test]
fn tar_is_windows_own() {
assert_eq!(
system_tar(&env(&[("SystemRoot", r"C:\WINDOWS")])),
PathBuf::from(r"C:\WINDOWS\System32\tar.exe")
);
}
#[derive(Clone, Default)]
struct Captured(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for Captured {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl Captured {
fn text(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
}
}
struct Release {
latest: &'static str,
zip: Vec<u8>,
}
impl Fetch for Release {
fn redirect(&self, _: &str) -> Result<Option<String>, SelfError> {
Ok(Some(format!("{}/tag/v{}", release::RELEASES, self.latest)))
}
fn download(&self, url: &str, to: &Path) -> Result<(), SelfError> {
let bytes = if url.ends_with(".sha256") {
use sha2::{Digest, Sha256};
let hex: String = Sha256::digest(&self.zip)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
format!("{hex} x\n").into_bytes()
} else {
self.zip.clone()
};
std::fs::write(to, bytes).unwrap();
Ok(())
}
}
fn tar() -> PathBuf {
system_tar(&Env::from_process())
}
fn release(latest: &'static str) -> Release {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("cuno.exe"), b"new").unwrap();
let zip = dir.path().join("out.zip");
let status = std::process::Command::new(tar())
.args(["-a", "-cf"])
.arg(&zip)
.arg("-C")
.arg(dir.path())
.arg("cuno.exe")
.status()
.unwrap();
assert!(status.success());
Release {
latest,
zip: std::fs::read(zip).unwrap(),
}
}
fn run(latest: &'static str, current: &str) -> (i32, String, Vec<u8>) {
let home = tempfile::tempdir().unwrap();
let exe = home.path().join("cuno.exe");
std::fs::write(&exe, b"old").unwrap();
std::fs::write(home.path().join("cuno.exe.old"), b"stale").unwrap();
let temp = tempfile::tempdir().unwrap();
let out = Captured::default();
let mut shell = Shell::new(Box::new(out.clone()), None, &env(&[]), false);
let code = updated(
&exe,
&release(latest),
Version::parse(current).unwrap(),
temp.path(),
&tar(),
&mut shell,
)
.unwrap();
let aside = std::fs::read(home.path().join("cuno.exe.old")).unwrap_or_default();
assert_ne!(aside, b"stale", "the stale copy was not removed");
(code, out.text(), std::fs::read(&exe).unwrap())
}
#[test]
fn each_outcome_is_said_as_the_spec_says() {
assert_eq!(
run("0.2.0", "0.2.0"),
(
0,
" Unchanged cuno 0.2.0 is the latest release\n".to_owned(),
b"old".to_vec()
)
);
assert_eq!(
run("0.2.0", "0.3.0"),
(
0,
" Unchanged cuno 0.3.0 is newer than the latest release, 0.2.0\n".to_owned(),
b"old".to_vec()
)
);
assert_eq!(
run("0.2.0", "0.1.0"),
(
0,
" Downloading cuno 0.2.0\n Updated cuno 0.1.0 -> 0.2.0\n".to_owned(),
b"new".to_vec()
)
);
assert_eq!(
run("0.2.0", "0.3.0-rc.1"),
(
0,
" Unchanged cuno 0.3.0-rc.1 is newer than the latest release, 0.2.0\n".to_owned(),
b"old".to_vec()
)
);
assert_eq!(
run("0.2.0", "0.2.0-rc.2"),
(
0,
" Downloading cuno 0.2.0\n Updated cuno 0.2.0-rc.2 -> 0.2.0\n".to_owned(),
b"new".to_vec()
)
);
}
#[test]
fn the_running_version_is_cunos_own() {
assert_eq!(current().to_string(), env!("CARGO_PKG_VERSION"));
}
#[test]
fn no_executable_path_is_an_error() {
let out = Captured::default();
let mut shell = Shell::new(Box::new(out.clone()), None, &env(&[]), false);
let temp = tempfile::tempdir().unwrap();
let error = update(
&Err("denied".to_owned()),
&env(&[]),
temp.path(),
&mut shell,
)
.unwrap_err();
assert_eq!(
error.to_string(),
"cannot find where cuno itself is: denied"
);
}
#[test]
fn tar_defaults_to_the_usual_windows() {
assert_eq!(
system_tar(&env(&[])),
PathBuf::from(r"C:\Windows\System32\tar.exe")
);
}
#[test]
fn paths_are_compared_as_the_host_compares_names() {
let given = env(&[("CUNO_HOME", r"D:\c")]);
assert_eq!(
method_of(Path::new(r"d:\C\BIN\cuno.exe"), &given).ok(),
Some(Method::Installer)
);
}
#[derive(Default)]
struct FakePath(std::cell::RefCell<Vec<PathBuf>>);
impl UserPath for FakePath {
fn remove(&self, dir: &Path) -> Result<bool, SelfError> {
self.0.borrow_mut().push(dir.to_owned());
Ok(true)
}
}
struct Setup {
dir: tempfile::TempDir,
env: Env,
exe: PathBuf,
}
impl Setup {
fn new() -> Setup {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
std::fs::create_dir_all(&home).unwrap();
std::fs::write(home.join("config.toml"), "").unwrap();
let user = dir.path().join("user");
let env = Env::from_pairs(
[
("CUNO_HOME".into(), home.into_os_string()),
("USERPROFILE".into(), user.into_os_string()),
(
"CARGO_HOME".into(),
dir.path().join("cargo").into_os_string(),
),
],
NameCase::Insensitive,
);
let exe = dir.path().join(r"tools\cuno.exe");
Setup { dir, env, exe }
}
fn home(&self) -> PathBuf {
self.dir.path().join("home")
}
fn run(&self, yes: bool, answer: &str, terminal: bool) -> (i32, String) {
let out = Captured::default();
let mut shell = Shell::new(Box::new(out.clone()), None, &self.env, false);
let mut stdin = std::io::Cursor::new(answer.as_bytes().to_vec());
let input = Input {
stdin: &mut stdin,
is_terminal: terminal,
};
let code = match uninstall_with(
&Ok(self.exe.clone()),
&self.env,
yes,
input,
&FakePath::default(),
&|_: &Path| -> Result<(), SelfError> { panic!("nothing is left running here") },
&mut shell,
) {
Ok(code) => code,
Err(e) => {
shell.error(&e);
if let Some(help) = e.help() {
shell.help(help);
}
e.exit_class().code()
}
};
(code, out.text())
}
}
#[test]
fn nothing_is_removed_without_a_yes() {
let s = Setup::new();
let (code, out) = s.run(false, "", false);
assert_eq!(code, 2, "{out}");
assert_eq!(
out,
"error: cuno self uninstall asks before deleting, and standard input is not a terminal\nhelp: pass -y to remove without asking\n"
);
assert!(s.home().exists());
for answer in ["", "n\n", "no\n", "yess\n"] {
let (code, out) = s.run(false, answer, true);
assert_eq!(code, 0, "{answer:?}: {out}");
assert_eq!(
out,
format!("This removes:\n {}\nContinue? [y/N] ", s.home().display())
);
assert!(s.home().exists(), "{answer:?}");
}
let (code, out) = s.run(false, "YES\n", true);
assert_eq!(code, 0, "{out}");
assert!(!s.home().exists());
assert!(
out.ends_with(&format!(
" Removed {}\nhelp: cuno itself is at {}; remove it yourself\n",
s.home().display(),
s.exe.display()
)),
"{out}"
);
}
#[test]
fn a_cargo_installed_cuno_is_pointed_to_cargo_uninstall() {
let s = Setup::new();
let cargo = Setup {
exe: s.dir.path().join("cargo").join("bin").join("cuno.exe"),
..s
};
let (code, out) = cargo.run(true, "", false);
assert_eq!(code, 0, "{out}");
let help = "help: cuno itself was installed by cargo install; run cargo uninstall cuno to remove it";
assert_eq!(
out,
format!(" Removed {}\n{help}\n", cargo.home().display())
);
assert!(!cargo.home().exists());
}
#[test]
fn yes_removes_without_asking() {
let s = Setup::new();
let (code, out) = s.run(true, "", false);
assert_eq!(code, 0, "{out}");
assert!(!out.contains("Continue?"), "{out}");
assert!(!s.home().exists());
}
#[test]
fn a_home_not_cunos_own_is_refused_and_a_missing_one_warned_of() {
let s = Setup::new();
let user = s.dir.path().join("user");
std::fs::create_dir_all(&user).unwrap();
let env = s.env.with("CUNO_HOME", user.clone().into_os_string());
let refused = Setup {
env,
..Setup::new()
};
let (code, out) = refused.run(false, "y\n", true);
assert_eq!(code, 3, "{out}");
assert!(out.starts_with("error: refusing to remove "), "{out}");
assert!(!out.contains("Continue?"), "{out}");
std::fs::remove_dir_all(s.home()).unwrap();
let (code, out) = s.run(true, "", false);
assert_eq!(code, 0);
assert_eq!(
out,
format!(
"warning: nothing to remove: {} does not exist\n",
s.home().display()
)
);
}
struct AnsweringPath {
present: bool,
asked: std::cell::RefCell<Vec<PathBuf>>,
}
impl UserPath for AnsweringPath {
fn remove(&self, dir: &Path) -> Result<bool, SelfError> {
self.asked.borrow_mut().push(dir.to_owned());
Ok(self.present)
}
}
fn run_installer(
answer: &str,
present: bool,
rest_fails: bool,
) -> (i32, String, Vec<PathBuf>, Setup) {
let s = Setup::new();
let bin = s.home().join("bin");
std::fs::create_dir_all(&bin).unwrap();
std::fs::write(bin.join("cuno.exe"), "").unwrap();
let installed = Setup {
exe: bin.join("cuno.exe"),
..s
};
let out = Captured::default();
let mut shell = Shell::new(Box::new(out.clone()), None, &installed.env, false);
let mut stdin = std::io::Cursor::new(answer.as_bytes().to_vec());
let input = Input {
stdin: &mut stdin,
is_terminal: true,
};
let path = AnsweringPath {
present,
asked: std::cell::RefCell::new(Vec::new()),
};
let given = std::cell::RefCell::new(Vec::new());
let remove_rest = |home: &Path| {
given.borrow_mut().push(home.to_owned());
if rest_fails {
return Err(SelfError::Helper {
reason: "gone".into(),
});
}
Ok(())
};
let code = match uninstall_with(
&Ok(installed.exe.clone()),
&installed.env,
false,
input,
&path,
&remove_rest,
&mut shell,
) {
Ok(code) => code,
Err(e) => {
shell.error(&e);
e.exit_class().code()
}
};
assert_eq!(*path.asked.borrow(), [bin]);
(code, out.text(), given.into_inner(), installed)
}
#[test]
fn the_installers_cuno_names_its_path_entry_and_leaves_the_rest_to_go() {
let (code, out, given, s) = run_installer("y\n", true, false);
let home = s.home();
let bin = home.join("bin");
assert_eq!(code, 0, "{out}");
assert_eq!(
out,
format!(
"This removes:\n {}\n {} from PATH\nContinue? [y/N] Removed {} from PATH\n Removed {}\n",
home.display(),
bin.display(),
bin.display(),
home.display()
)
);
assert_eq!(given, std::slice::from_ref(&home));
assert_eq!(std::fs::read_dir(&home).unwrap().count(), 1);
let (code, out, _, s) = run_installer("y\n", false, false);
assert_eq!(code, 0, "{out}");
assert!(!out.contains("from PATH\n Removed"), "{out}");
assert!(
out.ends_with(&format!(" Removed {}\n", s.home().display())),
"{out}"
);
}
#[test]
fn a_remover_that_cannot_start_is_an_error() {
let (code, out, _, _) = run_installer("y\n", true, true);
assert_eq!(code, 3, "{out}");
assert!(
out.contains("error: cannot start the process that removes cuno.exe: gone"),
"{out}"
);
}
}