Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle Ctrl-C explicitly in confirm prompt #11706

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 99 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion crates/uv-console/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@ doctest = false
workspace = true

[dependencies]
ctrlc = { workspace = true }
console = { workspace = true }
37 changes: 13 additions & 24 deletions crates/uv-console/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,6 @@ use std::{cmp::Ordering, iter};
/// This is a slimmed-down version of `dialoguer::Confirm`, with the post-confirmation report
/// enabled.
pub fn confirm(message: &str, term: &Term, default: bool) -> std::io::Result<bool> {
// Set the Ctrl-C handler to exit the process.
let result = ctrlc::set_handler(move || {
let term = Term::stderr();
term.show_cursor().ok();
term.flush().ok();

#[allow(clippy::exit, clippy::cast_possible_wrap)]
std::process::exit(if cfg!(windows) {
0xC000_013A_u32 as i32
} else {
130
});
});

match result {
Ok(()) => {}
Err(ctrlc::Error::MultipleHandlers) => {
// If multiple handlers were set, we assume that the existing handler is our
// confirmation handler, and continue.
}
Err(err) => return Err(std::io::Error::new(std::io::ErrorKind::Other, err)),
}

let prompt = format!(
"{} {} {} {} {}",
style("?".to_string()).for_stderr().yellow(),
Expand All @@ -47,11 +24,23 @@ pub fn confirm(message: &str, term: &Term, default: bool) -> std::io::Result<boo
// Match continuously on every keystroke, and do not wait for user to hit the
// `Enter` key.
let response = loop {
let input = term.read_key()?;
let input = term.read_key_raw()?;
match input {
Key::Char('y' | 'Y') => break true,
Key::Char('n' | 'N') => break false,
Key::Enter => break default,
Key::CtrlC => {
term.show_cursor()?;
term.write_str("\n")?;
term.flush()?;

#[allow(clippy::exit, clippy::cast_possible_wrap)]
std::process::exit(if cfg!(windows) {
0xC000_013A_u32 as i32
} else {
130
});
}
_ => {}
};
};
Expand Down
1 change: 1 addition & 0 deletions crates/uv/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ flate2 = { workspace = true, default-features = false }
ignore = { version = "0.4.23" }
indoc = { workspace = true }
insta = { version = "1.40.0", features = ["filters", "json"] }
portable-pty = "0.9.0"
predicates = { version = "3.1.2" }
regex = { workspace = true }
reqwest = { workspace = true, features = ["blocking"], default-features = false }
Expand Down
10 changes: 10 additions & 0 deletions crates/uv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,16 @@ async fn run(mut cli: Cli) -> Result<ExitStatus> {

anstream::ColorChoice::write_global(globals.color.into());

(match globals.color {
uv_cli::ColorChoice::Auto => None,
uv_cli::ColorChoice::Always => Some(true),
uv_cli::ColorChoice::Never => Some(false),
})
.inspect(|colors_enabled| {
console::set_colors_enabled(*colors_enabled);
console::set_colors_enabled_stderr(*colors_enabled);
});

miette::set_hook(Box::new(|_| {
Box::new(
miette::MietteHandlerOpts::new()
Expand Down
67 changes: 66 additions & 1 deletion crates/uv/tests/it/pip_install.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::io::Cursor;
use std::io::{Cursor, Read};
use std::process::Command;

use anyhow::Result;
Expand Down Expand Up @@ -9097,3 +9097,68 @@ fn unsupported_git_scheme() {
"###
);
}

/* This is a regression test for a bug where Ctrl-C'ing the installation
confirmation prompt would cause a crash due to the handling of Ctrl-C and the
resulting SIGINT. */
#[test]
fn ctrl_c_install_confirmation_prompt() -> Result<()> {
const EXPECTED_PROMPT: &str = "? `pyproject.toml` looks like a local metadata file but was passed as a package name. Did you mean `-r pyproject.toml`? [y/n] › yes";

let pty_sys = portable_pty::native_pty_system();

let pair = pty_sys.openpty(portable_pty::PtySize::default())?;

let context = TestContext::new("3.12");

let pyproject_toml = context.temp_dir.child("pyproject.toml");
pyproject_toml.touch()?;

let mut cmd = context.pip_install();
cmd.arg("pyproject.toml");
cmd.args(["--color", "never"]); // ANSI escapes make the expectations harder to read

let mut argv = Vec::new();

argv.push(cmd.get_program().into());
argv.extend(cmd.get_args().map(Into::into));

let mut cmdbuild = portable_pty::CommandBuilder::from_argv(argv);

for (key, value) in cmd.get_envs() {
match value {
Some(value) => {
cmdbuild.env(key, value);
}
None => {
cmdbuild.env_remove(key);
}
}
}

match cmd.get_current_dir() {
Some(cwd) => cmdbuild.cwd(cwd),
None => cmdbuild.clear_cwd(),
};

let mut child = pair.slave.spawn_command(cmdbuild)?;
let mut reader = pair.master.try_clone_reader()?;
let mut writer = pair.master.take_writer()?;

let mut buffer = [0u8; EXPECTED_PROMPT.len()];
reader.read_exact(&mut buffer)?;
let output = String::from_utf8_lossy(&buffer).to_string();

assert_eq!(output, EXPECTED_PROMPT);

// 0x03 = ETX
writer.write_all(&[0x03])?;
writer.flush()?;

let exit_status = child.wait()?;

let expected_exit_code = if cfg!(windows) { 0xC000_013A_u32 } else { 130 };
assert_eq!(exit_status.exit_code(), expected_exit_code);

Ok(())
}
Loading