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