From ae144e05ac519bd06f687ca90ccd4c2e555c94c7 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Wed, 4 Sep 2024 11:04:00 -0400 Subject: [PATCH] Revert `pyproject.toml` modifications on Ctrl-C (#7024) ## Summary Not perfect, but an improvement at least for an interactive experience. Closes #6818. --- Cargo.lock | 1 + crates/uv/Cargo.toml | 1 + crates/uv/src/commands/project/add.rs | 23 +++++++++++++++++++++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3ec23b39a890..97585de4e370 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4463,6 +4463,7 @@ dependencies = [ "byteorder", "cache-key", "clap", + "ctrlc", "distribution-types", "etcetera", "filetime", diff --git a/crates/uv/Cargo.toml b/crates/uv/Cargo.toml index 41f6b3f8c420..ab911538167b 100644 --- a/crates/uv/Cargo.toml +++ b/crates/uv/Cargo.toml @@ -48,6 +48,7 @@ anstream = { workspace = true } anyhow = { workspace = true } axoupdater = { workspace = true, features = ["github_releases", "tokio"], optional = true } clap = { workspace = true, features = ["derive", "string", "wrap_help"] } +ctrlc = { workspace = true } flate2 = { workspace = true, default-features = false } fs-err = { workspace = true, features = ["tokio"] } futures = { workspace = true } diff --git a/crates/uv/src/commands/project/add.rs b/crates/uv/src/commands/project/add.rs index 68b8bf98083e..8bb353078a1c 100644 --- a/crates/uv/src/commands/project/add.rs +++ b/crates/uv/src/commands/project/add.rs @@ -488,6 +488,25 @@ pub(crate) async fn add( .with_pyproject_toml(toml::from_str(&content).map_err(ProjectError::TomlParse)?) .ok_or(ProjectError::TomlUpdate)?; + // Set the Ctrl-C handler to revert changes on exit. + let _ = ctrlc::set_handler({ + let root = root.clone(); + let existing = existing.clone(); + move || { + // Revert the changes to the `pyproject.toml`, if necessary. + if modified { + let _ = fs_err::write(root.join("pyproject.toml"), &existing); + } + + #[allow(clippy::exit, clippy::cast_possible_wrap)] + std::process::exit(if cfg!(windows) { + 0xC000_013A_u32 as i32 + } else { + 130 + }); + } + }); + match lock_and_sync( project, &mut toml, @@ -518,7 +537,7 @@ pub(crate) async fn add( // Revert the changes to the `pyproject.toml`, if necessary. if modified { - fs_err::write(root.join("pyproject.toml"), existing)?; + fs_err::write(root.join("pyproject.toml"), &existing)?; } Ok(ExitStatus::Failure) @@ -526,7 +545,7 @@ pub(crate) async fn add( Err(err) => { // Revert the changes to the `pyproject.toml`, if necessary. if modified { - fs_err::write(root.join("pyproject.toml"), existing)?; + fs_err::write(root.join("pyproject.toml"), &existing)?; } Err(err.into()) }