environment.rs

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