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