From de22a7f4f559f129fb909d67ef073687fc73fb94 Mon Sep 17 00:00:00 2001 From: Alexander Sergeev Date: Sun, 29 Sep 2024 20:11:57 +0300 Subject: [PATCH] Add Ctrl+C handler on windows --- src/bin/cargo/main.rs | 24 ++++++++++++++++++++++++ src/cargo/util/mod.rs | 2 +- src/cargo/util/progress.rs | 2 +- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/bin/cargo/main.rs b/src/bin/cargo/main.rs index 5dbf9363460..81e41de2644 100644 --- a/src/bin/cargo/main.rs +++ b/src/bin/cargo/main.rs @@ -28,6 +28,7 @@ fn main() { } }; + let _ = ctrlc::set(); let result = if let Some(lock_addr) = cargo::ops::fix_get_proxy_lock_addr() { cargo::ops::fix_exec_rustc(&gctx, &lock_addr).map_err(|e| CliError::from(e)) } else { @@ -41,6 +42,29 @@ fn main() { } } +#[cfg(windows)] +mod ctrlc { + use super::ProcessError; + use anyhow::Result; + use cargo::util::TaskbarProgress; + use windows_sys::Win32::Foundation::{BOOL, FALSE, TRUE}; + use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; + + unsafe extern "system" fn ctrlc_handler(_: u32) -> BOOL { + eprintln!("{}", TaskbarProgress::None); + std::process::exit(0); + } + + pub fn set() -> Result<()> { + unsafe { + if SetConsoleCtrlHandler(Some(ctrlc_handler), TRUE) == FALSE { + return Err(ProcessError::new("Could not set Ctrl-C handler.", None, None).into()); + } + } + Ok(()) + } +} + fn setup_logger() -> Option { use tracing_subscriber::prelude::*; diff --git a/src/cargo/util/mod.rs b/src/cargo/util/mod.rs index 7b32f108fa7..3feec5b5219 100644 --- a/src/cargo/util/mod.rs +++ b/src/cargo/util/mod.rs @@ -18,7 +18,7 @@ pub use self::into_url::IntoUrl; pub use self::into_url_with_base::IntoUrlWithBase; pub(crate) use self::io::LimitErrorReader; pub use self::lockserver::{LockServer, LockServerClient, LockServerStarted}; -pub use self::progress::{Progress, ProgressStyle}; +pub use self::progress::{Progress, ProgressStyle, TaskbarProgress}; pub use self::queue::Queue; pub use self::rustc::Rustc; pub use self::semver_ext::{OptVersionReq, VersionExt}; diff --git a/src/cargo/util/progress.rs b/src/cargo/util/progress.rs index 89d7eeb25c9..56e0b792e35 100644 --- a/src/cargo/util/progress.rs +++ b/src/cargo/util/progress.rs @@ -76,7 +76,7 @@ struct Format { max_print: usize, } -enum TaskbarProgress { +pub enum TaskbarProgress { None, Value(u8), Error,