terminals.rs

  1use crate::Project;
  2use anyhow::{Context as _, Result};
  3use collections::HashMap;
  4use gpui::{AnyWindowHandle, App, AppContext as _, Context, Entity, Task, WeakEntity};
  5use itertools::Itertools;
  6use language::LanguageName;
  7use settings::{Settings, SettingsLocation};
  8use smol::channel::bounded;
  9use std::{
 10    borrow::Cow,
 11    env::{self},
 12    iter,
 13    path::{Path, PathBuf},
 14    sync::Arc,
 15};
 16use task::{Shell, ShellBuilder, SpawnInTerminal};
 17use terminal::{
 18    terminal_settings::{self, TerminalSettings, VenvSettings},
 19    TaskState, TaskStatus, Terminal, TerminalBuilder,
 20};
 21use util::ResultExt;
 22
 23// #[cfg(target_os = "macos")]
 24// use std::os::unix::ffi::OsStrExt;
 25
 26pub struct Terminals {
 27    pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
 28}
 29
 30/// Terminals are opened either for the users shell, or to run a task.
 31#[allow(clippy::large_enum_variant)]
 32#[derive(Debug)]
 33pub enum TerminalKind {
 34    /// Run a shell at the given path (or $HOME if None)
 35    Shell(Option<PathBuf>),
 36    /// Run a task.
 37    Task(SpawnInTerminal),
 38}
 39
 40/// SshCommand describes how to connect to a remote server
 41#[derive(Debug, Clone, PartialEq, Eq)]
 42pub struct SshCommand {
 43    arguments: Vec<String>,
 44}
 45
 46impl Project {
 47    pub fn active_project_directory(&self, cx: &App) -> Option<Arc<Path>> {
 48        let worktree = self
 49            .active_entry()
 50            .and_then(|entry_id| self.worktree_for_entry(entry_id, cx))
 51            .into_iter()
 52            .chain(self.worktrees(cx))
 53            .find_map(|tree| tree.read(cx).root_dir());
 54        worktree
 55    }
 56
 57    pub fn first_project_directory(&self, cx: &App) -> Option<PathBuf> {
 58        let worktree = self.worktrees(cx).next()?;
 59        let worktree = worktree.read(cx);
 60        if worktree.root_entry()?.is_dir() {
 61            Some(worktree.abs_path().to_path_buf())
 62        } else {
 63            None
 64        }
 65    }
 66
 67    pub fn ssh_details(&self, cx: &App) -> Option<(String, SshCommand)> {
 68        if let Some(ssh_client) = &self.ssh_client {
 69            let ssh_client = ssh_client.read(cx);
 70            if let Some(args) = ssh_client.ssh_args() {
 71                return Some((
 72                    ssh_client.connection_options().host.clone(),
 73                    SshCommand { arguments: args },
 74                ));
 75            }
 76        }
 77
 78        return None;
 79    }
 80
 81    pub fn create_terminal(
 82        &mut self,
 83        kind: TerminalKind,
 84        window: AnyWindowHandle,
 85        cx: &mut Context<Self>,
 86    ) -> Task<Result<Entity<Terminal>>> {
 87        let path: Option<Arc<Path>> = match &kind {
 88            TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
 89            TerminalKind::Task(spawn_task) => {
 90                if let Some(cwd) = &spawn_task.cwd {
 91                    Some(Arc::from(cwd.as_ref()))
 92                } else {
 93                    self.active_project_directory(cx)
 94                }
 95            }
 96        };
 97
 98        let mut settings_location = None;
 99        if let Some(path) = path.as_ref() {
100            if let Some((worktree, _)) = self.find_worktree(path, cx) {
101                settings_location = Some(SettingsLocation {
102                    worktree_id: worktree.read(cx).id(),
103                    path,
104                });
105            }
106        }
107        let settings = TerminalSettings::get(settings_location, cx).clone();
108
109        cx.spawn(move |project, mut cx| async move {
110            let python_venv_directory = if let Some(path) = path.clone() {
111                project
112                    .update(&mut cx, |this, cx| {
113                        this.python_venv_directory(path, settings.detect_venv.clone(), cx)
114                    })?
115                    .await
116            } else {
117                None
118            };
119            project.update(&mut cx, |project, cx| {
120                project.create_terminal_with_venv(kind, python_venv_directory, window, cx)
121            })?
122        })
123    }
124
125    pub fn terminal_settings<'a>(
126        &'a self,
127        path: &'a Option<PathBuf>,
128        cx: &'a App,
129    ) -> &'a TerminalSettings {
130        let mut settings_location = None;
131        if let Some(path) = path.as_ref() {
132            if let Some((worktree, _)) = self.find_worktree(path, cx) {
133                settings_location = Some(SettingsLocation {
134                    worktree_id: worktree.read(cx).id(),
135                    path,
136                });
137            }
138        }
139        TerminalSettings::get(settings_location, cx)
140    }
141
142    pub fn exec_in_shell(&self, command: String, cx: &App) -> std::process::Command {
143        let path = self.first_project_directory(cx);
144        let ssh_details = self.ssh_details(cx);
145        let settings = self.terminal_settings(&path, cx).clone();
146
147        let builder = ShellBuilder::new(ssh_details.is_none(), &settings.shell);
148        let (command, args) = builder.build(command, &Vec::new());
149
150        let mut env = self
151            .environment
152            .read(cx)
153            .get_cli_environment()
154            .unwrap_or_default();
155        env.extend(settings.env.clone());
156
157        match &self.ssh_details(cx) {
158            Some((_, ssh_command)) => {
159                let (command, args) = wrap_for_ssh(
160                    ssh_command,
161                    Some((&command, &args)),
162                    path.as_deref(),
163                    env,
164                    None,
165                );
166                let mut command = std::process::Command::new(command);
167                command.args(args);
168                command
169            }
170            None => {
171                let mut command = std::process::Command::new(command);
172                command.args(args);
173                command.envs(env);
174                if let Some(path) = path {
175                    command.current_dir(path);
176                }
177                command
178            }
179        }
180    }
181
182    pub fn create_terminal_with_venv(
183        &mut self,
184        kind: TerminalKind,
185        python_venv_directory: Option<PathBuf>,
186        window: AnyWindowHandle,
187        cx: &mut Context<Self>,
188    ) -> Result<Entity<Terminal>> {
189        let this = &mut *self;
190        let path: Option<Arc<Path>> = match &kind {
191            TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
192            TerminalKind::Task(spawn_task) => {
193                if let Some(cwd) = &spawn_task.cwd {
194                    Some(Arc::from(cwd.as_ref()))
195                } else {
196                    this.active_project_directory(cx)
197                }
198            }
199        };
200        let ssh_details = this.ssh_details(cx);
201
202        let mut settings_location = None;
203        if let Some(path) = path.as_ref() {
204            if let Some((worktree, _)) = this.find_worktree(path, cx) {
205                settings_location = Some(SettingsLocation {
206                    worktree_id: worktree.read(cx).id(),
207                    path,
208                });
209            }
210        }
211        let settings = TerminalSettings::get(settings_location, cx).clone();
212
213        let (completion_tx, completion_rx) = bounded(1);
214
215        // Start with the environment that we might have inherited from the Zed CLI.
216        let mut env = this
217            .environment
218            .read(cx)
219            .get_cli_environment()
220            .unwrap_or_default();
221        // Then extend it with the explicit env variables from the settings, so they take
222        // precedence.
223        env.extend(settings.env.clone());
224
225        let local_path = if ssh_details.is_none() {
226            path.clone()
227        } else {
228            None
229        };
230
231        let mut python_venv_activate_command = None;
232
233        let (spawn_task, shell) = match kind {
234            TerminalKind::Shell(_) => {
235                if let Some(python_venv_directory) = &python_venv_directory {
236                    python_venv_activate_command =
237                        this.python_activate_command(python_venv_directory, &settings.detect_venv);
238                }
239
240                match &ssh_details {
241                    Some((host, ssh_command)) => {
242                        log::debug!("Connecting to a remote server: {ssh_command:?}");
243
244                        // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
245                        // to properly display colors.
246                        // We do not have the luxury of assuming the host has it installed,
247                        // so we set it to a default that does not break the highlighting via ssh.
248                        env.entry("TERM".to_string())
249                            .or_insert_with(|| "xterm-256color".to_string());
250
251                        let (program, args) =
252                            wrap_for_ssh(&ssh_command, None, path.as_deref(), env, None);
253                        env = HashMap::default();
254                        (
255                            Option::<TaskState>::None,
256                            Shell::WithArguments {
257                                program,
258                                args,
259                                title_override: Some(format!("{} — Terminal", host).into()),
260                            },
261                        )
262                    }
263                    None => (None, settings.shell.clone()),
264                }
265            }
266            TerminalKind::Task(spawn_task) => {
267                let task_state = Some(TaskState {
268                    id: spawn_task.id,
269                    full_label: spawn_task.full_label,
270                    label: spawn_task.label,
271                    command_label: spawn_task.command_label,
272                    hide: spawn_task.hide,
273                    status: TaskStatus::Running,
274                    show_summary: spawn_task.show_summary,
275                    show_command: spawn_task.show_command,
276                    show_rerun: spawn_task.show_rerun,
277                    completion_rx,
278                });
279
280                env.extend(spawn_task.env);
281
282                if let Some(venv_path) = &python_venv_directory {
283                    env.insert(
284                        "VIRTUAL_ENV".to_string(),
285                        venv_path.to_string_lossy().to_string(),
286                    );
287                }
288
289                match &ssh_details {
290                    Some((host, ssh_command)) => {
291                        log::debug!("Connecting to a remote server: {ssh_command:?}");
292                        env.entry("TERM".to_string())
293                            .or_insert_with(|| "xterm-256color".to_string());
294                        let (program, args) = wrap_for_ssh(
295                            &ssh_command,
296                            Some((&spawn_task.command, &spawn_task.args)),
297                            path.as_deref(),
298                            env,
299                            python_venv_directory.as_deref(),
300                        );
301                        env = HashMap::default();
302                        (
303                            task_state,
304                            Shell::WithArguments {
305                                program,
306                                args,
307                                title_override: Some(format!("{} — Terminal", host).into()),
308                            },
309                        )
310                    }
311                    None => {
312                        if let Some(venv_path) = &python_venv_directory {
313                            add_environment_path(&mut env, &venv_path.join("bin")).log_err();
314                        }
315
316                        (
317                            task_state,
318                            Shell::WithArguments {
319                                program: spawn_task.command,
320                                args: spawn_task.args,
321                                title_override: None,
322                            },
323                        )
324                    }
325                }
326            }
327        };
328        TerminalBuilder::new(
329            local_path.map(|path| path.to_path_buf()),
330            python_venv_directory,
331            spawn_task,
332            shell,
333            env,
334            settings.cursor_shape.unwrap_or_default(),
335            settings.alternate_scroll,
336            settings.max_scroll_history_lines,
337            ssh_details.is_some(),
338            window,
339            completion_tx,
340            cx,
341        )
342        .map(|builder| {
343            let terminal_handle = cx.new(|cx| builder.subscribe(cx));
344
345            this.terminals
346                .local_handles
347                .push(terminal_handle.downgrade());
348
349            let id = terminal_handle.entity_id();
350            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
351                let handles = &mut project.terminals.local_handles;
352
353                if let Some(index) = handles
354                    .iter()
355                    .position(|terminal| terminal.entity_id() == id)
356                {
357                    handles.remove(index);
358                    cx.notify();
359                }
360            })
361            .detach();
362
363            if let Some(activate_command) = python_venv_activate_command {
364                this.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
365            }
366            terminal_handle
367        })
368    }
369
370    fn python_venv_directory(
371        &self,
372        abs_path: Arc<Path>,
373        venv_settings: VenvSettings,
374        cx: &Context<Project>,
375    ) -> Task<Option<PathBuf>> {
376        cx.spawn(move |this, mut cx| async move {
377            if let Some((worktree, _)) = this
378                .update(&mut cx, |this, cx| this.find_worktree(&abs_path, cx))
379                .ok()?
380            {
381                let toolchain = this
382                    .update(&mut cx, |this, cx| {
383                        this.active_toolchain(
384                            worktree.read(cx).id(),
385                            LanguageName::new("Python"),
386                            cx,
387                        )
388                    })
389                    .ok()?
390                    .await;
391
392                if let Some(toolchain) = toolchain {
393                    let toolchain_path = Path::new(toolchain.path.as_ref());
394                    return Some(toolchain_path.parent()?.parent()?.to_path_buf());
395                }
396            }
397            let venv_settings = venv_settings.as_option()?;
398            this.update(&mut cx, move |this, cx| {
399                if let Some(path) = this.find_venv_in_worktree(&abs_path, &venv_settings, cx) {
400                    return Some(path);
401                }
402                this.find_venv_on_filesystem(&abs_path, &venv_settings, cx)
403            })
404            .ok()
405            .flatten()
406        })
407    }
408
409    fn find_venv_in_worktree(
410        &self,
411        abs_path: &Path,
412        venv_settings: &terminal_settings::VenvSettingsContent,
413        cx: &App,
414    ) -> Option<PathBuf> {
415        let bin_dir_name = match std::env::consts::OS {
416            "windows" => "Scripts",
417            _ => "bin",
418        };
419        venv_settings
420            .directories
421            .iter()
422            .map(|name| abs_path.join(name))
423            .find(|venv_path| {
424                let bin_path = venv_path.join(bin_dir_name);
425                self.find_worktree(&bin_path, cx)
426                    .and_then(|(worktree, relative_path)| {
427                        worktree.read(cx).entry_for_path(&relative_path)
428                    })
429                    .is_some_and(|entry| entry.is_dir())
430            })
431    }
432
433    fn find_venv_on_filesystem(
434        &self,
435        abs_path: &Path,
436        venv_settings: &terminal_settings::VenvSettingsContent,
437        cx: &App,
438    ) -> Option<PathBuf> {
439        let (worktree, _) = self.find_worktree(abs_path, cx)?;
440        let fs = worktree.read(cx).as_local()?.fs();
441        let bin_dir_name = match std::env::consts::OS {
442            "windows" => "Scripts",
443            _ => "bin",
444        };
445        venv_settings
446            .directories
447            .iter()
448            .map(|name| abs_path.join(name))
449            .find(|venv_path| {
450                let bin_path = venv_path.join(bin_dir_name);
451                // One-time synchronous check is acceptable for terminal/task initialization
452                smol::block_on(fs.metadata(&bin_path))
453                    .ok()
454                    .flatten()
455                    .map_or(false, |meta| meta.is_dir)
456            })
457    }
458
459    fn python_activate_command(
460        &self,
461        venv_base_directory: &Path,
462        venv_settings: &VenvSettings,
463    ) -> Option<String> {
464        let venv_settings = venv_settings.as_option()?;
465        let activate_keyword = match venv_settings.activate_script {
466            terminal_settings::ActivateScript::Default => match std::env::consts::OS {
467                "windows" => ".",
468                _ => "source",
469            },
470            terminal_settings::ActivateScript::Nushell => "overlay use",
471            terminal_settings::ActivateScript::PowerShell => ".",
472            _ => "source",
473        };
474        let activate_script_name = match venv_settings.activate_script {
475            terminal_settings::ActivateScript::Default => "activate",
476            terminal_settings::ActivateScript::Csh => "activate.csh",
477            terminal_settings::ActivateScript::Fish => "activate.fish",
478            terminal_settings::ActivateScript::Nushell => "activate.nu",
479            terminal_settings::ActivateScript::PowerShell => "activate.ps1",
480        };
481        let path = venv_base_directory
482            .join(match std::env::consts::OS {
483                "windows" => "Scripts",
484                _ => "bin",
485            })
486            .join(activate_script_name)
487            .to_string_lossy()
488            .to_string();
489        let quoted = shlex::try_quote(&path).ok()?;
490        let line_ending = match std::env::consts::OS {
491            "windows" => "\r",
492            _ => "\n",
493        };
494        smol::block_on(self.fs.metadata(path.as_ref()))
495            .ok()
496            .flatten()?;
497
498        Some(format!(
499            "{} {} ; clear{}",
500            activate_keyword, quoted, line_ending
501        ))
502    }
503
504    fn activate_python_virtual_environment(
505        &self,
506        command: String,
507        terminal_handle: &Entity<Terminal>,
508        cx: &mut App,
509    ) {
510        terminal_handle.update(cx, |terminal, _| terminal.input_bytes(command.into_bytes()));
511    }
512
513    pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
514        &self.terminals.local_handles
515    }
516}
517
518fn wrap_for_ssh(
519    ssh_command: &SshCommand,
520    command: Option<(&String, &Vec<String>)>,
521    path: Option<&Path>,
522    env: HashMap<String, String>,
523    venv_directory: Option<&Path>,
524) -> (String, Vec<String>) {
525    let to_run = if let Some((command, args)) = command {
526        let command = Cow::Borrowed(command.as_str());
527        let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
528        iter::once(command).chain(args).join(" ")
529    } else {
530        "exec ${SHELL:-sh} -l".to_string()
531    };
532
533    let mut env_changes = String::new();
534    for (k, v) in env.iter() {
535        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
536            env_changes.push_str(&format!("{}={} ", k, v));
537        }
538    }
539    if let Some(venv_directory) = venv_directory {
540        if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
541            env_changes.push_str(&format!("PATH={}:$PATH ", str));
542        }
543    }
544
545    let commands = if let Some(path) = path {
546        let path_string = path.to_string_lossy().to_string();
547        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
548        // replace ith with something that works
549        let tilde_prefix = "~/";
550        if path.starts_with(tilde_prefix) {
551            let trimmed_path = path_string
552                .trim_start_matches("/")
553                .trim_start_matches("~")
554                .trim_start_matches("/");
555
556            format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
557        } else {
558            format!("cd {path:?}; {env_changes} {to_run}")
559        }
560    } else {
561        format!("cd; {env_changes} {to_run}")
562    };
563    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
564
565    let program = "ssh".to_string();
566    let mut args = ssh_command.arguments.clone();
567
568    args.push("-t".to_string());
569    args.push(shell_invocation);
570    (program, args)
571}
572
573fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
574    let mut env_paths = vec![new_path.to_path_buf()];
575    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
576        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
577        env_paths.append(&mut paths);
578    }
579
580    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
581    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
582
583    Ok(())
584}
585
586#[cfg(test)]
587mod tests {
588    use collections::HashMap;
589
590    #[test]
591    fn test_add_environment_path_with_existing_path() {
592        let tmp_path = std::path::PathBuf::from("/tmp/new");
593        let mut env = HashMap::default();
594        let old_path = if cfg!(windows) {
595            "/usr/bin;/usr/local/bin"
596        } else {
597            "/usr/bin:/usr/local/bin"
598        };
599        env.insert("PATH".to_string(), old_path.to_string());
600        env.insert("OTHER".to_string(), "aaa".to_string());
601
602        super::add_environment_path(&mut env, &tmp_path).unwrap();
603        if cfg!(windows) {
604            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
605        } else {
606            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
607        }
608        assert_eq!(env.get("OTHER").unwrap(), "aaa");
609    }
610
611    #[test]
612    fn test_add_environment_path_with_empty_path() {
613        let tmp_path = std::path::PathBuf::from("/tmp/new");
614        let mut env = HashMap::default();
615        env.insert("OTHER".to_string(), "aaa".to_string());
616        let os_path = std::env::var("PATH").unwrap();
617        super::add_environment_path(&mut env, &tmp_path).unwrap();
618        if cfg!(windows) {
619            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
620        } else {
621            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
622        }
623        assert_eq!(env.get("OTHER").unwrap(), "aaa");
624    }
625}