1use futures::{future::Shared, FutureExt};
2use std::{path::Path, sync::Arc};
3use util::ResultExt;
4
5use collections::HashMap;
6use gpui::{AppContext, Context, Model, ModelContext, 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 cli_environment: Option<HashMap<String, String>>,
17 get_environment_task: Option<Shared<Task<Option<HashMap<String, String>>>>>,
18 cached_shell_environments: HashMap<WorktreeId, HashMap<String, String>>,
19 environment_error_messages: HashMap<WorktreeId, EnvironmentErrorMessage>,
20}
21
22impl ProjectEnvironment {
23 pub fn new(
24 worktree_store: &Model<WorktreeStore>,
25 cli_environment: Option<HashMap<String, String>>,
26 cx: &mut AppContext,
27 ) -> Model<Self> {
28 cx.new_model(|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 cli_environment,
38 get_environment_task: None,
39 cached_shell_environments: Default::default(),
40 environment_error_messages: Default::default(),
41 }
42 })
43 }
44
45 #[cfg(any(test, feature = "test-support"))]
46 pub(crate) fn set_cached(
47 &mut self,
48 shell_environments: &[(WorktreeId, HashMap<String, String>)],
49 ) {
50 self.cached_shell_environments = shell_environments
51 .iter()
52 .cloned()
53 .collect::<HashMap<_, _>>();
54 }
55
56 pub(crate) fn remove_worktree_environment(&mut self, worktree_id: WorktreeId) {
57 self.cached_shell_environments.remove(&worktree_id);
58 self.environment_error_messages.remove(&worktree_id);
59 }
60
61 /// Returns the inherited CLI environment, if this project was opened from the Zed CLI.
62 pub(crate) fn get_cli_environment(&self) -> Option<HashMap<String, String>> {
63 if let Some(mut env) = self.cli_environment.clone() {
64 set_origin_marker(&mut env, EnvironmentOrigin::Cli);
65 Some(env)
66 } else {
67 None
68 }
69 }
70
71 /// Returns an iterator over all pairs `(worktree_id, error_message)` of
72 /// environment errors associated with this project environment.
73 pub(crate) fn environment_errors(
74 &self,
75 ) -> impl Iterator<Item = (&WorktreeId, &EnvironmentErrorMessage)> {
76 self.environment_error_messages.iter()
77 }
78
79 pub(crate) fn remove_environment_error(&mut self, worktree_id: WorktreeId) {
80 self.environment_error_messages.remove(&worktree_id);
81 }
82
83 /// Returns the project environment, if possible.
84 /// If the project was opened from the CLI, then the inherited CLI environment is returned.
85 /// If it wasn't opened from the CLI, and a worktree is given, then a shell is spawned in
86 /// the worktree's path, to get environment variables as if the user has `cd`'d into
87 /// the worktrees path.
88 pub(crate) fn get_environment(
89 &mut self,
90 worktree_id: Option<WorktreeId>,
91 worktree_abs_path: Option<Arc<Path>>,
92 cx: &ModelContext<Self>,
93 ) -> Shared<Task<Option<HashMap<String, String>>>> {
94 if let Some(task) = self.get_environment_task.as_ref() {
95 task.clone()
96 } else {
97 let task = self
98 .build_environment_task(worktree_id, worktree_abs_path, cx)
99 .shared();
100
101 self.get_environment_task = Some(task.clone());
102 task
103 }
104 }
105
106 fn build_environment_task(
107 &mut self,
108 worktree_id: Option<WorktreeId>,
109 worktree_abs_path: Option<Arc<Path>>,
110 cx: &ModelContext<Self>,
111 ) -> Task<Option<HashMap<String, String>>> {
112 let worktree = worktree_id.zip(worktree_abs_path);
113
114 let cli_environment = self.get_cli_environment();
115 if cli_environment.is_some() {
116 Task::ready(cli_environment)
117 } else if let Some((worktree_id, worktree_abs_path)) = worktree {
118 self.get_worktree_env(worktree_id, worktree_abs_path, cx)
119 } else {
120 Task::ready(None)
121 }
122 }
123
124 fn get_worktree_env(
125 &mut self,
126 worktree_id: WorktreeId,
127 worktree_abs_path: Arc<Path>,
128 cx: &ModelContext<Self>,
129 ) -> Task<Option<HashMap<String, String>>> {
130 let cached_env = self.cached_shell_environments.get(&worktree_id).cloned();
131 if let Some(env) = cached_env {
132 Task::ready(Some(env))
133 } else {
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_executor()
139 .spawn({
140 let cwd = worktree_abs_path.clone();
141 async move { load_shell_environment(&cwd, &load_direnv).await }
142 })
143 .await;
144
145 if let Some(shell_env) = shell_env.as_mut() {
146 this.update(&mut cx, |this, _| {
147 this.cached_shell_environments
148 .insert(worktree_id, shell_env.clone());
149 })
150 .log_err();
151
152 set_origin_marker(shell_env, EnvironmentOrigin::WorktreeShell);
153 }
154
155 if let Some(error) = error_message {
156 this.update(&mut cx, |this, _| {
157 this.environment_error_messages.insert(worktree_id, error);
158 })
159 .log_err();
160 }
161
162 shell_env
163 })
164 }
165 }
166}
167
168fn set_origin_marker(env: &mut HashMap<String, String>, origin: EnvironmentOrigin) {
169 env.insert(ZED_ENVIRONMENT_ORIGIN_MARKER.to_string(), origin.into());
170}
171
172const ZED_ENVIRONMENT_ORIGIN_MARKER: &str = "ZED_ENVIRONMENT";
173
174enum EnvironmentOrigin {
175 Cli,
176 WorktreeShell,
177}
178
179impl From<EnvironmentOrigin> for String {
180 fn from(val: EnvironmentOrigin) -> Self {
181 match val {
182 EnvironmentOrigin::Cli => "cli".into(),
183 EnvironmentOrigin::WorktreeShell => "worktree-shell".into(),
184 }
185 }
186}
187
188pub struct EnvironmentErrorMessage(pub String);
189
190impl EnvironmentErrorMessage {
191 #[allow(dead_code)]
192 fn from_str(s: &str) -> Self {
193 Self(String::from(s))
194 }
195}
196
197#[cfg(any(test, feature = "test-support"))]
198async fn load_shell_environment(
199 _dir: &Path,
200 _load_direnv: &DirenvSettings,
201) -> (
202 Option<HashMap<String, String>>,
203 Option<EnvironmentErrorMessage>,
204) {
205 let fake_env = [("ZED_FAKE_TEST_ENV".into(), "true".into())]
206 .into_iter()
207 .collect();
208 (Some(fake_env), None)
209}
210
211#[cfg(not(any(test, feature = "test-support")))]
212async fn load_shell_environment(
213 dir: &Path,
214 load_direnv: &DirenvSettings,
215) -> (
216 Option<HashMap<String, String>>,
217 Option<EnvironmentErrorMessage>,
218) {
219 use crate::direnv::{load_direnv_environment, DirenvError};
220 use std::path::PathBuf;
221 use util::parse_env_output;
222
223 fn message<T>(with: &str) -> (Option<T>, Option<EnvironmentErrorMessage>) {
224 let message = EnvironmentErrorMessage::from_str(with);
225 (None, Some(message))
226 }
227
228 let (direnv_environment, direnv_error) = match load_direnv {
229 DirenvSettings::ShellHook => (None, None),
230 DirenvSettings::Direct => match load_direnv_environment(dir).await {
231 Ok(env) => (Some(env), None),
232 Err(err) => (
233 None,
234 <Option<EnvironmentErrorMessage> as From<DirenvError>>::from(err),
235 ),
236 },
237 };
238 let direnv_environment = direnv_environment.unwrap_or(HashMap::default());
239
240 let marker = "ZED_SHELL_START";
241 let Some(shell) = std::env::var("SHELL").log_err() else {
242 return message("Failed to get login environment. SHELL environment variable is not set");
243 };
244
245 // What we're doing here is to spawn a shell and then `cd` into
246 // the project directory to get the env in there as if the user
247 // `cd`'d into it. We do that because tools like direnv, asdf, ...
248 // hook into `cd` and only set up the env after that.
249 //
250 // If the user selects `Direct` for direnv, it would set an environment
251 // variable that later uses to know that it should not run the hook.
252 // We would include in `.envs` call so it is okay to run the hook
253 // even if direnv direct mode is enabled.
254 //
255 // In certain shells we need to execute additional_command in order to
256 // trigger the behavior of direnv, etc.
257 //
258 //
259 // The `exit 0` is the result of hours of debugging, trying to find out
260 // why running this command here, without `exit 0`, would mess
261 // up signal process for our process so that `ctrl-c` doesn't work
262 // anymore.
263 //
264 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
265 // do that, but it does, and `exit 0` helps.
266 let additional_command = PathBuf::from(&shell)
267 .file_name()
268 .and_then(|f| f.to_str())
269 .and_then(|shell| match shell {
270 "fish" => Some("emit fish_prompt;"),
271 _ => None,
272 });
273
274 let command = format!(
275 "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
276 dir.display(),
277 additional_command.unwrap_or("")
278 );
279
280 let Some(output) = smol::process::Command::new(&shell)
281 .args(["-l", "-i", "-c", &command])
282 .envs(direnv_environment)
283 .output()
284 .await
285 .log_err()
286 else {
287 return message("Failed to spawn login shell to source login environment variables. See logs for details");
288 };
289
290 if !output.status.success() {
291 log::error!("login shell exited with {}", output.status);
292 return message("Login shell exited with nonzero exit code. See logs for details");
293 }
294
295 let stdout = String::from_utf8_lossy(&output.stdout);
296 let Some(env_output_start) = stdout.find(marker) else {
297 log::error!("failed to parse output of `env` command in login shell: {stdout}");
298 return message("Failed to parse stdout of env command. See logs for the output");
299 };
300
301 let mut parsed_env = HashMap::default();
302 let env_output = &stdout[env_output_start + marker.len()..];
303
304 parse_env_output(env_output, |key, value| {
305 parsed_env.insert(key, value);
306 });
307
308 (Some(parsed_env), direnv_error)
309}