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