terminals.rs

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