zed_util/
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    use std::process::Stdio;
37
38    let zed_path = super::get_shell_safe_zed_path()?;
39    let shell_kind = ShellKind::new(shell_path);
40
41    let mut command_string = String::new();
42    let mut command = std::process::Command::new(shell_path);
43    command.args(args);
44    // In some shells, file descriptors greater than 2 cannot be used in interactive mode,
45    // so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others.
46    // See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482
47    const FD_STDIN: std::os::fd::RawFd = 0;
48    const FD_STDOUT: std::os::fd::RawFd = 1;
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        _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
54    };
55    command.stdin(Stdio::null());
56    command.stdout(Stdio::piped());
57    command.stderr(Stdio::piped());
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(|| "Failed to deserialize environment variables from json")?;
97    Ok(env_map)
98}
99
100#[cfg(unix)]
101async fn spawn_and_read_fd(
102    mut command: std::process::Command,
103    child_fd: std::os::fd::RawFd,
104) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
105    use command_fds::{CommandFdExt, FdMapping};
106    use std::io::Read;
107
108    let (mut reader, writer) = std::io::pipe()?;
109
110    command.fd_mappings(vec![FdMapping {
111        parent_fd: writer.into(),
112        child_fd,
113    }])?;
114
115    let process = smol::process::Command::from(command).spawn()?;
116
117    let mut buffer = Vec::new();
118    reader.read_to_end(&mut buffer)?;
119
120    Ok((buffer, process.output().await?))
121}
122
123#[cfg(windows)]
124async fn capture_windows(
125    shell_path: &Path,
126    _args: &[String],
127    directory: &Path,
128) -> Result<collections::HashMap<String, String>> {
129    use std::process::Stdio;
130
131    let zed_path =
132        std::env::current_exe().context("Failed to determine current zed executable path.")?;
133
134    let shell_kind = ShellKind::new(shell_path);
135    let env_output = match shell_kind {
136        ShellKind::Posix | ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish => {
137            return Err(anyhow::anyhow!("unsupported shell kind"));
138        }
139        ShellKind::PowerShell => {
140            let output = crate::command::new_smol_command(shell_path)
141                .args([
142                    "-NonInteractive",
143                    "-NoProfile",
144                    "-Command",
145                    &format!(
146                        "Set-Location '{}'; & '{}' --printenv",
147                        directory.display(),
148                        zed_path.display()
149                    ),
150                ])
151                .stdin(Stdio::null())
152                .stdout(Stdio::piped())
153                .stderr(Stdio::piped())
154                .output()
155                .await?;
156
157            anyhow::ensure!(
158                output.status.success(),
159                "PowerShell command failed with {}. stdout: {:?}, stderr: {:?}",
160                output.status,
161                String::from_utf8_lossy(&output.stdout),
162                String::from_utf8_lossy(&output.stderr),
163            );
164            output
165        }
166        ShellKind::Nushell => {
167            let output = crate::command::new_smol_command(shell_path)
168                .args([
169                    "-c",
170                    &format!(
171                        "cd '{}'; {} --printenv",
172                        directory.display(),
173                        zed_path.display()
174                    ),
175                ])
176                .stdin(Stdio::null())
177                .stdout(Stdio::piped())
178                .stderr(Stdio::piped())
179                .output()
180                .await?;
181
182            anyhow::ensure!(
183                output.status.success(),
184                "Nushell command failed with {}. stdout: {:?}, stderr: {:?}",
185                output.status,
186                String::from_utf8_lossy(&output.stdout),
187                String::from_utf8_lossy(&output.stderr),
188            );
189            output
190        }
191        ShellKind::Cmd => {
192            let output = crate::command::new_smol_command(shell_path)
193                .args([
194                    "/c",
195                    &format!(
196                        "cd '{}'; {} --printenv",
197                        directory.display(),
198                        zed_path.display()
199                    ),
200                ])
201                .stdin(Stdio::null())
202                .stdout(Stdio::piped())
203                .stderr(Stdio::piped())
204                .output()
205                .await?;
206
207            anyhow::ensure!(
208                output.status.success(),
209                "Cmd command failed with {}. stdout: {:?}, stderr: {:?}",
210                output.status,
211                String::from_utf8_lossy(&output.stdout),
212                String::from_utf8_lossy(&output.stderr),
213            );
214            output
215        }
216    };
217
218    let env_output = String::from_utf8_lossy(&env_output.stdout);
219
220    // Parse the JSON output from zed --printenv
221    serde_json::from_str(&env_output)
222        .with_context(|| "Failed to deserialize environment variables from json")
223}