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