1pub mod container_folders;
15pub mod host_jobs;
16pub mod remote;
17pub mod git;
18pub mod jobs;
19pub mod platform;
20pub mod trash_worker;
21
22use std::collections::HashMap;
23use std::io;
24use std::iter::Peekable;
25use std::path::{Component, Path, PathBuf};
26use std::sync::{LazyLock, Mutex};
27use std::time::{Duration, Instant};
28
29use crate::backend::rpc_types::{
30 FsCreateKind, FsCreateReq, FsCreateResult, FsEntry, FsError, FsErrorKind, FsListReq,
31 FsListResult, FsPlace, FsPlaceKind, FsRenameReq, FsRenameResult,
32};
33
34use platform::display_path;
35
36pub fn resolve_request_path(raw: &str) -> Result<PathBuf, String> {
43 if raw.contains('\0') {
44 return Err("That path contains an invalid character.".to_string());
45 }
46 if raw.is_empty() {
47 return Err("No path was given.".to_string());
48 }
49 let converted = crate::backend::base::msys_to_windows_path(raw);
50 let expanded = crate::backend::base::expand_home_dir_safe(&converted);
51 if !expanded.is_absolute() {
52 return Err(format!("“{raw}” isn't a full path."));
53 }
54 Ok(expanded)
55}
56
57pub fn resolve_entry_path(raw: &str) -> Result<PathBuf, String> {
66 let path = resolve_request_path(raw)?;
67 let name = path.file_name().ok_or_else(|| {
68 if path.parent().is_none() {
69 ROOT_REFUSAL.to_string()
70 } else {
71 format!("“{raw}” isn't a valid path.")
72 }
73 })?;
74 let parent = path.parent().ok_or_else(|| ROOT_REFUSAL.to_string())?;
75 let canonical_parent = parent.canonicalize().map_err(|e| match e.kind() {
76 io::ErrorKind::NotFound => "The folder it's in doesn't exist anymore.".to_string(),
77 _ => format!("Couldn't open the folder it's in: {e}"),
78 })?;
79 Ok(canonical_parent.join(name))
80}
81
82fn path_key(path: &Path) -> PathBuf {
86 if cfg!(windows) {
87 PathBuf::from(display_path(path).to_lowercase())
88 } else {
89 path.to_path_buf()
90 }
91}
92
93fn file_name_string(path: &Path) -> String {
94 path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
95}
96
97pub const DEFAULT_LIST_LIMIT: u32 = 1000;
101pub const MAX_LIST_LIMIT: u32 = 5000;
103pub const CURSOR_TTL: Duration = Duration::from_secs(30);
107const MAX_CURSORS: usize = 256;
110const MAX_CONSECUTIVE_ENTRY_ERRORS: usize = 64;
113
114pub struct ListCursor {
116 iter: Peekable<std::fs::ReadDir>,
117 display: String,
118 last_used: Instant,
119}
120
121#[derive(Default)]
123pub struct CursorStore {
124 cursors: HashMap<String, ListCursor>,
125}
126
127impl CursorStore {
128 fn take(&mut self, id: &str, now: Instant) -> Option<ListCursor> {
130 let cursor = self.cursors.remove(id)?;
131 (now.saturating_duration_since(cursor.last_used) <= CURSOR_TTL).then_some(cursor)
132 }
133
134 fn put(&mut self, mut cursor: ListCursor, now: Instant) -> String {
137 self.sweep(now);
138 while self.cursors.len() >= MAX_CURSORS {
139 let Some(oldest) = self
140 .cursors
141 .iter()
142 .min_by_key(|(_, c)| c.last_used)
143 .map(|(id, _)| id.clone())
144 else {
145 break;
146 };
147 self.cursors.remove(&oldest);
148 }
149 cursor.last_used = now;
150 let id = uuid::Uuid::new_v4().to_string();
151 self.cursors.insert(id.clone(), cursor);
152 id
153 }
154
155 pub fn sweep(&mut self, now: Instant) {
158 self.cursors
159 .retain(|_, c| now.saturating_duration_since(c.last_used) <= CURSOR_TTL);
160 }
161
162 #[cfg(test)]
163 fn len(&self) -> usize {
164 self.cursors.len()
165 }
166}
167
168pub static CURSORS: LazyLock<Mutex<CursorStore>> = LazyLock::new(|| Mutex::new(CursorStore::default()));
172
173pub fn ensure_cursor_sweeper() {
177 static STARTED: std::sync::Once = std::sync::Once::new();
178 STARTED.call_once(|| {
179 tokio::spawn(async {
180 let mut tick = tokio::time::interval(Duration::from_secs(10));
181 loop {
182 tick.tick().await;
183 lock_store(&CURSORS).sweep(Instant::now());
184 }
185 });
186 });
187}
188
189pub fn list_page(req: &FsListReq) -> FsListResult {
191 list_page_in(&CURSORS, req, Instant::now())
192}
193
194pub fn list_page_in(store: &Mutex<CursorStore>, req: &FsListReq, now: Instant) -> FsListResult {
198 let limit = req.limit.unwrap_or(DEFAULT_LIST_LIMIT).clamp(1, MAX_LIST_LIMIT) as usize;
199
200 let mut cursor = match req.cursor.as_deref() {
201 Some(id) => {
202 let taken = lock_store(store).take(id, now);
203 match taken {
204 Some(c) => c,
205 None => {
206 let path = resolve_request_path(&req.path)
207 .map(|p| display_path(&p))
208 .unwrap_or_else(|_| req.path.clone());
209 return list_failure(path, FsErrorKind::Expired, "This listing expired. Reload the folder.".to_string());
210 }
211 }
212 }
213 None => match open_listing(&req.path) {
214 Ok(c) => c,
215 Err(failure) => return failure,
216 },
217 };
218
219 let mut entries = Vec::with_capacity(limit.min(1024));
220 let mut consecutive_errors = 0usize;
221 let mut gave_up = false;
222 while entries.len() < limit {
223 match cursor.iter.next() {
224 None => break,
225 Some(Ok(de)) => {
226 consecutive_errors = 0;
227 entries.push(build_entry(&de));
228 }
229 Some(Err(e)) => {
231 tracing::debug!(dir = %cursor.display, error = %e, "fs.list: skipping an unreadable directory entry");
232 consecutive_errors += 1;
233 if consecutive_errors >= MAX_CONSECUTIVE_ENTRY_ERRORS {
234 tracing::warn!(dir = %cursor.display, "fs.list: too many unreadable entries in a row; ending the listing");
235 gave_up = true;
236 break;
237 }
238 }
239 }
240 }
241
242 let display = cursor.display.clone();
243 let done = gave_up || cursor.iter.peek().is_none();
244 let next = if done {
245 None
246 } else {
247 Some(lock_store(store).put(cursor, now))
248 };
249 FsListResult { path: display, entries, cursor: next, error: None }
250}
251
252fn lock_store(store: &Mutex<CursorStore>) -> std::sync::MutexGuard<'_, CursorStore> {
256 store.lock().unwrap_or_else(|e| e.into_inner())
257}
258
259fn list_failure(path: String, kind: FsErrorKind, message: String) -> FsListResult {
260 FsListResult { path, entries: Vec::new(), cursor: None, error: Some(FsError { kind, message }) }
261}
262
263fn open_listing(raw: &str) -> Result<ListCursor, FsListResult> {
265 let path = resolve_request_path(raw)
266 .map_err(|msg| list_failure(raw.to_string(), FsErrorKind::Other, msg))?;
267 let canonical = path.canonicalize().map_err(|e| folder_failure(display_path(&path), &e))?;
268 let display = display_path(&canonical);
269 match std::fs::metadata(&canonical) {
270 Ok(meta) if !meta.is_dir() => {
271 return Err(list_failure(display, FsErrorKind::NotADirectory, "This isn't a folder.".to_string()));
272 }
273 Ok(_) => {}
274 Err(e) => return Err(folder_failure(display, &e)),
275 }
276 let iter = std::fs::read_dir(&canonical).map_err(|e| folder_failure(display.clone(), &e))?;
277 Ok(ListCursor { iter: iter.peekable(), display, last_used: Instant::now() })
278}
279
280fn folder_failure(display: String, err: &io::Error) -> FsListResult {
282 let (kind, message) = classify_folder_error(err);
283 list_failure(display, kind, message)
284}
285
286pub fn classify_folder_error(err: &io::Error) -> (FsErrorKind, String) {
287 match err.kind() {
288 io::ErrorKind::NotFound => (FsErrorKind::NotFound, "This folder doesn't exist.".to_string()),
289 io::ErrorKind::PermissionDenied if platform::is_os_blocked(err) => (
290 FsErrorKind::OsBlocked,
291 "macOS blocked AgentMux from reading this folder. Open System Settings → Privacy & Security → \
292 Files & Folders, turn AgentMux on, then try again."
293 .to_string(),
294 ),
295 io::ErrorKind::PermissionDenied => (
296 FsErrorKind::PermissionDenied,
297 "You don't have permission to open this folder.".to_string(),
298 ),
299 io::ErrorKind::NotADirectory => (FsErrorKind::NotADirectory, "This isn't a folder.".to_string()),
300 _ => (FsErrorKind::Other, format!("Couldn't open this folder: {err}")),
301 }
302}
303
304fn build_entry(de: &std::fs::DirEntry) -> FsEntry {
307 let name = de.file_name().to_string_lossy().into_owned();
308 let mut entry = FsEntry {
309 hidden: name.starts_with('.'),
310 name,
311 is_dir: false,
312 is_symlink: false,
313 size: None,
314 mtime: None,
315 readonly: false,
316 link_target: None,
317 error: None,
318 };
319
320 let own = match de.metadata() {
324 Ok(m) => m,
325 Err(e) => {
326 if let Ok(ft) = de.file_type() {
327 entry.is_symlink = ft.is_symlink();
328 entry.is_dir = ft.is_dir();
329 }
330 entry.error = Some(entry_error_message(&e));
331 return entry;
332 }
333 };
334 entry.hidden |= platform::has_hidden_attribute(&own);
335 entry.is_symlink = own.file_type().is_symlink();
336
337 let effective = if entry.is_symlink {
338 let path = de.path();
339 entry.link_target = std::fs::read_link(&path).ok().map(|t| display_path(&t));
340 match std::fs::metadata(&path) {
341 Ok(m) => m,
342 Err(e) => {
343 entry.error = Some(match e.kind() {
344 io::ErrorKind::NotFound => "The link's target doesn't exist.".to_string(),
345 _ => format!("Couldn't follow the link: {e}"),
346 });
347 return entry;
348 }
349 }
350 } else {
351 own
352 };
353
354 entry.is_dir = effective.is_dir();
355 if !entry.is_dir {
356 entry.size = Some(effective.len());
357 }
358 entry.mtime = effective
359 .modified()
360 .ok()
361 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
362 .map(|d| d.as_millis() as u64);
363 entry.readonly = !(cfg!(windows) && entry.is_dir) && effective.permissions().readonly();
366 entry
367}
368
369fn entry_error_message(err: &io::Error) -> String {
370 match err.kind() {
371 io::ErrorKind::NotFound => "It was removed while the folder was being read.".to_string(),
372 io::ErrorKind::PermissionDenied => "Access denied.".to_string(),
373 _ => err.to_string(),
374 }
375}
376
377pub fn home_and_known_places() -> (String, Vec<FsPlace>) {
383 let home = dirs::home_dir().map(|h| display_path(&h)).unwrap_or_default();
384 let mut places = Vec::new();
385 if !home.is_empty() {
386 places.push(FsPlace { id: "home".to_string(), label: "Home".to_string(), path: home.clone(), kind: FsPlaceKind::Home });
387 }
388 let known: [(&str, &str, Option<PathBuf>); 4] = [
389 ("desktop", "Desktop", dirs::desktop_dir()),
390 ("documents", "Documents", dirs::document_dir()),
391 ("downloads", "Downloads", dirs::download_dir()),
392 ("pictures", "Pictures", dirs::picture_dir()),
393 ];
394 for (id, label, dir) in known {
395 if let Some(dir) = dir {
396 places.push(FsPlace { id: id.to_string(), label: label.to_string(), path: display_path(&dir), kind: FsPlaceKind::Known });
397 }
398 }
399 (home, places)
400}
401
402pub fn validate_new_name(name: &str) -> Result<(), String> {
406 validate_name_rules(name, cfg!(windows))
407}
408
409const WINDOWS_RESERVED: &[&str] = &[
413 "con", "prn", "aux", "nul", "conin$", "conout$", "com0", "com1", "com2", "com3", "com4", "com5", "com6", "com7",
414 "com8", "com9", "com¹", "com²", "com³", "lpt0", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8",
415 "lpt9", "lpt¹", "lpt²", "lpt³",
416];
417
418const MAX_NAME_LEN: usize = 255;
421
422pub fn validate_name_rules(name: &str, windows: bool) -> Result<(), String> {
426 if name.trim().is_empty() {
427 return Err("A name can't be empty.".to_string());
428 }
429 if name == "." || name == ".." {
430 return Err("“.” and “..” can't be used as names.".to_string());
431 }
432 if name.contains('/') || name.contains('\\') {
433 return Err("A name can't contain / or \\.".to_string());
434 }
435 if name.contains('\0') {
436 return Err("A name can't contain a NUL character.".to_string());
437 }
438 if name.len() > MAX_NAME_LEN || name.encode_utf16().count() > MAX_NAME_LEN {
439 return Err("That name is too long.".to_string());
440 }
441 if windows {
442 if let Some(c) = name.chars().find(|c| matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*')) {
443 return Err(format!("Windows doesn't allow {c} in a name."));
444 }
445 if name.chars().any(|c| (c as u32) < 0x20) {
446 return Err("A name can't contain control characters.".to_string());
447 }
448 if name.ends_with('.') || name.ends_with(' ') {
452 return Err("Windows doesn't allow a name to end with a dot or a space.".to_string());
453 }
454 let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ').to_lowercase();
455 if WINDOWS_RESERVED.contains(&stem.as_str()) {
456 return Err(format!("“{name}” is reserved by Windows. Pick another name."));
457 }
458 }
459 Ok(())
460}
461
462const ROOT_REFUSAL: &str = "AgentMux won't change the root of a drive.";
465
466#[derive(Debug, Clone, Default)]
474pub struct ProtectedPaths {
475 home: Option<PathBuf>,
476 data_root: Option<PathBuf>,
479 install_dirs: Vec<PathBuf>,
480 system_roots: Vec<PathBuf>,
481 exempt_roots: Vec<PathBuf>,
484}
485
486impl ProtectedPaths {
487 pub fn current() -> Self {
490 let canon = |p: PathBuf| -> PathBuf { path_key(&p.canonicalize().unwrap_or(p)) };
491 let home = dirs::home_dir().map(canon);
492 let data_root = Some(canon(crate::backend::base::get_mux_data_dir()));
493
494 let covers_home = |dir: &Path| home.as_ref().is_some_and(|h| h.starts_with(dir));
497 let mut install_dirs = Vec::new();
498 if let Ok(exe) = std::env::current_exe() {
499 let exe = exe.canonicalize().unwrap_or(exe);
500 if let Some(dir) = install_dir_of(&exe).map(path_key) {
501 install_dirs.push(if covers_home(&dir) { path_key(&exe) } else { dir });
502 }
503 }
504 if let Some(app) = crate::backend::base::get_mux_app_path().map(canon) {
505 if !covers_home(&app) {
506 install_dirs.push(app);
507 }
508 }
509
510 let system_roots = system_roots().into_iter().map(canon).collect();
511 let exempt_roots = vec![canon(std::env::temp_dir())];
512 Self { home, data_root, install_dirs, system_roots, exempt_roots }
513 }
514
515 pub fn check(&self, target: &Path) -> Result<(), String> {
518 if target.parent().is_none() {
519 return Err(ROOT_REFUSAL.to_string());
520 }
521 if let Some(share) = crate::backend::remote::wsl_fs::share_of(target) {
522 return self.check_in_distro(&share);
523 }
524 let key = path_key(target);
525 let contains = |protected: &Path| protected.starts_with(&key);
526
527 if let Some(home) = &self.home {
528 if *home == key {
529 return Err("AgentMux won't rename, move or delete your home folder.".to_string());
530 }
531 if contains(home) {
532 return Err("This folder contains your home folder, so AgentMux won't change it.".to_string());
533 }
534 }
535
536 if let Some(data) = &self.data_root {
537 if contains(data) {
538 return Err("This is, or contains, AgentMux's own data folder; AgentMux won't change it.".to_string());
539 }
540 if let Ok(rel) = key.strip_prefix(data) {
541 let parts: Vec<Component<'_>> = rel.components().collect();
542 let in_workspace = parts.len() >= 3 && parts[0].as_os_str() == "agents";
543 if !in_workspace {
544 return Err(
545 "This is part of AgentMux's own data. Only files inside an agent's workspace can be changed here."
546 .to_string(),
547 );
548 }
549 }
550 }
551
552 for dir in &self.install_dirs {
553 if key.starts_with(dir) || contains(dir) {
554 return Err("This is part of the AgentMux installation; AgentMux won't change it.".to_string());
555 }
556 }
557
558 if cfg!(target_os = "macos")
562 && key
563 .ancestors()
564 .skip(1)
565 .any(|a| a.extension().is_some_and(|e| e.eq_ignore_ascii_case("app")))
566 {
567 return Err("AgentMux won't change the inside of an app bundle.".to_string());
568 }
569
570 let inside_home = self.home.as_ref().is_some_and(|h| key.starts_with(h));
571 let exempt = self.exempt_roots.iter().any(|r| key.starts_with(r));
572 if !inside_home && !exempt {
573 for root in &self.system_roots {
574 if key.starts_with(root) || contains(root) {
575 return Err("This is a protected system folder; AgentMux won't change it.".to_string());
576 }
577 }
578 }
579 Ok(())
580 }
581
582 fn check_in_distro(&self, share: &crate::backend::remote::wsl_fs::SharePath) -> Result<(), String> {
587 use crate::backend::remote::wsl_fs;
588 if share.linux == "/" {
589 return Err(ROOT_REFUSAL.to_string());
590 }
591 if let Some(windows) = wsl_fs::drive_path(&share.linux) {
592 return self.check(Path::new(&windows));
593 }
594 if wsl_fs::is_system_path(&share.linux) {
595 return Err(format!(
596 "This is a system folder of the {} WSL distribution; AgentMux won't change it.",
597 share.distro
598 ));
599 }
600 if share.linux == "/home" || wsl_fs::is_home(&share.linux) {
601 return Err("AgentMux won't rename, move or delete a home folder.".to_string());
602 }
603 Ok(())
604 }
605
606 #[cfg(test)]
607 fn for_test(home: &Path, data_root: &Path, install: &[&Path], system: &[&Path], exempt: &[&Path]) -> Self {
608 Self {
609 home: Some(path_key(home)),
610 data_root: Some(path_key(data_root)),
611 install_dirs: install.iter().map(|p| path_key(p)).collect(),
612 system_roots: system.iter().map(|p| path_key(p)).collect(),
613 exempt_roots: exempt.iter().map(|p| path_key(p)).collect(),
614 }
615 }
616}
617
618fn install_dir_of(exe: &Path) -> Option<&Path> {
624 exe.ancestors()
625 .skip(1)
626 .filter(|a| a.extension().is_some_and(|e| e.eq_ignore_ascii_case("app")))
627 .last()
628 .or_else(|| exe.parent())
629}
630
631fn system_roots() -> Vec<PathBuf> {
633 #[cfg(windows)]
634 {
635 let mut roots = Vec::new();
636 for (var, fallback) in [
637 ("SystemRoot", r"C:\Windows"),
638 ("ProgramFiles", r"C:\Program Files"),
639 ("ProgramFiles(x86)", r"C:\Program Files (x86)"),
640 ("ProgramW6432", r"C:\Program Files"),
641 ("ProgramData", r"C:\ProgramData"),
642 ] {
643 let dir = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from).unwrap_or_else(|| PathBuf::from(fallback));
644 if !roots.contains(&dir) {
645 roots.push(dir);
646 }
647 }
648 roots
649 }
650 #[cfg(not(windows))]
651 {
652 let mut roots: Vec<PathBuf> = ["/usr", "/bin", "/sbin", "/etc", "/var", "/boot", "/lib", "/lib32", "/lib64", "/proc", "/sys", "/dev"]
653 .iter()
654 .map(PathBuf::from)
655 .collect();
656 if cfg!(target_os = "macos") {
657 roots.extend(["/System", "/Library", "/private/etc", "/private/var"].iter().map(PathBuf::from));
660 }
661 roots
662 }
663}
664
665pub fn exists_message(name: &str) -> String {
672 format!("Something named “{name}” already exists here.")
673}
674
675pub const IN_USE: &str = "Another program is using this file. Close it there and try again.";
677
678fn in_use(err: &io::Error) -> bool {
680 cfg!(windows) && matches!(err.raw_os_error(), Some(32 | 33))
681}
682
683fn rename_patiently(from: &Path, to: &Path) -> io::Result<()> {
686 match platform::rename_no_replace(from, to) {
687 Err(e) if in_use(&e) => {
688 std::thread::sleep(Duration::from_millis(200));
689 platform::rename_no_replace(from, to)
690 }
691 done => done,
692 }
693}
694
695pub fn entry_display_path(raw: &str) -> Option<String> {
697 resolve_entry_path(raw).ok().map(|p| display_path(&p))
698}
699
700fn missing_or(err: io::Error, what: &str) -> String {
701 if in_use(&err) {
702 return IN_USE.to_string();
703 }
704 match err.kind() {
705 io::ErrorKind::NotFound => "It doesn't exist anymore.".to_string(),
706 io::ErrorKind::PermissionDenied => format!("You don't have permission to {what} it."),
707 _ => format!("Couldn't {what} it: {err}"),
708 }
709}
710
711pub fn rename(req: &FsRenameReq) -> Result<FsRenameResult, String> {
717 let protect = ProtectedPaths::current();
718 let src = resolve_entry_path(&req.path)?;
719 validate_new_name(&req.new_name)?;
720 std::fs::symlink_metadata(&src).map_err(|e| missing_or(e, "rename"))?;
721 protect.check(&src)?;
722 let parent = src.parent().ok_or_else(|| ROOT_REFUSAL.to_string())?.to_path_buf();
723 let dest = parent.join(&req.new_name);
724 protect.check(&dest)?;
725
726 let old_name = file_name_string(&src);
727 if old_name == req.new_name {
728 return Ok(FsRenameResult { new_path: display_path(&dest) });
729 }
730
731 let result = if old_name.to_lowercase() == req.new_name.to_lowercase() {
732 rename_case_only(&src, &dest, &parent, &req.new_name)
733 } else {
734 rename_patiently(&src, &dest).map_err(|e| match e.kind() {
735 io::ErrorKind::AlreadyExists => exists_message(&req.new_name),
736 _ => missing_or(e, "rename"),
737 })
738 };
739 tracing::info!(
740 op = "fs.rename",
741 from = %display_path(&src),
742 to = %display_path(&dest),
743 outcome = if result.is_ok() { "ok" } else { "error" },
744 error = result.as_ref().err().map(String::as_str).unwrap_or(""),
745 "fs mutation"
746 );
747 result.map(|()| FsRenameResult { new_path: display_path(&dest) })
748}
749
750fn rename_case_only(src: &Path, dest: &Path, parent: &Path, new_name: &str) -> Result<(), String> {
751 let taken = std::fs::read_dir(parent)
754 .map_err(|e| missing_or(e, "rename"))?
755 .flatten()
756 .any(|e| e.file_name() == std::ffi::OsStr::new(new_name));
757 if taken {
758 return Err(exists_message(new_name));
759 }
760 let tmp = parent.join(format!(".agentmux-rename-{}", uuid::Uuid::new_v4().simple()));
761 rename_patiently(src, &tmp).map_err(|e| missing_or(e, "rename"))?;
762 if let Err(e) = platform::rename_no_replace(&tmp, dest) {
763 let _ = platform::rename_no_replace(&tmp, src);
766 return Err(match e.kind() {
767 io::ErrorKind::AlreadyExists => exists_message(new_name),
768 _ => missing_or(e, "rename"),
769 });
770 }
771 Ok(())
772}
773
774pub fn create(req: &FsCreateReq) -> Result<FsCreateResult, String> {
778 let protect = ProtectedPaths::current();
779 validate_new_name(&req.name)?;
780 let parent = resolve_request_path(&req.parent)?.canonicalize().map_err(|e| match e.kind() {
781 io::ErrorKind::NotFound => "That folder doesn't exist anymore.".to_string(),
782 _ => format!("Couldn't open that folder: {e}"),
783 })?;
784 if !parent.is_dir() {
785 return Err("That isn't a folder.".to_string());
786 }
787 let target = parent.join(&req.name);
788 protect.check(&target)?;
789
790 let result = match req.kind {
791 FsCreateKind::File => std::fs::OpenOptions::new().write(true).create_new(true).open(&target).map(|_| ()),
792 FsCreateKind::Dir => std::fs::create_dir(&target),
793 }
794 .map_err(|e| match e.kind() {
795 io::ErrorKind::AlreadyExists => exists_message(&req.name),
796 io::ErrorKind::PermissionDenied => "You don't have permission to create something here.".to_string(),
797 _ => format!("Couldn't create it: {e}"),
798 });
799 tracing::info!(
800 op = "fs.create",
801 kind = ?req.kind,
802 path = %display_path(&target),
803 outcome = if result.is_ok() { "ok" } else { "error" },
804 error = result.as_ref().err().map(String::as_str).unwrap_or(""),
805 "fs mutation"
806 );
807 result.map(|()| FsCreateResult { path: display_path(&target) })
808}
809
810pub fn delete_permanently(raw: &str) -> Result<(), String> {
812 let protect = ProtectedPaths::current();
813 let target = resolve_entry_path(raw)?;
814 std::fs::symlink_metadata(&target).map_err(|e| missing_or(e, "delete"))?;
815 protect.check(&target)?;
816 let result = platform::remove_entry_no_follow(&target).map_err(|e| missing_or(e, "delete"));
817 tracing::info!(
818 op = "fs.delete",
819 path = %display_path(&target),
820 outcome = if result.is_ok() { "ok" } else { "error" },
821 error = result.as_ref().err().map(String::as_str).unwrap_or(""),
822 "fs mutation"
823 );
824 result
825}
826
827pub fn trash(raw: &str) -> Result<(), String> {
830 let protect = ProtectedPaths::current();
831 let target = resolve_entry_path(raw)?;
832 std::fs::symlink_metadata(&target).map_err(|e| missing_or(e, "move"))?;
833 protect.check(&target)?;
834 let result = match platform::trash_unavailable_reason(&target) {
835 Some(reason) => Err(reason.to_string()),
836 None => trash_worker::trash_path(&target),
837 };
838 tracing::info!(
839 op = "fs.trash",
840 path = %display_path(&target),
841 outcome = if result.is_ok() { "ok" } else { "error" },
842 error = result.as_ref().err().map(String::as_str).unwrap_or(""),
843 "fs mutation"
844 );
845 result
846}
847
848pub fn restore(raws: &[String]) -> Vec<Result<(), String>> {
852 let protect = ProtectedPaths::current();
853 let checked: Vec<Result<PathBuf, String>> = raws
856 .iter()
857 .map(|raw| {
858 let target = resolve_entry_path(raw)?;
859 protect.check(&target)?;
860 Ok(target)
861 })
862 .collect();
863 let valid: Vec<PathBuf> = checked.iter().filter_map(|c| c.as_ref().ok().cloned()).collect();
864 let mut restored = trash_worker::restore_paths(&valid).into_iter();
865 checked
866 .into_iter()
867 .map(|c| {
868 let target = c?;
869 let result = restored.next().unwrap_or_else(|| Err("Couldn't put it back.".to_string()));
870 tracing::info!(
871 op = "fs.restore",
872 path = %display_path(&target),
873 outcome = if result.is_ok() { "ok" } else { "error" },
874 error = result.as_ref().err().map(String::as_str).unwrap_or(""),
875 "fs mutation"
876 );
877 result
878 })
879 .collect()
880}
881
882pub fn open_or_reveal(raw: &str, reveal: bool) -> Result<(), String> {
885 let path = resolve_request_path(raw)?;
886 let target = if path.parent().is_none() { path } else { resolve_entry_path(raw)? };
888 std::fs::symlink_metadata(&target).map_err(|e| missing_or(e, "open"))?;
889 let started = if reveal { platform::reveal(&target) } else { platform::spawn_detached(platform::open_command(&target)) };
892 let result = started.map_err(|e| format!("Couldn't open it: {e}"));
893 tracing::info!(
894 op = if reveal { "fs.reveal" } else { "fs.open" },
895 path = %display_path(&target),
896 outcome = if result.is_ok() { "ok" } else { "error" },
897 "fs action"
898 );
899 result
900}
901
902#[cfg(test)]
903mod tests;