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 if let ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish | ShellKind::Xonsh =
145 shell_kind
146 {
147 return Err(anyhow::anyhow!("unsupported shell kind"));
148 }
149 let mut cmd = crate::command::new_smol_command(shell_path);
150 let cmd = match shell_kind {
151 ShellKind::Csh | ShellKind::Tcsh | ShellKind::Rc | ShellKind::Fish | ShellKind::Xonsh => {
152 unreachable!()
153 }
154 ShellKind::Posix => cmd.args([
155 "-c",
156 &format!(
157 "cd '{}'; '{}' --printenv",
158 directory.display(),
159 zed_path.display()
160 ),
161 ]),
162 ShellKind::PowerShell => cmd.args([
163 "-NonInteractive",
164 "-NoProfile",
165 "-Command",
166 &format!(
167 "Set-Location '{}'; & '{}' --printenv",
168 directory.display(),
169 zed_path.display()
170 ),
171 ]),
172 ShellKind::Elvish => cmd.args([
173 "-c",
174 &format!(
175 "cd '{}'; '{}' --printenv",
176 directory.display(),
177 zed_path.display()
178 ),
179 ]),
180 ShellKind::Nushell => cmd.args([
181 "-c",
182 &format!(
183 "cd '{}'; {}'{}' --printenv",
184 directory.display(),
185 shell_kind
186 .command_prefix()
187 .map(|prefix| prefix.to_string())
188 .unwrap_or_default(),
189 zed_path.display()
190 ),
191 ]),
192 ShellKind::Cmd => cmd.args([
193 "/c",
194 "cd",
195 &directory.display().to_string(),
196 "&&",
197 &zed_path.display().to_string(),
198 "--printenv",
199 ]),
200 }
201 .stdin(Stdio::null())
202 .stdout(Stdio::piped())
203 .stderr(Stdio::piped());
204 let output = cmd
205 .output()
206 .await
207 .with_context(|| format!("command {cmd:?}"))?;
208 anyhow::ensure!(
209 output.status.success(),
210 "Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}",
211 output.status,
212 String::from_utf8_lossy(&output.stdout),
213 String::from_utf8_lossy(&output.stderr),
214 );
215 let env_output = String::from_utf8_lossy(&output.stdout);
216
217 // Parse the JSON output from zed --printenv
218 serde_json::from_str(&env_output).with_context(|| {
219 format!("Failed to deserialize environment variables from json: {env_output}")
220 })
221}