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);
40 let zed_path = super::get_shell_safe_zed_path(shell_kind.as_ref())?;
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 Some(ShellKind::Rc) => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]`
54 Some(ShellKind::Nushell) | Some(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 Some(ShellKind::Xonsh) => (FD_STDERR, "o>e".to_string()),
58 Some(ShellKind::PowerShell) => (FD_STDIN, format!(">{}", FD_STDIN)),
59 _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0`
60 };
61
62 match shell_kind {
63 Some(ShellKind::Csh) | Some(ShellKind::Tcsh) => {
64 // For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`)
65 command.arg0("-");
66 }
67 Some(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.and_then(|k| k.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);
144 let mut cmd = crate::command::new_smol_command(shell_path);
145 cmd.args(args);
146 let cmd = match shell_kind {
147 Some(
148 ShellKind::Csh
149 | ShellKind::Tcsh
150 | ShellKind::Rc
151 | ShellKind::Fish
152 | ShellKind::Xonsh
153 | ShellKind::Posix(_),
154 ) => cmd.args([
155 "-l",
156 "-i",
157 "-c",
158 &format!(
159 "cd '{}'; '{}' --printenv",
160 directory.display(),
161 zed_path.display()
162 ),
163 ]),
164 Some(ShellKind::PowerShell) | Some(ShellKind::Pwsh) | None => cmd.args([
165 "-NonInteractive",
166 "-NoProfile",
167 "-Command",
168 &format!(
169 "Set-Location '{}'; & '{}' --printenv",
170 directory.display(),
171 zed_path.display()
172 ),
173 ]),
174 Some(ShellKind::Elvish) => cmd.args([
175 "-c",
176 &format!(
177 "cd '{}'; '{}' --printenv",
178 directory.display(),
179 zed_path.display()
180 ),
181 ]),
182 Some(ShellKind::Nushell) => cmd.args([
183 "-c",
184 &format!(
185 "cd '{}'; {}'{}' --printenv",
186 directory.display(),
187 ShellKind::Nushell
188 .command_prefix()
189 .map(|prefix| prefix.to_string())
190 .unwrap_or_default(),
191 zed_path.display()
192 ),
193 ]),
194 Some(ShellKind::Cmd) => cmd.args([
195 "/c",
196 "cd",
197 &directory.display().to_string(),
198 "&&",
199 &zed_path.display().to_string(),
200 "--printenv",
201 ]),
202 }
203 .stdin(Stdio::null())
204 .stdout(Stdio::piped())
205 .stderr(Stdio::piped());
206 let output = cmd
207 .output()
208 .await
209 .with_context(|| format!("command {cmd:?}"))?;
210 anyhow::ensure!(
211 output.status.success(),
212 "Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}",
213 output.status,
214 String::from_utf8_lossy(&output.stdout),
215 String::from_utf8_lossy(&output.stderr),
216 );
217 let env_output = String::from_utf8_lossy(&output.stdout);
218
219 // Parse the JSON output from zed --printenv
220 serde_json::from_str(&env_output).with_context(|| {
221 format!("Failed to deserialize environment variables from json: {env_output}")
222 })
223}