返回 CodeWhale
update.rs
根目录 / crates / tui / src / commands / groups / utility / update.rs
1 //! `/update` — check for and install a new CodeWhale release without leaving
2 //! the TUI.
3 //!
4 //! The updater itself is not reimplemented here. `codewhale update` (see
5 //! `crates/cli/src/update.rs`) already resolves the release, downloads the
6 //! platform-correct asset, verifies its SHA256, and atomically replaces the
7 //! running binary; this command finds that binary and runs it. Duplicating any
8 //! of that logic would give us two updaters to keep honest.
9 //!
10 //! Two deliberate limits:
11 //!
12 //! * **Package-managed installs get instructions, not an updater run.**
13 //! Overwriting a binary Homebrew, npm, or cargo owns leaves the manager's
14 //! metadata describing a version that is no longer on disk, and the next
15 //! upgrade silently reverts the user.
16 //! * **We do not relaunch.** This codebase has no self-exec/relaunch pattern,
17 //! and inventing one under a TUI holding the terminal is not a small change.
18 //! Telling the user to restart is the honest slice; that is also the only
19 //! possible answer on Windows, where the replaced image is the one running.
20
21 use std::io::Read;
22 use std::path::{Path, PathBuf};
23 use std::process::{Command, Output, Stdio};
24 use std::sync::atomic::{AtomicBool, Ordering};
25 use std::thread::JoinHandle;
26 use std::time::Duration;
27
28 use codewhale_command_contract::facets::{BackgroundCancel, BackgroundRequest};
29 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
30 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
31 use codewhale_command_contract::outcome::BackgroundCommandResult;
32 use codewhale_release::InstallMethod;
33
34 use crate::commands::CommandResult;
35
36 pub(in crate::commands) const COMMAND_INFO: CommandInfo = CommandInfo {
37 name: "update",
38 aliases: &["upgrade"],
39 usage: "/update [check|install|cancel]",
40 description_key: "cmd_update_description",
41 };
42
43 pub(in crate::commands) struct UpdateCmd;
44
45 impl RegisterCommand<CommandResult> for UpdateCmd {
46 fn info() -> &'static CommandInfo {
47 &COMMAND_INFO
48 }
49
50 fn handler() -> CommandHandler<CommandResult> {
51 CommandHandler::Contextual {
52 capabilities: CommandCapabilities::BACKGROUND,
53 handler: update,
54 }
55 }
56 }
57
58 /// What `/update` was asked to do.
59 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
60 pub(super) enum UpdateMode {
61 /// Explain what an install would do, and ask the updater whether one is
62 /// available. The default: `/update` never installs without being told to.
63 Check,
64 /// Actually run the updater.
65 Install,
66 }
67
68 fn is_cancel(arg: Option<&str>) -> bool {
69 arg.is_some_and(|arg| matches!(arg.trim().to_ascii_lowercase().as_str(), "cancel" | "stop"))
70 }
71
72 fn parse_mode(arg: Option<&str>) -> Result<UpdateMode, String> {
73 match arg
74 .map(str::trim)
75 .unwrap_or("")
76 .to_ascii_lowercase()
77 .as_str()
78 {
79 "" | "check" | "status" => Ok(UpdateMode::Check),
80 "install" | "now" | "apply" | "yes" => Ok(UpdateMode::Install),
81 other => Err(format!(
82 "Unknown /update argument {other:?}. Usage: {}",
83 COMMAND_INFO.usage
84 )),
85 }
86 }
87
88 /// How this install can be updated, resolved before anything runs.
89 #[derive(Debug, Clone, PartialEq, Eq)]
90 pub(super) enum UpdaterPlan {
91 /// Run this `codewhale` binary's `update` subcommand.
92 Run(PathBuf),
93 /// A package manager owns the binary; print its command instead.
94 Managed(InstallMethod),
95 /// Self-update would be correct, but no `codewhale` CLI is reachable —
96 /// e.g. a bare `codewhale-tui` build with no sibling CLI.
97 NoUpdater { exe: PathBuf },
98 }
99
100 /// The primary binary name. `codew` carries the same CLI and update subcommand.
101 const UPDATER_BIN_STEM: &str = "codewhale";
102
103 /// Resolve the update path without touching the process environment, so the
104 /// decision is testable. `exists` answers whether a candidate path is a file.
105 pub(super) fn resolve_updater(
106 exe: Option<&Path>,
107 method: InstallMethod,
108 exists: &dyn Fn(&Path) -> bool,
109 ) -> UpdaterPlan {
110 if !method.supports_self_update() {
111 return UpdaterPlan::Managed(method);
112 }
113 // No resolvable executable path is not a reason to guess at one: report it
114 // as "no updater here" and let the user run the CLI themselves.
115 let Some(exe) = exe else {
116 return UpdaterPlan::NoUpdater {
117 exe: PathBuf::from(UPDATER_BIN_STEM),
118 };
119 };
120 if matches!(
121 exe.file_stem().and_then(|stem| stem.to_str()),
122 Some(UPDATER_BIN_STEM | "codew")
123 ) {
124 return UpdaterPlan::Run(exe.to_path_buf());
125 }
126 // A `codewhale-tui` build has no `update` subcommand, but the CLI that
127 // does is normally installed right next to it.
128 if let Some(dir) = exe.parent() {
129 let extension = exe.extension().and_then(|ext| ext.to_str());
130 let mut sibling = dir.join(UPDATER_BIN_STEM);
131 if let Some(extension) = extension {
132 sibling.set_extension(extension);
133 }
134 if exists(&sibling) {
135 return UpdaterPlan::Run(sibling);
136 }
137 }
138 UpdaterPlan::NoUpdater {
139 exe: exe.to_path_buf(),
140 }
141 }
142
143 /// Instructions for an install this command must not update in place.
144 pub(super) fn managed_install_message(method: InstallMethod, exe: Option<&Path>) -> String {
145 format!(
146 "{} Restart Codewhale after updating.",
147 codewhale_release::installs::update_answer(
148 method,
149 exe.unwrap_or(Path::new(UPDATER_BIN_STEM))
150 )
151 )
152 }
153
154 /// Instructions when self-update is right but no updater binary is reachable.
155 pub(super) fn no_updater_message(exe: &Path) -> String {
156 format!(
157 "No `{UPDATER_BIN_STEM}` updater was found for this install ({exe}).\n\
158 The updater ships in the `{UPDATER_BIN_STEM}` CLI. Install or locate it, run \
159 `{UPDATER_BIN_STEM} update` in a shell, then restart Codewhale.",
160 exe = exe.display(),
161 )
162 }
163
164 /// What an install would do, stated before it is done.
165 fn install_preamble(updater: &Path) -> String {
166 format!(
167 "`/update install` will run `{updater} update`: it resolves the latest release, \
168 downloads the binary for this platform, verifies its SHA256 checksum, and atomically \
169 replaces {updater}.\n\
170 It does not restart Codewhale — you will need to do that yourself once it finishes. \
171 The updater runs in the background and reports here when it is done; \
172 `/update cancel` stops it.",
173 updater = updater.display(),
174 )
175 }
176
177 fn update(mut contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
178 let background = contexts.take_background();
179 if is_cancel(arg) {
180 return match background {
181 Some(background) => background
182 .cancel(COMMAND_INFO.name)
183 .map_or_else(CommandResult::error, CommandResult::message),
184 None => CommandResult::error("Command capability unavailable: background"),
185 };
186 }
187 let mode = match parse_mode(arg) {
188 Ok(mode) => mode,
189 Err(message) => return CommandResult::error(message),
190 };
191
192 let exe = std::env::current_exe().ok();
193 let method = match exe.as_deref() {
194 Some(path) => InstallMethod::detect(path),
195 None => InstallMethod::Binary,
196 };
197
198 match resolve_updater(exe.as_deref(), method, &|path: &Path| path.is_file()) {
199 UpdaterPlan::Managed(method) => {
200 CommandResult::message(managed_install_message(method, exe.as_deref()))
201 }
202 UpdaterPlan::NoUpdater { exe } => CommandResult::message(no_updater_message(&exe)),
203 UpdaterPlan::Run(updater) => match background {
204 Some(background) => background
205 .start(
206 COMMAND_INFO.name,
207 update_job,
208 BackgroundRequest {
209 updater,
210 argument: arg.unwrap_or_default().to_string(),
211 ..BackgroundRequest::default()
212 },
213 )
214 .map_or_else(CommandResult::error, CommandResult::message),
215 None => crate::commands::contract::run_owner_blocking(move || {
216 Ok(run_updater(&updater, mode))
217 })
218 .unwrap_or_else(CommandResult::error),
219 },
220 }
221 }
222
223 fn updater_command(updater: &Path, mode: UpdateMode) -> Command {
224 let mut command = Command::new(updater);
225 command.arg("update");
226 if mode == UpdateMode::Check {
227 command.arg("--check");
228 }
229 command
230 }
231
232 fn run_updater(updater: &Path, mode: UpdateMode) -> CommandResult {
233 updater_result(updater, mode, updater_command(updater, mode).output())
234 }
235
236 fn update_job(request: BackgroundRequest, cancel: BackgroundCancel) -> BackgroundCommandResult {
237 let mode = match parse_mode(Some(&request.argument)) {
238 Ok(mode) => mode,
239 Err(message) => return BackgroundCommandResult::error(message),
240 };
241 let updater = request.updater;
242 match run_until_cancelled(updater_command(&updater, mode), &cancel) {
243 Some(output) => updater_result(&updater, mode, output),
244 None => {
245 BackgroundCommandResult::error(format!("`{} update` was cancelled.", updater.display()))
246 }
247 }
248 }
249
250 const CANCEL_POLL: Duration = Duration::from_millis(50);
251
252 fn run_until_cancelled(
253 mut command: Command,
254 cancel: &AtomicBool,
255 ) -> Option<std::io::Result<Output>> {
256 command
257 .stdin(Stdio::null())
258 .stdout(Stdio::piped())
259 .stderr(Stdio::piped());
260 let mut child = match command.spawn() {
261 Ok(child) => child,
262 Err(err) => return Some(Err(err)),
263 };
264 let stdout = child.stdout.take().map(drain);
265 let stderr = child.stderr.take().map(drain);
266 loop {
267 if cancel.load(Ordering::SeqCst) {
268 let _ = child.kill();
269 let _ = child.wait();
270 return None;
271 }
272 match child.try_wait() {
273 Ok(Some(status)) => {
274 return Some(Ok(Output {
275 status,
276 stdout: collected(stdout),
277 stderr: collected(stderr),
278 }));
279 }
280 Ok(None) => std::thread::sleep(CANCEL_POLL),
281 Err(err) => {
282 let _ = child.kill();
283 let _ = child.wait();
284 return Some(Err(err));
285 }
286 }
287 }
288 }
289
290 fn drain(mut pipe: impl Read + Send + 'static) -> JoinHandle<Vec<u8>> {
291 std::thread::spawn(move || {
292 let mut bytes = Vec::new();
293 let _ = pipe.read_to_end(&mut bytes);
294 bytes
295 })
296 }
297
298 fn collected(reader: Option<JoinHandle<Vec<u8>>>) -> Vec<u8> {
299 reader
300 .and_then(|reader| reader.join().ok())
301 .unwrap_or_default()
302 }
303
304 fn updater_result<A>(
305 updater: &Path,
306 mode: UpdateMode,
307 output: std::io::Result<Output>,
308 ) -> codewhale_command_contract::outcome::CommandResult<A> {
309 use codewhale_command_contract::outcome::CommandResult;
310
311 let output = match output {
312 Ok(output) => output,
313 Err(err) => {
314 return CommandResult::error(format!(
315 "Failed to run `{} update`: {err}\nRun it in a shell instead, then restart Codewhale.",
316 updater.display()
317 ));
318 }
319 };
320
321 let transcript = updater_transcript(&output.stdout, &output.stderr);
322 if !output.status.success() {
323 return CommandResult::error(format!(
324 "`{updater} update` failed.\n{transcript}",
325 updater = updater.display()
326 ));
327 }
328
329 match mode {
330 UpdateMode::Check => {
331 CommandResult::message(format!("{}\n\n{transcript}", install_preamble(updater)))
332 }
333 UpdateMode::Install => CommandResult::message(format!(
334 "{transcript}\n\nRestart Codewhale to run the updated binary."
335 )),
336 }
337 }
338
339 /// Merge the updater's streams into one readable block, bounded so a pathological
340 /// run cannot flood the transcript.
341 fn updater_transcript(stdout: &[u8], stderr: &[u8]) -> String {
342 const MAX_CHARS: usize = 4_000;
343 let mut merged = String::new();
344 for stream in [stdout, stderr] {
345 let text = String::from_utf8_lossy(stream);
346 let text = text.trim();
347 if text.is_empty() {
348 continue;
349 }
350 if !merged.is_empty() {
351 merged.push('\n');
352 }
353 merged.push_str(text);
354 }
355 if merged.is_empty() {
356 return "(the updater printed nothing)".to_string();
357 }
358 if merged.chars().count() > MAX_CHARS {
359 let kept: String = merged.chars().take(MAX_CHARS).collect();
360 return format!("{kept}\n… output truncated.");
361 }
362 merged
363 }
364
365 #[cfg(test)]
366 mod tests {
367 use super::*;
368
369 #[test]
370 fn bare_and_explicit_modes_parse() {
371 assert_eq!(parse_mode(None), Ok(UpdateMode::Check));
372 assert_eq!(parse_mode(Some(" ")), Ok(UpdateMode::Check));
373 assert_eq!(parse_mode(Some("Check")), Ok(UpdateMode::Check));
374 assert_eq!(parse_mode(Some("install")), Ok(UpdateMode::Install));
375 assert_eq!(parse_mode(Some("NOW")), Ok(UpdateMode::Install));
376 assert!(parse_mode(Some("--force")).is_err());
377 }
378
379 #[test]
380 fn a_package_managed_install_gets_its_managers_command_not_an_updater_run() {
381 for method in [
382 InstallMethod::Npm,
383 InstallMethod::Homebrew,
384 InstallMethod::Cargo,
385 InstallMethod::Omarchy,
386 ] {
387 let plan = resolve_updater(
388 Some(Path::new("/opt/whatever/codewhale")),
389 method,
390 &|_: &Path| true,
391 );
392 assert_eq!(plan, UpdaterPlan::Managed(method), "{method:?}");
393
394 let message =
395 managed_install_message(method, Some(Path::new("/opt/whatever/codewhale")));
396 assert!(
397 message.contains(method.update_command()),
398 "{method:?} message must name its own update command: {message}"
399 );
400 assert!(
401 message.contains("Restart Codewhale"),
402 "{method:?} message must tell the user to restart: {message}"
403 );
404 }
405 }
406
407 #[test]
408 fn a_tui_only_build_without_a_sibling_cli_falls_back_to_instructions() {
409 let exe = Path::new("/usr/local/bin/codewhale-tui");
410 let plan = resolve_updater(Some(exe), InstallMethod::Binary, &|_: &Path| false);
411 assert_eq!(
412 plan,
413 UpdaterPlan::NoUpdater {
414 exe: exe.to_path_buf()
415 }
416 );
417
418 let message = no_updater_message(exe);
419 assert!(message.contains("codewhale update"), "{message}");
420 assert!(message.contains("restart Codewhale"), "{message}");
421 assert!(message.contains("codewhale-tui"), "{message}");
422 }
423
424 #[test]
425 fn a_tui_build_next_to_the_cli_runs_the_sibling_updater() {
426 let plan = resolve_updater(
427 Some(Path::new("/usr/local/bin/codewhale-tui")),
428 InstallMethod::Binary,
429 &|path: &Path| path == Path::new("/usr/local/bin/codewhale"),
430 );
431 assert_eq!(
432 plan,
433 UpdaterPlan::Run(PathBuf::from("/usr/local/bin/codewhale"))
434 );
435 }
436
437 #[test]
438 fn a_cli_install_runs_itself_including_the_windows_extension() {
439 assert_eq!(
440 resolve_updater(
441 Some(Path::new("/usr/local/bin/codewhale")),
442 InstallMethod::Binary,
443 &|_: &Path| false
444 ),
445 UpdaterPlan::Run(PathBuf::from("/usr/local/bin/codewhale"))
446 );
447 // Forward slashes so the case is meaningful on the host running the
448 // test: `\` is a plain filename character to a Unix `Path`, which
449 // would make this assert about nothing.
450 assert_eq!(
451 resolve_updater(
452 Some(Path::new("C:/tools/codewhale.exe")),
453 InstallMethod::Binary,
454 &|_: &Path| false
455 ),
456 UpdaterPlan::Run(PathBuf::from("C:/tools/codewhale.exe"))
457 );
458 }
459
460 #[test]
461 fn standalone_codew_uses_its_own_updater_without_a_companion() {
462 for exe in ["/usr/local/bin/codew", "C:/tools/codew.exe"] {
463 let exe = Path::new(exe);
464 assert_eq!(
465 resolve_updater(Some(exe), InstallMethod::Binary, &|_| {
466 panic!("the full codew CLI must not look for another installation")
467 }),
468 UpdaterPlan::Run(exe.to_path_buf())
469 );
470 }
471 }
472
473 #[test]
474 fn a_windows_tui_build_finds_the_sibling_cli_with_its_extension() {
475 assert_eq!(
476 resolve_updater(
477 Some(Path::new("C:/tools/codewhale-tui.exe")),
478 InstallMethod::Binary,
479 &|path: &Path| path == Path::new("C:/tools/codewhale.exe"),
480 ),
481 UpdaterPlan::Run(PathBuf::from("C:/tools/codewhale.exe"))
482 );
483 }
484
485 #[test]
486 fn an_unresolvable_executable_reports_no_updater_instead_of_guessing() {
487 assert_eq!(
488 resolve_updater(None, InstallMethod::Binary, &|_: &Path| true),
489 UpdaterPlan::NoUpdater {
490 exe: PathBuf::from("codewhale")
491 }
492 );
493 }
494
495 #[test]
496 fn the_check_preamble_states_what_install_would_do() {
497 let preamble = install_preamble(Path::new("/usr/local/bin/codewhale"));
498 assert!(
499 preamble.contains("/usr/local/bin/codewhale update"),
500 "{preamble}"
501 );
502 assert!(preamble.contains("SHA256"), "{preamble}");
503 assert!(preamble.contains("does not restart"), "{preamble}");
504 assert!(preamble.contains("/update cancel"), "{preamble}");
505 }
506
507 #[test]
508 fn updater_output_is_merged_and_bounded() {
509 assert_eq!(updater_transcript(b" out ", b""), "out");
510 assert_eq!(updater_transcript(b"out", b"err"), "out\nerr");
511 assert_eq!(
512 updater_transcript(b"", b" "),
513 "(the updater printed nothing)"
514 );
515
516 let flood = "x".repeat(9_000);
517 let bounded = updater_transcript(flood.as_bytes(), b"");
518 assert!(bounded.ends_with("… output truncated."));
519 assert!(bounded.chars().count() < flood.chars().count());
520 }
521
522 #[derive(Default)]
523 struct Background {
524 cancelled: Vec<&'static str>,
525 }
526
527 impl codewhale_command_contract::facets::CommandBackgroundContext for Background {
528 fn start(
529 &mut self,
530 command: &'static str,
531 _job: codewhale_command_contract::facets::BackgroundJob,
532 _request: BackgroundRequest,
533 ) -> Result<String, String> {
534 Err(format!("/{command} must not start in this test"))
535 }
536
537 fn cancel(&mut self, command: &'static str) -> Result<String, String> {
538 self.cancelled.push(command);
539 Ok(format!("/{command} cancelled"))
540 }
541 }
542
543 #[test]
544 fn cancel_goes_to_the_background_facet_and_never_reaches_the_updater() {
545 assert!(is_cancel(Some(" Cancel ")));
546 assert!(is_cancel(Some("stop")));
547 assert!(!is_cancel(None));
548 assert!(!is_cancel(Some("install")));
549
550 let mut background = Background::default();
551 let result = update(
552 CommandContexts::empty().with_background(&mut background),
553 Some("cancel"),
554 );
555 assert!(!result.is_error, "{result:?}");
556 assert_eq!(result.message.as_deref(), Some("/update cancelled"));
557 assert_eq!(background.cancelled, ["update"]);
558
559 let unavailable = update(CommandContexts::empty(), Some("cancel"));
560 assert!(unavailable.is_error, "{unavailable:?}");
561 }
562
563 #[test]
564 fn an_updater_that_cannot_be_spawned_is_reported_as_the_commands_error() {
565 let result: BackgroundCommandResult = updater_result(
566 Path::new("/usr/local/bin/codewhale"),
567 UpdateMode::Install,
568 Err(std::io::Error::other("no such file")),
569 );
570 assert!(result.is_error);
571 assert!(result.action.is_none());
572 let message = result.message.expect("error message");
573 assert!(
574 message.contains("/usr/local/bin/codewhale update"),
575 "{message}"
576 );
577 assert!(message.contains("no such file"), "{message}");
578 }
579
580 #[test]
581 fn a_background_updater_job_reports_a_missing_binary() {
582 let missing = std::env::temp_dir().join("codewhale-update-test-missing-binary");
583 let result = update_job(
584 BackgroundRequest {
585 updater: missing.clone(),
586 argument: "check".to_string(),
587 ..BackgroundRequest::default()
588 },
589 BackgroundCancel::default(),
590 );
591 assert!(result.is_error);
592 assert!(
593 result
594 .message
595 .expect("error message")
596 .contains(&missing.display().to_string())
597 );
598 }
599
600 #[cfg(unix)]
601 #[test]
602 fn a_finished_child_returns_its_output() {
603 let mut command = Command::new("sh");
604 command.args(["-c", "echo out; echo err >&2"]);
605 let output = run_until_cancelled(command, &AtomicBool::new(false))
606 .expect("not cancelled")
607 .expect("spawned");
608 assert!(output.status.success());
609 assert_eq!(
610 updater_transcript(&output.stdout, &output.stderr),
611 "out\nerr"
612 );
613 }
614
615 #[cfg(unix)]
616 #[test]
617 fn cancelling_kills_and_reaps_the_running_updater() {
618 let cancel = BackgroundCancel::default();
619 let trigger = cancel.clone();
620 let canceller = std::thread::spawn(move || {
621 std::thread::sleep(Duration::from_millis(100));
622 trigger.store(true, Ordering::SeqCst);
623 });
624 let mut command = Command::new("sleep");
625 command.arg("30");
626 let started = std::time::Instant::now();
627 assert!(run_until_cancelled(command, &cancel).is_none());
628 assert!(
629 started.elapsed() < Duration::from_secs(5),
630 "the child was killed, not waited out: {:?}",
631 started.elapsed()
632 );
633 canceller.join().unwrap();
634 }
635
636 #[test]
637 fn handler_declares_only_the_background_facet() {
638 let CommandHandler::Contextual { capabilities, .. } = UpdateCmd::handler() else {
639 panic!("/update must be contextual");
640 };
641 assert_eq!(capabilities, CommandCapabilities::BACKGROUND);
642 assert_eq!(UpdateCmd::info().description_key, "cmd_update_description");
643 assert_eq!(UpdateCmd::info().aliases, &["upgrade"]);
644 }
645 }
646
646 lines RUST