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 `(abs_path, 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
147#[derive(Debug)]
148pub struct EnvironmentErrorMessage(pub String);
149
150impl std::fmt::Display for EnvironmentErrorMessage {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        write!(f, "{}", self.0)
153    }
154}
155
156impl EnvironmentErrorMessage {
157    #[allow(dead_code)]
158    fn from_str(s: &str) -> Self {
159        Self(String::from(s))
160    }
161}
162
163async fn load_directory_shell_environment(
164    abs_path: &Path,
165    load_direnv: &DirenvSettings,
166) -> (
167    Option<HashMap<String, String>>,
168    Option<EnvironmentErrorMessage>,
169) {
170    match smol::fs::metadata(abs_path).await {
171        Ok(meta) => {
172            let dir = if meta.is_dir() {
173                abs_path
174            } else if let Some(parent) = abs_path.parent() {
175                parent
176            } else {
177                return (
178                    None,
179                    Some(EnvironmentErrorMessage(format!(
180                        "Failed to load shell environment in {}: not a directory",
181                        abs_path.display()
182                    ))),
183                );
184            };
185
186            load_shell_environment(&dir, load_direnv).await
187        }
188        Err(err) => (
189            None,
190            Some(EnvironmentErrorMessage(format!(
191                "Failed to load shell environment in {}: {}",
192                abs_path.display(),
193                err
194            ))),
195        ),
196    }
197}
198
199#[cfg(any(test, feature = "test-support"))]
200async fn load_shell_environment(
201    _dir: &Path,
202    _load_direnv: &DirenvSettings,
203) -> (
204    Option<HashMap<String, String>>,
205    Option<EnvironmentErrorMessage>,
206) {
207    let fake_env = [("ZED_FAKE_TEST_ENV".into(), "true".into())]
208        .into_iter()
209        .collect();
210    (Some(fake_env), None)
211}
212
213#[cfg(all(target_os = "windows", not(any(test, feature = "test-support"))))]
214async fn load_shell_environment(
215    _dir: &Path,
216    _load_direnv: &DirenvSettings,
217) -> (
218    Option<HashMap<String, String>>,
219    Option<EnvironmentErrorMessage>,
220) {
221    // TODO the current code works with Unix $SHELL only, implement environment loading on windows
222    (None, None)
223}
224
225#[cfg(not(any(target_os = "windows", test, feature = "test-support")))]
226async fn load_shell_environment(
227    dir: &Path,
228    load_direnv: &DirenvSettings,
229) -> (
230    Option<HashMap<String, String>>,
231    Option<EnvironmentErrorMessage>,
232) {
233    use crate::direnv::{DirenvError, load_direnv_environment};
234    use std::path::PathBuf;
235    use util::parse_env_output;
236
237    fn message<T>(with: &str) -> (Option<T>, Option<EnvironmentErrorMessage>) {
238        let message = EnvironmentErrorMessage::from_str(with);
239        (None, Some(message))
240    }
241
242    const MARKER: &str = "ZED_SHELL_START";
243    let Some(shell) = std::env::var("SHELL").log_err() else {
244        return message("Failed to get login environment. SHELL environment variable is not set");
245    };
246    let shell_path = PathBuf::from(&shell);
247    let shell_name = shell_path.file_name().and_then(|f| f.to_str());
248
249    // What we're doing here is to spawn a shell and then `cd` into
250    // the project directory to get the env in there as if the user
251    // `cd`'d into it. We do that because tools like direnv, asdf, ...
252    // hook into `cd` and only set up the env after that.
253    //
254    // If the user selects `Direct` for direnv, it would set an environment
255    // variable that later uses to know that it should not run the hook.
256    // We would include in `.envs` call so it is okay to run the hook
257    // even if direnv direct mode is enabled.
258    //
259    // In certain shells we need to execute additional_command in order to
260    // trigger the behavior of direnv, etc.
261    //
262    //
263    // The `exit 0` is the result of hours of debugging, trying to find out
264    // why running this command here, without `exit 0`, would mess
265    // up signal process for our process so that `ctrl-c` doesn't work
266    // anymore.
267    //
268    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
269    // do that, but it does, and `exit 0` helps.
270
271    let command = match shell_name {
272        Some("fish") => format!(
273            "cd '{}'; emit fish_prompt; printf '%s' {MARKER}; /usr/bin/env; exit 0;",
274            dir.display()
275        ),
276        _ => format!(
277            "cd '{}'; printf '%s' {MARKER}; /usr/bin/env; exit 0;",
278            dir.display()
279        ),
280    };
281
282    // csh/tcsh only supports `-l` if it's the only flag. So this won't be a login shell.
283    // Users must rely on vars from `~/.tcshrc` or `~/.cshrc` and not `.login` as a result.
284    let args = match shell_name {
285        Some("tcsh") | Some("csh") => vec!["-i", "-c", &command],
286        _ => vec!["-l", "-i", "-c", &command],
287    };
288
289    let Some(output) = smol::process::Command::new(&shell)
290        .args(&args)
291        .output()
292        .await
293        .log_err()
294    else {
295        return message(
296            "Failed to spawn login shell to source login environment variables. See logs for details",
297        );
298    };
299
300    if !output.status.success() {
301        log::error!("login shell exited with {}", output.status);
302        return message("Login shell exited with nonzero exit code. See logs for details");
303    }
304
305    let stdout = String::from_utf8_lossy(&output.stdout);
306    let Some(env_output_start) = stdout.find(MARKER) else {
307        let stderr = String::from_utf8_lossy(&output.stderr);
308        log::error!(
309            "failed to parse output of `env` command in login shell. stdout: {:?}, stderr: {:?}",
310            stdout,
311            stderr
312        );
313        return message("Failed to parse stdout of env command. See logs for the output");
314    };
315
316    let mut parsed_env = HashMap::default();
317    let env_output = &stdout[env_output_start + MARKER.len()..];
318
319    parse_env_output(env_output, |key, value| {
320        parsed_env.insert(key, value);
321    });
322
323    let (direnv_environment, direnv_error) = match load_direnv {
324        DirenvSettings::ShellHook => (None, None),
325        DirenvSettings::Direct => match load_direnv_environment(&parsed_env, dir).await {
326            Ok(env) => (Some(env), None),
327            Err(err) => (
328                None,
329                <Option<EnvironmentErrorMessage> as From<DirenvError>>::from(err),
330            ),
331        },
332    };
333
334    for (key, value) in direnv_environment.unwrap_or(HashMap::default()) {
335        parsed_env.insert(key, value);
336    }
337
338    (Some(parsed_env), direnv_error)
339}
340
341fn get_directory_env(
342    abs_path: Arc<Path>,
343    cx: &Context<ProjectEnvironment>,
344) -> Task<Option<HashMap<String, String>>> {
345    let load_direnv = ProjectSettings::get_global(cx).load_direnv.clone();
346
347    cx.spawn(async move |this, cx| {
348        let (mut shell_env, error_message) = cx
349            .background_spawn({
350                let abs_path = abs_path.clone();
351                async move { load_directory_shell_environment(&abs_path, &load_direnv).await }
352            })
353            .await;
354
355        if let Some(shell_env) = shell_env.as_mut() {
356            let path = shell_env
357                .get("PATH")
358                .map(|path| path.as_str())
359                .unwrap_or_default();
360            log::info!(
361                "using project environment variables shell launched in {:?}. PATH={:?}",
362                abs_path,
363                path
364            );
365
366            set_origin_marker(shell_env, EnvironmentOrigin::WorktreeShell);
367        }
368
369        if let Some(error) = error_message {
370            this.update(cx, |this, cx| {
371                log::error!(
372                    "error fetching environment for path {abs_path:?}: {}",
373                    error
374                );
375                this.environment_error_messages.insert(abs_path, error);
376                cx.emit(ProjectEnvironmentEvent::ErrorsUpdated)
377            })
378            .log_err();
379        }
380
381        shell_env
382    })
383}