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