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 window,
244 completion_tx,
245 cx,
246 )
247 .map(|builder| {
248 let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
249
250 self.terminals
251 .local_handles
252 .push(terminal_handle.downgrade());
253
254 let id = terminal_handle.entity_id();
255 cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
256 let handles = &mut project.terminals.local_handles;
257
258 if let Some(index) = handles
259 .iter()
260 .position(|terminal| terminal.entity_id() == id)
261 {
262 handles.remove(index);
263 cx.notify();
264 }
265 })
266 .detach();
267
268 if let Some(activate_command) = python_venv_activate_command {
269 self.activate_python_virtual_environment(activate_command, &terminal_handle, cx);
270 }
271 terminal_handle
272 });
273
274 terminal
275 }
276
277 pub fn python_venv_directory(
278 &self,
279 abs_path: &Path,
280 settings: &TerminalSettings,
281 cx: &AppContext,
282 ) -> Option<PathBuf> {
283 let venv_settings = settings.detect_venv.as_option()?;
284 let bin_dir_name = match std::env::consts::OS {
285 "windows" => "Scripts",
286 _ => "bin",
287 };
288 venv_settings
289 .directories
290 .iter()
291 .map(|virtual_environment_name| abs_path.join(virtual_environment_name))
292 .find(|venv_path| {
293 let bin_path = venv_path.join(bin_dir_name);
294 self.find_worktree(&bin_path, cx)
295 .and_then(|(worktree, relative_path)| {
296 worktree.read(cx).entry_for_path(&relative_path)
297 })
298 .is_some_and(|entry| entry.is_dir())
299 })
300 }
301
302 fn python_activate_command(
303 &self,
304 venv_base_directory: &Path,
305 settings: &TerminalSettings,
306 ) -> Option<String> {
307 let venv_settings = settings.detect_venv.as_option()?;
308 let activate_keyword = match venv_settings.activate_script {
309 terminal_settings::ActivateScript::Default => match std::env::consts::OS {
310 "windows" => ".",
311 _ => "source",
312 },
313 terminal_settings::ActivateScript::Nushell => "overlay use",
314 terminal_settings::ActivateScript::PowerShell => ".",
315 _ => "source",
316 };
317 let activate_script_name = match venv_settings.activate_script {
318 terminal_settings::ActivateScript::Default => "activate",
319 terminal_settings::ActivateScript::Csh => "activate.csh",
320 terminal_settings::ActivateScript::Fish => "activate.fish",
321 terminal_settings::ActivateScript::Nushell => "activate.nu",
322 terminal_settings::ActivateScript::PowerShell => "activate.ps1",
323 };
324 let path = venv_base_directory
325 .join(match std::env::consts::OS {
326 "windows" => "Scripts",
327 _ => "bin",
328 })
329 .join(activate_script_name)
330 .to_string_lossy()
331 .to_string();
332 let quoted = shlex::try_quote(&path).ok()?;
333 let line_ending = match std::env::consts::OS {
334 "windows" => "\r",
335 _ => "\n",
336 };
337 Some(format!("{} {}{}", activate_keyword, quoted, line_ending))
338 }
339
340 fn activate_python_virtual_environment(
341 &self,
342 command: String,
343 terminal_handle: &Model<Terminal>,
344 cx: &mut ModelContext<Project>,
345 ) {
346 terminal_handle.update(cx, |this, _| this.input_bytes(command.into_bytes()));
347 }
348
349 pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
350 &self.terminals.local_handles
351 }
352}
353
354pub fn wrap_for_ssh(
355 ssh_command: &SshCommand,
356 command: Option<(&String, &Vec<String>)>,
357 path: Option<&Path>,
358 env: HashMap<String, String>,
359 venv_directory: Option<PathBuf>,
360) -> (String, Vec<String>) {
361 let to_run = if let Some((command, args)) = command {
362 let command = Cow::Borrowed(command.as_str());
363 let args = args.iter().filter_map(|arg| shlex::try_quote(arg).ok());
364 iter::once(command).chain(args).join(" ")
365 } else {
366 "exec ${SHELL:-sh} -l".to_string()
367 };
368
369 let mut env_changes = String::new();
370 for (k, v) in env.iter() {
371 if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
372 env_changes.push_str(&format!("{}={} ", k, v));
373 }
374 }
375 if let Some(venv_directory) = venv_directory {
376 if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
377 env_changes.push_str(&format!("PATH={}:$PATH ", str));
378 }
379 }
380
381 let commands = if let Some(path) = path {
382 let path_string = path.to_string_lossy().to_string();
383 // shlex will wrap the command in single quotes (''), disabling ~ expansion,
384 // replace ith with something that works
385 let tilde_prefix = "~/";
386 if path.starts_with(tilde_prefix) {
387 let trimmed_path = path_string
388 .trim_start_matches("/")
389 .trim_start_matches("~")
390 .trim_start_matches("/");
391
392 format!("cd \"$HOME/{trimmed_path}\"; {env_changes} {to_run}")
393 } else {
394 format!("cd {path:?}; {env_changes} {to_run}")
395 }
396 } else {
397 format!("cd; {env_changes} {to_run}")
398 };
399 let shell_invocation = format!("sh -c {}", shlex::try_quote(&commands).unwrap());
400
401 let (program, mut args) = match ssh_command {
402 SshCommand::DevServer(ssh_command) => {
403 let mut args = shlex::split(ssh_command).unwrap_or_default();
404 let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
405 (program, args)
406 }
407 SshCommand::Direct(ssh_args) => ("ssh".to_string(), ssh_args.clone()),
408 };
409
410 args.push("-t".to_string());
411 args.push(shell_invocation);
412 (program, args)
413}
414
415fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
416 let mut env_paths = vec![new_path.to_path_buf()];
417 if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
418 let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
419 env_paths.append(&mut paths);
420 }
421
422 let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
423 env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
424
425 Ok(())
426}
427
428#[cfg(test)]
429mod tests {
430 use collections::HashMap;
431
432 #[test]
433 fn test_add_environment_path_with_existing_path() {
434 let tmp_path = std::path::PathBuf::from("/tmp/new");
435 let mut env = HashMap::default();
436 let old_path = if cfg!(windows) {
437 "/usr/bin;/usr/local/bin"
438 } else {
439 "/usr/bin:/usr/local/bin"
440 };
441 env.insert("PATH".to_string(), old_path.to_string());
442 env.insert("OTHER".to_string(), "aaa".to_string());
443
444 super::add_environment_path(&mut env, &tmp_path).unwrap();
445 if cfg!(windows) {
446 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
447 } else {
448 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
449 }
450 assert_eq!(env.get("OTHER").unwrap(), "aaa");
451 }
452
453 #[test]
454 fn test_add_environment_path_with_empty_path() {
455 let tmp_path = std::path::PathBuf::from("/tmp/new");
456 let mut env = HashMap::default();
457 env.insert("OTHER".to_string(), "aaa".to_string());
458 let os_path = std::env::var("PATH").unwrap();
459 super::add_environment_path(&mut env, &tmp_path).unwrap();
460 if cfg!(windows) {
461 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
462 } else {
463 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
464 }
465 assert_eq!(env.get("OTHER").unwrap(), "aaa");
466 }
467}