Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Fix pwsh-related issues with local and remote env variables detection (#66097)
Kirill Bulatov18f9d7e73183
diff --git a/crates/remote/src/transport/ssh.rs b/crates/remote/src/transport/ssh.rsindex e2b9579b941..306ff1da5a6 100644--- a/crates/remote/src/transport/ssh.rs+++ b/crates/remote/src/transport/ssh.rs@@ -8,7 +8,7 @@ use anyhow::{Context as _, Result, anyhow};use async_trait::async_trait;use collections::HashMap;use futures::{- AsyncReadExt as _, FutureExt as _,+ AsyncReadExt as _, AsyncWriteExt as _, FutureExt as _,channel::mpsc::{Sender, UnboundedReceiver, UnboundedSender},select_biased,};@@ -31,7 +31,7 @@ use std::{time::{Duration, Instant},};use tempfile::TempDir;-use util::command::{Child, Stdio};+use util::command::{Child, Command, Stdio};use util::{paths::{PathStyle, RemotePathBuf},rel_path::RelPath,@@ -1576,15 +1576,8 @@ impl SshSocket {args: &[impl AsRef<str>],allow_pseudo_tty: bool,) -> Result<String> {- let mut command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);- let output = command.output().await?;- log::debug!("{:?}: {:?}", command, output);- anyhow::ensure!(- output.status.success(),- "failed to run command {command:?}: {}",- String::from_utf8_lossy(&output.stderr)- );- Ok(String::from_utf8_lossy(&output.stdout).to_string())+ let command = self.ssh_command(shell_kind, program, args, allow_pseudo_tty);+ command_output(command, None).await}fn ssh_options<'a>(@@ -1641,13 +1634,15 @@ impl SshSocket {arguments}+ fn environment_posix_command(&self) -> Command {+ self.ssh_command(ShellKind::Posix, "sh", &["-s"], false)+ }+async fn environment_posix(&self) -> Result<RemoteEnvironment> {let script = RemoteEnvironment::posix_script();-- let output = self- .run_command(ShellKind::Posix, "sh", &["-c", &script], false)+ let output = command_output(self.environment_posix_command(), Some(script.as_bytes())).await- .context("Failed to determine remote environment")?;+ .context("determining remote environment")?;RemoteEnvironment::parse_posix(&output)}@@ -1759,6 +1754,33 @@ impl SshSocket {}}+async fn command_output(mut command: Command, input: Option<&[u8]>) -> Result<String> {+ let (output, write_result) = if let Some(input) = input {+ let mut child = command.kill_on_drop(true).spawn()?;+ let mut stdin = child.stdin.take().context("Command did not expose stdin")?;+ futures::join!(child.output(), async move {+ let result = async {+ stdin.write_all(input).await?;+ stdin.flush().await+ }+ .await;+ drop(stdin);+ result+ })+ } else {+ (command.output().await, Ok(()))+ };+ let output = output?;+ log::debug!("{command:?}: {output:?}");+ anyhow::ensure!(+ output.status.success(),+ "failed to run command {command:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ write_result.with_context(|| format!("writing stdin for command {command:?}"))?;+ Ok(String::from_utf8_lossy(&output.stdout).to_string())+}+fn parse_port_number(port_str: &str) -> Result<u16> {port_str.parse()@@ -2486,25 +2508,76 @@ mod tests {#[cfg(unix)]{- let output = smol::block_on(- util::command::new_command("/bin/sh")- .args(["-c", &RemoteEnvironment::posix_script()])- .env("SHELL", "/bin/sh")- .output(),- )?;- assert!(- output.status.success(),- "{}",- String::from_utf8_lossy(&output.stderr)- );-- let environment = RemoteEnvironment::parse_posix(std::str::from_utf8(&output.stdout)?)?;- assert_eq!(environment.shell, "/bin/sh");- assert!(environment.os_version.is_some());+ let socket = smol::block_on(SshSocket::new(+ SshConnectionOptions::default(),+ PathBuf::from("/tmp/zed-test.sock"),+ ))?;+ let command = socket.environment_posix_command();+ let remote_command = command+ .get_args()+ .last()+ .context("Missing remote command")?;+ let mut shells = vec![(PathBuf::from("/bin/sh"), &["-c"][..])];+ if let Ok(powershell) = which::which("pwsh") {+ shells.push((powershell, &["-NoProfile", "-NonInteractive", "-Command"]));+ }+ for (shell, args) in shells {+ let mut command = util::command::new_command(&shell);+ command+ .args(args)+ .arg(remote_command)+ .env("SHELL", "/usr/bin/pwsh")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ let output = smol::block_on(command_output(+ command,+ Some(RemoteEnvironment::posix_script().as_bytes()),+ ))?;+ let environment = RemoteEnvironment::parse_posix(&output)?;+ assert_eq!(environment.shell, "/usr/bin/pwsh");+ assert_eq!(environment.platform.arch.as_str(), std::env::consts::ARCH);+ assert!(environment.os_version.is_some());+ }+ assert_eq!(remote_command, "cd; sh -s");}Ok(())}+ #[cfg(unix)]+ #[test]+ fn command_output_drains_output_while_writing_input() -> Result<()> {+ let input = vec![b'x'; 1024 * 1024];+ let mut command = util::command::new_command("/bin/sh");+ command+ .args(["-c", "head -c 1048576 /dev/zero; cat"])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ let output = smol::block_on(command_output(command, Some(&input)))?;+ let mut expected = vec![0; 1024 * 1024];+ expected.extend_from_slice(&input);+ assert_eq!(output.as_bytes(), expected);+ Ok(())+ }++ #[cfg(unix)]+ #[test]+ fn command_output_preserves_stderr_when_input_fails() -> Result<()> {+ let input = vec![b'x'; 1024 * 1024];+ let mut command = util::command::new_command("/bin/sh");+ command+ .args(["-c", "exec 0<&-; printf 'probe failed' >&2; exit 7"])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ let expected = format!("failed to run command {command:?}: probe failed");+ let error = smol::block_on(command_output(command, Some(&input))).unwrap_err();+ assert_eq!(error.to_string(), expected);+ Ok(())+ }+#[cfg(unix)]#[test]fn version_query_failure_does_not_abort_probe() -> Result<()> {diff --git a/crates/util/src/shell_env.rs b/crates/util/src/shell_env.rsindex ee765a9a27c..5dea7d60e94 100644--- a/crates/util/src/shell_env.rs+++ b/crates/util/src/shell_env.rs@@ -87,22 +87,7 @@ async fn capture_unix(let mut command_string = String::new();let mut command = new_std_command(shell_path);command.args(args);- // In some shells, file descriptors greater than 2 cannot be used in interactive mode,- // so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others.- // See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482- const FD_STDIN: std::os::fd::RawFd = 0;- const FD_STDOUT: std::os::fd::RawFd = 1;- const FD_STDERR: std::os::fd::RawFd = 2;-- let (fd_num, redir) = match shell_kind {- ShellKind::Rc => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]`- ShellKind::Nushell | ShellKind::Tcsh => (FD_STDOUT, "".to_string()),- // xonsh doesn't support redirecting to stdin, and control sequences are printed to- // stdout on startup- ShellKind::Xonsh => (FD_STDERR, "o>e".to_string()),- ShellKind::PowerShell => (FD_STDIN, format!(">{}", FD_STDIN)),- _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`- };+ let (fd_num, redir) = capture_output_redirection(shell_kind);match shell_kind {ShellKind::Csh | ShellKind::Tcsh => {@@ -177,6 +162,26 @@ async fn capture_unix()}+#[cfg(unix)]+fn capture_output_redirection(shell_kind: ShellKind) -> (std::os::fd::RawFd, String) {+ // In some shells, file descriptors greater than 2 cannot be used in interactive mode,+ // so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others.+ // See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482+ const FD_STDIN: std::os::fd::RawFd = 0;+ const FD_STDOUT: std::os::fd::RawFd = 1;+ const FD_STDERR: std::os::fd::RawFd = 2;++ match shell_kind {+ ShellKind::Rc => (FD_STDIN, format!(">[1={FD_STDIN}]")), // `[1=0]`+ ShellKind::Nushell | ShellKind::Tcsh => (FD_STDOUT, "".to_string()),+ // xonsh doesn't support redirecting to stdin, and control sequences are printed to+ // stdout on startup+ ShellKind::Xonsh => (FD_STDERR, "o>e".to_string()),+ ShellKind::PowerShell | ShellKind::Pwsh => (FD_STDIN, format!("> /dev/fd/{FD_STDIN}")),+ _ => (FD_STDIN, format!(">&{FD_STDIN}")), // `>&0`+ }+}+#[cfg(unix)]async fn spawn_and_read_fd(mut command: std::process::Command,@@ -324,6 +329,32 @@ mod tests {ExitStatus::from_raw(code)}+ #[cfg(unix)]+ #[test]+ fn capture_powershell_environment_without_startup_output() -> Result<()> {+ for shell in ["pwsh", "powershell"] {+ let (descriptor, redirection) =+ capture_output_redirection(ShellKind::new(shell, false));+ if let Ok(shell_path) = which::which(shell) {+ let directory = tempfile::tempdir()?;+ let script =+ format!("Write-Output '{{}}'; /bin/echo '{{\"PROBE\":\"ok\"}}' {redirection}");+ let mut command = crate::command::new_std_command(shell_path);+ command+ .args(["-NoProfile", "-l", "-i", "-c", &script])+ .current_dir(directory.path());+ let (output, process_output) =+ smol::block_on(spawn_and_read_fd(command, descriptor))?;+ assert!(process_output.status.success(), "{process_output:?}");+ assert_eq!(output, b"{\"PROBE\":\"ok\"}\n");+ assert_eq!(process_output.stdout, b"{}\n");+ assert!(!directory.path().join("0").exists());+ }+ assert_eq!((descriptor, redirection), (0, String::from("> /dev/fd/0")));+ }+ Ok(())+ }+#[test]fn parse_env_output_accepts_valid_env_when_shell_exits_nonzero() {let env_json = serde_json::json!({