1use crate::{Project, ProjectPath};
2use anyhow::{Context as _, Result};
3use collections::HashMap;
4use gpui::{AnyWindowHandle, App, AppContext as _, Context, Entity, Task, WeakEntity};
5use itertools::Itertools;
6use language::LanguageName;
7use remote::ssh_session::SshArgs;
8use settings::{Settings, SettingsLocation};
9use smol::channel::bounded;
10use std::{
11 borrow::Cow,
12 env::{self},
13 path::{Path, PathBuf},
14 sync::Arc,
15};
16use task::{DEFAULT_REMOTE_SHELL, Shell, ShellBuilder, SpawnInTerminal};
17use terminal::{
18 TaskState, TaskStatus, Terminal, TerminalBuilder,
19 terminal_settings::{self, ActivateScript, TerminalSettings, VenvSettings},
20};
21use util::{
22 ResultExt,
23 paths::{PathStyle, RemotePathBuf},
24};
25
26pub struct Terminals {
27 pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
28}
29
30/// Terminals are opened either for the users shell, or to run a task.
31
32#[derive(Debug)]
33pub enum TerminalKind {
34 /// Run a shell at the given path (or $HOME if None)
35 Shell(Option<PathBuf>),
36 /// Run a task.
37 Task(SpawnInTerminal),
38}
39
40/// SshCommand describes how to connect to a remote server
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct SshCommand {
43 pub arguments: Vec<String>,
44}
45
46impl SshCommand {
47 pub fn add_port_forwarding(&mut self, local_port: u16, host: String, remote_port: u16) {
48 self.arguments.push("-L".to_string());
49 self.arguments
50 .push(format!("{}:{}:{}", local_port, host, remote_port));
51 }
52}
53
54pub struct SshDetails {
55 pub host: String,
56 pub ssh_command: SshCommand,
57 pub envs: Option<HashMap<String, String>>,
58 pub path_style: PathStyle,
59}
60
61impl Project {
62 pub fn active_project_directory(&self, cx: &App) -> Option<Arc<Path>> {
63 let worktree = self
64 .active_entry()
65 .and_then(|entry_id| self.worktree_for_entry(entry_id, cx))
66 .into_iter()
67 .chain(self.worktrees(cx))
68 .find_map(|tree| tree.read(cx).root_dir());
69 worktree
70 }
71
72 pub fn first_project_directory(&self, cx: &App) -> Option<PathBuf> {
73 let worktree = self.worktrees(cx).next()?;
74 let worktree = worktree.read(cx);
75 if worktree.root_entry()?.is_dir() {
76 Some(worktree.abs_path().to_path_buf())
77 } else {
78 None
79 }
80 }
81
82 pub fn ssh_details(&self, cx: &App) -> Option<SshDetails> {
83 if let Some(ssh_client) = &self.ssh_client {
84 let ssh_client = ssh_client.read(cx);
85 if let Some((SshArgs { arguments, envs }, path_style)) = ssh_client.ssh_info() {
86 return Some(SshDetails {
87 host: ssh_client.connection_options().host.clone(),
88 ssh_command: SshCommand { arguments },
89 envs,
90 path_style,
91 });
92 }
93 }
94
95 return None;
96 }
97
98 pub fn create_terminal(
99 &mut self,
100 kind: TerminalKind,
101 window: AnyWindowHandle,
102 cx: &mut Context<Self>,
103 ) -> Task<Result<Entity<Terminal>>> {
104 let path: Option<Arc<Path>> = match &kind {
105 TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
106 TerminalKind::Task(spawn_task) => {
107 if let Some(cwd) = &spawn_task.cwd {
108 Some(Arc::from(cwd.as_ref()))
109 } else {
110 self.active_project_directory(cx)
111 }
112 }
113 };
114
115 let mut settings_location = None;
116 if let Some(path) = path.as_ref() {
117 if let Some((worktree, _)) = self.find_worktree(path, cx) {
118 settings_location = Some(SettingsLocation {
119 worktree_id: worktree.read(cx).id(),
120 path,
121 });
122 }
123 }
124 let venv = TerminalSettings::get(settings_location, cx)
125 .detect_venv
126 .clone();
127
128 cx.spawn(async move |project, cx| {
129 let python_venv_directory = if let Some(path) = path {
130 project
131 .update(cx, |this, cx| this.python_venv_directory(path, venv, cx))?
132 .await
133 } else {
134 None
135 };
136 project.update(cx, |project, cx| {
137 project.create_terminal_with_venv(kind, python_venv_directory, window, cx)
138 })?
139 })
140 }
141
142 pub fn terminal_settings<'a>(
143 &'a self,
144 path: &'a Option<PathBuf>,
145 cx: &'a App,
146 ) -> &'a TerminalSettings {
147 let mut settings_location = None;
148 if let Some(path) = path.as_ref() {
149 if let Some((worktree, _)) = self.find_worktree(path, cx) {
150 settings_location = Some(SettingsLocation {
151 worktree_id: worktree.read(cx).id(),
152 path,
153 });
154 }
155 }
156 TerminalSettings::get(settings_location, cx)
157 }
158
159 pub fn exec_in_shell(&self, command: String, cx: &App) -> std::process::Command {
160 let path = self.first_project_directory(cx);
161 let ssh_details = self.ssh_details(cx);
162 let settings = self.terminal_settings(&path, cx).clone();
163
164 let builder = ShellBuilder::new(ssh_details.is_none(), &settings.shell).non_interactive();
165 let (command, args) = builder.build(Some(command), &Vec::new());
166
167 let mut env = self
168 .environment
169 .read(cx)
170 .get_cli_environment()
171 .unwrap_or_default();
172 env.extend(settings.env);
173
174 match self.ssh_details(cx) {
175 Some(SshDetails {
176 ssh_command,
177 envs,
178 path_style,
179 ..
180 }) => {
181 let (command, args) = wrap_for_ssh(
182 &ssh_command,
183 Some((&command, &args)),
184 path.as_deref(),
185 env,
186 None,
187 path_style,
188 );
189 let mut command = std::process::Command::new(command);
190 command.args(args);
191 if let Some(envs) = envs {
192 command.envs(envs);
193 }
194 command
195 }
196 None => {
197 let mut command = std::process::Command::new(command);
198 command.args(args);
199 command.envs(env);
200 if let Some(path) = path {
201 command.current_dir(path);
202 }
203 command
204 }
205 }
206 }
207
208 pub fn create_terminal_with_venv(
209 &mut self,
210 kind: TerminalKind,
211 python_venv_directory: Option<PathBuf>,
212 window: AnyWindowHandle,
213 cx: &mut Context<Self>,
214 ) -> Result<Entity<Terminal>> {
215 let this = &mut *self;
216 let ssh_details = this.ssh_details(cx);
217 let path: Option<Arc<Path>> = match &kind {
218 TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
219 TerminalKind::Task(spawn_task) => {
220 if let Some(cwd) = &spawn_task.cwd {
221 if ssh_details.is_some() {
222 Some(Arc::from(cwd.as_ref()))
223 } else {
224 let cwd = cwd.to_string_lossy();
225 let tilde_substituted = shellexpand::tilde(&cwd);
226 Some(Arc::from(Path::new(tilde_substituted.as_ref())))
227 }
228 } else {
229 this.active_project_directory(cx)
230 }
231 }
232 };
233
234 let is_ssh_terminal = ssh_details.is_some();
235
236 let mut settings_location = None;
237 if let Some(path) = path.as_ref() {
238 if let Some((worktree, _)) = this.find_worktree(path, cx) {
239 settings_location = Some(SettingsLocation {
240 worktree_id: worktree.read(cx).id(),
241 path,
242 });
243 }
244 }
245 let settings = TerminalSettings::get(settings_location, cx).clone();
246
247 let (completion_tx, completion_rx) = bounded(1);
248
249 // Start with the environment that we might have inherited from the Zed CLI.
250 let mut env = this
251 .environment
252 .read(cx)
253 .get_cli_environment()
254 .unwrap_or_default();
255 // Then extend it with the explicit env variables from the settings, so they take
256 // precedence.
257 env.extend(settings.env);
258
259 let local_path = if is_ssh_terminal { None } else { path.clone() };
260
261 let mut python_venv_activate_command = None;
262
263 let (spawn_task, shell) = match kind {
264 TerminalKind::Shell(_) => {
265 if let Some(python_venv_directory) = &python_venv_directory {
266 python_venv_activate_command = this.python_activate_command(
267 python_venv_directory,
268 &settings.detect_venv,
269 &settings.shell,
270 );
271 }
272
273 match ssh_details {
274 Some(SshDetails {
275 host,
276 ssh_command,
277 envs,
278 path_style,
279 }) => {
280 log::debug!("Connecting to a remote server: {ssh_command:?}");
281
282 // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
283 // to properly display colors.
284 // We do not have the luxury of assuming the host has it installed,
285 // so we set it to a default that does not break the highlighting via ssh.
286 env.entry("TERM".to_string())
287 .or_insert_with(|| "xterm-256color".to_string());
288
289 let (program, args) = wrap_for_ssh(
290 &ssh_command,
291 None,
292 path.as_deref(),
293 env,
294 None,
295 path_style,
296 );
297 env = HashMap::default();
298 if let Some(envs) = envs {
299 env.extend(envs);
300 }
301 (
302 Option::<TaskState>::None,
303 Shell::WithArguments {
304 program,
305 args,
306 title_override: Some(format!("{} — Terminal", host).into()),
307 },
308 )
309 }
310 None => (None, settings.shell),
311 }
312 }
313 TerminalKind::Task(spawn_task) => {
314 let task_state = Some(TaskState {
315 id: spawn_task.id,
316 full_label: spawn_task.full_label,
317 label: spawn_task.label,
318 command_label: spawn_task.command_label,
319 hide: spawn_task.hide,
320 status: TaskStatus::Running,
321 show_summary: spawn_task.show_summary,
322 show_command: spawn_task.show_command,
323 show_rerun: spawn_task.show_rerun,
324 completion_rx,
325 });
326
327 env.extend(spawn_task.env);
328
329 if let Some(venv_path) = &python_venv_directory {
330 env.insert(
331 "VIRTUAL_ENV".to_string(),
332 venv_path.to_string_lossy().to_string(),
333 );
334 }
335
336 match ssh_details {
337 Some(SshDetails {
338 host,
339 ssh_command,
340 envs,
341 path_style,
342 }) => {
343 log::debug!("Connecting to a remote server: {ssh_command:?}");
344 env.entry("TERM".to_string())
345 .or_insert_with(|| "xterm-256color".to_string());
346 let (program, args) = wrap_for_ssh(
347 &ssh_command,
348 spawn_task
349 .command
350 .as_ref()
351 .map(|command| (command, &spawn_task.args)),
352 path.as_deref(),
353 env,
354 python_venv_directory.as_deref(),
355 path_style,
356 );
357 env = HashMap::default();
358 if let Some(envs) = envs {
359 env.extend(envs);
360 }
361 (
362 task_state,
363 Shell::WithArguments {
364 program,
365 args,
366 title_override: Some(format!("{} — Terminal", host).into()),
367 },
368 )
369 }
370 None => {
371 if let Some(venv_path) = &python_venv_directory {
372 add_environment_path(&mut env, &venv_path.join("bin")).log_err();
373 }
374
375 let shell = if let Some(program) = spawn_task.command {
376 Shell::WithArguments {
377 program,
378 args: spawn_task.args,
379 title_override: None,
380 }
381 } else {
382 Shell::System
383 };
384 (task_state, shell)
385 }
386 }
387 }
388 };
389 TerminalBuilder::new(
390 local_path.map(|path| path.to_path_buf()),
391 python_venv_directory,
392 spawn_task,
393 shell,
394 env,
395 settings.cursor_shape.unwrap_or_default(),
396 settings.alternate_scroll,
397 settings.max_scroll_history_lines,
398 is_ssh_terminal,
399 window,
400 completion_tx,
401 cx,
402 )
403 .map(|builder| {
404 let terminal_handle = cx.new(|cx| builder.subscribe(cx));
405
406 this.terminals
407 .local_handles
408 .push(terminal_handle.downgrade());
409
410 let id = terminal_handle.entity_id();
411 cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
412 let handles = &mut project.terminals.local_handles;
413
414 if let Some(index) = handles
415 .iter()
416 .position(|terminal| terminal.entity_id() == id)
417 {
418 handles.remove(index);
419 cx.notify();
420 }
421 })
422 .detach();
423
424 if let Some(activate_command) = python_venv_activate_command {
425 this.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
426 }
427 terminal_handle
428 })
429 }
430
431 fn python_venv_directory(
432 &self,
433 abs_path: Arc<Path>,
434 venv_settings: VenvSettings,
435 cx: &Context<Project>,
436 ) -> Task<Option<PathBuf>> {
437 cx.spawn(async move |this, cx| {
438 if let Some((worktree, relative_path)) = this
439 .update(cx, |this, cx| this.find_worktree(&abs_path, cx))
440 .ok()?
441 {
442 let toolchain = this
443 .update(cx, |this, cx| {
444 this.active_toolchain(
445 ProjectPath {
446 worktree_id: worktree.read(cx).id(),
447 path: relative_path.into(),
448 },
449 LanguageName::new("Python"),
450 cx,
451 )
452 })
453 .ok()?
454 .await;
455
456 if let Some(toolchain) = toolchain {
457 let toolchain_path = Path::new(toolchain.path.as_ref());
458 return Some(toolchain_path.parent()?.parent()?.to_path_buf());
459 }
460 }
461 let venv_settings = venv_settings.as_option()?;
462 this.update(cx, move |this, cx| {
463 if let Some(path) = this.find_venv_in_worktree(&abs_path, &venv_settings, cx) {
464 return Some(path);
465 }
466 this.find_venv_on_filesystem(&abs_path, &venv_settings, cx)
467 })
468 .ok()
469 .flatten()
470 })
471 }
472
473 fn find_venv_in_worktree(
474 &self,
475 abs_path: &Path,
476 venv_settings: &terminal_settings::VenvSettingsContent,
477 cx: &App,
478 ) -> Option<PathBuf> {
479 let bin_dir_name = match std::env::consts::OS {
480 "windows" => "Scripts",
481 _ => "bin",
482 };
483 venv_settings
484 .directories
485 .iter()
486 .map(|name| abs_path.join(name))
487 .find(|venv_path| {
488 let bin_path = venv_path.join(bin_dir_name);
489 self.find_worktree(&bin_path, cx)
490 .and_then(|(worktree, relative_path)| {
491 worktree.read(cx).entry_for_path(&relative_path)
492 })
493 .is_some_and(|entry| entry.is_dir())
494 })
495 }
496
497 fn find_venv_on_filesystem(
498 &self,
499 abs_path: &Path,
500 venv_settings: &terminal_settings::VenvSettingsContent,
501 cx: &App,
502 ) -> Option<PathBuf> {
503 let (worktree, _) = self.find_worktree(abs_path, cx)?;
504 let fs = worktree.read(cx).as_local()?.fs();
505 let bin_dir_name = match std::env::consts::OS {
506 "windows" => "Scripts",
507 _ => "bin",
508 };
509 venv_settings
510 .directories
511 .iter()
512 .map(|name| abs_path.join(name))
513 .find(|venv_path| {
514 let bin_path = venv_path.join(bin_dir_name);
515 // One-time synchronous check is acceptable for terminal/task initialization
516 smol::block_on(fs.metadata(&bin_path))
517 .ok()
518 .flatten()
519 .map_or(false, |meta| meta.is_dir)
520 })
521 }
522
523 fn activate_script_kind(shell: Option<&str>) -> ActivateScript {
524 let shell_env = std::env::var("SHELL").ok();
525 let shell_path = shell.or_else(|| shell_env.as_deref());
526 let shell = std::path::Path::new(shell_path.unwrap_or(""))
527 .file_name()
528 .and_then(|name| name.to_str())
529 .unwrap_or("");
530 match shell {
531 "fish" => ActivateScript::Fish,
532 "tcsh" => ActivateScript::Csh,
533 "nu" => ActivateScript::Nushell,
534 "powershell" | "pwsh" => ActivateScript::PowerShell,
535 _ => ActivateScript::Default,
536 }
537 }
538
539 fn python_activate_command(
540 &self,
541 venv_base_directory: &Path,
542 venv_settings: &VenvSettings,
543 shell: &Shell,
544 ) -> Option<String> {
545 let venv_settings = venv_settings.as_option()?;
546 let activate_keyword = match venv_settings.activate_script {
547 terminal_settings::ActivateScript::Default => match std::env::consts::OS {
548 "windows" => ".",
549 _ => "source",
550 },
551 terminal_settings::ActivateScript::Nushell => "overlay use",
552 terminal_settings::ActivateScript::PowerShell => ".",
553 terminal_settings::ActivateScript::Pyenv => "pyenv",
554 _ => "source",
555 };
556 let script_kind =
557 if venv_settings.activate_script == terminal_settings::ActivateScript::Default {
558 match shell {
559 Shell::Program(program) => Self::activate_script_kind(Some(program)),
560 Shell::WithArguments {
561 program,
562 args: _,
563 title_override: _,
564 } => Self::activate_script_kind(Some(program)),
565 Shell::System => Self::activate_script_kind(None),
566 }
567 } else {
568 venv_settings.activate_script
569 };
570
571 let activate_script_name = match script_kind {
572 terminal_settings::ActivateScript::Default
573 | terminal_settings::ActivateScript::Pyenv => "activate",
574 terminal_settings::ActivateScript::Csh => "activate.csh",
575 terminal_settings::ActivateScript::Fish => "activate.fish",
576 terminal_settings::ActivateScript::Nushell => "activate.nu",
577 terminal_settings::ActivateScript::PowerShell => "activate.ps1",
578 };
579
580 let line_ending = match std::env::consts::OS {
581 "windows" => "\r",
582 _ => "\n",
583 };
584
585 if venv_settings.venv_name.is_empty() {
586 let path = venv_base_directory
587 .join(match std::env::consts::OS {
588 "windows" => "Scripts",
589 _ => "bin",
590 })
591 .join(activate_script_name)
592 .to_string_lossy()
593 .to_string();
594 let quoted = shlex::try_quote(&path).ok()?;
595 smol::block_on(self.fs.metadata(path.as_ref()))
596 .ok()
597 .flatten()?;
598
599 Some(format!(
600 "{} {} ; clear{}",
601 activate_keyword, quoted, line_ending
602 ))
603 } else {
604 Some(format!(
605 "{activate_keyword} {activate_script_name} {name}; clear{line_ending}",
606 name = venv_settings.venv_name
607 ))
608 }
609 }
610
611 fn activate_python_virtual_environment(
612 &self,
613 command: String,
614 terminal_handle: &Entity<Terminal>,
615 cx: &mut App,
616 ) {
617 terminal_handle.update(cx, |terminal, _| terminal.input(command.into_bytes()));
618 }
619
620 pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
621 &self.terminals.local_handles
622 }
623}
624
625pub fn wrap_for_ssh(
626 ssh_command: &SshCommand,
627 command: Option<(&String, &Vec<String>)>,
628 path: Option<&Path>,
629 env: HashMap<String, String>,
630 venv_directory: Option<&Path>,
631 path_style: PathStyle,
632) -> (String, Vec<String>) {
633 let to_run = if let Some((command, args)) = command {
634 // DEFAULT_REMOTE_SHELL is '"${SHELL:-sh}"' so must not be escaped
635 let command: Option<Cow<str>> = if command == DEFAULT_REMOTE_SHELL {
636 Some(command.into())
637 } else {
638 shlex::try_quote(command).ok()
639 };
640 let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
641 command.into_iter().chain(args).join(" ")
642 } else {
643 "exec ${SHELL:-sh} -l".to_string()
644 };
645
646 let mut env_changes = String::new();
647 for (k, v) in env.iter() {
648 if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
649 env_changes.push_str(&format!("{}={} ", k, v));
650 }
651 }
652 if let Some(venv_directory) = venv_directory {
653 if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
654 let path = RemotePathBuf::new(PathBuf::from(str.to_string()), path_style).to_string();
655 env_changes.push_str(&format!("PATH={}:$PATH ", path));
656 }
657 }
658
659 let commands = if let Some(path) = path {
660 let path = RemotePathBuf::new(path.to_path_buf(), path_style).to_string();
661 // shlex will wrap the command in single quotes (''), disabling ~ expansion,
662 // replace ith with something that works
663 let tilde_prefix = "~/";
664 if path.starts_with(tilde_prefix) {
665 let trimmed_path = path
666 .trim_start_matches("/")
667 .trim_start_matches("~")
668 .trim_start_matches("/");
669
670 format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
671 } else {
672 format!("cd \"{path}\"; {env_changes} {to_run}")
673 }
674 } else {
675 format!("cd; {env_changes} {to_run}")
676 };
677 let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
678
679 let program = "ssh".to_string();
680 let mut args = ssh_command.arguments.clone();
681
682 args.push("-t".to_string());
683 args.push(shell_invocation);
684 (program, args)
685}
686
687fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
688 let mut env_paths = vec![new_path.to_path_buf()];
689 if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
690 let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
691 env_paths.append(&mut paths);
692 }
693
694 let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
695 env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
696
697 Ok(())
698}
699
700#[cfg(test)]
701mod tests {
702 use collections::HashMap;
703
704 #[test]
705 fn test_add_environment_path_with_existing_path() {
706 let tmp_path = std::path::PathBuf::from("/tmp/new");
707 let mut env = HashMap::default();
708 let old_path = if cfg!(windows) {
709 "/usr/bin;/usr/local/bin"
710 } else {
711 "/usr/bin:/usr/local/bin"
712 };
713 env.insert("PATH".to_string(), old_path.to_string());
714 env.insert("OTHER".to_string(), "aaa".to_string());
715
716 super::add_environment_path(&mut env, &tmp_path).unwrap();
717 if cfg!(windows) {
718 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
719 } else {
720 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
721 }
722 assert_eq!(env.get("OTHER").unwrap(), "aaa");
723 }
724
725 #[test]
726 fn test_add_environment_path_with_empty_path() {
727 let tmp_path = std::path::PathBuf::from("/tmp/new");
728 let mut env = HashMap::default();
729 env.insert("OTHER".to_string(), "aaa".to_string());
730 let os_path = std::env::var("PATH").unwrap();
731 super::add_environment_path(&mut env, &tmp_path).unwrap();
732 if cfg!(windows) {
733 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
734 } else {
735 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
736 }
737 assert_eq!(env.get("OTHER").unwrap(), "aaa");
738 }
739}