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                    show_summary: spawn_task.show_summary,
178                    show_command: spawn_task.show_command,
179                    completion_rx,
180                });
181
182                env.extend(spawn_task.env);
183
184                if let Some(venv_path) = &python_venv_directory {
185                    env.insert(
186                        "VIRTUAL_ENV".to_string(),
187                        venv_path.to_string_lossy().to_string(),
188                    );
189                }
190
191                match &ssh_details {
192                    Some((host, ssh_command)) => {
193                        log::debug!("Connecting to a remote server: {ssh_command:?}");
194                        env.entry("TERM".to_string())
195                            .or_insert_with(|| "xterm-256color".to_string());
196                        let (program, args) = wrap_for_ssh(
197                            ssh_command,
198                            Some((&spawn_task.command, &spawn_task.args)),
199                            path.as_deref(),
200                            env,
201                            python_venv_directory,
202                        );
203                        env = HashMap::default();
204                        (
205                            task_state,
206                            Shell::WithArguments {
207                                program,
208                                args,
209                                title_override: Some(format!("{} — Terminal", host).into()),
210                            },
211                        )
212                    }
213                    None => {
214                        if let Some(venv_path) = &python_venv_directory {
215                            add_environment_path(&mut env, &venv_path.join("bin")).log_err();
216                        }
217
218                        (
219                            task_state,
220                            Shell::WithArguments {
221                                program: spawn_task.command,
222                                args: spawn_task.args,
223                                title_override: None,
224                            },
225                        )
226                    }
227                }
228            }
229        };
230
231        let terminal = TerminalBuilder::new(
232            local_path,
233            spawn_task,
234            shell,
235            env,
236            settings.cursor_shape.unwrap_or_default(),
237            settings.alternate_scroll,
238            settings.max_scroll_history_lines,
239            ssh_details.is_some(),
240            window,
241            completion_tx,
242            cx,
243        )
244        .map(|builder| {
245            let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
246
247            self.terminals
248                .local_handles
249                .push(terminal_handle.downgrade());
250
251            let id = terminal_handle.entity_id();
252            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
253                let handles = &mut project.terminals.local_handles;
254
255                if let Some(index) = handles
256                    .iter()
257                    .position(|terminal| terminal.entity_id() == id)
258                {
259                    handles.remove(index);
260                    cx.notify();
261                }
262            })
263            .detach();
264
265            if let Some(activate_command) = python_venv_activate_command {
266                self.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
267            }
268            terminal_handle
269        });
270
271        terminal
272    }
273
274    pub fn python_venv_directory(
275        &self,
276        abs_path: &Path,
277        settings: &TerminalSettings,
278        cx: &AppContext,
279    ) -> Option<PathBuf> {
280        let venv_settings = settings.detect_venv.as_option()?;
281        if let Some(path) = self.find_venv_in_worktree(abs_path, &venv_settings, cx) {
282            return Some(path);
283        }
284        self.find_venv_on_filesystem(abs_path, &venv_settings, cx)
285    }
286
287    fn find_venv_in_worktree(
288        &self,
289        abs_path: &Path,
290        venv_settings: &terminal_settings::VenvSettingsContent,
291        cx: &AppContext,
292    ) -> Option<PathBuf> {
293        let bin_dir_name = match std::env::consts::OS {
294            "windows" => "Scripts",
295            _ => "bin",
296        };
297        venv_settings
298            .directories
299            .iter()
300            .map(|name| abs_path.join(name))
301            .find(|venv_path| {
302                let bin_path = venv_path.join(bin_dir_name);
303                self.find_worktree(&bin_path, cx)
304                    .and_then(|(worktree, relative_path)| {
305                        worktree.read(cx).entry_for_path(&relative_path)
306                    })
307                    .is_some_and(|entry| entry.is_dir())
308            })
309    }
310
311    fn find_venv_on_filesystem(
312        &self,
313        abs_path: &Path,
314        venv_settings: &terminal_settings::VenvSettingsContent,
315        cx: &AppContext,
316    ) -> Option<PathBuf> {
317        let (worktree, _) = self.find_worktree(abs_path, cx)?;
318        let fs = worktree.read(cx).as_local()?.fs();
319        let bin_dir_name = match std::env::consts::OS {
320            "windows" => "Scripts",
321            _ => "bin",
322        };
323        venv_settings
324            .directories
325            .iter()
326            .map(|name| abs_path.join(name))
327            .find(|venv_path| {
328                let bin_path = venv_path.join(bin_dir_name);
329                // One-time synchronous check is acceptable for terminal/task initialization
330                smol::block_on(fs.metadata(&bin_path))
331                    .ok()
332                    .flatten()
333                    .map_or(false, |meta| meta.is_dir)
334            })
335    }
336
337    fn python_activate_command(
338        &self,
339        venv_base_directory: &Path,
340        settings: &TerminalSettings,
341    ) -> Option<String> {
342        let venv_settings = settings.detect_venv.as_option()?;
343        let activate_keyword = match venv_settings.activate_script {
344            terminal_settings::ActivateScript::Default => match std::env::consts::OS {
345                "windows" => ".",
346                _ => "source",
347            },
348            terminal_settings::ActivateScript::Nushell => "overlay use",
349            terminal_settings::ActivateScript::PowerShell => ".",
350            _ => "source",
351        };
352        let activate_script_name = match venv_settings.activate_script {
353            terminal_settings::ActivateScript::Default => "activate",
354            terminal_settings::ActivateScript::Csh => "activate.csh",
355            terminal_settings::ActivateScript::Fish => "activate.fish",
356            terminal_settings::ActivateScript::Nushell => "activate.nu",
357            terminal_settings::ActivateScript::PowerShell => "activate.ps1",
358        };
359        let path = venv_base_directory
360            .join(match std::env::consts::OS {
361                "windows" => "Scripts",
362                _ => "bin",
363            })
364            .join(activate_script_name)
365            .to_string_lossy()
366            .to_string();
367        let quoted = shlex::try_quote(&path).ok()?;
368        let line_ending = match std::env::consts::OS {
369            "windows" => "\r",
370            _ => "\n",
371        };
372        Some(format!("{} {}{}", activate_keyword, quoted, line_ending))
373    }
374
375    fn activate_python_virtual_environment(
376        &self,
377        command: String,
378        terminal_handle: &Model<Terminal>,
379        cx: &mut ModelContext<Project>,
380    ) {
381        terminal_handle.update(cx, |this, _| this.input_bytes(command.into_bytes()));
382    }
383
384    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
385        &self.terminals.local_handles
386    }
387}
388
389pub fn wrap_for_ssh(
390    ssh_command: &SshCommand,
391    command: Option<(&String, &Vec<String>)>,
392    path: Option<&Path>,
393    env: HashMap<String, String>,
394    venv_directory: Option<PathBuf>,
395) -> (String, Vec<String>) {
396    let to_run = if let Some((command, args)) = command {
397        let command = Cow::Borrowed(command.as_str());
398        let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
399        iter::once(command).chain(args).join(" ")
400    } else {
401        "exec ${SHELL:-sh} -l".to_string()
402    };
403
404    let mut env_changes = String::new();
405    for (k, v) in env.iter() {
406        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
407            env_changes.push_str(&format!("{}={} ", k, v));
408        }
409    }
410    if let Some(venv_directory) = venv_directory {
411        if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
412            env_changes.push_str(&format!("PATH={}:$PATH ", str));
413        }
414    }
415
416    let commands = if let Some(path) = path {
417        let path_string = path.to_string_lossy().to_string();
418        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
419        // replace ith with something that works
420        let tilde_prefix = "~/";
421        if path.starts_with(tilde_prefix) {
422            let trimmed_path = path_string
423                .trim_start_matches("/")
424                .trim_start_matches("~")
425                .trim_start_matches("/");
426
427            format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
428        } else {
429            format!("cd {path:?}; {env_changes} {to_run}")
430        }
431    } else {
432        format!("cd; {env_changes} {to_run}")
433    };
434    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
435
436    let program = "ssh".to_string();
437    let mut args = ssh_command.arguments.clone();
438
439    args.push("-t".to_string());
440    args.push(shell_invocation);
441    (program, args)
442}
443
444fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
445    let mut env_paths = vec![new_path.to_path_buf()];
446    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
447        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
448        env_paths.append(&mut paths);
449    }
450
451    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
452    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
453
454    Ok(())
455}
456
457#[cfg(test)]
458mod tests {
459    use collections::HashMap;
460
461    #[test]
462    fn test_add_environment_path_with_existing_path() {
463        let tmp_path = std::path::PathBuf::from("/tmp/new");
464        let mut env = HashMap::default();
465        let old_path = if cfg!(windows) {
466            "/usr/bin;/usr/local/bin"
467        } else {
468            "/usr/bin:/usr/local/bin"
469        };
470        env.insert("PATH".to_string(), old_path.to_string());
471        env.insert("OTHER".to_string(), "aaa".to_string());
472
473        super::add_environment_path(&mut env, &tmp_path).unwrap();
474        if cfg!(windows) {
475            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
476        } else {
477            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
478        }
479        assert_eq!(env.get("OTHER").unwrap(), "aaa");
480    }
481
482    #[test]
483    fn test_add_environment_path_with_empty_path() {
484        let tmp_path = std::path::PathBuf::from("/tmp/new");
485        let mut env = HashMap::default();
486        env.insert("OTHER".to_string(), "aaa".to_string());
487        let os_path = std::env::var("PATH").unwrap();
488        super::add_environment_path(&mut env, &tmp_path).unwrap();
489        if cfg!(windows) {
490            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
491        } else {
492            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
493        }
494        assert_eq!(env.get("OTHER").unwrap(), "aaa");
495    }
496}