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 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 // cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
98 command_string.push_str(&format!("cd '{}';", directory.display()));
99 if let Some(prefix) = shell_kind.command_prefix() {
100 command_string.push(prefix);
101 }
102 command_string.push_str(&format!("{} --printenv {}", zed_path, redir));
103
104 if let ShellKind::Nushell = shell_kind {
105 command_string.push_str("; exit");
106 }
107
108 command.arg(&command_string);
109
110 super::set_pre_exec_to_start_new_session(&mut command);
111
112 let (env_output, process_output) = spawn_and_read_fd(command, fd_num).await?;
113 let env_output = String::from_utf8_lossy(&env_output);
114
115 anyhow::ensure!(
116 process_output.status.success(),
117 "login shell exited with {}. stdout: {:?}, stderr: {:?}",
118 process_output.status,
119 String::from_utf8_lossy(&process_output.stdout),
120 String::from_utf8_lossy(&process_output.stderr),
121 );
122
123 // Parse the JSON output from zed --printenv
124 let env_map = parse_env_map_from_noisy_output(&env_output).with_context(|| {
125 format!("Failed to deserialize environment variables from json: {env_output}")
126 })?;
127 Ok(env_map)
128}
129
130#[cfg(unix)]
131async fn spawn_and_read_fd(
132 mut command: std::process::Command,
133 child_fd: std::os::fd::RawFd,
134) -> anyhow::Result<(Vec<u8>, std::process::Output)> {
135 use command_fds::{CommandFdExt, FdMapping};
136 use std::{io::Read, process::Stdio};
137
138 let (mut reader, writer) = std::io::pipe()?;
139
140 command.fd_mappings(vec![FdMapping {
141 parent_fd: writer.into(),
142 child_fd,
143 }])?;
144
145 let process = smol::process::Command::from(command)
146 .stdin(Stdio::null())
147 .stdout(Stdio::piped())
148 .stderr(Stdio::piped())
149 .spawn()?;
150
151 let mut buffer = Vec::new();
152 reader.read_to_end(&mut buffer)?;
153
154 Ok((buffer, process.output().await?))
155}
156
157#[cfg(windows)]
158async fn capture_windows(
159 shell_path: &Path,
160 args: &[String],
161 directory: &Path,
162) -> Result<collections::HashMap<String, String>> {
163 use std::process::Stdio;
164
165 let zed_path =
166 std::env::current_exe().context("Failed to determine current zed executable path.")?;
167
168 let shell_kind = ShellKind::new(shell_path, true);
169 let directory_string = directory.display().to_string();
170 let zed_path_string = zed_path.display().to_string();
171 let quote_for_shell = |value: &str| {
172 shell_kind
173 .try_quote(value)
174 .map(|quoted| quoted.into_owned())
175 .unwrap_or_else(|| value.to_owned())
176 };
177 let mut cmd = crate::command::new_command(shell_path);
178 cmd.args(args);
179 let cmd = match shell_kind {
180 ShellKind::Csh
181 | ShellKind::Tcsh
182 | ShellKind::Rc
183 | ShellKind::Fish
184 | ShellKind::Xonsh
185 | ShellKind::Posix => {
186 let quoted_directory = quote_for_shell(&directory_string);
187 let quoted_zed_path = quote_for_shell(&zed_path_string);
188 cmd.args([
189 "-l",
190 "-i",
191 "-c",
192 &format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path),
193 ])
194 }
195 ShellKind::PowerShell | ShellKind::Pwsh => {
196 let quoted_directory = ShellKind::quote_pwsh(&directory_string);
197 let quoted_zed_path = ShellKind::quote_pwsh(&zed_path_string);
198 cmd.args([
199 "-NonInteractive",
200 "-NoProfile",
201 "-Command",
202 &format!(
203 "Set-Location {}; & {} --printenv",
204 quoted_directory, quoted_zed_path
205 ),
206 ])
207 }
208 ShellKind::Elvish => {
209 let quoted_directory = quote_for_shell(&directory_string);
210 let quoted_zed_path = quote_for_shell(&zed_path_string);
211 cmd.args([
212 "-c",
213 &format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path),
214 ])
215 }
216 ShellKind::Nushell => {
217 let quoted_directory = quote_for_shell(&directory_string);
218 let quoted_zed_path = quote_for_shell(&zed_path_string);
219 let zed_command = shell_kind
220 .prepend_command_prefix("ed_zed_path)
221 .into_owned();
222 cmd.args([
223 "-c",
224 &format!("cd {}; {} --printenv", quoted_directory, zed_command),
225 ])
226 }
227 ShellKind::Cmd => {
228 let dir = directory_string.trim_end_matches('\\');
229 cmd.args(["/d", "/c", "cd", dir, "&&", &zed_path_string, "--printenv"])
230 }
231 }
232 .stdin(Stdio::null())
233 .stdout(Stdio::piped())
234 .stderr(Stdio::piped());
235 let output = cmd
236 .output()
237 .await
238 .with_context(|| format!("command {cmd:?}"))?;
239 anyhow::ensure!(
240 output.status.success(),
241 "Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}",
242 output.status,
243 String::from_utf8_lossy(&output.stdout),
244 String::from_utf8_lossy(&output.stderr),
245 );
246 let env_output = String::from_utf8_lossy(&output.stdout);
247
248 parse_env_map_from_noisy_output(&env_output).with_context(|| {
249 format!("Failed to deserialize environment variables from json: {env_output}")
250 })
251}