terminals.rs

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