1use crate::Project;
2use anyhow::Context as _;
3use collections::HashMap;
4use gpui::{
5 AnyWindowHandle, AppContext, Context, Entity, Model, ModelContext, SharedString, WeakModel,
6};
7use itertools::Itertools;
8use settings::{Settings, SettingsLocation};
9use smol::channel::bounded;
10use std::{
11 env,
12 fs::File,
13 io::Write,
14 path::{Path, PathBuf},
15};
16use task::{SpawnInTerminal, TerminalWorkDir};
17use terminal::{
18 terminal_settings::{self, Shell, TerminalSettings, VenvSettingsContent},
19 TaskState, TaskStatus, Terminal, TerminalBuilder,
20};
21use util::ResultExt;
22
23// #[cfg(target_os = "macos")]
24// use std::os::unix::ffi::OsStrExt;
25
26pub struct Terminals {
27 pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
28}
29
30#[derive(Debug, Clone)]
31pub struct ConnectRemoteTerminal {
32 pub ssh_connection_string: SharedString,
33 pub project_path: SharedString,
34}
35
36impl Project {
37 pub fn terminal_work_dir_for(
38 &self,
39 pathbuf: Option<&Path>,
40 cx: &AppContext,
41 ) -> Option<TerminalWorkDir> {
42 if self.is_local() {
43 return Some(TerminalWorkDir::Local(pathbuf?.to_owned()));
44 }
45 let dev_server_project_id = self.dev_server_project_id()?;
46 let projects_store = dev_server_projects::Store::global(cx).read(cx);
47 let ssh_command = projects_store
48 .dev_server_for_project(dev_server_project_id)?
49 .ssh_connection_string
50 .as_ref()?
51 .to_string();
52
53 let path = if let Some(pathbuf) = pathbuf {
54 pathbuf.to_string_lossy().to_string()
55 } else {
56 projects_store
57 .dev_server_project(dev_server_project_id)?
58 .path
59 .to_string()
60 };
61
62 Some(TerminalWorkDir::Ssh {
63 ssh_command,
64 path: Some(path),
65 })
66 }
67
68 pub fn create_terminal(
69 &mut self,
70 working_directory: Option<TerminalWorkDir>,
71 spawn_task: Option<SpawnInTerminal>,
72 window: AnyWindowHandle,
73 cx: &mut ModelContext<Self>,
74 ) -> anyhow::Result<Model<Terminal>> {
75 // used only for TerminalSettings::get
76 let worktree = {
77 let terminal_cwd = working_directory.as_ref().and_then(|cwd| cwd.local_path());
78 let task_cwd = spawn_task
79 .as_ref()
80 .and_then(|spawn_task| spawn_task.cwd.as_ref())
81 .and_then(|cwd| cwd.local_path());
82
83 terminal_cwd
84 .and_then(|terminal_cwd| self.find_local_worktree(&terminal_cwd, cx))
85 .or_else(|| task_cwd.and_then(|spawn_cwd| self.find_local_worktree(&spawn_cwd, cx)))
86 };
87
88 let settings_location = worktree.as_ref().map(|(worktree, path)| SettingsLocation {
89 worktree_id: worktree.read(cx).id().to_usize(),
90 path,
91 });
92
93 let is_terminal = spawn_task.is_none()
94 && working_directory
95 .as_ref()
96 .map_or(true, |work_dir| work_dir.is_local());
97 let settings = TerminalSettings::get(settings_location, cx);
98 let python_settings = settings.detect_venv.clone();
99 let (completion_tx, completion_rx) = bounded(1);
100
101 let mut env = settings.env.clone();
102 // Alacritty uses parent project's working directory when no working directory is provided
103 // https://github.com/alacritty/alacritty/blob/fd1a3cc79192d1d03839f0fd8c72e1f8d0fce42e/extra/man/alacritty.5.scd?plain=1#L47-L52
104
105 let mut retained_script = None;
106
107 let venv_base_directory = working_directory
108 .as_ref()
109 .and_then(|cwd| cwd.local_path())
110 .unwrap_or_else(|| Path::new(""));
111
112 let (spawn_task, shell) = match working_directory.as_ref() {
113 Some(TerminalWorkDir::Ssh { ssh_command, path }) => {
114 log::debug!("Connecting to a remote server: {ssh_command:?}");
115 let tmp_dir = tempfile::tempdir()?;
116 let ssh_shell_result = prepare_ssh_shell(
117 &mut env,
118 tmp_dir.path(),
119 spawn_task.as_ref(),
120 ssh_command,
121 path.as_deref(),
122 );
123 retained_script = Some(tmp_dir);
124 let ssh_shell = ssh_shell_result?;
125
126 (
127 spawn_task.map(|spawn_task| TaskState {
128 id: spawn_task.id,
129 full_label: spawn_task.full_label,
130 label: spawn_task.label,
131 command_label: spawn_task.command_label,
132 status: TaskStatus::Running,
133 completion_rx,
134 }),
135 ssh_shell,
136 )
137 }
138 _ => {
139 if let Some(spawn_task) = spawn_task {
140 log::debug!("Spawning task: {spawn_task:?}");
141 env.extend(spawn_task.env);
142 // Activate minimal Python virtual environment
143 if let Some(python_settings) = &python_settings.as_option() {
144 self.set_python_venv_path_for_tasks(
145 python_settings,
146 &venv_base_directory,
147 &mut env,
148 );
149 }
150 (
151 Some(TaskState {
152 id: spawn_task.id,
153 full_label: spawn_task.full_label,
154 label: spawn_task.label,
155 command_label: spawn_task.command_label,
156 status: TaskStatus::Running,
157 completion_rx,
158 }),
159 Shell::WithArguments {
160 program: spawn_task.command,
161 args: spawn_task.args,
162 },
163 )
164 } else {
165 (None, settings.shell.clone())
166 }
167 }
168 };
169
170 let terminal = TerminalBuilder::new(
171 working_directory
172 .as_ref()
173 .and_then(|cwd| cwd.local_path())
174 .map(ToOwned::to_owned),
175 spawn_task,
176 shell,
177 env,
178 Some(settings.blinking),
179 settings.alternate_scroll,
180 settings.max_scroll_history_lines,
181 window,
182 completion_tx,
183 cx,
184 )
185 .map(|builder| {
186 let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
187
188 self.terminals
189 .local_handles
190 .push(terminal_handle.downgrade());
191
192 let id = terminal_handle.entity_id();
193 cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
194 drop(retained_script);
195 let handles = &mut project.terminals.local_handles;
196
197 if let Some(index) = handles
198 .iter()
199 .position(|terminal| terminal.entity_id() == id)
200 {
201 handles.remove(index);
202 cx.notify();
203 }
204 })
205 .detach();
206
207 // if the terminal is not a task, activate full Python virtual environment
208 if is_terminal {
209 if let Some(python_settings) = &python_settings.as_option() {
210 if let Some(activate_script_path) =
211 self.find_activate_script_path(python_settings, &venv_base_directory)
212 {
213 self.activate_python_virtual_environment(
214 Project::get_activate_command(python_settings),
215 activate_script_path,
216 &terminal_handle,
217 cx,
218 );
219 }
220 }
221 }
222 terminal_handle
223 });
224
225 terminal
226 }
227
228 pub fn find_activate_script_path(
229 &mut self,
230 settings: &VenvSettingsContent,
231 venv_base_directory: &Path,
232 ) -> Option<PathBuf> {
233 let activate_script_name = match settings.activate_script {
234 terminal_settings::ActivateScript::Default => "activate",
235 terminal_settings::ActivateScript::Csh => "activate.csh",
236 terminal_settings::ActivateScript::Fish => "activate.fish",
237 terminal_settings::ActivateScript::Nushell => "activate.nu",
238 };
239
240 settings
241 .directories
242 .into_iter()
243 .find_map(|virtual_environment_name| {
244 let path = venv_base_directory
245 .join(virtual_environment_name)
246 .join("bin")
247 .join(activate_script_name);
248 path.exists().then_some(path)
249 })
250 }
251
252 pub fn set_python_venv_path_for_tasks(
253 &mut self,
254 settings: &VenvSettingsContent,
255 venv_base_directory: &Path,
256 env: &mut HashMap<String, String>,
257 ) {
258 let activate_path = settings
259 .directories
260 .into_iter()
261 .find_map(|virtual_environment_name| {
262 let path = venv_base_directory.join(virtual_environment_name);
263 path.exists().then_some(path)
264 });
265
266 if let Some(path) = activate_path {
267 // Some tools use VIRTUAL_ENV to detect the virtual environment
268 env.insert(
269 "VIRTUAL_ENV".to_string(),
270 path.to_string_lossy().to_string(),
271 );
272
273 // We need to set the PATH to include the virtual environment's bin directory
274 add_environment_path(env, &path.join("bin")).log_err();
275 }
276 }
277
278 fn get_activate_command(settings: &VenvSettingsContent) -> &'static str {
279 match settings.activate_script {
280 terminal_settings::ActivateScript::Nushell => "overlay use",
281 _ => "source",
282 }
283 }
284
285 fn activate_python_virtual_environment(
286 &mut self,
287 activate_command: &'static str,
288 activate_script: PathBuf,
289 terminal_handle: &Model<Terminal>,
290 cx: &mut ModelContext<Project>,
291 ) {
292 // Paths are not strings so we need to jump through some hoops to format the command without `format!`
293 let mut command = Vec::from(activate_command.as_bytes());
294 command.push(b' ');
295 // Wrapping path in double quotes to catch spaces in folder name
296 command.extend_from_slice(b"\"");
297 command.extend_from_slice(activate_script.as_os_str().as_encoded_bytes());
298 command.extend_from_slice(b"\"");
299 command.push(b'\n');
300
301 terminal_handle.update(cx, |this, _| this.input_bytes(command));
302 }
303
304 pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
305 &self.terminals.local_handles
306 }
307}
308
309fn prepare_ssh_shell(
310 env: &mut HashMap<String, String>,
311 tmp_dir: &Path,
312 spawn_task: Option<&SpawnInTerminal>,
313 ssh_command: &str,
314 path: Option<&str>,
315) -> anyhow::Result<Shell> {
316 // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
317 // to properly display colors.
318 // We do not have the luxury of assuming the host has it installed,
319 // so we set it to a default that does not break the highlighting via ssh.
320 env.entry("TERM".to_string())
321 .or_insert_with(|| "xterm-256color".to_string());
322
323 let real_ssh = which::which("ssh")?;
324 let ssh_path = tmp_dir.join("ssh");
325 let mut ssh_file = File::create(&ssh_path)?;
326
327 let to_run = if let Some(spawn_task) = spawn_task {
328 Some(shlex::try_quote(&spawn_task.command)?)
329 .into_iter()
330 .chain(
331 spawn_task
332 .args
333 .iter()
334 .filter_map(|arg| shlex::try_quote(arg).ok()),
335 )
336 .join(" ")
337 } else {
338 "exec $SHELL -l".to_string()
339 };
340
341 let commands = if let Some(path) = path {
342 format!("cd {path}; {to_run}")
343 } else {
344 format!("cd; {to_run}")
345 };
346 let shell_invocation = &format!("sh -c {}", shlex::try_quote(&commands)?);
347
348 // To support things like `gh cs ssh`/`coder ssh`, we run whatever command
349 // you have configured, but place our custom script on the path so that it will
350 // be run instead.
351 write!(
352 &mut ssh_file,
353 "#!/bin/sh\nexec {} \"$@\" {} {}",
354 real_ssh.to_string_lossy(),
355 if spawn_task.is_none() { "-t" } else { "" },
356 shlex::try_quote(shell_invocation)?,
357 )?;
358
359 // todo(windows)
360 #[cfg(not(target_os = "windows"))]
361 std::fs::set_permissions(ssh_path, smol::fs::unix::PermissionsExt::from_mode(0o755))?;
362
363 add_environment_path(env, tmp_dir)?;
364
365 let mut args = shlex::split(&ssh_command).unwrap_or_default();
366 let program = args.drain(0..1).next().unwrap_or("ssh".to_string());
367 Ok(Shell::WithArguments { program, args })
368}
369
370fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> anyhow::Result<()> {
371 let mut env_paths = vec![new_path.to_path_buf()];
372 if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
373 let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
374 env_paths.append(&mut paths);
375 }
376
377 let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
378 env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
379
380 Ok(())
381}
382
383#[cfg(test)]
384mod tests {
385 use collections::HashMap;
386
387 #[test]
388 fn test_add_environment_path_with_existing_path() {
389 let tmp_path = std::path::PathBuf::from("/tmp/new");
390 let mut env = HashMap::default();
391 let old_path = if cfg!(windows) {
392 "/usr/bin;/usr/local/bin"
393 } else {
394 "/usr/bin:/usr/local/bin"
395 };
396 env.insert("PATH".to_string(), old_path.to_string());
397 env.insert("OTHER".to_string(), "aaa".to_string());
398
399 super::add_environment_path(&mut env, &tmp_path).unwrap();
400 if cfg!(windows) {
401 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
402 } else {
403 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
404 }
405 assert_eq!(env.get("OTHER").unwrap(), "aaa");
406 }
407
408 #[test]
409 fn test_add_environment_path_with_empty_path() {
410 let tmp_path = std::path::PathBuf::from("/tmp/new");
411 let mut env = HashMap::default();
412 env.insert("OTHER".to_string(), "aaa".to_string());
413 let os_path = std::env::var("PATH").unwrap();
414 super::add_environment_path(&mut env, &tmp_path).unwrap();
415 if cfg!(windows) {
416 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
417 } else {
418 assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
419 }
420 assert_eq!(env.get("OTHER").unwrap(), "aaa");
421 }
422}