返回 CodeWhale
uninstall.rs
根目录 / crates / cli / src / update / uninstall.rs
1 use super::*;
2 use codewhale_runtime::delivery_files::GuardedFile;
3 use std::collections::BTreeMap;
4
5 const RECEIPT: &str = codewhale_release::installs::RECEIPT_FILE;
6 const MAX_RECEIPT: usize = 512;
7 pub(super) const COMMANDS: &[&str] = codewhale_release::installs::RECEIPT_COMMANDS;
8
9 pub(super) struct CommandReceipt {
10 directory: PathBuf,
11 receipt: GuardedFile,
12 hashes: BTreeMap<String, String>,
13 }
14
15 impl CommandReceipt {
16 pub(super) fn capture(executable: &Path) -> Result<Option<Self>> {
17 Self::capture_accepting(executable, None)
18 }
19
20 pub(super) fn capture_accepting(
21 executable: &Path,
22 updated: Option<&str>,
23 ) -> Result<Option<Self>> {
24 let directory = executable.parent().context("executable has no parent")?;
25 #[cfg(not(windows))]
26 let directory = directory.canonicalize()?;
27 #[cfg(windows)]
28 let directory = directory.to_path_buf();
29 let Some(mut receipt) = GuardedFile::open_bounded(&directory, RECEIPT, MAX_RECEIPT)? else {
30 return Ok(None);
31 };
32 receipt.verify_owned()?;
33 let bytes = receipt.read_bounded(MAX_RECEIPT)?;
34 let text = std::str::from_utf8(&bytes).context("command receipt is not UTF-8")?;
35 let hashes = installs::parse_command_receipt(text).with_context(|| {
36 format!(
37 "Invalid command ownership receipt {}; no files were changed",
38 directory.join(RECEIPT).display()
39 )
40 })?;
41 let names: Vec<&str> = hashes.keys().map(String::as_str).collect();
42 let mut files = GuardedFile::open_command_siblings(&directory, &names)?;
43 for (name, digest) in &hashes {
44 if let Some(mut file) = files.remove(name) {
45 file.verify_owned()?;
46 if file.sha256() != digest.as_str() && Some(file.sha256()) != updated {
47 bail!(
48 "Preserved modified command {}; receipt no longer matches",
49 directory.join(name).display()
50 );
51 }
52 }
53 }
54 Ok(Some(Self {
55 directory,
56 receipt,
57 hashes: hashes.into_iter().collect(),
58 }))
59 }
60
61 pub(super) fn renew(&mut self, verified: &[u8]) -> Result<()> {
62 self.renew_in(verified, codewhale_config::codewhale_home())
63 }
64
65 pub(super) fn renew_in(&mut self, verified: &[u8], home: Result<PathBuf>) -> Result<()> {
66 self.receipt.verify_owned()?;
67 let new_hash = sha256_hex(verified);
68 let mut text = String::new();
69 let names: Vec<&str> = self.hashes.keys().map(String::as_str).collect();
70 let mut files = GuardedFile::open_command_siblings(&self.directory, &names)?;
71 for (name, old_hash) in &self.hashes {
72 if let Some(mut file) = files.remove(name) {
73 if file.sha256() != old_hash.as_str() && file.sha256() != new_hash.as_str() {
74 bail!(
75 "Cannot renew ownership of modified command {}",
76 self.directory.join(name).display()
77 );
78 }
79 file.verify_owned()?;
80 text.push_str(&format!("{} {name}\n", file.sha256()));
81 }
82 }
83 if text.is_empty() {
84 bail!("No receipt-owned commands remain; ownership receipt was preserved");
85 }
86 if self.receipt.read_bounded(MAX_RECEIPT)? == text.as_bytes() {
87 return Ok(());
88 }
89 self.receipt.verify_owned()?;
90 let mut staged = GuardedFile::stage(&self.directory, text.as_bytes(), false)?;
91 staged.verify_owned()?;
92 let backup = GuardedFile::recovery_name();
93 self.receipt.move_to_vacant(&backup).with_context(|| {
94 format!(
95 "receipt retirement failed; recovery at {}",
96 self.directory.join(self.receipt.name()).display()
97 )
98 })?;
99 if let Err(error) = staged.move_to_vacant(RECEIPT) {
100 let restored = self.receipt.move_to_vacant(RECEIPT);
101 bail!(
102 "receipt publication failed: {error}; restoration: {restored:?}; previous receipt {}, staged receipt {}",
103 self.directory.join(self.receipt.name()).display(),
104 self.directory.join(staged.name()).display()
105 );
106 }
107 let retired = self.directory.join(&backup);
108 match home
109 .and_then(|home| installs::RecoveryBatch::open(&home))
110 .and_then(|mut batch| {
111 let moved = batch.move_in(&retired)?;
112 batch.finish();
113 Ok(moved)
114 }) {
115 Ok(moved) => println!(
116 "Renewed command ownership receipt; previous receipt kept at {}",
117 moved.to.display()
118 ),
119 Err(_) => println!(
120 "Renewed command ownership receipt; previous receipt retained at {}",
121 retired.display()
122 ),
123 }
124 self.receipt = staged;
125 Ok(())
126 }
127 }
128
129 pub(crate) fn run(yes: bool, purge_data: bool) -> Result<()> {
130 let selected = std::env::current_exe().ok();
131 if purge_data {
132 purge_targets(selected.as_deref())?;
133 }
134 let mut package_managed = false;
135 let result = remove(yes, &mut package_managed);
136 report_path_copies(selected.as_deref());
137 let removed = result?;
138 let outcome = if purge_data {
139 if !yes {
140 purge(false, selected.as_deref())
141 } else if removed {
142 purge(true, selected.as_deref())
143 } else {
144 println!(
145 "Data was not purged: this run did not remove a receipted installation. Data is shared by every install and is kept."
146 );
147 Ok(())
148 }
149 } else {
150 println!(
151 "User data was not touched. To also delete Codewhale's own data directory, add --purge-data."
152 );
153 Ok(())
154 };
155 outcome?;
156 if package_managed {
157 return Err(super::PackageManaged("Not removed: use the command above.").into());
158 }
159 Ok(())
160 }
161
162 fn remove(yes: bool, package_managed: &mut bool) -> Result<bool> {
163 let identity = update_executable_identity()?;
164 #[cfg(not(windows))]
165 let identity = UpdateExecutableIdentity {
166 path: identity
167 .path
168 .canonicalize()
169 .context("failed to resolve the selected executable path")?,
170 ..identity
171 };
172 let method = InstallMethod::detect(&identity.path);
173 println!("Selected executable: {}", identity.path.display());
174 println!(
175 "Program removal preserves user state, credentials, sessions, workspaces and services. For a receipted release copy it also removes this install's exact Codewhale PATH block from your shell profiles and Codewhale-generated completion files at the documented paths; nothing else in a profile is touched."
176 );
177 if !method.supports_self_update() || method == InstallMethod::WindowsInstaller {
178 println!(
179 "This copy belongs to {}. Remove it with: {}",
180 method.label(),
181 codewhale_release::installs::manager_command(method, &identity.path)
182 );
183 *package_managed = true;
184 return Ok(false);
185 }
186 let primary_name = identity
187 .path
188 .file_name()
189 .and_then(|name| name.to_str())
190 .context("executable basename is not UTF-8")?
191 .to_string();
192 if !COMMANDS.contains(&primary_name.as_str()) {
193 bail!(
194 "This command name has no installer ownership contract; preserved {}",
195 identity.path.display()
196 );
197 }
198 let ownership = match CommandReceipt::capture(&identity.path)? {
199 Some(ownership) => ownership,
200 None => {
201 let (directory, entries) = curl_install_entries(&identity)?.with_context(|| format!(
202 "No command ownership receipt beside {}. This legacy/manual copy is preserved. Inspect its exact path and provenance before removing it manually; reinstalling into a fresh directory creates a receipted install.", identity.path.display()))?;
203 println!(
204 "No ownership receipt yet: {} is a curl-installer location and these commands are byte-identical to this Codewhale {}.",
205 directory.display(),
206 env!("CARGO_PKG_VERSION")
207 );
208 if !yes {
209 for (name, _) in &entries {
210 println!("Would record and remove {}", directory.join(name).display());
211 }
212 println!(
213 "No files were changed. Run this executable again with uninstall --yes to record a receipt for exactly these files and remove them."
214 );
215 return Ok(false);
216 }
217 let text: String = entries
218 .iter()
219 .map(|(name, digest)| format!("{digest} {name}\n"))
220 .collect();
221 let mut staged = GuardedFile::stage(&directory, text.as_bytes(), false)?;
222 staged.verify_owned()?;
223 staged.move_to_vacant(RECEIPT).with_context(|| {
224 format!(
225 "could not record a receipt in {}; staged bytes retained at {}",
226 directory.display(),
227 directory.join(staged.name()).display()
228 )
229 })?;
230 println!("Recorded an install receipt in {}.", directory.display());
231 CommandReceipt::capture(&identity.path)?
232 .context("the adopted ownership receipt disappeared; nothing was removed")?
233 }
234 };
235 if ownership.hashes.get(&primary_name) != Some(&identity.file_hash) {
236 bail!("The receipt does not own the selected executable; nothing was removed");
237 }
238 remove_receipted_ownership(&identity, ownership, &primary_name, yes)
239 }
240
241 struct RemovalEntry {
242 file: GuardedFile,
243 is_command: bool,
244 inode_group: Option<usize>,
245 }
246
247 struct InodeGroupState {
248 remaining: usize,
249 prior_unlinked: bool,
250 }
251
252 fn assign_command_inode_groups(entries: &mut [RemovalEntry]) -> Result<Vec<InodeGroupState>> {
253 let mut groups: Vec<InodeGroupState> = Vec::new();
254 let mut exemplars: Vec<usize> = Vec::new();
255 for index in 0..entries.len() {
256 if !entries[index].is_command {
257 continue;
258 }
259 let mut matched = None;
260 for (group_id, &exemplar_idx) in exemplars.iter().enumerate() {
261 if entries[index]
262 .file
263 .same_inode(&entries[exemplar_idx].file)?
264 {
265 matched = Some(group_id);
266 break;
267 }
268 }
269 if let Some(group_id) = matched {
270 entries[index].inode_group = Some(group_id);
271 groups[group_id].remaining += 1;
272 } else {
273 let group_id = groups.len();
274 exemplars.push(index);
275 groups.push(InodeGroupState {
276 remaining: 1,
277 prior_unlinked: false,
278 });
279 entries[index].inode_group = Some(group_id);
280 }
281 }
282 Ok(groups)
283 }
284
285 fn remove_receipted_ownership(
286 identity: &UpdateExecutableIdentity,
287 ownership: CommandReceipt,
288 primary_name: &str,
289 yes: bool,
290 ) -> Result<bool> {
291 remove_receipted_ownership_with_options(identity, ownership, primary_name, yes, true)
292 }
293
294 fn remove_receipted_ownership_with_options(
295 identity: &UpdateExecutableIdentity,
296 ownership: CommandReceipt,
297 primary_name: &str,
298 yes: bool,
299 clean_shell: bool,
300 ) -> Result<bool> {
301 let directory = ownership.directory.clone();
302 let names: Vec<&str> = ownership.hashes.keys().map(String::as_str).collect();
303 let mut sibling_files = GuardedFile::open_command_siblings(&directory, &names)?;
304 let mut entries = Vec::new();
305 let mut primary = None;
306 for name in ownership.hashes.keys() {
307 if let Some(file) = sibling_files.remove(name) {
308 if ownership.hashes.get(name).map(String::as_str) != Some(file.sha256()) {
309 bail!(
310 "Command changed during uninstall preflight; preserved {}",
311 directory.join(name).display()
312 );
313 }
314 if name == primary_name {
315 primary = Some(file);
316 } else {
317 entries.push(RemovalEntry {
318 file,
319 is_command: true,
320 inode_group: None,
321 });
322 }
323 }
324 }
325 let target =
326 release_asset_stem_for_prefix("codewhale", std::env::consts::OS, std::env::consts::ARCH);
327 let companions =
328 compiled_host::owned_for_uninstall(&directory, target.trim_start_matches("codewhale-"))?;
329 if companions.is_empty() {
330 println!("Any unreceipted compiled-host files are preserved.");
331 }
332 for companion in companions {
333 entries.push(RemovalEntry {
334 file: companion,
335 is_command: false,
336 inode_group: None,
337 });
338 }
339 let mut receipt = ownership.receipt;
340 let receipt_bytes = receipt.read_bounded(MAX_RECEIPT)?;
341 entries.push(RemovalEntry {
342 file: receipt,
343 is_command: false,
344 inode_group: None,
345 });
346 entries.push(RemovalEntry {
347 file: primary.context("selected executable disappeared during preflight")?,
348 is_command: true,
349 inode_group: None,
350 });
351 let mut groups = assign_command_inode_groups(&mut entries)?;
352 for entry in &mut entries {
353 entry.file.verify_owned()?;
354 println!(
355 "{} {}",
356 if yes { "Remove" } else { "Would remove" },
357 directory.join(entry.file.name()).display()
358 );
359 }
360 let shell = if clean_shell {
361 ShellIntegration::plan(&directory, &identity.path, yes)
362 } else {
363 ShellIntegration::default()
364 };
365 validate_primary_update_identity(identity)?;
366 if !yes {
367 println!(
368 "No files were changed. Run this executable again with uninstall --yes to remove only this plan."
369 );
370 return Ok(false);
371 }
372 #[cfg(unix)]
373 {
374 let preflight = tempfile::Builder::new()
375 .prefix(".codewhale-uninstall-preflight-")
376 .tempdir_in(&directory)?
377 .keep();
378 std::fs::remove_dir(&preflight).with_context(|| {
379 format!(
380 "uninstall directory preflight failed at {}",
381 preflight.display()
382 )
383 })?;
384 }
385 let mut removed = Vec::new();
386 for entry in &mut entries {
387 let name = entry.file.name().to_string();
388 let mut unlinked = false;
389 let outcome = validate_primary_update_identity(identity).and_then(|()| {
390 if let Some(gid) = entry.inode_group {
391 let group = &mut groups[gid];
392 let expected_remaining = group
393 .remaining
394 .checked_sub(1)
395 .context("command inode group link count underflow")?;
396 let result = entry
397 .file
398 .remove_sibling_checked(
399 expected_remaining as u64,
400 group.prior_unlinked,
401 &mut unlinked,
402 )
403 .map_err(Into::into);
404 if unlinked {
405 group.remaining -= 1;
406 group.prior_unlinked = true;
407 }
408 result
409 } else {
410 entry.file.remove_checked(&mut unlinked).map_err(Into::into)
411 }
412 });
413 #[cfg(windows)]
414 let outcome = match outcome {
415 Err(error) if unlinked && name == primary_name => {
416 let retired = directory.join(entry.file.name());
417 delete_after_exit(&retired)
418 .map(|()| {
419 println!(
420 "The running executable was retired to {}; it is deleted after this process exits. Delete it by hand if it remains.",
421 retired.display()
422 )
423 })
424 .map_err(|schedule| {
425 error.context(format!(
426 "deferred removal of {} could not be scheduled: {schedule:#}",
427 retired.display()
428 ))
429 })
430 }
431 other => other,
432 };
433 if unlinked {
434 removed.push(name.clone());
435 }
436 if let Err(error) = outcome {
437 if removed.iter().any(|name| name == RECEIPT)
438 && !removed.iter().any(|name| name == primary_name)
439 {
440 let restore = (|| {
441 let mut staged = GuardedFile::stage(&directory, &receipt_bytes, false)?;
442 staged.verify_owned()?;
443 staged.move_to_vacant(RECEIPT).with_context(|| {
444 format!(
445 "receipt recovery bytes retained at {}",
446 directory.join(staged.name()).display()
447 )
448 })
449 })();
450 if let Err(restore) = restore {
451 eprintln!("Receipt recovery needs attention: {restore:#}");
452 }
453 }
454 bail!(
455 "Uninstall stopped at {name}: {error:#}. Already unlinked: {}. Any retained recovery locations are reported above; no unknown destination is overwritten.",
456 removed.join(", ")
457 );
458 }
459 }
460 #[cfg(windows)]
461 for entry in std::fs::read_dir(&directory)?.flatten() {
462 let name = entry.file_name().to_string_lossy().into_owned();
463 if name.starts_with("codewhale.old-") || name.starts_with("codew.old-") {
464 println!(
465 "Preserved a copy left by an earlier self-update; delete it by hand: {}",
466 entry.path().display()
467 );
468 }
469 }
470 let shell_failures = shell.apply();
471 println!(
472 "Removed this receipted release installation. Other installations were not removed. {}",
473 if cfg!(windows) {
474 "Remove its directory from your user PATH if you added it, then open a new terminal."
475 } else {
476 "Run hash -r in your shell."
477 }
478 );
479 if !shell_failures.is_empty() {
480 bail!(
481 "The program files were removed, but shell integration cleanup is incomplete: {}",
482 shell_failures.join("; ")
483 );
484 }
485 Ok(true)
486 }
487
488 const PATH_BLOCK_START: &str = "# >>> codewhale PATH >>>";
489 const PATH_BLOCK_END: &str = "# <<< codewhale PATH <<<";
490 const MAX_PROFILE: usize = 1024 * 1024;
491 const MAX_COMPLETION: usize = 1024 * 1024;
492
493 struct ProfileEdit {
494 profile: PathBuf,
495 file: GuardedFile,
496 updated: Vec<u8>,
497 #[cfg(unix)]
498 mode: u32,
499 }
500
501 #[derive(Default)]
502 struct ShellIntegration {
503 edits: Vec<ProfileEdit>,
504 completions: Vec<(PathBuf, GuardedFile)>,
505 }
506
507 impl ShellIntegration {
508 fn plan(directory: &Path, selected: &Path, yes: bool) -> Self {
509 let Some(home) = dirs::home_dir() else {
510 return Self::default();
511 };
512 let verb = if yes { "Remove" } else { "Would remove" };
513 Self {
514 edits: plan_path_blocks(&home, directory, verb),
515 completions: plan_completions(&home, directory, selected, verb),
516 }
517 }
518
519 fn apply(self) -> Vec<String> {
520 let mut failures = Vec::new();
521 for edit in self.edits {
522 let profile = edit.profile.clone();
523 match apply_profile_edit(edit) {
524 Ok(()) => println!(
525 "Removed the Codewhale PATH block from {}",
526 profile.display()
527 ),
528 Err(error) => failures.push(format!(
529 "{} was not changed ({error:#}); delete its Codewhale PATH block by hand",
530 profile.display()
531 )),
532 }
533 }
534 for (path, mut file) in self.completions {
535 let mut unlinked = false;
536 match file.remove_checked(&mut unlinked) {
537 Ok(()) => println!("Removed completion file {}", path.display()),
538 Err(error) => failures.push(format!(
539 "{} was not removed ({error}); delete it by hand",
540 path.display()
541 )),
542 }
543 }
544 failures
545 }
546 }
547
548 fn plan_path_blocks(home: &Path, directory: &Path, verb: &str) -> Vec<ProfileEdit> {
549 let zdotdir = std::env::var_os("ZDOTDIR").map(PathBuf::from);
550 let mut profiles: Vec<PathBuf> = [
551 ".zshrc",
552 ".bashrc",
553 ".bash_profile",
554 ".bash_login",
555 ".profile",
556 ]
557 .iter()
558 .map(|name| home.join(name))
559 .chain(zdotdir.map(|dir| dir.join(".zshrc")))
560 .chain(std::iter::once(
561 home.join(".config")
562 .join("fish")
563 .join("conf.d")
564 .join("codewhale.fish"),
565 ))
566 .collect();
567 profiles.sort();
568 profiles.dedup();
569 let install_directory = directory.canonicalize().ok();
570 let names_directory = |value: &str| {
571 let expanded = match value.strip_prefix("$HOME/") {
572 Some(rest) => home.join(rest),
573 None => PathBuf::from(value),
574 };
575 expanded
576 .canonicalize()
577 .is_ok_and(|path| install_directory.as_ref() == Some(&path))
578 };
579 let ours = |line: &str| {
580 line.strip_prefix("export PATH=\"")
581 .and_then(|rest| rest.strip_suffix(":$PATH\""))
582 .is_some_and(names_directory)
583 || line
584 .strip_prefix("contains -- \"")
585 .and_then(|rest| rest.split_once("\" $PATH; or set -gx PATH \""))
586 .is_some_and(|(value, rest)| {
587 rest == format!("{value}\" $PATH") && names_directory(value)
588 })
589 };
590 let mut edits = Vec::new();
591 for profile in profiles {
592 let (Some(parent), Some(name)) = (
593 profile.parent(),
594 profile.file_name().and_then(|name| name.to_str()),
595 ) else {
596 continue;
597 };
598 let mut file = match GuardedFile::open_bounded(parent, name, MAX_PROFILE) {
599 Ok(Some(file)) => file,
600 Ok(None) => continue,
601 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
602 Err(error) => {
603 println!(
604 "Not read: {} ({error}). If it holds a Codewhale PATH block, remove that block by hand.",
605 profile.display()
606 );
607 continue;
608 }
609 };
610 let bytes = match file.read_bounded(MAX_PROFILE) {
611 Ok(bytes) => bytes,
612 Err(error) => {
613 println!(
614 "Not read: {} ({error}). If it holds a Codewhale PATH block, remove that block by hand.",
615 profile.display()
616 );
617 continue;
618 }
619 };
620 let Ok(text) = String::from_utf8(bytes) else {
621 println!(
622 "Not read: {} is not a UTF-8 file within the size limit.",
623 profile.display()
624 );
625 continue;
626 };
627 let segments: Vec<&str> = text.split_inclusive('\n').collect();
628 let lines: Vec<&str> = segments.iter().map(|line| line.trim_end()).collect();
629 let mut removed = vec![false; lines.len()];
630 let mut index = 0;
631 while index < lines.len() {
632 if lines[index] == PATH_BLOCK_START {
633 if lines.get(index + 2) == Some(&PATH_BLOCK_END) && ours(lines[index + 1]) {
634 println!(
635 "{verb} the Codewhale PATH block for this install: {} lines {}-{}",
636 profile.display(),
637 index + 1,
638 index + 3
639 );
640 removed[index..index + 3].fill(true);
641 index += 3;
642 continue;
643 }
644 println!(
645 "Codewhale PATH marker at {} line {} does not form a block for this install; left unchanged.",
646 profile.display(),
647 index + 1
648 );
649 } else if lines[index] == PATH_BLOCK_END {
650 println!(
651 "Codewhale PATH end marker at {} line {} has no start marker; left unchanged.",
652 profile.display(),
653 index + 1
654 );
655 }
656 index += 1;
657 }
658 if !removed.contains(&true) {
659 continue;
660 }
661 #[cfg(unix)]
662 let mode = {
663 use std::os::unix::fs::PermissionsExt;
664 match std::fs::metadata(&profile) {
665 Ok(metadata) => metadata.permissions().mode() & 0o7777,
666 Err(error) => {
667 println!(
668 "Not changed: {} ({error}); delete its Codewhale PATH block by hand.",
669 profile.display()
670 );
671 continue;
672 }
673 }
674 };
675 let updated = segments
676 .iter()
677 .zip(&removed)
678 .filter(|(_, removed)| !**removed)
679 .flat_map(|(segment, _)| segment.bytes())
680 .collect();
681 edits.push(ProfileEdit {
682 profile,
683 file,
684 updated,
685 #[cfg(unix)]
686 mode,
687 });
688 }
689 edits
690 }
691
692 fn apply_profile_edit(edit: ProfileEdit) -> Result<()> {
693 let ProfileEdit {
694 profile,
695 mut file,
696 updated,
697 #[cfg(unix)]
698 mode,
699 } = edit;
700 let parent = profile
701 .parent()
702 .context("profile has no parent directory")?;
703 let name = profile
704 .file_name()
705 .and_then(|name| name.to_str())
706 .context("profile name is not UTF-8")?
707 .to_string();
708 #[cfg(unix)]
709 let mut staged = stage_profile(parent, &updated, mode)?;
710 #[cfg(not(unix))]
711 let mut staged = stage_profile(parent, &updated)?;
712 // Rename the profile aside instead of unlinking it: a failure while the
713 // replacement is installed can then put the user's own bytes back by name.
714 let retired = GuardedFile::recovery_name();
715 file.move_to_vacant(&retired).with_context(|| {
716 format!(
717 "{} could not be set aside for its replacement",
718 profile.display()
719 )
720 })?;
721 if let Err(error) = staged.move_to_vacant(&name) {
722 let restore = file.move_to_vacant(&name).map_err(|restore| {
723 format!(
724 "the unchanged profile is retained at {} and could not be restored ({restore})",
725 parent.join(&retired).display()
726 )
727 });
728 let mut discarded = false;
729 let _ = staged.remove_checked(&mut discarded);
730 return match restore {
731 Ok(()) => Err(error).with_context(|| {
732 format!(
733 "{} was left unchanged because its replacement could not be installed",
734 profile.display()
735 )
736 }),
737 Err(restore) => Err(anyhow!("{error}; {restore}")),
738 };
739 }
740 let mut unlinked = false;
741 if file.remove_checked(&mut unlinked).is_err() || !unlinked {
742 println!(
743 "Retired copy of {} is retained at {}; delete it by hand",
744 profile.display(),
745 parent.join(&retired).display()
746 );
747 }
748 Ok(())
749 }
750
751 /// Stage the replacement bytes, then adopt the profile's mode before the guard
752 /// captures them. `GuardedFile` pins ctime, so a chmod after `stage` invalidates
753 /// the very file the caller is about to move into place.
754 fn stage_profile(parent: &Path, updated: &[u8], #[cfg(unix)] mode: u32) -> Result<GuardedFile> {
755 let staged = GuardedFile::stage(parent, updated, false)?;
756 #[cfg(unix)]
757 {
758 use std::os::unix::fs::PermissionsExt;
759 let path = parent.join(staged.name());
760 let name = staged.name().to_string();
761 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))?;
762 drop(staged);
763 GuardedFile::open_bounded(parent, &name, MAX_PROFILE)?
764 .context("the staged profile replacement disappeared before it could be verified")
765 }
766 #[cfg(not(unix))]
767 Ok(staged)
768 }
769
770 fn plan_completions(
771 home: &Path,
772 directory: &Path,
773 selected: &Path,
774 verb: &str,
775 ) -> Vec<(PathBuf, GuardedFile)> {
776 let absolute = |name: &str| {
777 std::env::var_os(name)
778 .map(PathBuf::from)
779 .filter(|path| path.is_absolute())
780 };
781 let data = absolute("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local").join("share"));
782 let config = absolute("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"));
783 let candidates = [
784 (
785 clap_complete::Shell::Bash,
786 data.join("bash-completion").join("completions"),
787 "codewhale",
788 ),
789 (clap_complete::Shell::Zsh, home.join(".zfunc"), "_codewhale"),
790 (
791 clap_complete::Shell::Fish,
792 config.join("fish").join("completions"),
793 "codewhale.fish",
794 ),
795 ];
796 let present: Vec<_> = candidates
797 .into_iter()
798 .filter(|(_, directory, name)| directory.join(name).symlink_metadata().is_ok())
799 .collect();
800 if present.is_empty() {
801 return Vec::new();
802 }
803 // The receipt's other commands (`codew`) and the selected executable are
804 // this installation, not a second one. Only a copy outside the directory
805 // being removed keeps the completions.
806 let install_directory = std::fs::canonicalize(directory).ok();
807 let others_remain = codewhale_release::installs::inventory(Some(selected))
808 .entries
809 .iter()
810 .any(|entry| {
811 std::fs::canonicalize(&entry.path).ok().as_deref() != Some(selected)
812 && entry
813 .path
814 .parent()
815 .and_then(|parent| std::fs::canonicalize(parent).ok())
816 .is_none_or(|parent| Some(&parent) != install_directory.as_ref())
817 });
818 let mut files = Vec::new();
819 for (shell, directory, name) in present {
820 let path = directory.join(name);
821 if others_remain {
822 println!(
823 "Kept completion file {}: another Codewhale copy remains on PATH.",
824 path.display()
825 );
826 continue;
827 }
828 let mut file = match GuardedFile::open_bounded(&directory, name, MAX_COMPLETION) {
829 Ok(Some(file)) => file,
830 Ok(None) => continue,
831 Err(error) => {
832 println!(
833 "Not read: {} ({error}). If you generated it with codewhale completion, delete it by hand.",
834 path.display()
835 );
836 continue;
837 }
838 };
839 let generated = file
840 .read_bounded(MAX_COMPLETION)
841 .ok()
842 .and_then(|bytes| String::from_utf8(bytes).ok())
843 .is_some_and(|text| is_generated_completion(shell, &text));
844 if generated {
845 println!("{verb} completion file {}", path.display());
846 files.push((path, file));
847 } else {
848 println!(
849 "Left {} unchanged: it is not a Codewhale-generated completion script.",
850 path.display()
851 );
852 }
853 }
854 files
855 }
856
857 fn is_generated_completion(shell: clap_complete::Shell, text: &str) -> bool {
858 let bin = crate::COMPLETION_BIN_NAME;
859 match shell {
860 clap_complete::Shell::Bash => {
861 text.contains(&format!("_{bin}()")) && text.contains(&format!("complete -F _{bin}"))
862 }
863 clap_complete::Shell::Zsh => {
864 text.starts_with(&format!("#compdef {bin}")) && text.contains(&format!("_{bin}()"))
865 }
866 clap_complete::Shell::Fish => text.contains(&format!("complete -c {bin}")),
867 _ => false,
868 }
869 }
870
871 type CurlInstallEntries = (PathBuf, Vec<(String, String)>);
872
873 fn curl_install_entries(identity: &UpdateExecutableIdentity) -> Result<Option<CurlInstallEntries>> {
874 let Some(directory) = identity
875 .path
876 .parent()
877 .and_then(|parent| parent.canonicalize().ok())
878 else {
879 return Ok(None);
880 };
881 let Some(home) = dirs::home_dir().and_then(|home| home.canonicalize().ok()) else {
882 return Ok(None);
883 };
884 let local = home.join(".local");
885 let known = directory == local.join("bin")
886 || directory == local.join("codewhale").join("bin")
887 || (cfg!(windows) && directory == home.join("bin"))
888 || (directory.parent() == Some(local.as_path())
889 && directory
890 .file_name()
891 .and_then(|name| name.to_str())
892 .is_some_and(|name| name.starts_with("codewhale-release.")));
893 if !known {
894 return Ok(None);
895 }
896 let mut entries = Vec::new();
897 for name in COMMANDS.iter().copied() {
898 let Some(mut file) = GuardedFile::open(&directory, name)? else {
899 continue;
900 };
901 file.verify_owned()?;
902 if file.sha256() == identity.file_hash.as_str() {
903 entries.push((name.to_string(), identity.file_hash.clone()));
904 }
905 }
906 let selected_listed = identity.path.file_name().is_some_and(|file_name| {
907 entries
908 .iter()
909 .any(|(name, _)| file_name == std::ffi::OsStr::new(name))
910 });
911 Ok(selected_listed.then_some((directory, entries)))
912 }
913
914 #[cfg(windows)]
915 fn delete_after_exit(path: &Path) -> Result<()> {
916 use std::os::windows::process::CommandExt;
917 use windows::Win32::System::Threading::CREATE_NO_WINDOW;
918
919 let system = std::env::var_os("SystemRoot").context("SystemRoot is not set")?;
920 let powershell = Path::new(&system).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
921 std::process::Command::new(powershell)
922 .args(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"])
923 .arg(format!(
924 "Wait-Process -Id {} -ErrorAction SilentlyContinue; Remove-Item -LiteralPath $env:CODEWHALE_UNINSTALL_RETIRED_PATH -Force",
925 std::process::id()
926 ))
927 .env("CODEWHALE_UNINSTALL_RETIRED_PATH", path)
928 .stdin(std::process::Stdio::null())
929 .stdout(std::process::Stdio::null())
930 .stderr(std::process::Stdio::null())
931 .creation_flags(CREATE_NO_WINDOW.0)
932 .spawn()
933 .context("failed to start the deferred deletion helper")?;
934 Ok(())
935 }
936
937 fn purge_targets(selected: Option<&Path>) -> Result<Vec<PathBuf>> {
938 let home = codewhale_config::codewhale_home()?;
939 let explicit = codewhale_config::codewhale_home_is_explicit();
940 let mut targets = vec![home.clone()];
941 if !explicit {
942 targets.push(codewhale_config::legacy_deepseek_home()?.join("snapshots"));
943 }
944 let user_home = dirs::home_dir()
945 .context("failed to resolve home directory")?
946 .canonicalize()
947 .context("failed to resolve the real home directory")?;
948 let install_directory = selected
949 .and_then(Path::parent)
950 .map(std::fs::canonicalize)
951 .transpose()
952 .context("failed to resolve the install directory before data purge")?;
953 let mut present = Vec::new();
954 for target in targets {
955 let target: PathBuf = target.components().collect();
956 let metadata = match std::fs::symlink_metadata(&target) {
957 Ok(metadata) => metadata,
958 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
959 continue;
960 }
961 Err(error) => {
962 return Err(error)
963 .with_context(|| format!("failed to inspect {}", target.display()));
964 }
965 };
966 if !metadata.is_dir() {
967 bail!(
968 "Preserved {}: it is not a real directory; no data was deleted",
969 target.display()
970 );
971 }
972 if explicit && target == home && target.file_name().is_none_or(|name| name != ".codewhale")
973 {
974 bail!(
975 "Preserved explicit CODEWHALE_HOME {}: review it and delete it by hand; no data was deleted",
976 target.display()
977 );
978 }
979 #[cfg(unix)]
980 {
981 use std::os::unix::fs::MetadataExt;
982 if metadata.uid()
983 != codewhale_config::private_directory::PrivateDirectory::current_user_id()
984 {
985 bail!(
986 "Preserved {}: it belongs to another user; no data was deleted",
987 target.display()
988 );
989 }
990 }
991 let target = target
992 .canonicalize()
993 .with_context(|| format!("failed to resolve data directory {}", target.display()))?;
994 if user_home.starts_with(&target)
995 || target.parent().is_none()
996 || install_directory
997 .as_ref()
998 .is_some_and(|install| install.starts_with(&target))
999 {
1000 bail!(
1001 "Preserved {}: it contains the home or install directory; no data was deleted",
1002 target.display()
1003 );
1004 }
1005 present.push(target);
1006 }
1007 Ok(present)
1008 }
1009
1010 fn purge(yes: bool, selected: Option<&Path>) -> Result<()> {
1011 let present = purge_targets(selected)?;
1012 println!(
1013 "Data purge scope: Codewhale's config, plaintext secrets file, sessions, logs, skills, plugins, tasks, caches, recovery records and snapshots in the directories below. Nothing else is searched for. Data can be shared by other installations; purging it affects those copies too."
1014 );
1015 if present.is_empty() {
1016 println!("Codewhale data directories are already absent.");
1017 }
1018 for target in &present {
1019 println!(
1020 "{} {}",
1021 if yes { "Delete" } else { "Would delete" },
1022 target.display()
1023 );
1024 }
1025 println!(
1026 "Not covered: OS keychain/keyring entries (run codewhale auth clear --provider <id> before removing the program) and per-workspace .codewhale directories."
1027 );
1028 if !yes {
1029 println!(
1030 "No data was changed. Adding --yes deletes these directories only after a receipted installation is removed in the same run."
1031 );
1032 return Ok(());
1033 }
1034 for target in present {
1035 std::fs::remove_dir_all(&target).with_context(|| {
1036 format!(
1037 "data purge stopped at {}; inspect what remains",
1038 target.display()
1039 )
1040 })?;
1041 println!("Deleted {}", target.display());
1042 }
1043 Ok(())
1044 }
1045
1046 fn report_path_copies(selected: Option<&Path>) {
1047 let inventory = codewhale_release::installs::inventory(selected);
1048 let lines = inventory.summary_lines(false, env!("CARGO_PKG_VERSION"));
1049 if inventory
1050 .entries
1051 .iter()
1052 .all(|entry| Some(entry.path.as_path()) == selected)
1053 {
1054 println!("No other Codewhale command remains on PATH.");
1055 return;
1056 }
1057 println!("Other Codewhale copies on this machine (not changed by uninstall):");
1058 for line in lines {
1059 println!(" {line}");
1060 }
1061 }
1062
1063 #[cfg(all(test, unix, not(target_os = "android")))]
1064 mod tests {
1065 use super::*;
1066 use std::os::unix::fs::PermissionsExt;
1067
1068 fn write_exec(path: &Path, bytes: &[u8]) {
1069 std::fs::write(path, bytes).unwrap();
1070 std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
1071 }
1072
1073 #[test]
1074 fn uninstall_removes_hard_linked_receipted_siblings_and_receipt() {
1075 for invoked_name in ["codewhale", "codew"] {
1076 let dir = tempfile::TempDir::new().unwrap();
1077 let bin_dir = dir.path().join("bin");
1078 std::fs::create_dir(&bin_dir).unwrap();
1079 std::fs::set_permissions(&bin_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
1080
1081 let bytes = b"uninstall-binary";
1082 let hash = crate::hashing::sha256_hex(bytes);
1083 let primary = bin_dir.join("codewhale");
1084 let sibling = bin_dir.join("codew");
1085 write_exec(&primary, bytes);
1086 std::fs::hard_link(&primary, &sibling).unwrap();
1087 let receipt_path = bin_dir.join(RECEIPT);
1088 std::fs::write(&receipt_path, format!("{hash} codewhale\n{hash} codew\n")).unwrap();
1089 std::fs::set_permissions(&receipt_path, std::fs::Permissions::from_mode(0o644))
1090 .unwrap();
1091
1092 let invoked = bin_dir.join(invoked_name);
1093 let ownership = CommandReceipt::capture(&invoked)
1094 .unwrap()
1095 .expect("receipted pair should capture");
1096 let identity = UpdateExecutableIdentity {
1097 path: invoked,
1098 file_hash: hash,
1099 };
1100 let removed = remove_receipted_ownership_with_options(
1101 &identity,
1102 ownership,
1103 invoked_name,
1104 true,
1105 false,
1106 )
1107 .unwrap();
1108 assert!(removed);
1109 assert!(!primary.exists());
1110 assert!(!sibling.exists());
1111 assert!(!receipt_path.exists());
1112 }
1113 }
1114
1115 #[test]
1116 fn receipt_capture_fails_closed_on_external_or_unreceipted_hard_link() {
1117 let dir = tempfile::TempDir::new().unwrap();
1118 let bin_dir = dir.path().join("bin");
1119 std::fs::create_dir(&bin_dir).unwrap();
1120 std::fs::set_permissions(&bin_dir, std::fs::Permissions::from_mode(0o755)).unwrap();
1121
1122 let bytes = b"uninstall-binary";
1123 let hash = crate::hashing::sha256_hex(bytes);
1124 let primary = bin_dir.join("codewhale");
1125 let sibling = bin_dir.join("codew");
1126 let foreign = dir.path().join("foreign-link");
1127 write_exec(&primary, bytes);
1128 std::fs::hard_link(&primary, &sibling).unwrap();
1129 std::fs::hard_link(&primary, &foreign).unwrap();
1130
1131 let receipt_path = bin_dir.join(RECEIPT);
1132 std::fs::write(&receipt_path, format!("{hash} codewhale\n{hash} codew\n")).unwrap();
1133 std::fs::set_permissions(&receipt_path, std::fs::Permissions::from_mode(0o644)).unwrap();
1134 assert!(CommandReceipt::capture(&primary).is_err());
1135
1136 std::fs::remove_file(&foreign).unwrap();
1137 std::fs::write(&receipt_path, format!("{hash} codewhale\n")).unwrap();
1138 assert!(CommandReceipt::capture(&primary).is_err());
1139 assert!(primary.exists());
1140 assert!(sibling.exists());
1141 assert!(receipt_path.exists());
1142 }
1143 }
1144
1144 lines RUST