Skip to content

Visual Studio Code, rebuilt in Rust

Rust

fix(terminal): take the pid to kill as upstream's capturePid does

rokartur25670b92056c
diff --git a/native/crates/app/src/workbench/terminal_quick_fix.rs b/native/crates/app/src/workbench/terminal_quick_fix.rs
index 3c98318912a..2cb40334d90 100644
--- a/native/crates/app/src/workbench/terminal_quick_fix.rs
+++ b/native/crates/app/src/workbench/terminal_quick_fix.rs
@@ -193,8 +193,7 @@ impl Workbench {
let listing = std::process::Command::new("netstat").arg("-ano").output().ok()?;
let listing = String::from_utf8_lossy(&listing.stdout).into_owned();
let line = listing.lines().find(|line| line.contains(&port) && !line.trim().is_empty())?;
- // ptyService.ts `capturePid`: the first number with blanks around it.
- let pid: i32 = line.split_whitespace().find_map(|field| field.parse().ok())?;
+ let pid = capture_pid(line)?;
// SAFETY: kill(2) with a pid and SIGTERM has no memory effects.
#[cfg(unix)]
unsafe {
@@ -242,10 +241,27 @@ fn parse_extension_fix(id: &str, extension: &str, explain: bool, answer: &Value)
Some(QuickFix { id: id.to_owned(), source: extension.to_owned(), explain, fix })
}
+/// ptyService.ts `capturePid`, `/\s+(\d+)(?:\s+|$)/`: the first field of digits after a blank. Never the command
+/// name that starts an `lsof` line, and never a signed number: `kill` takes 0 and -1 as "every process".
+fn capture_pid(line: &str) -> Option<i32> {
+ let after_blank = |index: usize| index > 0 || line.starts_with(char::is_whitespace);
+ let (_, digits) = line.split_whitespace().enumerate().find(|(index, field)| after_blank(*index) && field.bytes().all(|byte| byte.is_ascii_digit()))?;
+ digits.parse().ok()
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn the_pid_of_a_listing_is_its_first_field_of_digits_after_a_blank() {
+ assert_eq!(capture_pid("node 4242 user 23u IPv4 0x1 0t0 TCP *:3000 (LISTEN)"), Some(4242));
+ assert_eq!(capture_pid(" TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 4242"), Some(4242));
+ assert_eq!(capture_pid("-1 4242 user 23u IPv4 0x1 0t0 TCP *:3000 (LISTEN)"), Some(4242), "a process named -1");
+ assert_eq!(capture_pid("0 4242 user 23u IPv4 0x1 0t0 TCP *:3000 (LISTEN)"), Some(4242), "a process named 0");
+ assert_eq!(capture_pid("node *:3000"), None);
+ }
+
#[test]
fn extension_answers_become_fixes_by_their_shape() {
let fix = |answer: Value| parse_extension_fix("ms-vscode.npm-command", "vscode.npm", false, &answer).map(|fix| fix.label());