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        let bin_dir_name = match std::env::consts::OS {
280            "windows" => "Scripts",
281            _ => "bin",
282        };
283        venv_settings
284            .directories
285            .iter()
286            .map(|virtual_environment_name| abs_path.join(virtual_environment_name))
287            .find(|venv_path| {
288                let bin_path = venv_path.join(bin_dir_name);
289                self.find_worktree(&bin_path, cx)
290                    .and_then(|(worktree, relative_path)| {
291                        worktree.read(cx).entry_for_path(&relative_path)
292                    })
293                    .is_some_and(|entry| entry.is_dir())
294            })
295    }
296
297    fn python_activate_command(
298        &self,
299        venv_base_directory: &Path,
300        settings: &TerminalSettings,
301    ) -> Option<String> {
302        let venv_settings = settings.detect_venv.as_option()?;
303        let activate_keyword = match venv_settings.activate_script {
304            terminal_settings::ActivateScript::Default => match std::env::consts::OS {
305                "windows" => ".",
306                _ => "source",
307            },
308            terminal_settings::ActivateScript::Nushell => "overlay use",
309            terminal_settings::ActivateScript::PowerShell => ".",
310            _ => "source",
311        };
312        let activate_script_name = match venv_settings.activate_script {
313            terminal_settings::ActivateScript::Default => "activate",
314            terminal_settings::ActivateScript::Csh => "activate.csh",
315            terminal_settings::ActivateScript::Fish => "activate.fish",
316            terminal_settings::ActivateScript::Nushell => "activate.nu",
317            terminal_settings::ActivateScript::PowerShell => "activate.ps1",
318        };
319        let path = venv_base_directory
320            .join(match std::env::consts::OS {
321                "windows" => "Scripts",
322                _ => "bin",
323            })
324            .join(activate_script_name)
325            .to_string_lossy()
326            .to_string();
327        let quoted = shlex::try_quote(&path).ok()?;
328        let line_ending = match std::env::consts::OS {
329            "windows" => "\r",
330            _ => "\n",
331        };
332        Some(format!("{} {}{}", activate_keyword, quoted, line_ending))
333    }
334
335    fn activate_python_virtual_environment(
336        &self,
337        command: String,
338        terminal_handle: &Model<Terminal>,
339        cx: &mut ModelContext<Project>,
340    ) {
341        terminal_handle.update(cx, |this, _| this.input_bytes(command.into_bytes()));
342    }
343
344    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
345        &self.terminals.local_handles
346    }
347}
348
349pub fn wrap_for_ssh(
350    ssh_command: &SshCommand,
351    command: Option<(&String, &Vec<String>)>,
352    path: Option<&Path>,
353    env: HashMap<String, String>,
354    venv_directory: Option<PathBuf>,
355) -> (String, Vec<String>) {
356    let to_run = if let Some((command, args)) = command {
357        let command = Cow::Borrowed(command.as_str());
358        let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
359        iter::once(command).chain(args).join(" ")
360    } else {
361        "exec ${SHELL:-sh} -l".to_string()
362    };
363
364    let mut env_changes = String::new();
365    for (k, v) in env.iter() {
366        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
367            env_changes.push_str(&format!("{}={} ", k, v));
368        }
369    }
370    if let Some(venv_directory) = venv_directory {
371        if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
372            env_changes.push_str(&format!("PATH={}:$PATH ", str));
373        }
374    }
375
376    let commands = if let Some(path) = path {
377        let path_string = path.to_string_lossy().to_string();
378        // shlex will wrap the command in single quotes (''), disabling ~ expansion,
379        // replace ith with something that works
380        let tilde_prefix = "~/";
381        if path.starts_with(tilde_prefix) {
382            let trimmed_path = path_string
383                .trim_start_matches("/")
384                .trim_start_matches("~")
385                .trim_start_matches("/");
386
387            format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
388        } else {
389            format!("cd {path:?}; {env_changes} {to_run}")
390        }
391    } else {
392        format!("cd; {env_changes} {to_run}")
393    };
394    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
395
396    let program = "ssh".to_string();
397    let mut args = ssh_command.arguments.clone();
398
399    args.push("-t".to_string());
400    args.push(shell_invocation);
401    (program, args)
402}
403
404fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
405    let mut env_paths = vec![new_path.to_path_buf()];
406    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
407        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
408        env_paths.append(&mut paths);
409    }
410
411    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
412    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
413
414    Ok(())
415}
416
417#[cfg(test)]
418mod tests {
419    use collections::HashMap;
420
421    #[test]
422    fn test_add_environment_path_with_existing_path() {
423        let tmp_path = std::path::PathBuf::from("/tmp/new");
424        let mut env = HashMap::default();
425        let old_path = if cfg!(windows) {
426            "/usr/bin;/usr/local/bin"
427        } else {
428            "/usr/bin:/usr/local/bin"
429        };
430        env.insert("PATH".to_string(), old_path.to_string());
431        env.insert("OTHER".to_string(), "aaa".to_string());
432
433        super::add_environment_path(&mut env, &tmp_path).unwrap();
434        if cfg!(windows) {
435            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
436        } else {
437            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
438        }
439        assert_eq!(env.get("OTHER").unwrap(), "aaa");
440    }
441
442    #[test]
443    fn test_add_environment_path_with_empty_path() {
444        let tmp_path = std::path::PathBuf::from("/tmp/new");
445        let mut env = HashMap::default();
446        env.insert("OTHER".to_string(), "aaa".to_string());
447        let os_path = std::env::var("PATH").unwrap();
448        super::add_environment_path(&mut env, &tmp_path).unwrap();
449        if cfg!(windows) {
450            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
451        } else {
452            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
453        }
454        assert_eq!(env.get("OTHER").unwrap(), "aaa");
455    }
456}