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