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    env::{self},
 10    iter,
 11    path::{Path, PathBuf},
 12};
 13use task::{Shell, SpawnInTerminal};
 14use terminal::{
 15    terminal_settings::{self, TerminalSettings},
 16    TaskState, TaskStatus, Terminal, TerminalBuilder,
 17};
 18use util::ResultExt;
 19
 20// #[cfg(target_os = "macos")]
 21// use std::os::unix::ffi::OsStrExt;
 22
 23pub struct Terminals {
 24    pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
 25}
 26
 27/// Terminals are opened either for the users shell, or to run a task.
 28#[allow(clippy::large_enum_variant)]
 29#[derive(Debug)]
 30pub enum TerminalKind {
 31    /// Run a shell at the given path (or $HOME if None)
 32    Shell(Option<PathBuf>),
 33    /// Run a task.
 34    Task(SpawnInTerminal),
 35}
 36
 37/// SshCommand describes how to connect to a remote server
 38#[derive(Debug, Clone, PartialEq, Eq)]
 39pub enum SshCommand {
 40    /// DevServers give a string from the user
 41    DevServer(String),
 42    /// Direct ssh has a list of arguments to pass to ssh
 43    Direct(Vec<String>),
 44}
 45
 46impl Project {
 47    pub fn active_project_directory(&self, cx: &AppContext) -> Option<PathBuf> {
 48        let worktree = self
 49            .active_entry()
 50            .and_then(|entry_id| self.worktree_for_entry(entry_id, cx))
 51            .or_else(|| self.worktrees(cx).next())?;
 52        let worktree = worktree.read(cx);
 53        if !worktree.root_entry()?.is_dir() {
 54            return None;
 55        }
 56        Some(worktree.abs_path().to_path_buf())
 57    }
 58
 59    pub fn first_project_directory(&self, cx: &AppContext) -> Option<PathBuf> {
 60        let worktree = self.worktrees(cx).next()?;
 61        let worktree = worktree.read(cx);
 62        if worktree.root_entry()?.is_dir() {
 63            return Some(worktree.abs_path().to_path_buf());
 64        } else {
 65            None
 66        }
 67    }
 68
 69    fn ssh_command(&self, cx: &AppContext) -> Option<SshCommand> {
 70        if let Some(ssh_session) = self.ssh_session.as_ref() {
 71            return Some(SshCommand::Direct(ssh_session.ssh_args()));
 72        }
 73
 74        let dev_server_project_id = self.dev_server_project_id()?;
 75        let projects_store = dev_server_projects::Store::global(cx).read(cx);
 76        let ssh_command = projects_store
 77            .dev_server_for_project(dev_server_project_id)?
 78            .ssh_connection_string
 79            .as_ref()?
 80            .to_string();
 81        Some(SshCommand::DevServer(ssh_command))
 82    }
 83
 84    pub fn create_terminal(
 85        &mut self,
 86        kind: TerminalKind,
 87        window: AnyWindowHandle,
 88        cx: &mut ModelContext<Self>,
 89    ) -> anyhow::Result<Model<Terminal>> {
 90        let path = match &kind {
 91            TerminalKind::Shell(path) => path.as_ref().map(|path| path.to_path_buf()),
 92            TerminalKind::Task(spawn_task) => {
 93                if let Some(cwd) = &spawn_task.cwd {
 94                    Some(cwd.clone())
 95                } else {
 96                    self.active_project_directory(cx)
 97                }
 98            }
 99        };
100        let ssh_command = self.ssh_command(cx);
101
102        let mut settings_location = None;
103        if let Some(path) = path.as_ref() {
104            if let Some((worktree, _)) = self.find_worktree(path, cx) {
105                settings_location = Some(SettingsLocation {
106                    worktree_id: worktree.read(cx).id().to_usize(),
107                    path,
108                });
109            }
110        }
111        let settings = TerminalSettings::get(settings_location, cx);
112
113        let (completion_tx, completion_rx) = bounded(1);
114
115        let mut env = settings.env.clone();
116
117        let local_path = if ssh_command.is_none() {
118            path.clone()
119        } else {
120            None
121        };
122        let python_venv_directory = path
123            .as_ref()
124            .and_then(|path| self.python_venv_directory(path, settings, cx));
125        let mut python_venv_activate_command = None;
126
127        let (spawn_task, shell) = match kind {
128            TerminalKind::Shell(_) => {
129                if let Some(python_venv_directory) = python_venv_directory {
130                    python_venv_activate_command =
131                        self.python_activate_command(&python_venv_directory, settings);
132                }
133
134                match &ssh_command {
135                    Some(ssh_command) => {
136                        log::debug!("Connecting to a remote server: {ssh_command:?}");
137
138                        // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
139                        // to properly display colors.
140                        // We do not have the luxury of assuming the host has it installed,
141                        // so we set it to a default that does not break the highlighting via ssh.
142                        env.entry("TERM".to_string())
143                            .or_insert_with(|| "xterm-256color".to_string());
144
145                        let (program, args) =
146                            wrap_for_ssh(ssh_command, None, path.as_deref(), env, None);
147                        env = HashMap::default();
148                        (None, Shell::WithArguments { program, args })
149                    }
150                    None => (None, settings.shell.clone()),
151                }
152            }
153            TerminalKind::Task(spawn_task) => {
154                let task_state = Some(TaskState {
155                    id: spawn_task.id,
156                    full_label: spawn_task.full_label,
157                    label: spawn_task.label,
158                    command_label: spawn_task.command_label,
159                    hide: spawn_task.hide,
160                    status: TaskStatus::Running,
161                    completion_rx,
162                });
163
164                env.extend(spawn_task.env);
165
166                if let Some(venv_path) = &python_venv_directory {
167                    env.insert(
168                        "VIRTUAL_ENV".to_string(),
169                        venv_path.to_string_lossy().to_string(),
170                    );
171                }
172
173                match &ssh_command {
174                    Some(ssh_command) => {
175                        log::debug!("Connecting to a remote server: {ssh_command:?}");
176                        env.entry("TERM".to_string())
177                            .or_insert_with(|| "xterm-256color".to_string());
178                        let (program, args) = wrap_for_ssh(
179                            ssh_command,
180                            Some((&spawn_task.command, &spawn_task.args)),
181                            path.as_deref(),
182                            env,
183                            python_venv_directory,
184                        );
185                        env = HashMap::default();
186                        (task_state, Shell::WithArguments { program, args })
187                    }
188                    None => {
189                        if let Some(venv_path) = &python_venv_directory {
190                            add_environment_path(&mut env, &venv_path.join("bin")).log_err();
191                        }
192
193                        (
194                            task_state,
195                            Shell::WithArguments {
196                                program: spawn_task.command,
197                                args: spawn_task.args,
198                            },
199                        )
200                    }
201                }
202            }
203        };
204
205        let terminal = TerminalBuilder::new(
206            local_path,
207            spawn_task,
208            shell,
209            env,
210            Some(settings.blinking),
211            settings.alternate_scroll,
212            settings.max_scroll_history_lines,
213            window,
214            completion_tx,
215            cx,
216        )
217        .map(|builder| {
218            let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
219
220            self.terminals
221                .local_handles
222                .push(terminal_handle.downgrade());
223
224            let id = terminal_handle.entity_id();
225            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
226                let handles = &mut project.terminals.local_handles;
227
228                if let Some(index) = handles
229                    .iter()
230                    .position(|terminal| terminal.entity_id() == id)
231                {
232                    handles.remove(index);
233                    cx.notify();
234                }
235            })
236            .detach();
237
238            if let Some(activate_command) = python_venv_activate_command {
239                self.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
240            }
241            terminal_handle
242        });
243
244        terminal
245    }
246
247    pub fn python_venv_directory(
248        &self,
249        abs_path: &Path,
250        settings: &TerminalSettings,
251        cx: &AppContext,
252    ) -> Option<PathBuf> {
253        let venv_settings = settings.detect_venv.as_option()?;
254        venv_settings
255            .directories
256            .into_iter()
257            .map(|virtual_environment_name| abs_path.join(virtual_environment_name))
258            .find(|venv_path| {
259                self.find_worktree(&venv_path, cx)
260                    .and_then(|(worktree, relative_path)| {
261                        worktree.read(cx).entry_for_path(&relative_path)
262                    })
263                    .is_some_and(|entry| entry.is_dir())
264            })
265    }
266
267    fn python_activate_command(
268        &self,
269        venv_base_directory: &Path,
270        settings: &TerminalSettings,
271    ) -> Option<String> {
272        let venv_settings = settings.detect_venv.as_option()?;
273        let activate_script_name = match venv_settings.activate_script {
274            terminal_settings::ActivateScript::Default => "activate",
275            terminal_settings::ActivateScript::Csh => "activate.csh",
276            terminal_settings::ActivateScript::Fish => "activate.fish",
277            terminal_settings::ActivateScript::Nushell => "activate.nu",
278        };
279        let path = venv_base_directory
280            .join("bin")
281            .join(activate_script_name)
282            .to_string_lossy()
283            .to_string();
284        let quoted = shlex::try_quote(&path).ok()?;
285
286        Some(match venv_settings.activate_script {
287            terminal_settings::ActivateScript::Nushell => format!("overlay use {}\n", quoted),
288            _ => format!("source {}\n", quoted),
289        })
290    }
291
292    fn activate_python_virtual_environment(
293        &self,
294        command: String,
295        terminal_handle: &Model<Terminal>,
296        cx: &mut ModelContext<Project>,
297    ) {
298        terminal_handle.update(cx, |this, _| this.input_bytes(command.into_bytes()));
299    }
300
301    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
302        &self.terminals.local_handles
303    }
304}
305
306pub fn wrap_for_ssh(
307    ssh_command: &SshCommand,
308    command: Option<(&String, &Vec<String>)>,
309    path: Option<&Path>,
310    env: HashMap<String, String>,
311    venv_directory: Option<PathBuf>,
312) -> (String, Vec<String>) {
313    let to_run = if let Some((command, args)) = command {
314        iter::once(command)
315            .chain(args)
316            .filter_map(|arg| shlex::try_quote(arg).ok())
317            .join(" ")
318    } else {
319        "exec ${SHELL:-sh} -l".to_string()
320    };
321
322    let mut env_changes = String::new();
323    for (k, v) in env.iter() {
324        if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
325            env_changes.push_str(&format!("{}={} ", k, v));
326        }
327    }
328    if let Some(venv_directory) = venv_directory {
329        if let Some(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()).ok() {
330            env_changes.push_str(&format!("PATH={}:$PATH ", str));
331        }
332    }
333
334    let commands = if let Some(path) = path {
335        format!("cd {:?}; {} {}", path, env_changes, to_run)
336    } else {
337        format!("cd; {env_changes} {to_run}")
338    };
339    let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
340
341    let (program, mut args) = match ssh_command {
342        SshCommand::DevServer(ssh_command) => {
343            let mut args = shlex::split(&ssh_command).unwrap_or_default();
344            let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
345            (program, args)
346        }
347        SshCommand::Direct(ssh_args) => ("ssh".to_string(), ssh_args.clone()),
348    };
349
350    if command.is_none() {
351        args.push("-t".to_string())
352    }
353    args.push(shell_invocation);
354    (program, args)
355}
356
357fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
358    let mut env_paths = vec![new_path.to_path_buf()];
359    if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
360        let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
361        env_paths.append(&mut paths);
362    }
363
364    let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
365    env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
366
367    Ok(())
368}
369
370#[cfg(test)]
371mod tests {
372    use collections::HashMap;
373
374    #[test]
375    fn test_add_environment_path_with_existing_path() {
376        let tmp_path = std::path::PathBuf::from("/tmp/new");
377        let mut env = HashMap::default();
378        let old_path = if cfg!(windows) {
379            "/usr/bin;/usr/local/bin"
380        } else {
381            "/usr/bin:/usr/local/bin"
382        };
383        env.insert("PATH".to_string(), old_path.to_string());
384        env.insert("OTHER".to_string(), "aaa".to_string());
385
386        super::add_environment_path(&mut env, &tmp_path).unwrap();
387        if cfg!(windows) {
388            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
389        } else {
390            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
391        }
392        assert_eq!(env.get("OTHER").unwrap(), "aaa");
393    }
394
395    #[test]
396    fn test_add_environment_path_with_empty_path() {
397        let tmp_path = std::path::PathBuf::from("/tmp/new");
398        let mut env = HashMap::default();
399        env.insert("OTHER".to_string(), "aaa".to_string());
400        let os_path = std::env::var("PATH").unwrap();
401        super::add_environment_path(&mut env, &tmp_path).unwrap();
402        if cfg!(windows) {
403            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
404        } else {
405            assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
406        }
407        assert_eq!(env.get("OTHER").unwrap(), "aaa");
408    }
409}