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.read(cx).entry_for_path(&relative_path)
482                    })
483                    .is_some_and(|entry| entry.is_dir())
484            })
485    }
486
487    fn find_venv_on_filesystem(
488        &self,
489        abs_path: &Path,
490        venv_settings: &terminal_settings::VenvSettingsContent,
491        cx: &App,
492    ) -> Option<PathBuf> {
493        let (worktree, _) = self.find_worktree(abs_path, cx)?;
494        let fs = worktree.read(cx).as_local()?.fs();
495        let bin_dir_name = match std::env::consts::OS {
496            "windows" => "Scripts",
497            _ => "bin",
498        };
499        venv_settings
500            .directories
501            .iter()
502            .map(|name| abs_path.join(name))
503            .find(|venv_path| {
504                let bin_path = venv_path.join(bin_dir_name);
505                // One-time synchronous check is acceptable for terminal/task initialization
506                smol::block_on(fs.metadata(&bin_path))
507                    .ok()
508                    .flatten()
509                    .map_or(false, |meta| meta.is_dir)
510            })
511    }
512
513    fn python_activate_command(
514        &self,
515        venv_base_directory: &Path,
516        venv_settings: &VenvSettings,
517    ) -> Option<String> {
518        let venv_settings = venv_settings.as_option()?;
519        let activate_keyword = match venv_settings.activate_script {
520            terminal_settings::ActivateScript::Default => match std::env::consts::OS {
521                "windows" => ".",
522                _ => "source",
523            },
524            terminal_settings::ActivateScript::Nushell => "overlay use",
525            terminal_settings::ActivateScript::PowerShell => ".",
526            _ => "source",
527        };
528        let activate_script_name = match venv_settings.activate_script {
529            terminal_settings::ActivateScript::Default => "activate",
530            terminal_settings::ActivateScript::Csh => "activate.csh",
531            terminal_settings::ActivateScript::Fish => "activate.fish",
532            terminal_settings::ActivateScript::Nushell => "activate.nu",
533            terminal_settings::ActivateScript::PowerShell => "activate.ps1",
534        };
535        let path = venv_base_directory
536            .join(match std::env::consts::OS {
537                "windows" => "Scripts",
538                _ => "bin",
539            })
540            .join(activate_script_name)
541            .to_string_lossy()
542            .to_string();
543        let quoted = shlex::try_quote(&path).ok()?;
544        let line_ending = match std::env::consts::OS {
545            "windows" => "\r",
546            _ => "\n",
547        };
548        smol::block_on(self.fs.metadata(path.as_ref()))
549            .ok()
550            .flatten()?;
551
552        Some(format!(
553            "{} {} ; clear{}",
554            activate_keyword, quoted, line_ending
555        ))
556    }
557
558    fn activate_python_virtual_environment(
559        &self,
560        command: String,
561        terminal_handle: &Entity<Terminal>,
562        cx: &mut App,
563    ) {
564        terminal_handle.update(cx, |terminal, _| terminal.input(command.into_bytes()));
565    }
566
567    pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
568        &self.terminals.local_handles
569    }
570}
571
572pub fn wrap_for_ssh(
573    ssh_command: &SshCommand,
574    command: Option<(&String, &Vec<String>)>,
575    path: Option<&Path>,
576    env: HashMap<String, String>,
577    venv_directory: Option<&Path>,
578    path_style: PathStyle,
579) -> (String, Vec<String>) {
580    let to_run = if let Some((command, args)) = command {
581        // DEFAULT_REMOTE_SHELL is '"${SHELL:-sh}"' so must not be escaped
582        let command: Option<Cow<str>> = if command == DEFAULT_REMOTE_SHELL {
583            Some(command.into())
584        } else {
585            shlex::try_quote(command).ok()
586        };
587        let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
588        command.into_iter().chain(args).join(" ")
589    } else {
590        "exec ${SHELL:-sh} -l".to_string()
591    };
592
593    let mut env_changes = String::new();
594    for (k, v) in env.iter() {
595        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
596            env_changes.push_str(&format!("{}={} ", k, v));
597        }
598    }
599    if let Some(venv_directory) = venv_directory {
600        if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
601            let path = RemotePathBuf::new(PathBuf::from(str.to_string()), path_style).to_string();
602            env_changes.push_str(&format!("PATH={}:$PATH ", path));
603        }
604    }
605
606    let commands = if let Some(path) = path {
607        let path = RemotePathBuf::new(path.to_path_buf(), path_style).to_string();
608        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
609        // replace ith with something that works
610        let tilde_prefix = "~/";
611        if path.starts_with(tilde_prefix) {
612            let trimmed_path = path
613                .trim_start_matches("/")
614                .trim_start_matches("~")
615                .trim_start_matches("/");
616
617            format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
618        } else {
619            format!("cd {path}; {env_changes} {to_run}")
620        }
621    } else {
622        format!("cd; {env_changes} {to_run}")
623    };
624    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
625
626    let program = "ssh".to_string();
627    let mut args = ssh_command.arguments.clone();
628
629    args.push("-t".to_string());
630    args.push(shell_invocation);
631    (program, args)
632}
633
634fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
635    let mut env_paths = vec![new_path.to_path_buf()];
636    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
637        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
638        env_paths.append(&mut paths);
639    }
640
641    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
642    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
643
644    Ok(())
645}
646
647#[cfg(test)]
648mod tests {
649    use collections::HashMap;
650
651    #[test]
652    fn test_add_environment_path_with_existing_path() {
653        let tmp_path = std::path::PathBuf::from("/tmp/new");
654        let mut env = HashMap::default();
655        let old_path = if cfg!(windows) {
656            "/usr/bin;/usr/local/bin"
657        } else {
658            "/usr/bin:/usr/local/bin"
659        };
660        env.insert("PATH".to_string(), old_path.to_string());
661        env.insert("OTHER".to_string(), "aaa".to_string());
662
663        super::add_environment_path(&mut env, &tmp_path).unwrap();
664        if cfg!(windows) {
665            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
666        } else {
667            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
668        }
669        assert_eq!(env.get("OTHER").unwrap(), "aaa");
670    }
671
672    #[test]
673    fn test_add_environment_path_with_empty_path() {
674        let tmp_path = std::path::PathBuf::from("/tmp/new");
675        let mut env = HashMap::default();
676        env.insert("OTHER".to_string(), "aaa".to_string());
677        let os_path = std::env::var("PATH").unwrap();
678        super::add_environment_path(&mut env, &tmp_path).unwrap();
679        if cfg!(windows) {
680            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
681        } else {
682            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
683        }
684        assert_eq!(env.get("OTHER").unwrap(), "aaa");
685    }
686}