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
75fn 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
81fn 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
88fn 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
100fn owned_dirs(paths: &Paths) -> Vec<PathBuf> {
103 let mut dirs_out = vec![paths.base_dir()];
104 if let Some(config) = paths.config_path().parent() {
105 dirs_out.push(config.to_path_buf());
106 }
107 let shared: Vec<PathBuf> = [dirs::home_dir(), dirs::cache_dir(), dirs::config_dir()]
108 .into_iter()
109 .flatten()
110 .collect();
111 let mut out: Vec<PathBuf> = Vec::new();
112 for dir in dirs_out {
113 let unsafe_dir =
114 dir.parent().is_none() || dir.as_os_str().is_empty() || dir == Path::new(".");
115 if unsafe_dir || shared.contains(&dir) || !dir.is_dir() || out.contains(&dir) {
116 continue;
117 }
118 out.push(dir);
119 }
120 out
121}
122
123fn dir_size(dir: &Path) -> u64 {
124 let Ok(entries) = std::fs::read_dir(dir) else {
125 return 0;
126 };
127 entries
128 .flatten()
129 .map(|e| match e.metadata() {
130 Ok(m) if m.is_dir() => dir_size(&e.path()),
131 Ok(m) => m.len(),
132 Err(_) => 0,
133 })
134 .sum()
135}
136
137#[derive(Debug, PartialEq, Eq)]
138pub enum DataOutcome {
139 Nothing,
140 Kept,
141 DryRun(u64),
142 NeedsYes,
143 Cancelled,
144 Removed(u64),
145}
146
147pub fn remove_data(
149 dirs: &[PathBuf],
150 args: &UninstallArgs,
151 interactive: bool,
152 input: &mut dyn BufRead,
153) -> Result<DataOutcome> {
154 if args.keep_data {
155 return Ok(DataOutcome::Kept);
156 }
157 if dirs.is_empty() {
158 println!("No Paper data found.");
159 return Ok(DataOutcome::Nothing);
160 }
161 let total: u64 = dirs.iter().map(|d| dir_size(d)).sum();
162 println!("Paper data ({}):", format_bytes(total));
163 for dir in dirs {
164 println!(" {}", dir.display());
165 }
166 if args.dry_run {
167 println!("(dry run) would delete the above");
168 return Ok(DataOutcome::DryRun(total));
169 }
170 if !args.yes {
171 if !interactive {
172 println!("Not deleting: stdin is not a terminal. Re-run with --yes to delete it.");
173 return Ok(DataOutcome::NeedsYes);
174 }
175 print!("Delete these? [y/N] ");
176 std::io::Write::flush(&mut std::io::stdout()).ok();
177 let mut answer = String::new();
178 input.read_line(&mut answer)?;
179 if !matches!(answer.trim().to_lowercase().as_str(), "y" | "yes") {
180 println!("Data kept.");
181 return Ok(DataOutcome::Cancelled);
182 }
183 }
184 for dir in dirs {
185 std::fs::remove_dir_all(dir).with_context(|| format!("deleting {}", dir.display()))?;
186 }
187 println!("Deleted Paper data.");
188 Ok(DataOutcome::Removed(total))
189}
190
191fn remove_service(dry_run: bool) -> &'static str {
192 #[cfg(feature = "daemon")]
193 {
194 if dry_run {
195 println!("(dry run) would remove the background service");
196 return "service (dry run)";
197 }
198 match crate::cli::daemon::uninstall_service() {
199 Ok(path) => {
200 println!("Removed background service: {}", path.display());
201 "service removed"
202 }
203 Err(error) => {
204 println!("Background service not removed ({error:#}); continuing.");
205 "service not removed"
206 }
207 }
208 }
209 #[cfg(not(feature = "daemon"))]
210 {
211 let _ = dry_run;
212 "service skipped"
213 }
214}
215
216fn handle_binary(
218 method: &InstallMethod,
219 exe: &Path,
220 receipt: Option<&Path>,
221 dry_run: bool,
222) -> Result<Option<String>> {
223 match method {
224 InstallMethod::Homebrew => println!("finish with: brew uninstall paper"),
225 InstallMethod::Npm => println!("finish with: npm uninstall -g paperscope"),
226 InstallMethod::Cargo => println!("finish with: cargo uninstall paperscope"),
227 InstallMethod::Unknown => println!("delete the binary yourself: {}", exe.display()),
228 InstallMethod::ShellInstaller => {
229 if dry_run {
230 println!("(dry run) would delete {}", exe.display());
231 if let Some(r) = receipt.filter(|r| r.exists()) {
232 println!("(dry run) would delete {}", r.display());
233 }
234 } else {
235 if let Some(r) = receipt.filter(|r| r.exists()) {
236 std::fs::remove_file(r).with_context(|| format!("deleting {}", r.display()))?;
237 println!("Deleted install receipt: {}", r.display());
238 }
239 if cfg!(windows) {
240 println!("delete the binary after this exits: {}", exe.display());
241 } else {
242 std::fs::remove_file(exe)
243 .with_context(|| format!("deleting {}", exe.display()))?;
244 println!("Deleted binary: {}", exe.display());
245 }
246 }
247 println!(
248 "The installer may have added a PATH line to ~/.bashrc, ~/.zshrc, ~/.profile or \
249 your fish config; you can remove it. Paper does not edit those files."
250 );
251 if cfg!(windows) {
252 return Ok(Some(format!("the binary {}", exe.display())));
253 }
254 return Ok(Some("any PATH line in your shell startup file".into()));
255 }
256 }
257 Ok(Some(match method {
258 InstallMethod::Homebrew => "the Homebrew package".into(),
259 InstallMethod::Npm => "the npm package".into(),
260 InstallMethod::Cargo => "the cargo package".into(),
261 _ => format!("the binary {}", exe.display()),
262 }))
263}
264
265pub async fn run(args: UninstallArgs) -> Result<i32> {
266 let service = remove_service(args.dry_run);
267
268 let dirs = owned_dirs(&Paths::new());
269 let interactive = std::io::stdin().is_terminal();
270 let data = remove_data(&dirs, &args, interactive, &mut std::io::stdin().lock())?;
271
272 let exe = std::env::current_exe()
273 .and_then(|p| p.canonicalize())
274 .context("locating the paper binary")?;
275 let home = dirs::home_dir();
276 let cargo = cargo_home(home.as_deref());
277 let receipt = receipt_path(home.as_deref());
278 let method = detect_install_method(
279 &exe,
280 cargo.as_deref(),
281 home.as_deref(),
282 cargo.as_deref().is_some_and(cargo_lists_paper),
283 );
284 let left = handle_binary(&method, &exe, receipt.as_deref(), args.dry_run)?;
285
286 let data_note = match data {
287 DataOutcome::Removed(b) => format!("data deleted ({})", format_bytes(b)),
288 DataOutcome::DryRun(_) => "data would be deleted".into(),
289 DataOutcome::Kept => "data kept (--keep-data)".into(),
290 DataOutcome::Cancelled | DataOutcome::NeedsYes => "data kept".into(),
291 DataOutcome::Nothing => "no data found".into(),
292 };
293 let prefix = if args.dry_run {
294 "Dry run, nothing changed: "
295 } else {
296 "Done: "
297 };
298 println!(
299 "{prefix}{service}; {data_note}. Left for you: {}.",
300 left.unwrap_or_else(|| "nothing".into())
301 );
302 Ok(super::EXIT_FOUND)
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 fn detect(exe: &str, listed: bool, _receipt: bool) -> InstallMethod {
311 detect_install_method(
312 Path::new(exe),
313 Some(Path::new("/home/u/.cargo")),
314 Some(Path::new("/home/u")),
315 listed,
316 )
317 }
318
319 #[test]
320 fn detects_homebrew() {
321 assert_eq!(
322 detect("/opt/homebrew/bin/paper", false, false),
323 InstallMethod::Homebrew
324 );
325 assert_eq!(
326 detect("/usr/local/Cellar/paper/0.3.1/bin/paper", false, false),
327 InstallMethod::Homebrew
328 );
329 }
330
331 #[test]
332 fn detects_npm() {
333 let exe = "/usr/lib/node_modules/paperscope/bin/paper";
334 assert_eq!(detect(exe, false, true), InstallMethod::Npm);
335 }
336
337 #[test]
338 fn detects_cargo_only_when_listed() {
339 let exe = "/home/u/.cargo/bin/paper";
340 assert_eq!(detect(exe, true, false), InstallMethod::Cargo);
341 assert_eq!(detect(exe, false, false), InstallMethod::ShellInstaller);
342 }
343
344 #[test]
345 fn detects_shell_installer_by_folder_never_by_receipt_alone() {
346 assert_eq!(detect("/srv/paper", false, true), InstallMethod::Unknown);
347 assert_eq!(
348 detect("/home/u/.local/bin/paper", false, false),
349 InstallMethod::ShellInstaller
350 );
351 }
352
353 #[test]
354 fn unknown_otherwise() {
355 assert_eq!(detect("/srv/paper", false, false), InstallMethod::Unknown);
356 }
357
358 fn args(yes: bool, keep_data: bool, dry_run: bool) -> UninstallArgs {
359 UninstallArgs {
360 yes,
361 keep_data,
362 dry_run,
363 }
364 }
365
366 #[test]
367 fn data_step_modes() {
368 let tmp = tempfile::tempdir().unwrap();
369 let dir = tmp.path().join("paper");
370 std::fs::create_dir_all(dir.join("models")).unwrap();
371 std::fs::write(dir.join("chunks.db"), b"abc").unwrap();
372 let dirs = vec![dir.clone()];
373
374 let r = |a: UninstallArgs, tty: bool, input: &str| {
375 remove_data(&dirs, &a, tty, &mut input.as_bytes()).unwrap()
376 };
377 assert_eq!(r(args(true, false, true), true, ""), DataOutcome::DryRun(3));
378 assert_eq!(r(args(true, true, false), true, ""), DataOutcome::Kept);
379 assert_eq!(
380 r(args(false, false, false), false, "y\n"),
381 DataOutcome::NeedsYes
382 );
383 assert_eq!(
384 r(args(false, false, false), true, "n\n"),
385 DataOutcome::Cancelled
386 );
387 assert_eq!(
388 r(args(false, false, false), true, "\n"),
389 DataOutcome::Cancelled
390 );
391 assert!(dir.join("chunks.db").exists());
392 assert_eq!(
393 r(args(false, false, false), true, "Yes\n"),
394 DataOutcome::Removed(3)
395 );
396 assert!(!dir.exists());
397 }
398
399 #[test]
400 fn owned_dirs_skips_missing_and_shared() {
401 let tmp = tempfile::tempdir().unwrap();
402 assert_eq!(
403 owned_dirs(&Paths::with_base(tmp.path())),
404 vec![tmp.path().to_path_buf()]
405 );
406 assert!(owned_dirs(&Paths::with_base(tmp.path().join("nope"))).is_empty());
407 if let Some(home) = dirs::home_dir() {
408 assert!(owned_dirs(&Paths::with_base(home)).is_empty());
409 }
410 }
411}