1use futures::{future::Shared, FutureExt};
2use std::{path::Path, sync::Arc};
3use util::ResultExt;
4
5use collections::HashMap;
6use gpui::{App, AppContext as _, Context, Entity, Task};
7use settings::Settings as _;
8use worktree::WorktreeId;
9
10use crate::{
11 project_settings::{DirenvSettings, ProjectSettings},
12 worktree_store::{WorktreeStore, WorktreeStoreEvent},
13};
14
15pub struct ProjectEnvironment {
16 worktree_store: Entity<WorktreeStore>,
17 cli_environment: Option<HashMap<String, String>>,
18 environments: HashMap<WorktreeId, Shared<Task<Option<HashMap<String, String>>>>>,
19 environment_error_messages: HashMap<WorktreeId, EnvironmentErrorMessage>,
20}
21
22impl ProjectEnvironment {
23 pub fn new(
24 worktree_store: &Entity<WorktreeStore>,
25 cli_environment: Option<HashMap<String, String>>,
26 cx: &mut App,
27 ) -> Entity<Self> {
28 cx.new(|cx| {
29 cx.subscribe(worktree_store, |this: &mut Self, _, event, _| {
30 if let WorktreeStoreEvent::WorktreeRemoved(_, id) = event {
31 this.remove_worktree_environment(*id);
32 }
33 })
34 .detach();
35
36 Self {
37 worktree_store: worktree_store.clone(),
38 cli_environment,
39 environments: Default::default(),
40 environment_error_messages: Default::default(),
41 }
42 })
43 }
44
45 pub(crate) fn remove_worktree_environment(&mut self, worktree_id: WorktreeId) {
46 self.environment_error_messages.remove(&worktree_id);
47 self.environments.remove(&worktree_id);
48 }
49
50 /// Returns the inherited CLI environment, if this project was opened from the Zed CLI.
51 pub(crate) fn get_cli_environment(&self) -> Option<HashMap<String, String>> {
52 if let Some(mut env) = self.cli_environment.clone() {
53 set_origin_marker(&mut env, EnvironmentOrigin::Cli);
54 Some(env)
55 } else {
56 None
57 }
58 }
59
60 /// Returns an iterator over all pairs `(worktree_id, error_message)` of
61 /// environment errors associated with this project environment.
62 pub(crate) fn environment_errors(
63 &self,
64 ) -> impl Iterator<Item = (&WorktreeId, &EnvironmentErrorMessage)> {
65 self.environment_error_messages.iter()
66 }
67
68 pub(crate) fn remove_environment_error(&mut self, worktree_id: WorktreeId) {
69 self.environment_error_messages.remove(&worktree_id);
70 }
71
72 /// Returns the project environment, if possible.
73 /// If the project was opened from the CLI, then the inherited CLI environment is returned.
74 /// If it wasn't opened from the CLI, and a worktree is given, then a shell is spawned in
75 /// the worktree's path, to get environment variables as if the user has `cd`'d into
76 /// the worktrees path.
77 pub(crate) fn get_environment(
78 &mut self,
79 worktree_id: Option<WorktreeId>,
80 worktree_abs_path: Option<Arc<Path>>,
81 cx: &Context<Self>,
82 ) -> Shared<Task<Option<HashMap<String, String>>>> {
83 if cfg!(any(test, feature = "test-support")) {
84 return Task::ready(Some(HashMap::default())).shared();
85 }
86
87 if let Some(cli_environment) = self.get_cli_environment() {
88 return cx
89 .spawn(|_, _| async move {
90 let path = cli_environment
91 .get("PATH")
92 .map(|path| path.as_str())
93 .unwrap_or_default();
94 log::info!(
95 "using project environment variables from CLI. PATH={:?}",
96 path
97 );
98 Some(cli_environment)
99 })
100 .shared();
101 }
102
103 let Some((worktree_id, worktree_abs_path)) = worktree_id.zip(worktree_abs_path) else {
104 return Task::ready(None).shared();
105 };
106
107 if self
108 .worktree_store
109 .read(cx)
110 .worktree_for_id(worktree_id, cx)
111 .map(|w| !w.read(cx).is_local())
112 .unwrap_or(true)
113 {
114 return Task::ready(None).shared();
115 }
116
117 if let Some(task) = self.environments.get(&worktree_id) {
118 task.clone()
119 } else {
120 let task = self
121 .get_worktree_env(worktree_id, worktree_abs_path, cx)
122 .shared();
123 self.environments.insert(worktree_id, task.clone());
124 task
125 }
126 }
127
128 fn get_worktree_env(
129 &mut self,
130 worktree_id: WorktreeId,
131 worktree_abs_path: Arc<Path>,
132 cx: &Context<Self>,
133 ) -> Task<Option<HashMap<String, String>>> {
134 let load_direnv = ProjectSettings::get_global(cx).load_direnv.clone();
135
136 cx.spawn(|this, mut cx| async move {
137 let (mut shell_env, error_message) = cx
138 .background_spawn({
139 let worktree_abs_path = worktree_abs_path.clone();
140 async move {
141 load_worktree_shell_environment(&worktree_abs_path, &load_direnv).await
142 }
143 })
144 .await;
145
146 if let Some(shell_env) = shell_env.as_mut() {
147 let path = shell_env
148 .get("PATH")
149 .map(|path| path.as_str())
150 .unwrap_or_default();
151 log::info!(
152 "using project environment variables shell launched in {:?}. PATH={:?}",
153 worktree_abs_path,
154 path
155 );
156
157 set_origin_marker(shell_env, EnvironmentOrigin::WorktreeShell);
158 }
159
160 if let Some(error) = error_message {
161 this.update(&mut cx, |this, _| {
162 this.environment_error_messages.insert(worktree_id, error);
163 })
164 .log_err();
165 }
166
167 shell_env
168 })
169 }
170}
171
172fn set_origin_marker(env: &mut HashMap<String, String>, origin: EnvironmentOrigin) {
173 env.insert(ZED_ENVIRONMENT_ORIGIN_MARKER.to_string(), origin.into());
174}
175
176const ZED_ENVIRONMENT_ORIGIN_MARKER: &str = "ZED_ENVIRONMENT";
177
178enum EnvironmentOrigin {
179 Cli,
180 WorktreeShell,
181}
182
183impl From<EnvironmentOrigin> for String {
184 fn from(val: EnvironmentOrigin) -> Self {
185 match val {
186 EnvironmentOrigin::Cli => "cli".into(),
187 EnvironmentOrigin::WorktreeShell => "worktree-shell".into(),
188 }
189 }
190}
191
192pub struct EnvironmentErrorMessage(pub String);
193
194impl EnvironmentErrorMessage {
195 #[allow(dead_code)]
196 fn from_str(s: &str) -> Self {
197 Self(String::from(s))
198 }
199}
200
201async fn load_worktree_shell_environment(
202 worktree_abs_path: &Path,
203 load_direnv: &DirenvSettings,
204) -> (
205 Option<HashMap<String, String>>,
206 Option<EnvironmentErrorMessage>,
207) {
208 match smol::fs::metadata(worktree_abs_path).await {
209 Ok(meta) => {
210 let dir = if meta.is_dir() {
211 worktree_abs_path
212 } else if let Some(parent) = worktree_abs_path.parent() {
213 parent
214 } else {
215 return (
216 None,
217 Some(EnvironmentErrorMessage(format!(
218 "Failed to load shell environment in {}: not a directory",
219 worktree_abs_path.display()
220 ))),
221 );
222 };
223
224 load_shell_environment(&dir, load_direnv).await
225 }
226 Err(err) => (
227 None,
228 Some(EnvironmentErrorMessage(format!(
229 "Failed to load shell environment in {}: {}",
230 worktree_abs_path.display(),
231 err
232 ))),
233 ),
234 }
235}
236
237#[cfg(any(test, feature = "test-support"))]
238async fn load_shell_environment(
239 _dir: &Path,
240 _load_direnv: &DirenvSettings,
241) -> (
242 Option<HashMap<String, String>>,
243 Option<EnvironmentErrorMessage>,
244) {
245 let fake_env = [("ZED_FAKE_TEST_ENV".into(), "true".into())]
246 .into_iter()
247 .collect();
248 (Some(fake_env), None)
249}
250
251#[cfg(all(target_os = "windows", not(any(test, feature = "test-support"))))]
252async fn load_shell_environment(
253 _dir: &Path,
254 _load_direnv: &DirenvSettings,
255) -> (
256 Option<HashMap<String, String>>,
257 Option<EnvironmentErrorMessage>,
258) {
259 // TODO the current code works with Unix $SHELL only, implement environment loading on windows
260 (None, None)
261}
262
263#[cfg(not(any(target_os = "windows", test, feature = "test-support")))]
264async fn load_shell_environment(
265 dir: &Path,
266 load_direnv: &DirenvSettings,
267) -> (
268 Option<HashMap<String, String>>,
269 Option<EnvironmentErrorMessage>,
270) {
271 use crate::direnv::{load_direnv_environment, DirenvError};
272 use std::path::PathBuf;
273 use util::parse_env_output;
274
275 fn message<T>(with: &str) -> (Option<T>, Option<EnvironmentErrorMessage>) {
276 let message = EnvironmentErrorMessage::from_str(with);
277 (None, Some(message))
278 }
279
280 const MARKER: &str = "ZED_SHELL_START";
281 let Some(shell) = std::env::var("SHELL").log_err() else {
282 return message("Failed to get login environment. SHELL environment variable is not set");
283 };
284 let shell_path = PathBuf::from(&shell);
285 let shell_name = shell_path.file_name().and_then(|f| f.to_str());
286
287 // What we're doing here is to spawn a shell and then `cd` into
288 // the project directory to get the env in there as if the user
289 // `cd`'d into it. We do that because tools like direnv, asdf, ...
290 // hook into `cd` and only set up the env after that.
291 //
292 // If the user selects `Direct` for direnv, it would set an environment
293 // variable that later uses to know that it should not run the hook.
294 // We would include in `.envs` call so it is okay to run the hook
295 // even if direnv direct mode is enabled.
296 //
297 // In certain shells we need to execute additional_command in order to
298 // trigger the behavior of direnv, etc.
299 //
300 //
301 // The `exit 0` is the result of hours of debugging, trying to find out
302 // why running this command here, without `exit 0`, would mess
303 // up signal process for our process so that `ctrl-c` doesn't work
304 // anymore.
305 //
306 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
307 // do that, but it does, and `exit 0` helps.
308
309 let command = match shell_name {
310 Some("fish") => format!(
311 "cd '{}'; emit fish_prompt; printf '%s' {MARKER}; /usr/bin/env; exit 0;",
312 dir.display()
313 ),
314 _ => format!(
315 "cd '{}'; printf '%s' {MARKER}; /usr/bin/env; exit 0;",
316 dir.display()
317 ),
318 };
319
320 // csh/tcsh only supports `-l` if it's the only flag. So this won't be a login shell.
321 // Users must rely on vars from `~/.tcshrc` or `~/.cshrc` and not `.login` as a result.
322 let args = match shell_name {
323 Some("tcsh") | Some("csh") => vec!["-i", "-c", &command],
324 _ => vec!["-l", "-i", "-c", &command],
325 };
326
327 let Some(output) = smol::process::Command::new(&shell)
328 .args(&args)
329 .output()
330 .await
331 .log_err()
332 else {
333 return message("Failed to spawn login shell to source login environment variables. See logs for details");
334 };
335
336 if !output.status.success() {
337 log::error!("login shell exited with {}", output.status);
338 return message("Login shell exited with nonzero exit code. See logs for details");
339 }
340
341 let stdout = String::from_utf8_lossy(&output.stdout);
342 let Some(env_output_start) = stdout.find(MARKER) else {
343 let stderr = String::from_utf8_lossy(&output.stderr);
344 log::error!(
345 "failed to parse output of `env` command in login shell. stdout: {:?}, stderr: {:?}",
346 stdout,
347 stderr
348 );
349 return message("Failed to parse stdout of env command. See logs for the output");
350 };
351
352 let mut parsed_env = HashMap::default();
353 let env_output = &stdout[env_output_start + MARKER.len()..];
354
355 parse_env_output(env_output, |key, value| {
356 parsed_env.insert(key, value);
357 });
358
359 let (direnv_environment, direnv_error) = match load_direnv {
360 DirenvSettings::ShellHook => (None, None),
361 DirenvSettings::Direct => match load_direnv_environment(&parsed_env, dir).await {
362 Ok(env) => (Some(env), None),
363 Err(err) => (
364 None,
365 <Option<EnvironmentErrorMessage> as From<DirenvError>>::from(err),
366 ),
367 },
368 };
369
370 for (key, value) in direnv_environment.unwrap_or(HashMap::default()) {
371 parsed_env.insert(key, value);
372 }
373
374 (Some(parsed_env), direnv_error)
375}