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