|
| 1 | +use std::fs; |
| 2 | +use std::io::{self, Write}; |
| 3 | +use std::path::Path; |
| 4 | + |
| 5 | +use anyhow::{Context, Result, bail}; |
| 6 | + |
| 7 | +use crate::config; |
| 8 | + |
| 9 | +pub fn run(assume_yes: bool) -> Result<()> { |
| 10 | + let binary = std::env::current_exe().context("locating the rgpt executable")?; |
| 11 | + let data_dir = config::app_dir()?; |
| 12 | + |
| 13 | + if !assume_yes { |
| 14 | + println!("This will remove:"); |
| 15 | + println!(" {}", binary.display()); |
| 16 | + println!( |
| 17 | + " {} (configuration, chats, roles, and cache)", |
| 18 | + data_dir.display() |
| 19 | + ); |
| 20 | + print!("Continue? [y/N] "); |
| 21 | + io::stdout().flush().ok(); |
| 22 | + |
| 23 | + let mut answer = String::new(); |
| 24 | + io::stdin() |
| 25 | + .read_line(&mut answer) |
| 26 | + .context("reading uninstall confirmation")?; |
| 27 | + if !matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes") { |
| 28 | + bail!("Uninstall cancelled."); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + remove_data_dir(&data_dir)?; |
| 33 | + fs::remove_file(&binary) |
| 34 | + .with_context(|| format!("removing executable {}", binary.display()))?; |
| 35 | + println!("rgpt has been uninstalled."); |
| 36 | + Ok(()) |
| 37 | +} |
| 38 | + |
| 39 | +fn remove_data_dir(path: &Path) -> Result<()> { |
| 40 | + if path.exists() { |
| 41 | + fs::remove_dir_all(path) |
| 42 | + .with_context(|| format!("removing application data directory {}", path.display()))?; |
| 43 | + } |
| 44 | + Ok(()) |
| 45 | +} |
| 46 | + |
| 47 | +#[cfg(test)] |
| 48 | +mod tests { |
| 49 | + use super::remove_data_dir; |
| 50 | + |
| 51 | + #[test] |
| 52 | + fn removes_application_data_directory() { |
| 53 | + let dir = std::env::temp_dir().join(format!("rgpt-uninstall-test-{}", std::process::id())); |
| 54 | + std::fs::create_dir_all(&dir).unwrap(); |
| 55 | + std::fs::write(dir.join("config"), "secret").unwrap(); |
| 56 | + |
| 57 | + remove_data_dir(&dir).unwrap(); |
| 58 | + |
| 59 | + assert!(!dir.exists()); |
| 60 | + } |
| 61 | +} |
0 commit comments