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