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