environment.rs

  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    let marker = "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
285    // What we're doing here is to spawn a shell and then `cd` into
286    // the project directory to get the env in there as if the user
287    // `cd`'d into it. We do that because tools like direnv, asdf, ...
288    // hook into `cd` and only set up the env after that.
289    //
290    // If the user selects `Direct` for direnv, it would set an environment
291    // variable that later uses to know that it should not run the hook.
292    // We would include in `.envs` call so it is okay to run the hook
293    // even if direnv direct mode is enabled.
294    //
295    // In certain shells we need to execute additional_command in order to
296    // trigger the behavior of direnv, etc.
297    //
298    //
299    // The `exit 0` is the result of hours of debugging, trying to find out
300    // why running this command here, without `exit 0`, would mess
301    // up signal process for our process so that `ctrl-c` doesn't work
302    // anymore.
303    //
304    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
305    // do that, but it does, and `exit 0` helps.
306    let additional_command = PathBuf::from(&shell)
307        .file_name()
308        .and_then(|f| f.to_str())
309        .and_then(|shell| match shell {
310            "fish" => Some("emit fish_prompt;"),
311            _ => None,
312        });
313
314    let command = format!(
315        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
316        dir.display(),
317        additional_command.unwrap_or("")
318    );
319
320    let Some(output) = smol::process::Command::new(&shell)
321        .args(["-l", "-i", "-c", &command])
322        .output()
323        .await
324        .log_err()
325    else {
326        return message("Failed to spawn login shell to source login environment variables. See logs for details");
327    };
328
329    if !output.status.success() {
330        log::error!("login shell exited with {}", output.status);
331        return message("Login shell exited with nonzero exit code. See logs for details");
332    }
333
334    let stdout = String::from_utf8_lossy(&output.stdout);
335    let Some(env_output_start) = stdout.find(marker) else {
336        let stderr = String::from_utf8_lossy(&output.stderr);
337        log::error!(
338            "failed to parse output of `env` command in login shell. stdout: {:?}, stderr: {:?}",
339            stdout,
340            stderr
341        );
342        return message("Failed to parse stdout of env command. See logs for the output");
343    };
344
345    let mut parsed_env = HashMap::default();
346    let env_output = &stdout[env_output_start + marker.len()..];
347
348    parse_env_output(env_output, |key, value| {
349        parsed_env.insert(key, value);
350    });
351
352    let (direnv_environment, direnv_error) = match load_direnv {
353        DirenvSettings::ShellHook => (None, None),
354        DirenvSettings::Direct => match load_direnv_environment(&parsed_env, dir).await {
355            Ok(env) => (Some(env), None),
356            Err(err) => (
357                None,
358                <Option<EnvironmentErrorMessage> as From<DirenvError>>::from(err),
359            ),
360        },
361    };
362
363    for (key, value) in direnv_environment.unwrap_or(HashMap::default()) {
364        parsed_env.insert(key, value);
365    }
366
367    (Some(parsed_env), direnv_error)
368}