| 1 | #![cfg(unix)] |
| 2 | |
| 3 | use std::fs; |
| 4 | use std::os::unix::fs::PermissionsExt; |
| 5 | use std::path::PathBuf; |
| 6 | use std::process::Command; |
| 7 | |
| 8 | use sha2::{Digest, Sha256}; |
| 9 | |
| 10 | fn codewhale_binary() -> PathBuf { |
| 11 | if let Some(path) = std::env::var_os("CARGO_BIN_EXE_codewhale").filter(|v| !v.is_empty()) { |
| 12 | return PathBuf::from(path); |
| 13 | } |
| 14 | if let Some(path) = option_env!("CARGO_BIN_EXE_codewhale") { |
| 15 | return PathBuf::from(path); |
| 16 | } |
| 17 | let mut path = std::env::current_exe().expect("current test executable path"); |
| 18 | path.pop(); |
| 19 | if path.ends_with("deps") { |
| 20 | path.pop(); |
| 21 | } |
| 22 | path.push("codewhale"); |
| 23 | path |
| 24 | } |
| 25 | |
| 26 | #[test] |
| 27 | fn uninstall_yes_removes_a_receipted_install_and_keeps_user_data() { |
| 28 | let root = tempfile::tempdir().unwrap(); |
| 29 | let root_path = root.path().canonicalize().unwrap(); |
| 30 | let bin = root_path.join("bin"); |
| 31 | let home = root_path.join("home"); |
| 32 | fs::create_dir(&bin).unwrap(); |
| 33 | fs::create_dir(&home).unwrap(); |
| 34 | fs::set_permissions(&bin, fs::Permissions::from_mode(0o755)).unwrap(); |
| 35 | |
| 36 | let installed = bin.join("codewhale"); |
| 37 | fs::copy(codewhale_binary(), &installed).unwrap(); |
| 38 | fs::set_permissions(&installed, fs::Permissions::from_mode(0o755)).unwrap(); |
| 39 | let digest: String = Sha256::digest(fs::read(&installed).unwrap()) |
| 40 | .iter() |
| 41 | .map(|byte| format!("{byte:02x}")) |
| 42 | .collect(); |
| 43 | let receipt = bin.join(".codewhale-install.sha256"); |
| 44 | fs::write(&receipt, format!("{digest} codewhale\n")).unwrap(); |
| 45 | fs::set_permissions(&receipt, fs::Permissions::from_mode(0o644)).unwrap(); |
| 46 | |
| 47 | let data = home.join(".codewhale"); |
| 48 | fs::create_dir(&data).unwrap(); |
| 49 | fs::write(data.join("config.toml"), "keep = true\n").unwrap(); |
| 50 | |
| 51 | let xdg_data = root_path.join("xdg_data"); |
| 52 | let xdg_config = root_path.join("xdg_config"); |
| 53 | fs::create_dir(&xdg_data).unwrap(); |
| 54 | fs::create_dir(&xdg_config).unwrap(); |
| 55 | |
| 56 | let output = Command::new(&installed) |
| 57 | .env_clear() |
| 58 | .args(["uninstall", "--yes"]) |
| 59 | .env("HOME", &home) |
| 60 | .env("CODEWHALE_HOME", &data) |
| 61 | .env("XDG_DATA_HOME", &xdg_data) |
| 62 | .env("XDG_CONFIG_HOME", &xdg_config) |
| 63 | .env("PATH", &bin) |
| 64 | .output() |
| 65 | .unwrap(); |
| 66 | let stdout = String::from_utf8_lossy(&output.stdout); |
| 67 | let stderr = String::from_utf8_lossy(&output.stderr); |
| 68 | assert!( |
| 69 | output.status.success(), |
| 70 | "stdout: {stdout}\nstderr: {stderr}" |
| 71 | ); |
| 72 | assert!(!installed.exists(), "stdout: {stdout}"); |
| 73 | assert!(!receipt.exists(), "stdout: {stdout}"); |
| 74 | assert!(data.join("config.toml").exists()); |
| 75 | } |
| 76 |