acp_thread: Respect terminal settings shell for terminal tool environment (#39349)
When sourcing the project environment for the terminal tool, we will now do so by spawning the shell specified by the users `terminal.shell` setting (or as usual fall back to the login shell). Closes #37687 Release Notes: - N/A
This commit is contained in:
+132
-61
@@ -1,60 +1,81 @@
|
||||
#![cfg_attr(not(unix), allow(unused))]
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context as _, Result};
|
||||
use collections::HashMap;
|
||||
|
||||
/// Capture all environment variables from the login shell.
|
||||
use crate::shell::ShellKind;
|
||||
|
||||
pub fn print_env() {
|
||||
let env_vars: HashMap<String, String> = std::env::vars().collect();
|
||||
let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
|
||||
eprintln!("Error serializing environment variables: {}", err);
|
||||
std::process::exit(1);
|
||||
});
|
||||
println!("{}", json);
|
||||
}
|
||||
|
||||
/// Capture all environment variables from the login shell in the given directory.
|
||||
pub async fn capture(
|
||||
shell_path: impl AsRef<Path>,
|
||||
args: &[String],
|
||||
directory: impl AsRef<Path>,
|
||||
) -> Result<collections::HashMap<String, String>> {
|
||||
#[cfg(windows)]
|
||||
return capture_windows(shell_path.as_ref(), args, directory.as_ref()).await;
|
||||
#[cfg(unix)]
|
||||
return capture_unix(shell_path.as_ref(), args, directory.as_ref()).await;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub async fn capture(directory: &std::path::Path) -> Result<collections::HashMap<String, String>> {
|
||||
async fn capture_unix(
|
||||
shell_path: &Path,
|
||||
args: &[String],
|
||||
directory: &Path,
|
||||
) -> Result<collections::HashMap<String, String>> {
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::Stdio;
|
||||
|
||||
let zed_path = super::get_shell_safe_zed_path()?;
|
||||
let shell_path = std::env::var("SHELL").map(std::path::PathBuf::from)?;
|
||||
let shell_name = shell_path.file_name().and_then(std::ffi::OsStr::to_str);
|
||||
let shell_kind = ShellKind::new(shell_path);
|
||||
|
||||
let mut command_string = String::new();
|
||||
let mut command = std::process::Command::new(&shell_path);
|
||||
let mut command = std::process::Command::new(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;
|
||||
|
||||
let (fd_num, redir) = match shell_name {
|
||||
Some("rc") => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]`
|
||||
Some("nu") | Some("tcsh") => (FD_STDOUT, "".to_string()),
|
||||
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()),
|
||||
_ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
|
||||
};
|
||||
command.stdin(Stdio::null());
|
||||
command.stdout(Stdio::piped());
|
||||
command.stderr(Stdio::piped());
|
||||
|
||||
let mut command_prefix = String::new();
|
||||
match shell_name {
|
||||
Some("tcsh" | "csh") => {
|
||||
match shell_kind {
|
||||
ShellKind::Csh | ShellKind::Tcsh => {
|
||||
// For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
|
||||
command.arg0("-");
|
||||
}
|
||||
Some("fish") => {
|
||||
ShellKind::Fish => {
|
||||
// in fish, asdf, direnv attach to the `fish_prompt` event
|
||||
command_string.push_str("emit fish_prompt;");
|
||||
command.arg("-l");
|
||||
}
|
||||
Some("nu") => {
|
||||
// nu needs special handling for -- options.
|
||||
command_prefix = String::from("^");
|
||||
}
|
||||
_ => {
|
||||
command.arg("-l");
|
||||
}
|
||||
}
|
||||
// cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
|
||||
command_string.push_str(&format!("cd '{}';", directory.display()));
|
||||
command_string.push_str(&format!(
|
||||
"{}{} --printenv {}",
|
||||
command_prefix, zed_path, redir
|
||||
));
|
||||
if let Some(prefix) = shell_kind.command_prefix() {
|
||||
command_string.push(prefix);
|
||||
}
|
||||
command_string.push_str(&format!("{} --printenv {}", zed_path, redir));
|
||||
command.args(["-i", "-c", &command_string]);
|
||||
|
||||
super::set_pre_exec_to_start_new_session(&mut command);
|
||||
@@ -99,54 +120,104 @@ async fn spawn_and_read_fd(
|
||||
Ok((buffer, process.output().await?))
|
||||
}
|
||||
|
||||
/// Capture all environment variables from the shell on Windows.
|
||||
#[cfg(windows)]
|
||||
pub async fn capture(directory: &std::path::Path) -> Result<collections::HashMap<String, String>> {
|
||||
async fn capture_windows(
|
||||
shell_path: &Path,
|
||||
_args: &[String],
|
||||
directory: &Path,
|
||||
) -> Result<collections::HashMap<String, String>> {
|
||||
use std::process::Stdio;
|
||||
|
||||
let zed_path =
|
||||
std::env::current_exe().context("Failed to determine current zed executable path.")?;
|
||||
|
||||
// Use PowerShell to get environment variables in the directory context
|
||||
let output = crate::command::new_smol_command(crate::get_windows_system_shell())
|
||||
.args([
|
||||
"-NonInteractive",
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
&format!(
|
||||
"Set-Location '{}'; & '{}' --printenv",
|
||||
directory.display(),
|
||||
zed_path.display()
|
||||
),
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.await?;
|
||||
let shell_kind = ShellKind::new(shell_path);
|
||||
let env_output = match shell_kind {
|
||||
ShellKind::Posix | ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish => {
|
||||
return Err(anyhow::anyhow!("unsupported shell kind"));
|
||||
}
|
||||
ShellKind::PowerShell => {
|
||||
let output = crate::command::new_smol_command(shell_path)
|
||||
.args([
|
||||
"-NonInteractive",
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
&format!(
|
||||
"Set-Location '{}'; & '{}' --printenv",
|
||||
directory.display(),
|
||||
zed_path.display()
|
||||
),
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"PowerShell command failed with {}. stdout: {:?}, stderr: {:?}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"PowerShell command failed with {}. stdout: {:?}, stderr: {:?}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
output
|
||||
}
|
||||
ShellKind::Nushell => {
|
||||
let output = crate::command::new_smol_command(shell_path)
|
||||
.args([
|
||||
"-c",
|
||||
&format!(
|
||||
"cd '{}'; {} --printenv",
|
||||
directory.display(),
|
||||
zed_path.display()
|
||||
),
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
let env_output = String::from_utf8_lossy(&output.stdout);
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"Nushell command failed with {}. stdout: {:?}, stderr: {:?}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
output
|
||||
}
|
||||
ShellKind::Cmd => {
|
||||
let output = crate::command::new_smol_command(shell_path)
|
||||
.args([
|
||||
"/c",
|
||||
&format!(
|
||||
"cd '{}'; {} --printenv",
|
||||
directory.display(),
|
||||
zed_path.display()
|
||||
),
|
||||
])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"Cmd command failed with {}. stdout: {:?}, stderr: {:?}",
|
||||
output.status,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
output
|
||||
}
|
||||
};
|
||||
|
||||
let env_output = String::from_utf8_lossy(&env_output.stdout);
|
||||
|
||||
// Parse the JSON output from zed --printenv
|
||||
let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
|
||||
.with_context(|| "Failed to deserialize environment variables from json")?;
|
||||
Ok(env_map)
|
||||
}
|
||||
|
||||
pub fn print_env() {
|
||||
let env_vars: HashMap<String, String> = std::env::vars().collect();
|
||||
let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
|
||||
eprintln!("Error serializing environment variables: {}", err);
|
||||
std::process::exit(1);
|
||||
});
|
||||
println!("{}", json);
|
||||
std::process::exit(0);
|
||||
serde_json::from_str(&env_output)
|
||||
.with_context(|| "Failed to deserialize environment variables from json")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user