terminals.rs

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