shell_env.rs

  1use std::path::Path;
  2
  3use anyhow::{Context as _, Result};
  4use collections::HashMap;
  5
  6use crate::shell::ShellKind;
  7
  8pub fn print_env() {
  9    let env_vars: HashMap<String, String> = std::env::vars().collect();
 10    let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| {
 11        eprintln!("Error serializing environment variables: {}", err);
 12        std::process::exit(1);
 13    });
 14    println!("{}", json);
 15}
 16
 17/// Capture all environment variables from the login shell in the given directory.
 18pub async fn capture(
 19    shell_path: impl AsRef<Path>,
 20    args: &[String],
 21    directory: impl AsRef<Path>,
 22) -> Result<collections::HashMap<String, String>> {
 23    #[cfg(windows)]
 24    return capture_windows(shell_path.as_ref(), args, directory.as_ref()).await;
 25    #[cfg(unix)]
 26    return capture_unix(shell_path.as_ref(), args, directory.as_ref()).await;
 27}
 28
 29#[cfg(unix)]
 30async fn capture_unix(
 31    shell_path: &Path,
 32    args: &[String],
 33    directory: &Path,
 34) -> Result<collections::HashMap<String, String>> {
 35    use std::os::unix::process::CommandExt;
 36
 37    use crate::command::new_std_command;
 38
 39    let shell_kind = ShellKind::new(shell_path, false);
 40    let zed_path = super::get_shell_safe_zed_path(shell_kind)?;
 41
 42    let mut command_string = String::new();
 43    let mut command = new_std_command(shell_path);
 44    command.args(args);
 45    // In some shells, file descriptors greater than 2 cannot be used in interactive mode,
 46    // so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others.
 47    // See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482
 48    const FD_STDIN: std::os::fd::RawFd = 0;
 49    const FD_STDOUT: std::os::fd::RawFd = 1;
 50    const FD_STDERR: std::os::fd::RawFd = 2;
 51
 52    let (fd_num, redir) = match shell_kind {
 53        ShellKind::Rc => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]`
 54        ShellKind::Nushell | ShellKind::Tcsh => (FD_STDOUT, "".to_string()),
 55        // xonsh doesn't support redirecting to stdin, and control sequences are printed to
 56        // stdout on startup
 57        ShellKind::Xonsh => (FD_STDERR, "o>e".to_string()),
 58        _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
 59    };
 60
 61    match shell_kind {
 62        ShellKind::Csh | ShellKind::Tcsh => {
 63            // For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
 64            command.arg0("-");
 65        }
 66        ShellKind::Fish => {
 67            // in fish, asdf, direnv attach to the `fish_prompt` event
 68            command_string.push_str("emit fish_prompt;");
 69            command.arg("-l");
 70        }
 71        _ => {
 72            command.arg("-l");
 73        }
 74    }
 75    // cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
 76    command_string.push_str(&format!("cd '{}';", directory.display()));
 77    if let Some(prefix) = shell_kind.command_prefix() {
 78        command_string.push(prefix);
 79    }
 80    command_string.push_str(&format!("{} --printenv {}", zed_path, redir));
 81    command.args(["-i", "-c", &command_string]);
 82
 83    super::set_pre_exec_to_start_new_session(&mut command);
 84
 85    let (env_output, process_output) = spawn_and_read_fd(command, fd_num).await?;
 86    let env_output = String::from_utf8_lossy(&env_output);
 87
 88    anyhow::ensure!(
 89        process_output.status.success(),
 90        "login shell exited with {}. stdout: {:?}, stderr: {:?}",
 91        process_output.status,
 92        String::from_utf8_lossy(&process_output.stdout),
 93        String::from_utf8_lossy(&process_output.stderr),
 94    );
 95
 96    // Parse the JSON output from zed --printenv
 97    let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
 98        .with_context(|| {
 99            format!("Failed to deserialize environment variables from json: {env_output}")
100        })?;
101    Ok(env_map)
102}
103
104#[cfg(unix)]
105async fn spawn_and_read_fd(
106    mut command: std::process::Command,
107    child_fd: std::os::fd::RawFd,
108) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
109    use command_fds::{CommandFdExt, FdMapping};
110    use std::{io::Read, process::Stdio};
111
112    let (mut reader, writer) = std::io::pipe()?;
113
114    command.fd_mappings(vec![FdMapping {
115        parent_fd: writer.into(),
116        child_fd,
117    }])?;
118
119    let process = smol::process::Command::from(command)
120        .stdin(Stdio::null())
121        .stdout(Stdio::piped())
122        .stderr(Stdio::piped())
123        .spawn()?;
124
125    let mut buffer = Vec::new();
126    reader.read_to_end(&mut buffer)?;
127
128    Ok((buffer, process.output().await?))
129}
130
131#[cfg(windows)]
132async fn capture_windows(
133    shell_path: &Path,
134    _args: &[String],
135    directory: &Path,
136) -> Result<collections::HashMap<String, String>> {
137    use std::process::Stdio;
138
139    let zed_path =
140        std::env::current_exe().context("Failed to determine current zed executable path.")?;
141
142    let shell_kind = ShellKind::new(shell_path, true);
143    if let ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish | ShellKind::Xonsh =
144        shell_kind
145    {
146        return Err(anyhow::anyhow!("unsupported shell kind"));
147    }
148    let mut cmd = crate::command::new_smol_command(shell_path);
149    let cmd = match shell_kind {
150        ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish | ShellKind::Xonsh => {
151            unreachable!()
152        }
153        ShellKind::Posix => cmd.args([
154            "-c",
155            &format!(
156                "cd '{}'; '{}' --printenv",
157                directory.display(),
158                zed_path.display()
159            ),
160        ]),
161        ShellKind::PowerShell => cmd.args([
162            "-NonInteractive",
163            "-NoProfile",
164            "-Command",
165            &format!(
166                "Set-Location '{}'; & '{}' --printenv",
167                directory.display(),
168                zed_path.display()
169            ),
170        ]),
171        ShellKind::Elvish => cmd.args([
172            "-c",
173            &format!(
174                "cd '{}'; '{}' --printenv",
175                directory.display(),
176                zed_path.display()
177            ),
178        ]),
179        ShellKind::Nushell => cmd.args([
180            "-c",
181            &format!(
182                "cd '{}'; {}'{}' --printenv",
183                directory.display(),
184                shell_kind
185                    .command_prefix()
186                    .map(|prefix| prefix.to_string())
187                    .unwrap_or_default(),
188                zed_path.display()
189            ),
190        ]),
191        ShellKind::Cmd => cmd.args([
192            "/c",
193            "cd",
194            &directory.display().to_string(),
195            "&&",
196            &zed_path.display().to_string(),
197            "--printenv",
198        ]),
199    }
200    .stdin(Stdio::null())
201    .stdout(Stdio::piped())
202    .stderr(Stdio::piped());
203    let output = cmd
204        .output()
205        .await
206        .with_context(|| format!("command {cmd:?}"))?;
207    anyhow::ensure!(
208        output.status.success(),
209        "Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}",
210        output.status,
211        String::from_utf8_lossy(&output.stdout),
212        String::from_utf8_lossy(&output.stderr),
213    );
214    let env_output = String::from_utf8_lossy(&output.stdout);
215
216    // Parse the JSON output from zed --printenv
217    serde_json::from_str(&env_output).with_context(|| {
218        format!("Failed to deserialize environment variables from json: {env_output}")
219    })
220}