返回 CodeWhale
installs.rs
根目录 / crates / release / src / installs.rs
1 //! Every Codewhale copy on this machine, who owns it, and what we may do with it.
2 //!
3 //! The inventory never executes a file it finds. It reads names, metadata, the
4 //! install receipt, package-manager metadata and, for candidate files, the
5 //! bytes (bounded) to look for a marker compiled into every Codewhale build.
6 //!
7 //! What we may change is decided here once, for `doctor`, `doctor --fix`,
8 //! `update`, `uninstall` and the installers:
9 //!
10 //! - receipt-owned and adoptable copies may be updated;
11 //! - backup leftovers may be moved into the recovery folder, never deleted;
12 //! - package-managed, app-bundled, symlinked, other-user and foreign files are
13 //! only ever reported, with the owner's own command where there is one.
14 //!
15 //! Known limits: candidates come from `PATH`, the running executable's
16 //! directory, `~/.local/bin` and `~/.cargo/bin`, not the whole disk. A copy
17 //! whose bytes differ from the running one reports "version unknown" because
18 //! it is never run. Recovery expiry deletes only what a recovery manifest lists.
19
20 use std::collections::{BTreeMap, BTreeSet, HashMap};
21 use std::fs;
22 use std::io::{BufRead, Read, Write};
23 use std::path::{Path, PathBuf};
24 use std::time::{Duration, SystemTime, UNIX_EPOCH};
25
26 use anyhow::{Context, Result, bail};
27 use sha2::{Digest, Sha256};
28
29 use crate::install::InstallMethod;
30
31 pub const RECEIPT_FILE: &str = ".codewhale-install.sha256";
32 #[cfg(windows)]
33 pub const RECEIPT_COMMANDS: &[&str] = &["codewhale.exe", "codew.exe", "codewhale.bat"];
34 #[cfg(not(windows))]
35 pub const RECEIPT_COMMANDS: &[&str] = &["codewhale", "codew"];
36 pub const RECOVERY_DIR: &str = "recovery";
37 pub const RECOVERY_MANIFEST: &str = "manifest.tsv";
38 pub const RECOVERY_RETENTION_DAYS: u64 = 30;
39 const VOLUME_RECOVERY_DIR: &str = ".codewhale-recovery";
40 const MAX_SCAN_BYTES: u64 = 1024 * 1024 * 1024;
41 const COMMAND_NAMES: &[&str] = &[
42 "codewhale-tui",
43 "deepseek-tui",
44 "codewhale",
45 "deepseek",
46 "codew",
47 ];
48 const MARKERS: &[&[u8]] = &[crate::UPDATE_USER_AGENT.as_bytes(), b"deepseek-tui"];
49 const LEFTOVER_DIR_PREFIXES: &[&str] = &[
50 ".codewhale-backup-",
51 ".codewhale-uninstall-",
52 ".codewhale-update-",
53 ".codewhale-install.",
54 ".codewhale-receipt.",
55 ];
56 const STALE_AFTER: Duration = Duration::from_secs(60 * 60);
57
58 #[derive(Debug, Clone, PartialEq, Eq)]
59 pub enum InstallClass {
60 ReceiptOwned,
61 PackageManaged(InstallMethod),
62 AppBundle,
63 OursUnreceipted,
64 BackupLeftover,
65 NotOurs(&'static str),
66 }
67
68 impl InstallClass {
69 #[must_use]
70 pub fn label(&self) -> &'static str {
71 match self {
72 Self::ReceiptOwned => "receipt-owned",
73 Self::PackageManaged(_) => "package-managed",
74 Self::AppBundle => "desktop app",
75 Self::OursUnreceipted => "unreceipted",
76 Self::BackupLeftover => "backup",
77 Self::NotOurs(_) => "left alone",
78 }
79 }
80 }
81
82 #[derive(Debug, Clone, PartialEq, Eq)]
83 pub struct InstallEntry {
84 pub path: PathBuf,
85 pub class: InstallClass,
86 pub is_dir: bool,
87 pub bytes: u64,
88 pub active: bool,
89 pub same_as_running: bool,
90 }
91
92 impl InstallEntry {
93 #[must_use]
94 pub fn owner_command(&self) -> Option<String> {
95 match &self.class {
96 InstallClass::PackageManaged(method) => Some(manager_command(*method, &self.path)),
97 InstallClass::AppBundle => Some(crate::install::DESKTOP_APP_UPDATE.to_string()),
98 _ => None,
99 }
100 }
101 }
102
103 #[derive(Debug, Clone, Default)]
104 pub struct Inventory {
105 pub entries: Vec<InstallEntry>,
106 pub running: Option<PathBuf>,
107 }
108
109 impl Inventory {
110 pub fn leftovers(&self) -> impl Iterator<Item = &InstallEntry> {
111 self.entries
112 .iter()
113 .filter(|entry| entry.class == InstallClass::BackupLeftover)
114 }
115
116 #[must_use]
117 pub fn leftover_bytes(&self) -> u64 {
118 self.leftovers().map(|entry| entry.bytes).sum()
119 }
120
121 #[must_use]
122 pub fn active(&self, command: &str) -> Option<&InstallEntry> {
123 self.entries
124 .iter()
125 .find(|entry| entry.active && command_stem(&entry.path) == Some(command))
126 }
127
128 #[must_use]
129 pub fn summary_lines(&self, brief: bool, version: &str) -> Vec<String> {
130 let mut lines = Vec::new();
131 let others: Vec<&InstallEntry> = self
132 .entries
133 .iter()
134 .filter(|entry| {
135 entry.class != InstallClass::BackupLeftover
136 && !entry.active
137 && Some(entry.path.as_path()) != self.running.as_deref()
138 && !(entry.same_as_running
139 && entry.path.parent() == self.running.as_deref().and_then(Path::parent))
140 })
141 .collect();
142 let leftovers = self.leftovers().count();
143 if brief && leftovers == 0 && others.is_empty() {
144 return lines;
145 }
146 match self.active("codewhale") {
147 Some(active) => lines.push(format!(
148 "Your shell runs {} ({}, {}).",
149 display(&active.path),
150 if active.same_as_running {
151 format!("v{version}")
152 } else {
153 "version unknown".to_string()
154 },
155 active.class.label()
156 )),
157 None => lines.push("No codewhale command is on PATH.".to_string()),
158 }
159 if leftovers > 0 {
160 lines.push(format!(
161 "{leftovers} old Codewhale backup(s) use {}. `codewhale doctor --fix` moves them to the recovery folder (kept {RECOVERY_RETENTION_DAYS} days); nothing is deleted.",
162 human_bytes(self.leftover_bytes())
163 ));
164 }
165 for entry in self
166 .entries
167 .iter()
168 .filter(|entry| entry.class == InstallClass::OursUnreceipted && !entry.same_as_running)
169 {
170 lines.push(format!(
171 "{} is an older Codewhale without a receipt; `codewhale update` or `codewhale doctor --fix` brings it in line.",
172 display(&entry.path)
173 ));
174 }
175 if !others.is_empty() {
176 lines.push("Left alone (not changed):".to_string());
177 for entry in others.iter().take(if brief { 6 } else { usize::MAX }) {
178 let why = match &entry.class {
179 InstallClass::PackageManaged(method) => format!(
180 "managed by {}: {}",
181 method.label(),
182 entry.owner_command().unwrap_or_default()
183 ),
184 InstallClass::AppBundle => {
185 format!(
186 "part of the Codewhale app: {}",
187 crate::install::DESKTOP_APP_UPDATE
188 )
189 }
190 InstallClass::NotOurs(reason) => (*reason).to_string(),
191 InstallClass::ReceiptOwned => "another receipted install".to_string(),
192 InstallClass::OursUnreceipted => "another Codewhale copy".to_string(),
193 InstallClass::BackupLeftover => unreachable!(),
194 };
195 lines.push(format!(" {} {why}", display(&entry.path)));
196 }
197 if brief && others.len() > 6 {
198 lines.push(format!(
199 " and {} more (codewhale doctor --installs)",
200 others.len() - 6
201 ));
202 }
203 }
204 lines
205 }
206 }
207
208 #[must_use]
209 pub fn inventory(running: Option<&Path>) -> Inventory {
210 let running_hash = running.and_then(|path| file_sha256(path).ok());
211 let path_dirs: Vec<PathBuf> =
212 std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()).collect();
213 let mut dirs: Vec<PathBuf> = Vec::new();
214 let home = home_dir();
215 let mut push = |dir: PathBuf| {
216 if dir.as_os_str().is_empty() || !dir.is_absolute() {
217 return;
218 }
219 let key = fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
220 if !dirs
221 .iter()
222 .any(|seen| fs::canonicalize(seen).unwrap_or_else(|_| seen.clone()) == key)
223 {
224 dirs.push(dir);
225 }
226 };
227 for dir in &path_dirs {
228 push(dir.clone());
229 }
230 if let Some(parent) = running.and_then(Path::parent) {
231 push(parent.to_path_buf());
232 }
233 if let Some(home) = &home {
234 push(home.join(".local").join("bin"));
235 push(home.join(".cargo").join("bin"));
236 }
237
238 let owner = home.as_deref().and_then(owner_id);
239 let mut entries = Vec::new();
240 for dir in &dirs {
241 let Ok(read) = fs::read_dir(dir) else {
242 continue;
243 };
244 let mut names: Vec<_> = read.flatten().map(|entry| entry.file_name()).collect();
245 names.sort();
246 for name in names {
247 let Some(name) = name.to_str() else { continue };
248 let path = dir.join(name);
249 if let Some(class) = classify(&path, name, owner, running_hash.as_deref()) {
250 let meta = fs::symlink_metadata(&path).ok();
251 let is_dir = meta.as_ref().is_some_and(fs::Metadata::is_dir);
252 let bytes = if is_dir {
253 dir_bytes(&path)
254 } else {
255 meta.as_ref().map_or(0, fs::Metadata::len)
256 };
257 let same_as_running = !is_dir
258 && running_hash.is_some()
259 && meta.as_ref().is_some_and(|meta| meta.is_file())
260 && command_stem(&path).is_some()
261 && file_sha256(&path).ok() == running_hash;
262 entries.push(InstallEntry {
263 path,
264 class,
265 is_dir,
266 bytes,
267 active: false,
268 same_as_running,
269 });
270 }
271 }
272 }
273 for command in ["codewhale", "codew"] {
274 let file = format!("{command}{}", std::env::consts::EXE_SUFFIX);
275 if let Some(first) = path_dirs
276 .iter()
277 .map(|dir| dir.join(&file))
278 .find(|path| fs::symlink_metadata(path).is_ok())
279 && let Some(entry) = entries.iter_mut().find(|entry| entry.path == first)
280 {
281 entry.active = true;
282 }
283 }
284 Inventory {
285 entries,
286 running: running.map(Path::to_path_buf),
287 }
288 }
289
290 fn classify(
291 path: &Path,
292 name: &str,
293 owner: Option<u64>,
294 running_hash: Option<&str>,
295 ) -> Option<InstallClass> {
296 let meta = fs::symlink_metadata(path).ok()?;
297 let stem = name
298 .strip_suffix(std::env::consts::EXE_SUFFIX)
299 .filter(|_| !std::env::consts::EXE_SUFFIX.is_empty())
300 .unwrap_or(name);
301 let exact = COMMAND_NAMES.contains(&stem);
302 let leftover_name = is_backup_name(name);
303 let leftover_dir = name != RECEIPT_FILE
304 && LEFTOVER_DIR_PREFIXES
305 .iter()
306 .any(|prefix| name.starts_with(prefix));
307 let host_recovery = name.starts_with(".codewhale-host-recovery-");
308 let related = exact
309 || leftover_name
310 || leftover_dir
311 || host_recovery
312 || name.starts_with("codew")
313 || name.starts_with("deepseek");
314 if !related {
315 return None;
316 }
317 let method = InstallMethod::owner(path);
318 if method == InstallMethod::DesktopApp {
319 return Some(InstallClass::AppBundle);
320 }
321 if !method.supports_self_update()
322 && (method != InstallMethod::Cargo
323 || meta.is_symlink()
324 || cargo_record_lists(path, name) == Some(true))
325 {
326 return Some(InstallClass::PackageManaged(method));
327 }
328 if meta.is_symlink() {
329 return Some(InstallClass::NotOurs("symlink; not changed"));
330 }
331 if !owned_by(&meta, owner) {
332 return Some(InstallClass::NotOurs("owned by another user"));
333 }
334 if leftover_dir {
335 let stale = meta
336 .modified()
337 .ok()
338 .and_then(|modified| modified.elapsed().ok())
339 .is_some_and(|age| age > STALE_AFTER);
340 return Some(if !stale {
341 InstallClass::NotOurs("changed within the last hour, so it may be in use; not changed")
342 } else if meta.is_dir() || name.starts_with(".codewhale-update-") {
343 InstallClass::BackupLeftover
344 } else {
345 InstallClass::NotOurs("an install receipt or marker file, not a backup; not changed")
346 });
347 }
348 if host_recovery {
349 return Some(if meta.is_file() && meta.len() <= 64 * 1024 {
350 InstallClass::BackupLeftover
351 } else {
352 InstallClass::NotOurs("not a Codewhale backup")
353 });
354 }
355 if !meta.is_file() {
356 return Some(InstallClass::NotOurs("not a regular file"));
357 }
358 if exact {
359 if receipt_owns(path, name).unwrap_or(false) {
360 return Some(InstallClass::ReceiptOwned);
361 }
362 if running_hash.is_some() && file_sha256(path).ok().as_deref() == running_hash {
363 return Some(InstallClass::OursUnreceipted);
364 }
365 return Some(if is_codewhale_binary(path) {
366 InstallClass::OursUnreceipted
367 } else {
368 InstallClass::NotOurs("not a Codewhale binary")
369 });
370 }
371 if leftover_name {
372 return Some(if is_codewhale_binary(path) {
373 InstallClass::BackupLeftover
374 } else {
375 InstallClass::NotOurs("not a Codewhale binary")
376 });
377 }
378 Some(InstallClass::NotOurs("different program"))
379 }
380
381 #[must_use]
382 pub fn is_backup_name(name: &str) -> bool {
383 let name = name
384 .strip_suffix(".exe")
385 .filter(|_| cfg!(windows))
386 .unwrap_or(name);
387 COMMAND_NAMES.iter().any(|base| {
388 let Some(rest) = name.strip_prefix(base) else {
389 return false;
390 };
391 let Some(suffix) = rest.strip_prefix(['-', '.']) else {
392 return false;
393 };
394 let suffix = suffix.strip_prefix(['v', 'V']).unwrap_or(suffix);
395 if [
396 "bak", "before-", "pre-", "pre_", "prev", "debug-", "orig", "backup",
397 ]
398 .iter()
399 .any(|prefix| suffix.starts_with(prefix))
400 {
401 return true;
402 }
403 if let Some(pid) = suffix.strip_prefix("old-") {
404 return pid.starts_with(|c: char| c.is_ascii_digit());
405 }
406 semver_backup_suffix(suffix)
407 })
408 }
409
410 fn semver_backup_suffix(suffix: &str) -> bool {
411 let mut parts = suffix.splitn(3, '.');
412 let (Some(major), Some(minor), Some(rest)) = (parts.next(), parts.next(), parts.next()) else {
413 return false;
414 };
415 let digits = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit());
416 if !digits(major) || !digits(minor) {
417 return false;
418 }
419 let patch_len = rest.chars().take_while(char::is_ascii_digit).count();
420 if patch_len == 0 {
421 return false;
422 }
423 let mut tail = &rest[patch_len..];
424 if let Some(hex) = tail.strip_prefix('-') {
425 let len = hex.chars().take_while(char::is_ascii_hexdigit).count();
426 if len == 0 {
427 return false;
428 }
429 tail = &hex[len..];
430 }
431 tail.is_empty()
432 || tail.starts_with(".bak")
433 || tail.starts_with("-bak")
434 || tail.starts_with(".old")
435 }
436
437 fn command_stem(path: &Path) -> Option<&str> {
438 let name = path.file_name()?.to_str()?;
439 let stem = name
440 .strip_suffix(std::env::consts::EXE_SUFFIX)
441 .filter(|_| !std::env::consts::EXE_SUFFIX.is_empty())
442 .unwrap_or(name);
443 COMMAND_NAMES.contains(&stem).then_some(stem)
444 }
445
446 #[must_use]
447 pub fn is_codewhale_binary(path: &Path) -> bool {
448 let Ok(mut file) = fs::File::open(path) else {
449 return false;
450 };
451 let mut magic = [0u8; 4];
452 if file.read_exact(&mut magic).is_err() {
453 return false;
454 }
455 let native = magic == *b"\x7fELF"
456 || magic[..2] == *b"MZ"
457 || matches!(
458 u32::from_be_bytes(magic),
459 0xfeed_face | 0xfeed_facf | 0xcefa_edfe | 0xcffa_edfe | 0xcafe_babe
460 );
461 if !native {
462 return false;
463 }
464 let longest = MARKERS.iter().map(|m| m.len()).max().unwrap_or(0);
465 let mut reader = std::io::BufReader::with_capacity(1 << 20, file.take(MAX_SCAN_BYTES));
466 let mut carry: Vec<u8> = magic.to_vec();
467 loop {
468 let chunk = match reader.fill_buf() {
469 Ok([]) => return false,
470 Ok(chunk) => chunk,
471 Err(_) => return false,
472 };
473 let len = chunk.len();
474 carry.extend_from_slice(chunk);
475 reader.consume(len);
476 if MARKERS
477 .iter()
478 .any(|marker| carry.windows(marker.len()).any(|window| window == *marker))
479 {
480 return true;
481 }
482 let keep = carry.len().saturating_sub(longest);
483 carry.drain(..keep);
484 }
485 }
486
487 pub fn file_sha256(path: &Path) -> Result<String> {
488 let file =
489 fs::File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
490 reader_sha256(file).with_context(|| format!("failed to read {}", path.display()))
491 }
492
493 pub fn reader_sha256(mut reader: impl Read) -> std::io::Result<String> {
494 let mut hasher = Sha256::new();
495 let mut buffer = vec![0u8; 1 << 20];
496 loop {
497 let read = match reader.read(&mut buffer) {
498 Ok(0) => break,
499 Ok(read) => read,
500 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
501 Err(error) => return Err(error),
502 };
503 hasher.update(&buffer[..read]);
504 }
505 Ok(hex(&hasher.finalize()[..]))
506 }
507
508 #[must_use]
509 pub fn sha256_hex(bytes: &[u8]) -> String {
510 hex(&Sha256::digest(bytes)[..])
511 }
512
513 fn hex(bytes: &[u8]) -> String {
514 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
515 }
516
517 fn receipt_owns(path: &Path, name: &str) -> Result<bool> {
518 let receipt = path.with_file_name(RECEIPT_FILE);
519 let Ok(text) = read_small(&receipt, 4096) else {
520 return Ok(false);
521 };
522 let digest = file_sha256(path)?;
523 Ok(text.lines().any(|line| {
524 let mut parts = line.split_whitespace();
525 parts.next() == Some(digest.as_str())
526 && parts.next().map(|n| n.trim_start_matches('*')) == Some(name)
527 }))
528 }
529
530 fn read_small(path: &Path, limit: u64) -> Result<String> {
531 let meta = fs::symlink_metadata(path)?;
532 if !meta.is_file() || meta.len() > limit {
533 bail!("{} is not a small regular file", path.display());
534 }
535 Ok(fs::read_to_string(path)?)
536 }
537
538 fn cargo_root_beside(path: &Path) -> Option<PathBuf> {
539 let bin = path.parent()?;
540 if bin.file_name()? != "bin" {
541 return None;
542 }
543 let root = bin.parent()?;
544 [".crates.toml", ".crates2.json"]
545 .iter()
546 .any(|name| fs::symlink_metadata(root.join(name)).is_ok())
547 .then(|| root.to_path_buf())
548 }
549
550 pub(crate) fn cargo_owns_a_command_beside(path: &Path) -> bool {
551 RECEIPT_COMMANDS
552 .iter()
553 .any(|name| cargo_record_lists(path, name) == Some(true))
554 }
555
556 pub(crate) fn cargo_record_lists(path: &Path, name: &str) -> Option<bool> {
557 let root = cargo_root_beside(path)?;
558 let quoted = format!("\"{name}\"");
559 for file in [".crates.toml", ".crates2.json"] {
560 let record = root.join(file);
561 if fs::symlink_metadata(&record).is_err() {
562 continue;
563 }
564 if read_small(&record, 4 * 1024 * 1024).map_or(true, |text| text.contains(&quoted)) {
565 return Some(true);
566 }
567 }
568 Some(false)
569 }
570
571 #[cfg(unix)]
572 fn owner_id(path: &Path) -> Option<u64> {
573 use std::os::unix::fs::MetadataExt;
574 fs::metadata(path).ok().map(|meta| u64::from(meta.uid()))
575 }
576
577 #[cfg(not(unix))]
578 fn owner_id(_path: &Path) -> Option<u64> {
579 None
580 }
581
582 #[cfg(unix)]
583 fn owned_by(meta: &fs::Metadata, owner: Option<u64>) -> bool {
584 use std::os::unix::fs::MetadataExt;
585 owner.is_none_or(|owner| u64::from(meta.uid()) == owner)
586 }
587
588 #[cfg(not(unix))]
589 fn owned_by(_meta: &fs::Metadata, _owner: Option<u64>) -> bool {
590 true
591 }
592
593 fn home_dir() -> Option<PathBuf> {
594 std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })
595 .filter(|home| !home.is_empty())
596 .map(PathBuf::from)
597 }
598
599 fn dir_bytes(path: &Path) -> u64 {
600 let Ok(entries) = fs::read_dir(path) else {
601 return 0;
602 };
603 entries
604 .flatten()
605 .filter_map(|entry| fs::symlink_metadata(entry.path()).ok().map(|m| (entry, m)))
606 .map(|(entry, meta)| {
607 if meta.is_dir() {
608 dir_bytes(&entry.path())
609 } else if meta.is_file() {
610 meta.len()
611 } else {
612 0
613 }
614 })
615 .sum()
616 }
617
618 fn display(path: &Path) -> String {
619 if let Some(home) = home_dir()
620 && let Ok(rest) = path.strip_prefix(&home)
621 {
622 return format!("~/{}", rest.display());
623 }
624 path.display().to_string()
625 }
626
627 #[must_use]
628 pub fn human_bytes(bytes: u64) -> String {
629 const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
630 let mut value = bytes as f64;
631 let mut unit = 0;
632 while value >= 1000.0 && unit + 1 < UNITS.len() {
633 value /= 1000.0;
634 unit += 1;
635 }
636 if unit == 0 {
637 format!("{bytes} B")
638 } else {
639 format!("{value:.1} {}", UNITS[unit])
640 }
641 }
642
643 fn quoted(path: &Path) -> String {
644 format!("\"{}\"", path.display())
645 }
646
647 /// The command that removes the copy at `executable` through its owner.
648 #[must_use]
649 pub fn manager_command(method: InstallMethod, executable: &Path) -> String {
650 owner_command(method, executable, false)
651 }
652
653 /// The command that updates the copy at `executable` through its owner,
654 /// with the exact Cargo root or npm prefix that installed it.
655 #[must_use]
656 pub fn manager_update_command(method: InstallMethod, executable: &Path) -> String {
657 owner_command(method, executable, true)
658 }
659
660 /// One line answering "can this copy update itself, and if not, what does?"
661 /// Shared by `codewhale update`, `/update`, rollback and `doctor`.
662 #[must_use]
663 pub fn update_answer(method: InstallMethod, executable: &Path) -> String {
664 match method {
665 InstallMethod::DesktopApp => crate::install::DESKTOP_APP_UPDATE_HELP.to_string(),
666 InstallMethod::System => "This copy is in a system or package directory, so it cannot update itself; update it with the package manager that installed it.".to_string(),
667 InstallMethod::ReadOnly => format!(
668 "This copy is in {}, which this account cannot write, so it cannot update itself; rerun the installer into a folder you own, or update it as that folder's owner.",
669 quoted(executable.parent().unwrap_or(executable))
670 ),
671 InstallMethod::Npm => format!(
672 "This copy belongs to {}, so it cannot update itself; update it with `{}`.",
673 npm_family(executable).map_or("npm", |family| family.0),
674 manager_update_command(method, executable)
675 ),
676 method if method.supports_self_update() => {
677 "This copy updates itself: `codewhale update`.".to_string()
678 }
679 method => format!(
680 "This copy belongs to {}, so it cannot update itself; update it with `{}`.",
681 method.label(),
682 manager_update_command(method, executable)
683 ),
684 }
685 }
686
687 fn owner_command(method: InstallMethod, executable: &Path, update: bool) -> String {
688 let real = fs::canonicalize(executable).unwrap_or_else(|_| executable.to_path_buf());
689 let names: Vec<_> = real.components().map(|part| part.as_os_str()).collect();
690 let position = |marker: &str| {
691 names
692 .iter()
693 .position(|name| name.eq_ignore_ascii_case(marker))
694 };
695 let fallback = || {
696 if update {
697 method.update_command()
698 } else {
699 method.uninstall_command()
700 }
701 .to_string()
702 };
703 match method {
704 InstallMethod::Cargo => match real.parent().and_then(Path::parent) {
705 Some(root) if update => format!(
706 "cargo install codewhale-cli --locked --force --root {}",
707 quoted(root)
708 ),
709 Some(root) => format!("cargo uninstall codewhale-cli --root {}", quoted(root)),
710 None => fallback(),
711 },
712 InstallMethod::Homebrew if !update => {
713 match position("Cellar").and_then(|index| names.get(index + 1)) {
714 Some(formula) => format!("brew uninstall {}", formula.to_string_lossy()),
715 None => fallback(),
716 }
717 }
718 InstallMethod::Npm if npm_family(&real).is_some() => {
719 let (_, update_command, uninstall_command) = npm_family(&real).unwrap_or_default();
720 if update {
721 update_command
722 } else {
723 uninstall_command
724 }
725 .to_string()
726 }
727 InstallMethod::Npm => match position("node_modules") {
728 Some(index) if index > 0 => {
729 let mut root: PathBuf = names[..index].iter().collect();
730 if !cfg!(windows) && root.file_name().is_some_and(|name| name == "lib") {
731 root.pop();
732 }
733 if update {
734 format!("npm install -g codewhale@latest --prefix {}", quoted(&root))
735 } else {
736 format!("npm uninstall -g codewhale --prefix {}", quoted(&root))
737 }
738 }
739 _ => fallback(),
740 },
741 InstallMethod::WindowsInstaller if !update => {
742 match crate::install::windows_installer_uninstaller(&real) {
743 Some(uninstaller) => format!("{}, or run {}", fallback(), quoted(&uninstaller)),
744 None => fallback(),
745 }
746 }
747 _ => fallback(),
748 }
749 }
750
751 /// The npm-compatible manager whose global folder holds `executable`:
752 /// `(label, update command, uninstall command)`. `None` for npm itself.
753 fn npm_family(executable: &Path) -> Option<(&'static str, &'static str, &'static str)> {
754 let real = fs::canonicalize(executable).unwrap_or_else(|_| executable.to_path_buf());
755 let has = |marker: &str| {
756 real.components()
757 .any(|part| part.as_os_str().eq_ignore_ascii_case(marker))
758 };
759 [
760 (
761 "pnpm",
762 "pnpm",
763 "pnpm add -g codewhale@latest",
764 "pnpm remove -g codewhale",
765 ),
766 (
767 ".bun",
768 "Bun",
769 "bun add -g codewhale@latest",
770 "bun remove -g codewhale",
771 ),
772 (
773 "yarn",
774 "Yarn",
775 "yarn global add codewhale@latest",
776 "yarn global remove codewhale",
777 ),
778 (
779 ".volta",
780 "Volta",
781 "volta install codewhale@latest",
782 "volta uninstall codewhale",
783 ),
784 (
785 "mise",
786 "mise",
787 "mise use -g npm:codewhale@latest",
788 "mise uninstall npm:codewhale",
789 ),
790 ]
791 .into_iter()
792 .find(|(marker, ..)| has(marker))
793 .map(|(_, label, update, uninstall)| (label, update, uninstall))
794 }
795
796 #[must_use]
797 pub fn utc_stamp(unix: u64) -> String {
798 let days = (unix / 86_400) as i64;
799 let secs = unix % 86_400;
800 let z = days + 719_468;
801 let era = z.div_euclid(146_097);
802 let doe = z - era * 146_097;
803 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
804 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
805 let mp = (5 * doy + 2) / 153;
806 let day = doy - (153 * mp + 2) / 5 + 1;
807 let month = if mp < 10 { mp + 3 } else { mp - 9 };
808 let year = yoe + era * 400 + i64::from(month <= 2);
809 format!(
810 "{year:04}{month:02}{day:02}T{:02}{:02}{:02}Z",
811 secs / 3600,
812 (secs % 3600) / 60,
813 secs % 60
814 )
815 }
816
817 fn stamp_unix(stamp: &str) -> Option<u64> {
818 let digits: String = stamp
819 .chars()
820 .filter(char::is_ascii_digit)
821 .take(14)
822 .collect();
823 if digits.len() != 14 {
824 return None;
825 }
826 let num = |range: std::ops::Range<usize>| digits[range].parse::<i64>().ok();
827 let (year, month, day) = (num(0..4)?, num(4..6)?, num(6..8)?);
828 let (hour, minute, second) = (num(8..10)?, num(10..12)?, num(12..14)?);
829 let year = year - i64::from(month <= 2);
830 let era = year.div_euclid(400);
831 let yoe = year - era * 400;
832 let mp = (month + 9) % 12;
833 let doy = (153 * mp + 2) / 5 + day - 1;
834 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
835 let days = era * 146_097 + doe - 719_468;
836 u64::try_from(days * 86_400 + hour * 3600 + minute * 60 + second).ok()
837 }
838
839 fn now_unix() -> u64 {
840 SystemTime::now()
841 .duration_since(UNIX_EPOCH)
842 .map_or(0, |elapsed| elapsed.as_secs())
843 }
844
845 #[derive(Debug, Clone, PartialEq, Eq)]
846 pub struct RecoveryMove {
847 pub from: PathBuf,
848 pub to: PathBuf,
849 pub bytes: u64,
850 }
851
852 impl RecoveryMove {
853 #[must_use]
854 pub fn undo_command(&self) -> String {
855 if cfg!(windows) {
856 format!(
857 "Move-Item -LiteralPath '{}' -Destination '{}'",
858 self.to.display(),
859 self.from.display()
860 )
861 } else {
862 format!(
863 "mv -n {} {}",
864 shell_quote(&self.to),
865 shell_quote(&self.from)
866 )
867 }
868 }
869 }
870
871 fn shell_quote(path: &Path) -> String {
872 format!("'{}'", path.display().to_string().replace('\'', "'\\''"))
873 }
874
875 pub struct RecoveryBatch {
876 pub stamp: String,
877 pub dir: PathBuf,
878 pub moves: Vec<RecoveryMove>,
879 next: usize,
880 }
881
882 impl RecoveryBatch {
883 pub fn open(home: &Path) -> Result<Self> {
884 let root = home.join(RECOVERY_DIR);
885 create_private_dir(&root)?;
886 let base = utc_stamp(now_unix());
887 for attempt in 0..100 {
888 let stamp = if attempt == 0 {
889 base.clone()
890 } else {
891 format!("{base}-{attempt}")
892 };
893 let dir = root.join(&stamp);
894 match fs::create_dir(&dir) {
895 Ok(()) => {
896 return Ok(Self {
897 stamp,
898 dir,
899 moves: Vec::new(),
900 next: 1,
901 });
902 }
903 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
904 Err(error) => {
905 return Err(error)
906 .with_context(|| format!("failed to create {}", dir.display()));
907 }
908 }
909 }
910 bail!(
911 "could not choose a recovery folder under {}",
912 root.display()
913 )
914 }
915
916 pub fn move_in(&mut self, path: &Path) -> Result<RecoveryMove> {
917 self.move_in_replaced(path, None)
918 }
919
920 fn move_in_replaced(&mut self, path: &Path, replacement: Option<&str>) -> Result<RecoveryMove> {
921 let original = path.to_string_lossy();
922 if original.contains(['\t', '\n', '\r']) {
923 bail!(
924 "refusing to move {}: its name contains a tab or newline",
925 path.display()
926 );
927 }
928 let meta = fs::symlink_metadata(path)
929 .with_context(|| format!("failed to inspect {}", path.display()))?;
930 if meta.is_symlink() {
931 bail!("refusing to move symlink {}", path.display());
932 }
933 let digest = if meta.is_file() && meta.len() <= MAX_SCAN_BYTES {
934 file_sha256(path)?
935 } else {
936 "-".to_string()
937 };
938 let bytes = if meta.is_dir() {
939 dir_bytes(path)
940 } else {
941 meta.len()
942 };
943 let name = path
944 .file_name()
945 .context("path has no file name")?
946 .to_string_lossy()
947 .into_owned();
948 let stored_name = format!("{:03}-{name}", self.next);
949 self.next += 1;
950 let mut to = self.dir.join(&stored_name);
951 if let Err(error) = fs::rename(path, &to) {
952 if !is_cross_device(&error) {
953 return Err(error).with_context(|| {
954 format!("failed to move {} to {}", path.display(), to.display())
955 });
956 }
957 let volume = path
958 .parent()
959 .context("path has no parent")?
960 .join(VOLUME_RECOVERY_DIR)
961 .join(&self.stamp);
962 fs::create_dir_all(&volume)
963 .with_context(|| format!("failed to create {}", volume.display()))?;
964 to = volume.join(&stored_name);
965 fs::rename(path, &to).with_context(|| {
966 format!("failed to move {} to {}", path.display(), to.display())
967 })?;
968 }
969 let suffix = replacement
970 .map(|digest| format!("\t{digest}"))
971 .unwrap_or_default();
972 let line = format!("{original}\t{}\t{digest}\t{bytes}{suffix}\n", to.display());
973 let mut manifest = fs::OpenOptions::new()
974 .create(true)
975 .append(true)
976 .open(self.dir.join(RECOVERY_MANIFEST))
977 .context("failed to open the recovery manifest")?;
978 manifest
979 .write_all(line.as_bytes())
980 .and_then(|()| manifest.sync_all())
981 .context("failed to record the move in the recovery manifest")?;
982 let moved = RecoveryMove {
983 from: path.to_path_buf(),
984 to,
985 bytes,
986 };
987 self.moves.push(moved.clone());
988 Ok(moved)
989 }
990
991 pub fn finish(self) -> Vec<RecoveryMove> {
992 if self.moves.is_empty() {
993 let _ = fs::remove_dir(&self.dir);
994 }
995 self.moves
996 }
997 }
998
999 fn is_cross_device(error: &std::io::Error) -> bool {
1000 error.kind() == std::io::ErrorKind::CrossesDevices || error.raw_os_error() == Some(18)
1001 }
1002
1003 fn create_private_dir(dir: &Path) -> Result<()> {
1004 fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;
1005 #[cfg(unix)]
1006 {
1007 use std::os::unix::fs::PermissionsExt;
1008 let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
1009 }
1010 Ok(())
1011 }
1012
1013 #[derive(Debug, Clone)]
1014 pub struct RecoveryRecord {
1015 pub original: PathBuf,
1016 pub stored: PathBuf,
1017 pub sha256: Option<String>,
1018 pub bytes: u64,
1019 pub replacement_sha256: Option<String>,
1020 }
1021
1022 #[derive(Debug, Clone)]
1023 pub struct RecoveryFolder {
1024 pub stamp: String,
1025 pub dir: PathBuf,
1026 pub records: Vec<RecoveryRecord>,
1027 pub created_unix: Option<u64>,
1028 }
1029
1030 impl RecoveryFolder {
1031 #[must_use]
1032 pub fn bytes(&self) -> u64 {
1033 self.records.iter().map(|record| record.bytes).sum()
1034 }
1035
1036 #[must_use]
1037 pub fn expires_in_days(&self, now: u64) -> Option<u64> {
1038 let created = self.created_unix?;
1039 let expiry = created + RECOVERY_RETENTION_DAYS * 86_400;
1040 Some(expiry.saturating_sub(now).div_ceil(86_400))
1041 }
1042 }
1043
1044 #[must_use]
1045 pub fn recovery_folders(home: &Path) -> Vec<RecoveryFolder> {
1046 let root = home.join(RECOVERY_DIR);
1047 let Ok(read) = fs::read_dir(&root) else {
1048 return Vec::new();
1049 };
1050 let mut folders: Vec<RecoveryFolder> = read
1051 .flatten()
1052 .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
1053 .filter_map(|entry| {
1054 let stamp = entry.file_name().to_str()?.to_string();
1055 let dir = entry.path();
1056 let records = read_manifest(&dir);
1057 Some(RecoveryFolder {
1058 created_unix: stamp_unix(&stamp),
1059 stamp,
1060 dir,
1061 records,
1062 })
1063 })
1064 .collect();
1065 folders.sort_by(|a, b| a.stamp.cmp(&b.stamp));
1066 folders
1067 }
1068
1069 fn read_manifest(dir: &Path) -> Vec<RecoveryRecord> {
1070 let Ok(text) = fs::read_to_string(dir.join(RECOVERY_MANIFEST)) else {
1071 return Vec::new();
1072 };
1073 text.lines()
1074 .filter_map(|line| {
1075 let mut fields = line.split('\t');
1076 let original = PathBuf::from(fields.next()?);
1077 let stored = PathBuf::from(fields.next()?);
1078 let sha256 = fields
1079 .next()
1080 .filter(|digest| digest.len() == 64)
1081 .map(str::to_ascii_lowercase);
1082 let bytes = fields.next().and_then(|n| n.parse().ok()).unwrap_or(0);
1083 Some(RecoveryRecord {
1084 original,
1085 stored,
1086 sha256,
1087 bytes,
1088 replacement_sha256: fields.next().map(str::to_string),
1089 })
1090 })
1091 .collect()
1092 }
1093
1094 fn stored_inside_recovery(folder: &RecoveryFolder, stored: &Path) -> bool {
1095 stored.starts_with(&folder.dir)
1096 || stored.parent().is_some_and(|parent| {
1097 parent.file_name().and_then(|n| n.to_str()) == Some(folder.stamp.as_str())
1098 && parent
1099 .parent()
1100 .and_then(Path::file_name)
1101 .is_some_and(|n| n == VOLUME_RECOVERY_DIR)
1102 })
1103 }
1104
1105 #[derive(Debug, Default)]
1106 pub struct RestoreReport {
1107 pub restored: Vec<PathBuf>,
1108 pub skipped: Vec<(PathBuf, String)>,
1109 pub displaced: Option<String>,
1110 }
1111
1112 pub fn parse_command_receipt(text: &str) -> Result<HashMap<String, String>> {
1113 let hashes = crate::parse_checksum_manifest(text)?;
1114 if hashes.is_empty()
1115 || hashes.len() != text.lines().count()
1116 || hashes
1117 .keys()
1118 .any(|name| !RECEIPT_COMMANDS.contains(&name.as_str()))
1119 {
1120 bail!("invalid command ownership receipt");
1121 }
1122 Ok(hashes)
1123 }
1124
1125 fn verified_recovery_file(
1126 folder: &RecoveryFolder,
1127 record: &RecoveryRecord,
1128 ) -> Result<fs::Metadata> {
1129 if !stored_inside_recovery(folder, &record.stored) {
1130 bail!("manifest entry points outside the recovery folder");
1131 }
1132 let meta = fs::symlink_metadata(&record.stored).context("no longer in the recovery folder")?;
1133 if meta.is_symlink() {
1134 bail!("stored entry is a symlink");
1135 }
1136 if record.sha256.is_some() && !meta.is_file() {
1137 bail!("stored entry is no longer a regular file");
1138 }
1139 if meta.is_file() {
1140 match &record.sha256 {
1141 Some(expected) => {
1142 if &file_sha256(&record.stored)? != expected {
1143 bail!("its bytes changed in the recovery folder");
1144 }
1145 }
1146 None if record.bytes != meta.len() => {
1147 bail!("its size changed in the recovery folder");
1148 }
1149 None => {}
1150 }
1151 }
1152 Ok(meta)
1153 }
1154
1155 struct DisplacedReceipt {
1156 path: PathBuf,
1157 retained: Vec<(String, String)>,
1158 }
1159
1160 fn command_receipt_to_displace(
1161 directory: &Path,
1162 records: &BTreeMap<&Path, &RecoveryRecord>,
1163 owner: Option<u64>,
1164 ) -> Result<Option<DisplacedReceipt>> {
1165 let receipt = directory.join(RECEIPT_FILE);
1166 let meta = match fs::symlink_metadata(&receipt) {
1167 Ok(meta) => meta,
1168 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1169 Err(error) => return Err(error.into()),
1170 };
1171 let dir_meta = fs::symlink_metadata(directory)?;
1172 if !dir_meta.is_dir()
1173 || !owned_by(&dir_meta, owner)
1174 || !directory_is_private(directory)
1175 || !meta.is_file()
1176 || !owned_by(&meta, owner)
1177 {
1178 bail!("preserved untrusted command receipt {}", receipt.display());
1179 }
1180 let claims = parse_command_receipt(&read_small(&receipt, 512)?)?;
1181 let mut changes_owned_bytes = false;
1182 let mut retained = Vec::new();
1183 for name in RECEIPT_COMMANDS {
1184 let command = directory.join(name);
1185 if let Some(record) = records.get(command.as_path())
1186 && record.replacement_sha256.is_none()
1187 && !claims.contains_key(*name)
1188 && fs::symlink_metadata(&command).is_ok()
1189 {
1190 bail!("preserved unclaimed command {}", command.display());
1191 }
1192 }
1193 for (name, expected) in claims {
1194 let path = directory.join(&name);
1195 match fs::symlink_metadata(&path) {
1196 Ok(current)
1197 if current.is_file()
1198 && owned_by(&current, owner)
1199 && file_sha256(&path)? == expected => {}
1200 Err(error)
1201 if error.kind() == std::io::ErrorKind::NotFound
1202 && records.contains_key(path.as_path()) => {}
1203 _ => bail!("preserved modified command {}", path.display()),
1204 }
1205 if let Some(record) = records.get(path.as_path()) {
1206 let changes = match &record.sha256 {
1207 Some(digest) => digest != &expected,
1208 None => file_sha256(&record.stored)? != expected,
1209 };
1210 if changes {
1211 changes_owned_bytes = true;
1212 continue;
1213 }
1214 }
1215 retained.push((name, expected));
1216 }
1217 let saved = records.contains_key(receipt.as_path());
1218 if saved {
1219 retained.clear();
1220 }
1221 Ok((changes_owned_bytes || saved).then_some(DisplacedReceipt {
1222 path: receipt,
1223 retained,
1224 }))
1225 }
1226
1227 fn validate_saved_command_receipt(
1228 record: &RecoveryRecord,
1229 pending: &BTreeMap<&Path, &RecoveryRecord>,
1230 ) -> Result<()> {
1231 let directory = record
1232 .original
1233 .parent()
1234 .context("command receipt has no directory")?;
1235 for (name, expected) in parse_command_receipt(&read_small(&record.stored, 512)?)? {
1236 let command = directory.join(name);
1237 let bytes = pending
1238 .get(command.as_path())
1239 .map_or(command.as_path(), |entry| entry.stored.as_path());
1240 if !fs::symlink_metadata(bytes)?.is_file() || file_sha256(bytes)? != expected {
1241 bail!(
1242 "preserved recovery receipt: {} has different bytes",
1243 command.display()
1244 );
1245 }
1246 }
1247 Ok(())
1248 }
1249
1250 pub fn restore(home: &Path, stamp: Option<&str>) -> Result<(String, RestoreReport)> {
1251 let folders = recovery_folders(home);
1252 let folder = match stamp {
1253 Some(stamp) => folders
1254 .into_iter()
1255 .find(|folder| folder.stamp == stamp)
1256 .with_context(|| {
1257 format!(
1258 "no recovery folder {stamp} under {}",
1259 home.join(RECOVERY_DIR).display()
1260 )
1261 })?,
1262 None => folders
1263 .into_iter()
1264 .rev()
1265 .find(|folder| !folder.records.is_empty())
1266 .context("there is no recovery folder to restore")?,
1267 };
1268 let mut report = RestoreReport::default();
1269 let mut remaining = Vec::new();
1270 let records: BTreeMap<_, _> = folder
1271 .records
1272 .iter()
1273 .map(|record| (record.original.as_path(), record))
1274 .collect();
1275 let directories: BTreeSet<_> = records
1276 .keys()
1277 .filter_map(|path| {
1278 path.parent().filter(|_| {
1279 path.file_name()
1280 .and_then(|s| s.to_str())
1281 .is_some_and(|name| name == RECEIPT_FILE || RECEIPT_COMMANDS.contains(&name))
1282 })
1283 })
1284 .collect();
1285 for record in records.values() {
1286 if let Some(expected) = &record.replacement_sha256 {
1287 let current = match fs::symlink_metadata(&record.original) {
1288 Ok(meta) => meta,
1289 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1290 Err(error) => return Err(error.into()),
1291 };
1292 if !current.is_file()
1293 || !owned_by(&current, owner_id(home))
1294 || file_sha256(&record.original)? != *expected
1295 {
1296 bail!("preserved modified command {}", record.original.display());
1297 }
1298 }
1299 }
1300 let mut receipts = Vec::new();
1301 for dir in directories {
1302 let receipt = dir.join(RECEIPT_FILE);
1303 let displace = command_receipt_to_displace(dir, &records, owner_id(home))?;
1304 let saved = records.get(receipt.as_path());
1305 if saved.is_some() || displace.is_some() {
1306 for name in RECEIPT_COMMANDS {
1307 if let Some(command) = records.get(dir.join(name).as_path())
1308 && !verified_recovery_file(&folder, command)?.is_file()
1309 {
1310 bail!(
1311 "saved command {} is not a regular file",
1312 command.stored.display()
1313 );
1314 }
1315 }
1316 }
1317 if let Some(saved) = saved {
1318 verified_recovery_file(&folder, saved)?;
1319 validate_saved_command_receipt(saved, &records)?;
1320 }
1321 if let Some(receipt) = displace {
1322 receipts.push(receipt);
1323 }
1324 }
1325 let mut displaced = None;
1326 if !receipts.is_empty() {
1327 let mut batch = RecoveryBatch::open(home)?;
1328 for receipt in &receipts {
1329 batch.move_in(&receipt.path)?;
1330 }
1331 displaced = Some(batch);
1332 }
1333 let mut ordered: Vec<_> = folder.records.iter().collect();
1334 ordered.sort_by_key(|record| {
1335 record
1336 .original
1337 .file_name()
1338 .is_some_and(|name| name == RECEIPT_FILE)
1339 });
1340 for record in ordered {
1341 let outcome = (|| -> Result<()> {
1342 let meta = verified_recovery_file(&folder, record)?;
1343 if record
1344 .original
1345 .file_name()
1346 .is_some_and(|name| name == RECEIPT_FILE)
1347 {
1348 validate_saved_command_receipt(record, &BTreeMap::new())?;
1349 }
1350 if let Ok(current) = fs::symlink_metadata(&record.original) {
1351 if !current.is_file() || !meta.is_file() {
1352 bail!("something else is at the original path now");
1353 }
1354 if displaced.is_none() {
1355 displaced = Some(RecoveryBatch::open(home)?);
1356 }
1357 let batch = displaced.as_mut().expect("batch was just opened");
1358 let replacement = record
1359 .original
1360 .file_name()
1361 .and_then(|name| name.to_str())
1362 .filter(|name| RECEIPT_COMMANDS.contains(name))
1363 .map(|_| file_sha256(&record.stored))
1364 .transpose()?;
1365 batch.move_in_replaced(&record.original, replacement.as_deref())?;
1366 }
1367 fs::rename(&record.stored, &record.original).context("move back failed")?;
1368 Ok(())
1369 })();
1370 match outcome {
1371 Ok(()) => report.restored.push(record.original.clone()),
1372 Err(error) => {
1373 if fs::symlink_metadata(&record.stored).is_ok() {
1374 remaining.push(record.clone());
1375 }
1376 report
1377 .skipped
1378 .push((record.original.clone(), format!("{error:#}")));
1379 }
1380 }
1381 }
1382 if let Some(batch) = displaced {
1383 let stamp = batch.stamp.clone();
1384 if !batch.finish().is_empty() {
1385 report.displaced = Some(stamp);
1386 }
1387 }
1388 for receipt in receipts {
1389 if !receipt.retained.is_empty()
1390 && !adopt_receipt(
1391 receipt.path.parent().context("receipt has no directory")?,
1392 &receipt.retained,
1393 )?
1394 {
1395 bail!("command ownership receipt changed during restore");
1396 }
1397 }
1398 rewrite_manifest(&folder.dir, &remaining)?;
1399 if remaining.is_empty() {
1400 let _ = fs::remove_file(folder.dir.join(RECOVERY_MANIFEST));
1401 let _ = fs::remove_dir(&folder.dir);
1402 }
1403 Ok((folder.stamp, report))
1404 }
1405
1406 fn rewrite_manifest(dir: &Path, records: &[RecoveryRecord]) -> Result<()> {
1407 let text: String = records
1408 .iter()
1409 .map(|record| {
1410 format!(
1411 "{}\t{}\t{}\t{}{}\n",
1412 record.original.display(),
1413 record.stored.display(),
1414 record.sha256.as_deref().unwrap_or("-"),
1415 record.bytes,
1416 record
1417 .replacement_sha256
1418 .as_ref()
1419 .map(|digest| format!("\t{digest}"))
1420 .unwrap_or_default()
1421 )
1422 })
1423 .collect();
1424 write_file_atomically(dir, RECOVERY_MANIFEST, text.as_bytes(), false)
1425 .context("failed to replace the recovery manifest")
1426 }
1427
1428 fn sync_dir(dir: &Path) {
1429 #[cfg(unix)]
1430 let _ = fs::File::open(dir).and_then(|file| file.sync_all());
1431 #[cfg(not(unix))]
1432 let _ = dir;
1433 }
1434
1435 pub fn prune_expired(home: &Path) -> Vec<(String, u64)> {
1436 let now = now_unix();
1437 let mut pruned = Vec::new();
1438 for folder in recovery_folders(home) {
1439 let Some(created) = folder.created_unix else {
1440 continue;
1441 };
1442 if now.saturating_sub(created) < RECOVERY_RETENTION_DAYS * 86_400 {
1443 continue;
1444 }
1445 let mut complete = true;
1446 for record in &folder.records {
1447 if !stored_inside_recovery(&folder, &record.stored) {
1448 complete = false;
1449 continue;
1450 }
1451 let meta = match fs::symlink_metadata(&record.stored) {
1452 Ok(meta) => meta,
1453 Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
1454 Err(_) => {
1455 complete = false;
1456 continue;
1457 }
1458 };
1459 let removed = if meta.is_dir() {
1460 fs::remove_dir_all(&record.stored)
1461 } else {
1462 fs::remove_file(&record.stored)
1463 };
1464 complete &= removed.is_ok();
1465 if let Some(parent) = record.stored.parent()
1466 && !parent.starts_with(&folder.dir)
1467 {
1468 let _ = fs::remove_dir(parent);
1469 if let Some(volume) = parent.parent() {
1470 let _ = fs::remove_dir(volume);
1471 }
1472 }
1473 }
1474 if complete {
1475 let _ = fs::remove_file(folder.dir.join(RECOVERY_MANIFEST));
1476 if fs::remove_dir(&folder.dir).is_ok() {
1477 pruned.push((folder.stamp.clone(), folder.bytes()));
1478 }
1479 }
1480 }
1481 pruned
1482 }
1483
1484 pub fn adopt_receipt(directory: &Path, entries: &[(String, String)]) -> Result<bool> {
1485 let receipt = directory.join(RECEIPT_FILE);
1486 if fs::symlink_metadata(&receipt).is_ok() {
1487 return Ok(false);
1488 }
1489 if !directory_is_private(directory) {
1490 bail!(
1491 "{} is writable by group or others, so a receipt there could not be trusted by `codewhale uninstall`; run `chmod go-w {}` first",
1492 directory.display(),
1493 directory.display()
1494 );
1495 }
1496 if entries.is_empty() {
1497 bail!("no commands to record in a receipt");
1498 }
1499 let mut seen = BTreeSet::new();
1500 let mut text = String::new();
1501 for (name, digest) in entries {
1502 if !seen.insert(name.clone()) {
1503 continue;
1504 }
1505 let path = directory.join(name);
1506 let meta = fs::symlink_metadata(&path)?;
1507 if !meta.is_file() || &file_sha256(&path)? != digest {
1508 bail!("{} changed while writing its receipt", path.display());
1509 }
1510 text.push_str(&format!("{digest} {name}\n"));
1511 }
1512 let tmp = directory.join(format!(".codewhale-receipt.{}", std::process::id()));
1513 let mut file = fs::OpenOptions::new()
1514 .write(true)
1515 .create_new(true)
1516 .open(&tmp)
1517 .with_context(|| format!("failed to create {}", tmp.display()))?;
1518 let written = file
1519 .write_all(text.as_bytes())
1520 .and_then(|()| file.sync_all());
1521 drop(file);
1522 let published = written.and_then(|()| fs::hard_link(&tmp, &receipt));
1523 let _ = fs::remove_file(&tmp);
1524 match published {
1525 Ok(()) => Ok(true),
1526 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
1527 Err(error) => Err(error).with_context(|| format!("failed to write {}", receipt.display())),
1528 }
1529 }
1530
1531 pub fn write_file_atomically(dir: &Path, name: &str, bytes: &[u8], executable: bool) -> Result<()> {
1532 fs::create_dir_all(dir).with_context(|| format!("failed to create {}", dir.display()))?;
1533 let mut tmp = tempfile::Builder::new()
1534 .prefix(&format!(".{name}.tmp-"))
1535 .tempfile_in(dir)
1536 .with_context(|| format!("failed to create temp file in {}", dir.display()))?;
1537 tmp.write_all(bytes)
1538 .with_context(|| format!("failed to write {}", tmp.path().display()))?;
1539 #[cfg(unix)]
1540 if executable {
1541 use std::os::unix::fs::PermissionsExt;
1542 tmp.as_file()
1543 .set_permissions(fs::Permissions::from_mode(0o755))
1544 .with_context(|| format!("failed to mark {} executable", tmp.path().display()))?;
1545 }
1546 #[cfg(not(unix))]
1547 let _ = executable;
1548 tmp.as_file()
1549 .sync_all()
1550 .with_context(|| format!("failed to sync {}", tmp.path().display()))?;
1551 let target = dir.join(name);
1552 tmp.persist(&target)
1553 .map_err(|error| error.error)
1554 .with_context(|| format!("failed to write {}", target.display()))?;
1555 sync_dir(dir);
1556 Ok(())
1557 }
1558
1559 #[cfg(unix)]
1560 #[must_use]
1561 pub fn directory_is_private(directory: &Path) -> bool {
1562 use std::os::unix::fs::MetadataExt;
1563 fs::metadata(directory).is_ok_and(|meta| meta.mode() & 0o022 == 0)
1564 }
1565
1566 #[cfg(not(unix))]
1567 #[must_use]
1568 pub fn directory_is_private(_directory: &Path) -> bool {
1569 true
1570 }
1571
1572 #[cfg(test)]
1573 mod npm_family_tests {
1574 use super::*;
1575
1576 #[test]
1577 fn npm_compatible_managers_get_their_own_command() {
1578 let pnpm =
1579 Path::new("/home/u/.local/share/pnpm/global/5/node_modules/codewhale/bin/codewhale");
1580 assert_eq!(
1581 update_answer(InstallMethod::Npm, pnpm),
1582 "This copy belongs to pnpm, so it cannot update itself; update it with `pnpm add -g codewhale@latest`."
1583 );
1584 let bun = Path::new("/home/u/.bun/install/global/node_modules/codewhale/bin/codewhale");
1585 assert!(update_answer(InstallMethod::Npm, bun).contains("`bun add -g codewhale@latest`"));
1586 }
1587 }
1588
1589 #[cfg(test)]
1590 mod cargo_record_tests {
1591 use super::*;
1592
1593 fn cargo_bin(record: impl FnOnce(&Path)) -> (tempfile::TempDir, PathBuf) {
1594 let root = tempfile::tempdir().unwrap();
1595 let cargo = root.path().join(".cargo");
1596 let bin = cargo.join("bin");
1597 fs::create_dir_all(&bin).unwrap();
1598 record(&cargo);
1599 let exe = bin.join("codewhale");
1600 fs::write(&exe, b"binary").unwrap();
1601 (root, exe)
1602 }
1603
1604 fn agree(exe: &Path) -> (InstallMethod, Option<InstallClass>) {
1605 (
1606 InstallMethod::detect(exe),
1607 classify(exe, "codewhale", None, None),
1608 )
1609 }
1610
1611 #[test]
1612 fn unreadable_cargo_record_is_cargo_for_update_and_inventory() {
1613 let (_root, exe) = cargo_bin(|cargo| fs::create_dir(cargo.join(".crates.toml")).unwrap());
1614 let (method, class) = agree(&exe);
1615 assert_eq!(method, InstallMethod::Cargo);
1616 assert_eq!(
1617 class,
1618 Some(InstallClass::PackageManaged(InstallMethod::Cargo))
1619 );
1620 }
1621
1622 #[test]
1623 fn record_listing_another_crate_leaves_the_file_ours_for_update_and_inventory() {
1624 let (_root, exe) = cargo_bin(|cargo| {
1625 fs::write(
1626 cargo.join(".crates.toml"),
1627 b"[v1]\n\"other 0.1.0 (path+file:///src/other)\" = [\"other-bin\"]\n",
1628 )
1629 .unwrap();
1630 });
1631 let (method, class) = agree(&exe);
1632 assert!(method.supports_self_update());
1633 assert!(!matches!(class, Some(InstallClass::PackageManaged(_))));
1634 }
1635
1636 #[test]
1637 fn cargo_owns_only_the_names_its_record_lists_in_the_inventory() {
1638 let root = tempfile::tempdir().unwrap();
1639 let bin = root.path().join("bin");
1640 fs::create_dir_all(&bin).unwrap();
1641 let name = format!("codewhale{}", std::env::consts::EXE_SUFFIX);
1642 fs::write(
1643 root.path().join(".crates.toml"),
1644 format!(
1645 "[v1]\n\"codewhale-cli 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)\" = [\"{name}\"]\n"
1646 ),
1647 )
1648 .unwrap();
1649 let listed = bin.join(&name);
1650 let backup = bin.join("codewhale.bak-1");
1651 let staging = bin.join(".codewhale-update-1");
1652 fs::write(&listed, b"binary").unwrap();
1653 fs::write(&backup, b"binary").unwrap();
1654 fs::create_dir(&staging).unwrap();
1655 assert_eq!(
1656 classify(&listed, &name, None, None),
1657 Some(InstallClass::PackageManaged(InstallMethod::Cargo))
1658 );
1659 for (path, name) in [
1660 (&backup, "codewhale.bak-1"),
1661 (&staging, ".codewhale-update-1"),
1662 ] {
1663 assert!(
1664 !matches!(
1665 classify(path, name, None, None),
1666 Some(InstallClass::PackageManaged(_))
1667 ),
1668 "{name}"
1669 );
1670 }
1671 }
1672
1673 #[test]
1674 fn cargo_bin_without_a_record_is_judged_by_name_in_the_inventory() {
1675 let (_root, exe) = cargo_bin(|_| {});
1676 assert_eq!(InstallMethod::detect(&exe), InstallMethod::Cargo);
1677 assert!(!matches!(
1678 classify(&exe, "codewhale", None, None),
1679 Some(InstallClass::PackageManaged(_))
1680 ));
1681 }
1682 }
1683
1684 #[cfg(test)]
1685 mod receipt_file_tests {
1686 use super::*;
1687
1688 #[test]
1689 fn the_install_receipt_is_not_a_leftover() {
1690 let dir = tempfile::tempdir().unwrap();
1691 let receipt = dir.path().join(RECEIPT_FILE);
1692 fs::write(&receipt, b"abc codewhale\n").unwrap();
1693 assert_eq!(classify(&receipt, RECEIPT_FILE, None, None), None);
1694 }
1695 }
1696
1696 lines RUST