shell_env.rs

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