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