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