1#[allow(unused_imports)]
2use std::process::Command;
3
4use crate::state::PackageItem;
5#[cfg(not(target_os = "windows"))]
6use crate::state::Source;
7
8#[cfg(not(target_os = "windows"))]
9use super::command::build_install_command;
10#[cfg(all(target_os = "windows", not(test)))]
11use super::command::build_install_command;
12#[cfg(not(target_os = "windows"))]
13use super::logging::log_installed;
14#[cfg(not(target_os = "windows"))]
15use super::utils::{choose_terminal_index_prefer_path, command_on_path, shell_single_quote};
16
17#[cfg(not(target_os = "windows"))]
18fn try_spawn_terminal(
35 term: &str,
36 args: &[&str],
37 needs_xfce_command: bool,
38 cmd_str: &str,
39 item_name: &str,
40 src: &str,
41 dry_run: bool,
42) -> bool {
43 let mut cmd = Command::new(term);
44 if needs_xfce_command && term == "xfce4-terminal" {
45 let quoted = shell_single_quote(cmd_str);
46 cmd.arg("--command").arg(format!("bash -lc {quoted}"));
47 } else {
48 cmd.args(args.iter().copied()).arg(cmd_str);
49 }
50 if let Ok(p) = std::env::var("PACSEA_TEST_OUT") {
51 if let Some(parent) = std::path::Path::new(&p).parent() {
52 let _ = std::fs::create_dir_all(parent);
53 }
54 cmd.env("PACSEA_TEST_OUT", p);
55 }
56 match cmd.spawn() {
57 Ok(_) => {
58 tracing::info!(
59 terminal = %term,
60 names = %item_name,
61 total = 1,
62 aur_count = usize::from(src == "aur"),
63 official_count = usize::from(src == "official"),
64 dry_run,
65 "launched terminal for install"
66 );
67 true
68 }
69 Err(e) => {
70 tracing::warn!(
71 terminal = %term,
72 error = %e,
73 names = %item_name,
74 "failed to spawn terminal, trying next"
75 );
76 false
77 }
78 }
79}
80
81#[cfg(not(target_os = "windows"))]
82fn get_terminal_preferences() -> &'static [(&'static str, &'static [&'static str], bool)] {
93 let is_gnome =
94 std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|v| v.to_uppercase().contains("GNOME"));
95 if is_gnome {
96 &[
97 ("gnome-terminal", &["--", "bash", "-lc"], false),
98 ("gnome-console", &["--", "bash", "-lc"], false),
99 ("kgx", &["--", "bash", "-lc"], false),
100 ("alacritty", &["-e", "bash", "-lc"], false),
101 ("kitty", &["bash", "-lc"], false),
102 ("xterm", &["-hold", "-e", "bash", "-lc"], false),
103 ("konsole", &["-e", "bash", "-lc"], false),
104 ("xfce4-terminal", &[], true),
105 ("tilix", &["--", "bash", "-lc"], false),
106 ("mate-terminal", &["--", "bash", "-lc"], false),
107 ]
108 } else {
109 &[
110 ("alacritty", &["-e", "bash", "-lc"], false),
111 ("kitty", &["bash", "-lc"], false),
112 ("xterm", &["-hold", "-e", "bash", "-lc"], false),
113 ("gnome-terminal", &["--", "bash", "-lc"], false),
114 ("gnome-console", &["--", "bash", "-lc"], false),
115 ("kgx", &["--", "bash", "-lc"], false),
116 ("konsole", &["-e", "bash", "-lc"], false),
117 ("xfce4-terminal", &[], true),
118 ("tilix", &["--", "bash", "-lc"], false),
119 ("mate-terminal", &["--", "bash", "-lc"], false),
120 ]
121 }
122}
123
124#[cfg(not(target_os = "windows"))]
125pub fn spawn_install(item: &PackageItem, password: Option<&str>, dry_run: bool) {
137 #[cfg(test)]
139 if std::env::var("PACSEA_TEST_OUT").is_err() {
140 return;
141 }
142
143 let (cmd_str, uses_sudo) = match build_install_command(item, password, dry_run) {
144 Ok(v) => v,
145 Err(err) => {
146 tracing::error!(error = %err, names = %item.name, "privilege tool resolution failed for install");
147 return;
148 }
149 };
150 let src = match item.source {
151 Source::Official { .. } => "official",
152 Source::Aur => "aur",
153 };
154 tracing::info!(
155 names = %item.name,
156 total = 1,
157 aur_count = usize::from(src == "aur"),
158 official_count = usize::from(src == "official"),
159 dry_run = dry_run,
160 uses_sudo,
161 "spawning install"
162 );
163
164 let terms = get_terminal_preferences();
165
166 let mut launched = choose_terminal_index_prefer_path(terms).is_some_and(|idx| {
168 let (term, args, needs_xfce_command) = terms[idx];
169 try_spawn_terminal(
170 term,
171 args,
172 needs_xfce_command,
173 &cmd_str,
174 &item.name,
175 src,
176 dry_run,
177 )
178 });
179
180 if !launched {
182 for (term, args, needs_xfce_command) in terms {
183 if command_on_path(term) {
184 launched = try_spawn_terminal(
185 term,
186 args,
187 *needs_xfce_command,
188 &cmd_str,
189 &item.name,
190 src,
191 dry_run,
192 );
193 if launched {
194 break;
195 }
196 }
197 }
198 }
199
200 if !launched {
202 let res = Command::new("bash").args(["-lc", &cmd_str]).spawn();
203 if let Err(e) = res {
204 tracing::error!(error = %e, names = %item.name, "failed to spawn bash to run install command");
205 } else {
206 tracing::info!(
207 names = %item.name,
208 total = 1,
209 aur_count = usize::from(src == "aur"),
210 official_count = usize::from(src == "official"),
211 dry_run = dry_run,
212 "launched bash for install"
213 );
214 }
215 }
216
217 if !dry_run && let Err(e) = log_installed(std::slice::from_ref(&item.name)) {
218 tracing::warn!(error = %e, names = %item.name, "failed to write install audit log");
219 }
220}
221
222#[cfg(all(test, not(target_os = "windows")))]
223mod tests {
224 #[test]
225 fn install_single_uses_gnome_terminal_double_dash() {
237 use std::fs;
238 use std::os::unix::fs::PermissionsExt;
239 use std::path::PathBuf;
240
241 let mut dir: PathBuf = std::env::temp_dir();
242 dir.push(format!(
243 "pacsea_test_inst_single_gnome_{}_{}",
244 std::process::id(),
245 std::time::SystemTime::now()
246 .duration_since(std::time::UNIX_EPOCH)
247 .expect("System time is before UNIX epoch")
248 .as_nanos()
249 ));
250 fs::create_dir_all(&dir).expect("Failed to create test directory");
251 let mut out_path = dir.clone();
252 out_path.push("args.txt");
253 let mut term_path = dir.clone();
254 term_path.push("gnome-terminal");
255 let script = "#!/bin/sh\n: > \"$PACSEA_TEST_OUT\"\nfor a in \"$@\"; do printf '%s\n' \"$a\" >> \"$PACSEA_TEST_OUT\"; done\n";
256 fs::write(&term_path, script.as_bytes()).expect("Failed to write test terminal script");
257 let mut perms = fs::metadata(&term_path)
258 .expect("Failed to read test terminal script metadata")
259 .permissions();
260 perms.set_mode(0o755);
261 fs::set_permissions(&term_path, perms)
262 .expect("Failed to set test terminal script permissions");
263
264 let orig_path = std::env::var_os("PATH");
265 unsafe {
266 std::env::set_var("PATH", dir.display().to_string());
267 std::env::set_var("PACSEA_TEST_OUT", out_path.display().to_string());
268 }
269
270 let pkg = crate::state::PackageItem {
271 name: "ripgrep".into(),
272 version: "1".into(),
273 description: String::new(),
274 source: crate::state::Source::Official {
275 repo: "extra".into(),
276 arch: "x86_64".into(),
277 },
278 popularity: None,
279 out_of_date: None,
280 orphaned: false,
281 };
282 super::spawn_install(&pkg, None, true);
283 std::thread::sleep(std::time::Duration::from_millis(50));
284
285 let body = fs::read_to_string(&out_path).expect("fake terminal args file written");
286 let lines: Vec<&str> = body.lines().collect();
287 assert!(lines.len() >= 3, "expected at least 3 args, got: {body}");
288 assert_eq!(lines[0], "--");
289 assert_eq!(lines[1], "bash");
290 assert_eq!(lines[2], "-lc");
291
292 unsafe {
293 if let Some(v) = orig_path {
294 std::env::set_var("PATH", v);
295 } else {
296 std::env::remove_var("PATH");
297 }
298 std::env::remove_var("PACSEA_TEST_OUT");
299 }
300 }
301}
302
303#[cfg(target_os = "windows")]
304#[allow(unused_variables, clippy::missing_const_for_fn)]
319pub fn spawn_install(item: &PackageItem, password: Option<&str>, dry_run: bool) {
320 #[cfg(not(test))]
321 {
322 let (cmd_str, _uses_sudo) = match build_install_command(item, password, dry_run) {
323 Ok(v) => v,
324 Err(err) => {
325 tracing::error!(error = %err, "privilege tool resolution failed for install");
326 return;
327 }
328 };
329
330 if dry_run && super::utils::is_powershell_available() {
331 let powershell_cmd = format!(
333 "Write-Host 'DRY RUN: Simulating install of {}' -ForegroundColor Yellow; Write-Host 'Command: {}' -ForegroundColor Cyan; Write-Host ''; Write-Host 'Press any key to close...'; $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')",
334 item.name,
335 cmd_str.replace('\'', "''")
336 );
337 let _ = Command::new("powershell.exe")
338 .args(["-NoProfile", "-Command", &powershell_cmd])
339 .spawn();
340 } else {
341 let _ = Command::new("cmd")
342 .args(["/C", "start", "Pacsea Install", "cmd", "/K", &cmd_str])
343 .spawn();
344 }
345
346 if !dry_run {
347 let _ = super::logging::log_installed(std::slice::from_ref(&item.name));
348 }
349 }
350}