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