1use std::io::{BufRead, IsTerminal};
8use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result};
11use clap::Args;
12
13use crate::core::paths::Paths;
14use crate::util::format_bytes;
15
16#[derive(Args)]
17pub struct UninstallArgs {
18 #[arg(long, short = 'y')]
20 pub yes: bool,
21 #[arg(long)]
23 pub keep_data: bool,
24 #[arg(long)]
26 pub dry_run: bool,
27}
28
29#[derive(Debug, PartialEq, Eq)]
30pub enum InstallMethod {
31 Homebrew,
32 Npm,
33 Cargo,
34 ShellInstaller,
35 Unknown,
36}
37
38const BREW_PREFIXES: &[&str] = &[
39 "/opt/homebrew",
40 "/usr/local/Cellar",
41 "/home/linuxbrew/.linuxbrew",
42];
43
44pub fn detect_install_method(
47 exe: &Path,
48 cargo_home: Option<&Path>,
49 home: Option<&Path>,
50 cargo_lists_paper: bool,
51) -> InstallMethod {
52 let text = exe.to_string_lossy().replace('\\', "/");
53 if text.contains("/Cellar/") || BREW_PREFIXES.iter().any(|p| exe.starts_with(p)) {
54 return InstallMethod::Homebrew;
55 }
56 if text.contains("node_modules") {
57 return InstallMethod::Npm;
58 }
59 let in_dir = |dir: Option<PathBuf>| dir.is_some_and(|d| exe.starts_with(d));
60 let in_cargo_bin = in_dir(cargo_home.map(|c| c.join("bin")));
61 if in_cargo_bin && cargo_lists_paper {
62 return InstallMethod::Cargo;
63 }
64 let in_installer_dir = in_cargo_bin
65 || in_dir(home.map(|h| h.join(".cargo/bin")))
66 || in_dir(home.map(|h| h.join(".local/bin")));
67 if in_installer_dir {
70 return InstallMethod::ShellInstaller;
71 }
72 InstallMethod::Unknown
73}
74
75pub(crate) fn cargo_home(home: Option<&Path>) -> Option<PathBuf> {
76 std::env::var_os("CARGO_HOME")
77 .map(PathBuf::from)
78 .or_else(|| home.map(|h| h.join(".cargo")))
79}
80
81pub(crate) fn cargo_lists_paper(cargo_home: &Path) -> bool {
82 [".crates2.json", ".crates.toml"].iter().any(|name| {
83 std::fs::read_to_string(cargo_home.join(name))
84 .is_ok_and(|text| text.contains("\"paperscope "))
85 })
86}
87
88pub(crate) fn receipt_path(home: Option<&Path>) -> Option<PathBuf> {
89 let dir = if cfg!(windows) {
90 dirs::data_local_dir()?
91 } else {
92 match std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
93 Some(xdg) => PathBuf::from(xdg),
94 None => home?.join(".config"),
95 }
96 };
97 Some(dir.join("paperscope").join("paperscope-receipt.json"))
98}
99
100#[cfg(feature = "daemon")]
102pub(crate) fn current_install_method() -> InstallMethod {
103 let Some(exe) = std::env::current_exe()
104 .ok()
105 .and_then(|p| p.canonicalize().ok())
106 else {
107 return InstallMethod::Unknown;
108 };
109 let home = dirs::home_dir();
110 let cargo = cargo_home(home.as_deref());
111 detect_install_method(
112 &exe,
113 cargo.as_deref(),
114 home.as_deref(),
115 cargo.as_deref().is_some_and(cargo_lists_paper),
116 )
117}
118
119fn owned_dirs(paths: &Paths) -> Vec<PathBuf> {
122 let mut dirs_out = vec![paths.base_dir()];
123 if let Some(config) = paths.config_path().parent() {
124 dirs_out.push(config.to_path_buf());
125 }
126 let shared: Vec<PathBuf> = [dirs::home_dir(), dirs::cache_dir(), dirs::config_dir()]
127 .into_iter()
128 .flatten()
129 .collect();
130 let mut out: Vec<PathBuf> = Vec::new();
131 for dir in dirs_out {
132 let unsafe_dir =
133 dir.parent().is_none() || dir.as_os_str().is_empty() || dir == Path::new(".");
134 if unsafe_dir || shared.contains(&dir) || !dir.is_dir() || out.contains(&dir) {
135 continue;
136 }
137 out.push(dir);
138 }
139 out
140}
141
142fn dir_size(dir: &Path) -> u64 {
143 let Ok(entries) = std::fs::read_dir(dir) else {
144 return 0;
145 };
146 entries
147 .flatten()
148 .map(|e| match e.metadata() {
149 Ok(m) if m.is_dir() => dir_size(&e.path()),
150 Ok(m) => m.len(),
151 Err(_) => 0,
152 })
153 .sum()
154}
155
156#[derive(Debug, PartialEq, Eq)]
157pub enum DataOutcome {
158 Nothing,
159 Kept,
160 DryRun(u64),
161 NeedsYes,
162 Cancelled,
163 Removed(u64),
164}
165
166pub fn remove_data(
168 dirs: &[PathBuf],
169 args: &UninstallArgs,
170 interactive: bool,
171 input: &mut dyn BufRead,
172) -> Result<DataOutcome> {
173 if args.keep_data {
174 return Ok(DataOutcome::Kept);
175 }
176 if dirs.is_empty() {
177 println!("No Paper data found.");
178 return Ok(DataOutcome::Nothing);
179 }
180 let total: u64 = dirs.iter().map(|d| dir_size(d)).sum();
181 println!("Paper data ({}):", format_bytes(total));
182 for dir in dirs {
183 println!(" {}", dir.display());
184 }
185 if args.dry_run {
186 println!("(dry run) would delete the above");
187 return Ok(DataOutcome::DryRun(total));
188 }
189 if !args.yes {
190 if !interactive {
191 println!("Not deleting: stdin is not a terminal. Re-run with --yes to delete it.");
192 return Ok(DataOutcome::NeedsYes);
193 }
194 print!("Delete these? [y/N] ");
195 std::io::Write::flush(&mut std::io::stdout()).ok();
196 let mut answer = String::new();
197 input.read_line(&mut answer)?;
198 if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
199 println!("Data kept.");
200 return Ok(DataOutcome::Cancelled);
201 }
202 }
203 for dir in dirs {
204 std::fs::remove_dir_all(dir).with_context(|| format!("deleting {}", dir.display()))?;
205 }
206 println!("Deleted Paper data.");
207 Ok(DataOutcome::Removed(total))
208}
209
210fn remove_service(dry_run: bool) -> &'static str {
211 #[cfg(feature = "daemon")]
212 {
213 if dry_run {
214 println!("(dry run) would remove the background service");
215 return "service (dry run)";
216 }
217 match crate::cli::daemon::uninstall_service() {
218 Ok(path) => {
219 println!("Removed background service: {}", path.display());
220 "service removed"
221 }
222 Err(error) => {
223 println!("Background service not removed ({error:#}); continuing.");
224 "service not removed"
225 }
226 }
227 }
228 #[cfg(not(feature = "daemon"))]
229 {
230 let _ = dry_run;
231 "service skipped"
232 }
233}
234
235fn handle_binary(
237 method: &InstallMethod,
238 exe: &Path,
239 receipt: Option<&Path>,
240 dry_run: bool,
241) -> Result<Option<String>> {
242 match method {
243 InstallMethod::Homebrew => println!("finish with: brew uninstall paper"),
244 InstallMethod::Npm => println!("finish with: npm uninstall -g paperscope"),
245 InstallMethod::Cargo => println!("finish with: cargo uninstall paperscope"),
246 InstallMethod::Unknown => println!("delete the binary yourself: {}", exe.display()),
247 InstallMethod::ShellInstaller => {
248 if dry_run {
249 println!("(dry run) would delete {}", exe.display());
250 if let Some(r) = receipt.filter(|r| r.exists()) {
251 println!("(dry run) would delete {}", r.display());
252 }
253 } else {
254 if let Some(r) = receipt.filter(|r| r.exists()) {
255 std::fs::remove_file(r).with_context(|| format!("deleting {}", r.display()))?;
256 println!("Deleted install receipt: {}", r.display());
257 }
258 if cfg!(windows) {
259 println!("delete the binary after this exits: {}", exe.display());
260 } else {
261 std::fs::remove_file(exe)
262 .with_context(|| format!("deleting {}", exe.display()))?;
263 println!("Deleted binary: {}", exe.display());
264 }
265 }
266 println!(
267 "The installer may have added a PATH line to ~/.bashrc, ~/.zshrc, ~/.profile or \
268 your fish config; you can remove it. Paper does not edit those files."
269 );
270 if cfg!(windows) {
271 return Ok(Some(format!("the binary {}", exe.display())));
272 }
273 return Ok(Some("any PATH line in your shell startup file".into()));
274 }
275 }
276 Ok(Some(match method {
277 InstallMethod::Homebrew => "the Homebrew package".into(),
278 InstallMethod::Npm => "the npm package".into(),
279 InstallMethod::Cargo => "the cargo package".into(),
280 _ => format!("the binary {}", exe.display()),
281 }))
282}
283
284pub async fn run(args: UninstallArgs) -> Result<i32> {
285 let service = remove_service(args.dry_run);
286
287 let dirs = owned_dirs(&Paths::new());
288 let interactive = std::io::stdin().is_terminal();
289 let data = remove_data(&dirs, &args, interactive, &mut std::io::stdin().lock())?;
290
291 let exe = std::env::current_exe()
292 .and_then(|p| p.canonicalize())
293 .context("locating the paper binary")?;
294 let home = dirs::home_dir();
295 let cargo = cargo_home(home.as_deref());
296 let receipt = receipt_path(home.as_deref());
297 let method = detect_install_method(
298 &exe,
299 cargo.as_deref(),
300 home.as_deref(),
301 cargo.as_deref().is_some_and(cargo_lists_paper),
302 );
303 let left = handle_binary(&method, &exe, receipt.as_deref(), args.dry_run)?;
304
305 let data_note = match data {
306 DataOutcome::Removed(b) => format!("data deleted ({})", format_bytes(b)),
307 DataOutcome::DryRun(_) => "data would be deleted".into(),
308 DataOutcome::Kept => "data kept (--keep-data)".into(),
309 DataOutcome::Cancelled | DataOutcome::NeedsYes => "data kept".into(),
310 DataOutcome::Nothing => "no data found".into(),
311 };
312 let prefix = if args.dry_run {
313 "Dry run, nothing changed: "
314 } else {
315 "Done: "
316 };
317 println!(
318 "{prefix}{service}; {data_note}. Left for you: {}.",
319 left.unwrap_or_else(|| "nothing".into())
320 );
321 Ok(super::EXIT_FOUND)
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 fn detect(exe: &str, listed: bool, _receipt: bool) -> InstallMethod {
330 detect_install_method(
331 Path::new(exe),
332 Some(Path::new("/home/u/.cargo")),
333 Some(Path::new("/home/u")),
334 listed,
335 )
336 }
337
338 #[test]
339 fn detects_homebrew() {
340 assert_eq!(
341 detect("/opt/homebrew/bin/paper", false, false),
342 InstallMethod::Homebrew
343 );
344 assert_eq!(
345 detect("/usr/local/Cellar/paper/0.3.1/bin/paper", false, false),
346 InstallMethod::Homebrew
347 );
348 }
349
350 #[test]
351 fn detects_npm() {
352 let exe = "/usr/lib/node_modules/paperscope/bin/paper";
353 assert_eq!(detect(exe, false, true), InstallMethod::Npm);
354 }
355
356 #[test]
357 fn detects_cargo_only_when_listed() {
358 let exe = "/home/u/.cargo/bin/paper";
359 assert_eq!(detect(exe, true, false), InstallMethod::Cargo);
360 assert_eq!(detect(exe, false, false), InstallMethod::ShellInstaller);
361 }
362
363 #[test]
364 fn detects_shell_installer_by_folder_never_by_receipt_alone() {
365 assert_eq!(detect("/srv/paper", false, true), InstallMethod::Unknown);
366 assert_eq!(
367 detect("/home/u/.local/bin/paper", false, false),
368 InstallMethod::ShellInstaller
369 );
370 }
371
372 #[test]
373 fn unknown_otherwise() {
374 assert_eq!(detect("/srv/paper", false, false), InstallMethod::Unknown);
375 }
376
377 fn args(yes: bool, keep_data: bool, dry_run: bool) -> UninstallArgs {
378 UninstallArgs {
379 yes,
380 keep_data,
381 dry_run,
382 }
383 }
384
385 #[test]
386 fn data_step_modes() {
387 let tmp = tempfile::tempdir().unwrap();
388 let dir = tmp.path().join("paper");
389 std::fs::create_dir_all(dir.join("models")).unwrap();
390 std::fs::write(dir.join("chunks.db"), b"abc").unwrap();
391 let dirs = vec![dir.clone()];
392
393 let r = |a: UninstallArgs, tty: bool, input: &str| {
394 remove_data(&dirs, &a, tty, &mut input.as_bytes()).unwrap()
395 };
396 assert_eq!(r(args(true, false, true), true, ""), DataOutcome::DryRun(3));
397 assert_eq!(r(args(true, true, false), true, ""), DataOutcome::Kept);
398 assert_eq!(
399 r(args(false, false, false), false, "y\n"),
400 DataOutcome::NeedsYes
401 );
402 assert_eq!(
403 r(args(false, false, false), true, "n\n"),
404 DataOutcome::Cancelled
405 );
406 assert_eq!(
407 r(args(false, false, false), true, "\n"),
408 DataOutcome::Cancelled
409 );
410 assert!(dir.join("chunks.db").exists());
411 assert_eq!(
412 r(args(false, false, false), true, "Yes\n"),
413 DataOutcome::Removed(3)
414 );
415 assert!(!dir.exists());
416 }
417
418 #[test]
419 fn owned_dirs_skips_missing_and_shared() {
420 let tmp = tempfile::tempdir().unwrap();
421 assert_eq!(
422 owned_dirs(&Paths::with_base(tmp.path())),
423 vec![tmp.path().to_path_buf()]
424 );
425 assert!(owned_dirs(&Paths::with_base(tmp.path().join("nope"))).is_empty());
426 if let Some(home) = dirs::home_dir() {
427 assert!(owned_dirs(&Paths::with_base(home)).is_empty());
428 }
429 }
430}