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, 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.clone());
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.clone());
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 =
260                        this.python_activate_command(python_venv_directory, &settings.detect_venv);
261                }
262
263                match ssh_details {
264                    Some(SshDetails {
265                        host,
266                        ssh_command,
267                        envs,
268                        path_style,
269                    }) => {
270                        log::debug!("Connecting to a remote server: {ssh_command:?}");
271
272                        // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
273                        // to properly display colors.
274                        // We do not have the luxury of assuming the host has it installed,
275                        // so we set it to a default that does not break the highlighting via ssh.
276                        env.entry("TERM".to_string())
277                            .or_insert_with(|| "xterm-256color".to_string());
278
279                        let (program, args) = wrap_for_ssh(
280                            &ssh_command,
281                            None,
282                            path.as_deref(),
283                            env,
284                            None,
285                            path_style,
286                        );
287                        env = HashMap::default();
288                        if let Some(envs) = envs {
289                            env.extend(envs);
290                        }
291                        (
292                            Option::<TaskState>::None,
293                            Shell::WithArguments {
294                                program,
295                                args,
296                                title_override: Some(format!("{} — Terminal", host).into()),
297                            },
298                        )
299                    }
300                    None => (None, settings.shell),
301                }
302            }
303            TerminalKind::Task(spawn_task) => {
304                let task_state = Some(TaskState {
305                    id: spawn_task.id,
306                    full_label: spawn_task.full_label,
307                    label: spawn_task.label,
308                    command_label: spawn_task.command_label,
309                    hide: spawn_task.hide,
310                    status: TaskStatus::Running,
311                    show_summary: spawn_task.show_summary,
312                    show_command: spawn_task.show_command,
313                    show_rerun: spawn_task.show_rerun,
314                    completion_rx,
315                });
316
317                env.extend(spawn_task.env);
318
319                if let Some(venv_path) = &python_venv_directory {
320                    env.insert(
321                        "VIRTUAL_ENV".to_string(),
322                        venv_path.to_string_lossy().to_string(),
323                    );
324                }
325
326                match ssh_details {
327                    Some(SshDetails {
328                        host,
329                        ssh_command,
330                        envs,
331                        path_style,
332                    }) => {
333                        log::debug!("Connecting to a remote server: {ssh_command:?}");
334                        env.entry("TERM".to_string())
335                            .or_insert_with(|| "xterm-256color".to_string());
336                        let (program, args) = wrap_for_ssh(
337                            &ssh_command,
338                            spawn_task
339                                .command
340                                .as_ref()
341                                .map(|command| (command, &spawn_task.args)),
342                            path.as_deref(),
343                            env,
344                            python_venv_directory.as_deref(),
345                            path_style,
346                        );
347                        env = HashMap::default();
348                        if let Some(envs) = envs {
349                            env.extend(envs);
350                        }
351                        (
352                            task_state,
353                            Shell::WithArguments {
354                                program,
355                                args,
356                                title_override: Some(format!("{} — Terminal", host).into()),
357                            },
358                        )
359                    }
360                    None => {
361                        if let Some(venv_path) = &python_venv_directory {
362                            add_environment_path(&mut env, &venv_path.join("bin")).log_err();
363                        }
364
365                        let shell = if let Some(program) = spawn_task.command {
366                            Shell::WithArguments {
367                                program,
368                                args: spawn_task.args,
369                                title_override: None,
370                            }
371                        } else {
372                            Shell::System
373                        };
374                        (task_state, shell)
375                    }
376                }
377            }
378        };
379        TerminalBuilder::new(
380            local_path.map(|path| path.to_path_buf()),
381            python_venv_directory,
382            spawn_task,
383            shell,
384            env,
385            settings.cursor_shape.unwrap_or_default(),
386            settings.alternate_scroll,
387            settings.max_scroll_history_lines,
388            is_ssh_terminal,
389            window,
390            completion_tx,
391            cx,
392        )
393        .map(|builder| {
394            let terminal_handle = cx.new(|cx| builder.subscribe(cx));
395
396            this.terminals
397                .local_handles
398                .push(terminal_handle.downgrade());
399
400            let id = terminal_handle.entity_id();
401            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
402                let handles = &mut project.terminals.local_handles;
403
404                if let Some(index) = handles
405                    .iter()
406                    .position(|terminal| terminal.entity_id() == id)
407                {
408                    handles.remove(index);
409                    cx.notify();
410                }
411            })
412            .detach();
413
414            if let Some(activate_command) = python_venv_activate_command {
415                this.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
416            }
417            terminal_handle
418        })
419    }
420
421    fn python_venv_directory(
422        &self,
423        abs_path: Arc<Path>,
424        venv_settings: VenvSettings,
425        cx: &Context<Project>,
426    ) -> Task<Option<PathBuf>> {
427        cx.spawn(async move |this, cx| {
428            if let Some((worktree, relative_path)) = this
429                .update(cx, |this, cx| this.find_worktree(&abs_path, cx))
430                .ok()?
431            {
432                let toolchain = this
433                    .update(cx, |this, cx| {
434                        this.active_toolchain(
435                            ProjectPath {
436                                worktree_id: worktree.read(cx).id(),
437                                path: relative_path.into(),
438                            },
439                            LanguageName::new("Python"),
440                            cx,
441                        )
442                    })
443                    .ok()?
444                    .await;
445
446                if let Some(toolchain) = toolchain {
447                    let toolchain_path = Path::new(toolchain.path.as_ref());
448                    return Some(toolchain_path.parent()?.parent()?.to_path_buf());
449                }
450            }
451            let venv_settings = venv_settings.as_option()?;
452            this.update(cx, move |this, cx| {
453                if let Some(path) = this.find_venv_in_worktree(&abs_path, &venv_settings, cx) {
454                    return Some(path);
455                }
456                this.find_venv_on_filesystem(&abs_path, &venv_settings, cx)
457            })
458            .ok()
459            .flatten()
460        })
461    }
462
463    fn find_venv_in_worktree(
464        &self,
465        abs_path: &Path,
466        venv_settings: &terminal_settings::VenvSettingsContent,
467        cx: &App,
468    ) -> Option<PathBuf> {
469        let bin_dir_name = match std::env::consts::OS {
470            "windows" => "Scripts",
471            _ => "bin",
472        };
473        venv_settings
474            .directories
475            .iter()
476            .map(|name| abs_path.join(name))
477            .find(|venv_path| {
478                let bin_path = venv_path.join(bin_dir_name);
479                self.find_worktree(&bin_path, cx)
480                    .and_then(|(worktree, relative_path)| {
481                        worktree
482                            .read(cx)
483                            .entry_for_path(&relative_path)
484                            .map(|entry| entry.is_dir())
485                    })
486                    .unwrap_or(false)
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().clone();
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 python_activate_command(
517        &self,
518        venv_base_directory: &Path,
519        venv_settings: &VenvSettings,
520    ) -> Option<String> {
521        let venv_settings = venv_settings.as_option()?;
522        let activate_keyword = match venv_settings.activate_script {
523            terminal_settings::ActivateScript::Default => match std::env::consts::OS {
524                "windows" => ".",
525                _ => "source",
526            },
527            terminal_settings::ActivateScript::Nushell => "overlay use",
528            terminal_settings::ActivateScript::PowerShell => ".",
529            _ => "source",
530        };
531        let activate_script_name = match venv_settings.activate_script {
532            terminal_settings::ActivateScript::Default => "activate",
533            terminal_settings::ActivateScript::Csh => "activate.csh",
534            terminal_settings::ActivateScript::Fish => "activate.fish",
535            terminal_settings::ActivateScript::Nushell => "activate.nu",
536            terminal_settings::ActivateScript::PowerShell => "activate.ps1",
537        };
538        let path = venv_base_directory
539            .join(match std::env::consts::OS {
540                "windows" => "Scripts",
541                _ => "bin",
542            })
543            .join(activate_script_name)
544            .to_string_lossy()
545            .to_string();
546        let quoted = shlex::try_quote(&path).ok()?;
547        let line_ending = match std::env::consts::OS {
548            "windows" => "\r",
549            _ => "\n",
550        };
551        smol::block_on(self.fs.metadata(path.as_ref()))
552            .ok()
553            .flatten()?;
554
555        Some(format!(
556            "{} {} ; clear{}",
557            activate_keyword, quoted, line_ending
558        ))
559    }
560
561    fn activate_python_virtual_environment(
562        &self,
563        command: String,
564        terminal_handle: &Entity<Terminal>,
565        cx: &mut App,
566    ) {
567        terminal_handle.update(cx, |terminal, _| terminal.input(command.into_bytes()));
568    }
569
570    pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
571        &self.terminals.local_handles
572    }
573}
574
575pub fn wrap_for_ssh(
576    ssh_command: &SshCommand,
577    command: Option<(&String, &Vec<String>)>,
578    path: Option<&Path>,
579    env: HashMap<String, String>,
580    venv_directory: Option<&Path>,
581    path_style: PathStyle,
582) -> (String, Vec<String>) {
583    let to_run = if let Some((command, args)) = command {
584        // DEFAULT_REMOTE_SHELL is '"${SHELL:-sh}"' so must not be escaped
585        let command: Option<Cow<str>> = if command == DEFAULT_REMOTE_SHELL {
586            Some(command.into())
587        } else {
588            shlex::try_quote(command).ok()
589        };
590        let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
591        command.into_iter().chain(args).join(" ")
592    } else {
593        "exec ${SHELL:-sh} -l".to_string()
594    };
595
596    let mut env_changes = String::new();
597    for (k, v) in env.iter() {
598        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
599            env_changes.push_str(&format!("{}={} ", k, v));
600        }
601    }
602    if let Some(venv_directory) = venv_directory {
603        if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
604            let path = RemotePathBuf::new(PathBuf::from(str.to_string()), path_style).to_string();
605            env_changes.push_str(&format!("PATH={}:$PATH ", path));
606        }
607    }
608
609    let commands = if let Some(path) = path {
610        let path = RemotePathBuf::new(path.to_path_buf(), path_style).to_string();
611        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
612        // replace ith with something that works
613        let tilde_prefix = "~/";
614        if path.starts_with(tilde_prefix) {
615            let trimmed_path = path
616                .trim_start_matches("/")
617                .trim_start_matches("~")
618                .trim_start_matches("/");
619
620            format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
621        } else {
622            format!("cd {path}; {env_changes} {to_run}")
623        }
624    } else {
625        format!("cd; {env_changes} {to_run}")
626    };
627    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
628
629    let program = "ssh".to_string();
630    let mut args = ssh_command.arguments.clone();
631
632    args.push("-t".to_string());
633    args.push(shell_invocation);
634    (program, args)
635}
636
637fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
638    let mut env_paths = vec![new_path.to_path_buf()];
639    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
640        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
641        env_paths.append(&mut paths);
642    }
643
644    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
645    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
646
647    Ok(())
648}
649
650#[cfg(test)]
651mod tests {
652    use collections::HashMap;
653
654    #[test]
655    fn test_add_environment_path_with_existing_path() {
656        let tmp_path = std::path::PathBuf::from("/tmp/new");
657        let mut env = HashMap::default();
658        let old_path = if cfg!(windows) {
659            "/usr/bin;/usr/local/bin"
660        } else {
661            "/usr/bin:/usr/local/bin"
662        };
663        env.insert("PATH".to_string(), old_path.to_string());
664        env.insert("OTHER".to_string(), "aaa".to_string());
665
666        super::add_environment_path(&mut env, &tmp_path).unwrap();
667        if cfg!(windows) {
668            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
669        } else {
670            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
671        }
672        assert_eq!(env.get("OTHER").unwrap(), "aaa");
673    }
674
675    #[test]
676    fn test_add_environment_path_with_empty_path() {
677        let tmp_path = std::path::PathBuf::from("/tmp/new");
678        let mut env = HashMap::default();
679        env.insert("OTHER".to_string(), "aaa".to_string());
680        let os_path = std::env::var("PATH").unwrap();
681        super::add_environment_path(&mut env, &tmp_path).unwrap();
682        if cfg!(windows) {
683            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
684        } else {
685            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
686        }
687        assert_eq!(env.get("OTHER").unwrap(), "aaa");
688    }
689}