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 quoted_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 ShellKind::PowerShell => (FD_STDIN, format!(">{}", FD_STDIN)),
59 _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
60 };
61
62 match shell_kind {
63 ShellKind::Csh | ShellKind::Tcsh => {
64 // For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
65 command.arg0("-");
66 }
67 ShellKind::Fish => {
68 // in fish, asdf, direnv attach to the `fish_prompt` event
69 command_string.push_str("emit fish_prompt;");
70 command.arg("-l");
71 }
72 _ => {
73 command.arg("-l");
74 }
75 }
76
77 match shell_kind {
78 // Nushell does not allow non-interactive login shells.
79 // Instead of doing "-l -i -c '<command>'"
80 // use "-l -e '<command>; exit'" instead
81 ShellKind::Nushell => command.arg("-e"),
82 _ => command.args(["-i", "-c"]),
83 };
84
85 // Prefix with "./" if the path starts with "-" to prevent cd from interpreting it as a flag
86 let dir_str = directory.to_string_lossy();
87 let dir_str = if dir_str.starts_with('-') {
88 format!("./{dir_str}").into()
89 } else {
90 dir_str
91 };
92 let quoted_dir = shell_kind
93 .try_quote(&dir_str)
94 .context("unexpected null in directory name")?;
95
96 // cd into the directory, triggering directory specific side-effects (asdf, direnv, etc)
97 command_string.push_str(&format!("cd {};", quoted_dir));
98 if let Some(prefix) = shell_kind.command_prefix() {
99 command_string.push(prefix);
100 }
101 command_string.push_str(&format!("{} --printenv {}", quoted_zed_path, redir));
102
103 if let ShellKind::Nushell = shell_kind {
104 command_string.push_str("; exit");
105 }
106
107 command.arg(&command_string);
108
109 super::set_pre_exec_to_start_new_session(&mut command);
110
111 let (env_output, process_output) = spawn_and_read_fd(command, fd_num).await?;
112 let env_output = String::from_utf8_lossy(&env_output);
113
114 anyhow::ensure!(
115 process_output.status.success(),
116 "login shell exited with {}. stdout: {:?}, stderr: {:?}",
117 process_output.status,
118 String::from_utf8_lossy(&process_output.stdout),
119 String::from_utf8_lossy(&process_output.stderr),
120 );
121
122 // Parse the JSON output from zed --printenv
123 let env_map: collections::HashMap<String, String> = serde_json::from_str(&env_output)
124 .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 // Prefix with "./" if the path starts with "-" to prevent cd from interpreting it as a flag
170 let directory_string = directory.display().to_string();
171 let directory_string = if directory_string.starts_with('-') {
172 format!("./{directory_string}")
173 } else {
174 directory_string
175 };
176 let zed_path_string = zed_path.display().to_string();
177 let quote_for_shell = |value: &str| {
178 shell_kind
179 .try_quote(value)
180 .map(|quoted| quoted.into_owned())
181 .context("unexpected null in directory name")
182 };
183 let mut cmd = crate::command::new_command(shell_path);
184 cmd.args(args);
185 let quoted_directory = quote_for_shell(&directory_string)?;
186 let quoted_zed_path = quote_for_shell(&zed_path_string)?;
187 let cmd = match shell_kind {
188 ShellKind::Csh
189 | ShellKind::Tcsh
190 | ShellKind::Rc
191 | ShellKind::Fish
192 | ShellKind::Xonsh
193 | ShellKind::Posix => cmd.args([
194 "-l",
195 "-i",
196 "-c",
197 &format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path),
198 ]),
199 ShellKind::PowerShell | ShellKind::Pwsh => cmd.args([
200 "-NonInteractive",
201 "-NoProfile",
202 "-Command",
203 &format!(
204 "Set-Location {}; & {} --printenv",
205 quoted_directory, quoted_zed_path
206 ),
207 ]),
208 ShellKind::Elvish => cmd.args([
209 "-c",
210 &format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path),
211 ]),
212 ShellKind::Nushell => {
213 let zed_command = shell_kind
214 .prepend_command_prefix("ed_zed_path)
215 .into_owned();
216 cmd.args([
217 "-c",
218 &format!("cd {}; {} --printenv", quoted_directory, zed_command),
219 ])
220 }
221 ShellKind::Cmd => cmd.args([
222 "/c",
223 "cd",
224 &directory_string,
225 "&&",
226 &zed_path_string,
227 "--printenv",
228 ]),
229 }
230 .stdin(Stdio::null())
231 .stdout(Stdio::piped())
232 .stderr(Stdio::piped());
233 let output = cmd
234 .output()
235 .await
236 .with_context(|| format!("command {cmd:?}"))?;
237 anyhow::ensure!(
238 output.status.success(),
239 "Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}",
240 output.status,
241 String::from_utf8_lossy(&output.stdout),
242 String::from_utf8_lossy(&output.stderr),
243 );
244 let env_output = String::from_utf8_lossy(&output.stdout);
245
246 // Parse the JSON output from zed --printenv
247 serde_json::from_str(&env_output).with_context(|| {
248 format!("Failed to deserialize environment variables from json: {env_output}")
249 })
250}