agentmux_srv_core/backend/fs_ops/
platform.rs1use std::io;
14use std::path::Path;
15use std::process::{Command, Stdio};
16
17pub fn display_path(path: &Path) -> String {
24 let s = path.to_string_lossy();
25 if cfg!(windows) {
26 strip_verbatim(&s)
27 } else {
28 s.into_owned()
29 }
30}
31
32pub fn strip_verbatim(s: &str) -> String {
36 if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
37 return format!(r"\\{rest}");
38 }
39 if let Some(rest) = s.strip_prefix(r"\\?\") {
40 let b = rest.as_bytes();
41 if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
42 return rest.to_string();
43 }
44 }
45 s.to_string()
46}
47
48#[cfg(any(windows, test))]
50const ATTR_HIDDEN: u32 = 0x2;
51#[cfg(any(windows, test))]
53const ATTR_SYSTEM: u32 = 0x4;
54
55#[cfg(any(windows, test))]
58pub fn attributes_mark_hidden(attributes: u32) -> bool {
59 attributes & (ATTR_HIDDEN | ATTR_SYSTEM) != 0
60}
61
62pub fn has_hidden_attribute(meta: &std::fs::Metadata) -> bool {
66 #[cfg(windows)]
67 {
68 use std::os::windows::fs::MetadataExt;
69 attributes_mark_hidden(meta.file_attributes())
70 }
71 #[cfg(not(windows))]
72 {
73 let _ = meta;
74 false
75 }
76}
77
78pub fn is_os_blocked(err: &io::Error) -> bool {
83 #[cfg(target_os = "macos")]
84 {
85 err.raw_os_error() == Some(libc::EPERM)
86 }
87 #[cfg(not(target_os = "macos"))]
88 {
89 let _ = err;
90 false
91 }
92}
93
94pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
104 agentmux_remote::rename::rename_no_replace(from, to)
105}
106
107pub fn remove_entry_no_follow(path: &Path) -> io::Result<()> {
115 let file_type = std::fs::symlink_metadata(path)?.file_type();
116 if file_type.is_symlink() {
117 #[cfg(windows)]
120 {
121 use std::os::windows::fs::FileTypeExt;
122 if file_type.is_symlink_dir() {
123 return std::fs::remove_dir(path);
124 }
125 }
126 return std::fs::remove_file(path);
127 }
128 if file_type.is_dir() {
129 std::fs::remove_dir_all(path)
130 } else {
131 std::fs::remove_file(path)
132 }
133}
134
135pub fn open_no_follow(path: &Path) -> io::Result<std::fs::File> {
144 #[cfg(unix)]
145 {
146 use std::os::unix::fs::OpenOptionsExt;
147 std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(path)
148 }
149 #[cfg(not(unix))]
150 {
151 std::fs::File::open(path)
152 }
153}
154
155pub fn create_symlink(target: &Path, link: &Path, like: &std::fs::FileType) -> io::Result<()> {
159 #[cfg(unix)]
160 {
161 let _ = like;
162 std::os::unix::fs::symlink(target, link)
163 }
164 #[cfg(windows)]
165 {
166 use std::os::windows::fs::FileTypeExt;
167 if like.is_symlink_dir() {
168 std::os::windows::fs::symlink_dir(target, link)
169 } else {
170 std::os::windows::fs::symlink_file(target, link)
171 }
172 }
173 #[cfg(not(any(unix, windows)))]
174 {
175 let _ = (target, link, like);
176 Err(io::Error::new(io::ErrorKind::Unsupported, "symlinks aren't supported here"))
177 }
178}
179
180pub fn is_symlink_privilege_error(err: &io::Error) -> bool {
183 const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
184 cfg!(windows) && err.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD)
185}
186
187pub fn remove_file_force(path: &Path) -> io::Result<()> {
191 match std::fs::remove_file(path) {
192 #[cfg(windows)]
193 Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
194 let meta = std::fs::symlink_metadata(path)?;
195 if !meta.is_file() || !meta.permissions().readonly() {
196 return Err(e);
197 }
198 let mut perms = meta.permissions();
199 #[allow(clippy::permissions_set_readonly_false)]
202 perms.set_readonly(false);
203 std::fs::set_permissions(path, perms)?;
204 std::fs::remove_file(path)
205 }
206 other => other,
207 }
208}
209
210pub fn trash_unavailable_reason(path: &Path) -> Option<&'static str> {
217 #[cfg(windows)]
218 {
219 const NETWORK: &str = "Network locations have no Recycle Bin. Use Delete permanently instead.";
220 const REMOVABLE: &str = "This drive has no Recycle Bin. Use Delete permanently instead.";
221 const DRIVE_REMOVABLE: u32 = 2;
224 const DRIVE_REMOTE: u32 = 4;
225 let display = display_path(path);
226 if display.starts_with(r"\\") {
227 return Some(NETWORK);
228 }
229 let b = display.as_bytes();
230 if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
231 let root: Vec<u16> = format!("{}:\\", b[0] as char).encode_utf16().chain(std::iter::once(0)).collect();
232 let kind = unsafe { windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(root.as_ptr()) };
234 return match kind {
235 DRIVE_REMOTE => Some(NETWORK),
236 DRIVE_REMOVABLE => Some(REMOVABLE),
237 _ => None,
238 };
239 }
240 None
241 }
242 #[cfg(not(windows))]
243 {
244 let _ = path;
245 None
246 }
247}
248
249#[cfg_attr(not(windows), allow(dead_code))]
254pub fn explorer_quote(display: &str) -> String {
255 let b = display.as_bytes();
256 if b.len() == 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\' {
257 return display.to_string();
258 }
259 format!("\"{}\"", display.trim_end_matches('\\'))
260}
261
262pub fn open_command(path: &Path) -> Command {
265 #[cfg(windows)]
266 {
267 use std::os::windows::process::CommandExt;
268 let mut cmd = Command::new("explorer.exe");
273 cmd.raw_arg(explorer_quote(&display_path(path)));
274 cmd
275 }
276 #[cfg(target_os = "macos")]
277 {
278 let mut cmd = Command::new("open");
279 cmd.arg(path);
280 cmd
281 }
282 #[cfg(not(any(windows, target_os = "macos")))]
283 {
284 let mut cmd = Command::new("xdg-open");
285 cmd.arg(path);
286 cmd
287 }
288}
289
290pub fn reveal_command(path: &Path) -> Command {
294 #[cfg(windows)]
295 {
296 use std::os::windows::process::CommandExt;
297 let mut cmd = Command::new("explorer.exe");
298 cmd.raw_arg(format!("/select,{}", explorer_quote(&display_path(path))));
299 cmd
300 }
301 #[cfg(target_os = "macos")]
302 {
303 let mut cmd = Command::new("open");
304 cmd.arg("-R").arg(path);
305 cmd
306 }
307 #[cfg(not(any(windows, target_os = "macos")))]
308 {
309 let mut cmd = Command::new("xdg-open");
310 cmd.arg(path.parent().unwrap_or(path));
311 cmd
312 }
313}
314
315pub fn file_uri(path: &Path) -> String {
319 let mut uri = String::from("file://");
320 for &b in path.to_string_lossy().as_bytes() {
321 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~' | b'/') {
322 uri.push(b as char);
323 } else {
324 uri.push_str(&format!("%{b:02X}"));
325 }
326 }
327 uri
328}
329
330pub fn dbus_show_items_command(path: &Path) -> Command {
334 let mut cmd = Command::new("dbus-send");
335 cmd.args([
336 "--session",
337 "--print-reply",
338 "--dest=org.freedesktop.FileManager1",
339 "--type=method_call",
340 "/org/freedesktop/FileManager1",
341 "org.freedesktop.FileManager1.ShowItems",
342 ])
343 .arg(format!("array:string:{}", file_uri(path)))
344 .arg("string:");
345 cmd
346}
347
348pub const DBUS_REVEAL_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
351
352#[cfg_attr(any(windows, target_os = "macos"), allow(dead_code))]
356fn succeeds_within(mut cmd: Command, limit: std::time::Duration) -> bool {
357 crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
358 let Ok(mut child) = cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else {
359 return false;
360 };
361 let deadline = std::time::Instant::now() + limit;
362 loop {
363 match child.try_wait() {
364 Ok(Some(status)) => return status.success(),
365 Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),
366 _ => {
367 let _ = child.kill();
368 let _ = child.wait();
369 return false;
370 }
371 }
372 }
373}
374
375pub fn reveal_linux(
381 path: &Path,
382 dbus: impl FnOnce(Command) -> bool,
383 fallback: impl FnOnce(Command) -> io::Result<()>,
384) -> io::Result<()> {
385 let folder = path.is_dir();
386 if !folder && dbus(dbus_show_items_command(path)) {
387 return Ok(());
388 }
389 let mut cmd = Command::new("xdg-open");
390 cmd.arg(if folder { path } else { path.parent().unwrap_or(path) });
391 fallback(cmd)
392}
393
394pub fn reveal(path: &Path) -> io::Result<()> {
398 #[cfg(any(windows, target_os = "macos"))]
399 {
400 spawn_detached(reveal_command(path))
401 }
402 #[cfg(not(any(windows, target_os = "macos")))]
403 {
404 reveal_linux(path, |cmd| succeeds_within(cmd, DBUS_REVEAL_LIMIT), spawn_detached)
405 }
406}
407
408pub fn spawn_detached(mut cmd: Command) -> io::Result<()> {
420 crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
421 let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()?;
422 std::thread::Builder::new()
423 .name("fs-open-reaper".to_string())
424 .spawn(move || {
425 let _ = child.wait();
426 })?;
427 Ok(())
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 #[test]
435 fn verbatim_prefixes_are_stripped_for_display() {
436 assert_eq!(strip_verbatim(r"\\?\C:\Users\me"), r"C:\Users\me");
437 assert_eq!(strip_verbatim(r"\\?\C:\"), r"C:\");
438 assert_eq!(strip_verbatim(r"\\?\UNC\nas\share\dir"), r"\\nas\share\dir");
439 assert_eq!(strip_verbatim(r"\\?\Volume{abc}\x"), r"\\?\Volume{abc}\x");
441 assert_eq!(strip_verbatim("/home/me"), "/home/me");
442 assert_eq!(strip_verbatim(r"C:\plain"), r"C:\plain");
443 }
444
445 #[test]
446 fn hidden_and_system_attributes_both_hide() {
447 assert!(attributes_mark_hidden(0x2));
448 assert!(attributes_mark_hidden(0x4));
449 assert!(attributes_mark_hidden(0x2 | 0x20));
450 assert!(!attributes_mark_hidden(0x20)); assert!(!attributes_mark_hidden(0x10)); assert!(!attributes_mark_hidden(0x1)); }
454
455 #[test]
456 fn explorer_arguments_stay_in_one_piece() {
457 assert_eq!(explorer_quote(r"C:\a b\c,d.txt"), r#""C:\a b\c,d.txt""#);
458 assert_eq!(explorer_quote(r"C:\"), r"C:\");
459 assert_eq!(explorer_quote(r"\\nas\My Share\"), r#""\\nas\My Share""#);
460 }
461
462 #[test]
463 fn rename_no_replace_refuses_an_existing_destination() {
464 let dir = tempfile::tempdir().unwrap();
465 let (a, b) = (dir.path().join("a.txt"), dir.path().join("b.txt"));
466 std::fs::write(&a, "a").unwrap();
467 std::fs::write(&b, "b").unwrap();
468 let err = rename_no_replace(&a, &b).unwrap_err();
469 assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{err}");
470 assert_eq!(std::fs::read_to_string(&b).unwrap(), "b", "the destination must be untouched");
471
472 let c = dir.path().join("c.txt");
473 rename_no_replace(&a, &c).unwrap();
474 assert!(!a.exists());
475 assert_eq!(std::fs::read_to_string(&c).unwrap(), "a");
476 }
477
478 #[test]
479 fn deleting_a_link_keeps_its_target() {
480 let dir = tempfile::tempdir().unwrap();
481 let target = dir.path().join("target");
482 std::fs::create_dir(&target).unwrap();
483 std::fs::write(target.join("keep.txt"), "x").unwrap();
484 let link = dir.path().join("link");
485 #[cfg(unix)]
486 let made = std::os::unix::fs::symlink(&target, &link).is_ok();
487 #[cfg(windows)]
490 let made = std::os::windows::fs::symlink_dir(&target, &link).is_ok();
491 if !made {
492 return;
493 }
494 remove_entry_no_follow(&link).unwrap();
495 assert!(std::fs::symlink_metadata(&link).is_err(), "the link is gone");
496 assert!(target.join("keep.txt").exists(), "the target and its contents remain");
497 }
498
499 #[test]
500 fn deleting_a_directory_removes_its_contents() {
501 let dir = tempfile::tempdir().unwrap();
502 let sub = dir.path().join("sub");
503 std::fs::create_dir_all(sub.join("deeper")).unwrap();
504 std::fs::write(sub.join("deeper").join("f.txt"), "x").unwrap();
505 remove_entry_no_follow(&sub).unwrap();
506 assert!(!sub.exists());
507 }
508
509 #[test]
510 fn a_file_uri_keeps_a_path_in_one_piece() {
511 assert_eq!(file_uri(Path::new("/home/me/a.txt")), "file:///home/me/a.txt");
512 assert_eq!(file_uri(Path::new("/home/me/a b#c%d,e.txt")), "file:///home/me/a%20b%23c%25d%2Ce.txt");
514 assert_eq!(file_uri(Path::new("/home/me/é.txt")), "file:///home/me/%C3%A9.txt");
516 assert_eq!(file_uri(Path::new("/home/me/a-b_c~d.e")), "file:///home/me/a-b_c~d.e");
517 }
518
519 #[test]
520 fn the_dbus_call_names_the_file_managers_show_items_method_and_the_file() {
521 let cmd = dbus_show_items_command(Path::new("/home/me/a b.txt"));
522 assert_eq!(cmd.get_program().to_string_lossy(), "dbus-send");
523 let args: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
524 assert_eq!(
525 args,
526 [
527 "--session",
528 "--print-reply",
529 "--dest=org.freedesktop.FileManager1",
530 "--type=method_call",
531 "/org/freedesktop/FileManager1",
532 "org.freedesktop.FileManager1.ShowItems",
533 "array:string:file:///home/me/a%20b.txt",
534 "string:",
535 ]
536 );
537 }
538
539 #[test]
540 fn linux_selects_the_file_through_dbus_and_never_opens_the_folder_when_it_worked() {
541 let asked = std::cell::RefCell::new(Vec::new());
542 let r = reveal_linux(
543 Path::new("/home/me/a.txt"),
544 |cmd| {
545 asked.borrow_mut().push(cmd.get_program().to_string_lossy().into_owned());
546 true
547 },
548 |_| panic!("xdg-open must not run when ShowItems worked"),
549 );
550 assert!(r.is_ok());
551 assert_eq!(*asked.borrow(), ["dbus-send"]);
552 }
553
554 #[test]
555 fn linux_opens_the_containing_folder_when_dbus_did_not_work() {
556 let opened = std::cell::RefCell::new(None);
558 let r = reveal_linux(
559 Path::new("/home/me/dir/a.txt"),
560 |_| false,
561 |cmd| {
562 let args: Vec<String> = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect();
563 *opened.borrow_mut() = Some((cmd.get_program().to_string_lossy().into_owned(), args));
564 Ok(())
565 },
566 );
567 assert!(r.is_ok());
568 assert_eq!(opened.into_inner(), Some(("xdg-open".to_string(), vec!["/home/me/dir".to_string()])));
569 }
570
571 #[test]
572 fn linux_reports_a_failed_fallback() {
573 let r = reveal_linux(Path::new("/home/me/a.txt"), |_| false, |_| Err(io::Error::new(io::ErrorKind::NotFound, "no xdg-open")));
574 assert_eq!(r.unwrap_err().kind(), io::ErrorKind::NotFound);
575 }
576
577 #[test]
578 fn linux_opens_a_folder_itself_and_never_asks_dbus_to_select_it() {
579 let dir = tempfile::tempdir().unwrap();
580 let opened = std::cell::RefCell::new(Vec::new());
581 let r = reveal_linux(
582 dir.path(),
583 |_| panic!("ShowItems would show the folder's parent"),
584 |cmd| {
585 opened.borrow_mut().push(cmd.get_args().map(|a| a.to_os_string()).collect::<Vec<_>>());
586 Ok(())
587 },
588 );
589 assert!(r.is_ok());
590 assert_eq!(*opened.borrow(), [vec![dir.path().as_os_str().to_os_string()]]);
591 }
592
593 #[test]
594 fn a_missing_program_is_not_a_success() {
595 let cmd = Command::new("agentmux-no-such-program-for-this-test");
596 assert!(!succeeds_within(cmd, std::time::Duration::from_secs(1)));
597 }
598
599 #[cfg(unix)]
600 #[test]
601 fn a_program_that_exits_zero_is_a_success_and_one_that_exits_non_zero_is_not() {
602 assert!(succeeds_within(Command::new("true"), std::time::Duration::from_secs(5)));
603 assert!(!succeeds_within(Command::new("false"), std::time::Duration::from_secs(5)));
604 }
605
606 #[cfg(unix)]
607 #[test]
608 fn a_program_still_running_at_the_limit_is_stopped_and_is_not_a_success() {
609 let mut cmd = Command::new("sleep");
610 cmd.arg("30");
611 let started = std::time::Instant::now();
612 assert!(!succeeds_within(cmd, std::time::Duration::from_millis(150)));
613 assert!(started.elapsed() < std::time::Duration::from_secs(10), "it waited for the program instead of stopping it");
614 }
615}