1#[cfg(target_os = "macos")]
2mod mac_watcher;
3
4#[cfg(not(target_os = "macos"))]
5pub mod fs_watcher;
6
7use parking_lot::Mutex;
8use std::sync::atomic::{AtomicUsize, Ordering};
9use std::time::Instant;
10
11use anyhow::{Context as _, Result, anyhow};
12#[cfg(any(target_os = "linux", target_os = "freebsd"))]
13use ashpd::desktop::trash;
14use futures::stream::iter;
15use gpui::App;
16use gpui::BackgroundExecutor;
17use gpui::Global;
18use gpui::ReadGlobal as _;
19use gpui::SharedString;
20use std::borrow::Cow;
21use util::command::new_smol_command;
22
23#[cfg(unix)]
24use std::os::fd::{AsFd, AsRawFd};
25
26#[cfg(unix)]
27use std::os::unix::fs::{FileTypeExt, MetadataExt};
28
29#[cfg(any(target_os = "macos", target_os = "freebsd"))]
30use std::mem::MaybeUninit;
31
32use async_tar::Archive;
33use futures::{AsyncRead, Stream, StreamExt, future::BoxFuture};
34use git::repository::{GitRepository, RealGitRepository};
35use is_executable::IsExecutable;
36use rope::Rope;
37use serde::{Deserialize, Serialize};
38use smol::io::AsyncWriteExt;
39use std::{
40 io::{self, Write},
41 path::{Component, Path, PathBuf},
42 pin::Pin,
43 sync::Arc,
44 time::{Duration, SystemTime, UNIX_EPOCH},
45};
46use tempfile::TempDir;
47use text::LineEnding;
48
49#[cfg(feature = "test-support")]
50mod fake_git_repo;
51#[cfg(feature = "test-support")]
52use collections::{BTreeMap, btree_map};
53#[cfg(feature = "test-support")]
54use fake_git_repo::FakeGitRepositoryState;
55#[cfg(feature = "test-support")]
56use git::{
57 repository::{InitialGraphCommitData, RepoPath, repo_path},
58 status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus},
59};
60
61#[cfg(feature = "test-support")]
62use smol::io::AsyncReadExt;
63#[cfg(feature = "test-support")]
64use std::ffi::OsStr;
65
66pub trait Watcher: Send + Sync {
67 fn add(&self, path: &Path) -> Result<()>;
68 fn remove(&self, path: &Path) -> Result<()>;
69}
70
71#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
72pub enum PathEventKind {
73 Removed,
74 Created,
75 Changed,
76}
77
78#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
79pub struct PathEvent {
80 pub path: PathBuf,
81 pub kind: Option<PathEventKind>,
82}
83
84impl From<PathEvent> for PathBuf {
85 fn from(event: PathEvent) -> Self {
86 event.path
87 }
88}
89
90#[async_trait::async_trait]
91pub trait Fs: Send + Sync {
92 async fn create_dir(&self, path: &Path) -> Result<()>;
93 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()>;
94 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()>;
95 async fn create_file_with(
96 &self,
97 path: &Path,
98 content: Pin<&mut (dyn AsyncRead + Send)>,
99 ) -> Result<()>;
100 async fn extract_tar_file(
101 &self,
102 path: &Path,
103 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
104 ) -> Result<()>;
105 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()>;
106 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()>;
107 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()>;
108 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
109 self.remove_dir(path, options).await
110 }
111 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()>;
112 async fn trash_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
113 self.remove_file(path, options).await
114 }
115 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>>;
116 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>>;
117 async fn load(&self, path: &Path) -> Result<String> {
118 Ok(String::from_utf8(self.load_bytes(path).await?)?)
119 }
120 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>>;
121 async fn atomic_write(&self, path: PathBuf, text: String) -> Result<()>;
122 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()>;
123 async fn write(&self, path: &Path, content: &[u8]) -> Result<()>;
124 async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
125 async fn is_file(&self, path: &Path) -> bool;
126 async fn is_dir(&self, path: &Path) -> bool;
127 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
128 async fn read_link(&self, path: &Path) -> Result<PathBuf>;
129 async fn read_dir(
130 &self,
131 path: &Path,
132 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>>;
133
134 async fn watch(
135 &self,
136 path: &Path,
137 latency: Duration,
138 ) -> (
139 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
140 Arc<dyn Watcher>,
141 );
142
143 fn open_repo(
144 &self,
145 abs_dot_git: &Path,
146 system_git_binary_path: Option<&Path>,
147 ) -> Option<Arc<dyn GitRepository>>;
148 async fn git_init(&self, abs_work_directory: &Path, fallback_branch_name: String)
149 -> Result<()>;
150 async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()>;
151 fn is_fake(&self) -> bool;
152 async fn is_case_sensitive(&self) -> Result<bool>;
153 fn subscribe_to_jobs(&self) -> JobEventReceiver;
154
155 #[cfg(feature = "test-support")]
156 fn as_fake(&self) -> Arc<FakeFs> {
157 panic!("called as_fake on a real fs");
158 }
159}
160
161struct GlobalFs(Arc<dyn Fs>);
162
163impl Global for GlobalFs {}
164
165impl dyn Fs {
166 /// Returns the global [`Fs`].
167 pub fn global(cx: &App) -> Arc<Self> {
168 GlobalFs::global(cx).0.clone()
169 }
170
171 /// Sets the global [`Fs`].
172 pub fn set_global(fs: Arc<Self>, cx: &mut App) {
173 cx.set_global(GlobalFs(fs));
174 }
175}
176
177#[derive(Copy, Clone, Default)]
178pub struct CreateOptions {
179 pub overwrite: bool,
180 pub ignore_if_exists: bool,
181}
182
183#[derive(Copy, Clone, Default)]
184pub struct CopyOptions {
185 pub overwrite: bool,
186 pub ignore_if_exists: bool,
187}
188
189#[derive(Copy, Clone, Default)]
190pub struct RenameOptions {
191 pub overwrite: bool,
192 pub ignore_if_exists: bool,
193 /// Whether to create parent directories if they do not exist.
194 pub create_parents: bool,
195}
196
197#[derive(Copy, Clone, Default)]
198pub struct RemoveOptions {
199 pub recursive: bool,
200 pub ignore_if_not_exists: bool,
201}
202
203#[derive(Copy, Clone, Debug)]
204pub struct Metadata {
205 pub inode: u64,
206 pub mtime: MTime,
207 pub is_symlink: bool,
208 pub is_dir: bool,
209 pub len: u64,
210 pub is_fifo: bool,
211 pub is_executable: bool,
212}
213
214/// Filesystem modification time. The purpose of this newtype is to discourage use of operations
215/// that do not make sense for mtimes. In particular, it is not always valid to compare mtimes using
216/// `<` or `>`, as there are many things that can cause the mtime of a file to be earlier than it
217/// was. See ["mtime comparison considered harmful" - apenwarr](https://apenwarr.ca/log/20181113).
218///
219/// Do not derive Ord, PartialOrd, or arithmetic operation traits.
220#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
221#[serde(transparent)]
222pub struct MTime(SystemTime);
223
224pub type JobId = usize;
225
226#[derive(Clone, Debug)]
227pub struct JobInfo {
228 pub start: Instant,
229 pub message: SharedString,
230 pub id: JobId,
231}
232
233#[derive(Debug, Clone)]
234pub enum JobEvent {
235 Started { info: JobInfo },
236 Completed { id: JobId },
237}
238
239pub type JobEventSender = futures::channel::mpsc::UnboundedSender<JobEvent>;
240pub type JobEventReceiver = futures::channel::mpsc::UnboundedReceiver<JobEvent>;
241
242struct JobTracker {
243 id: JobId,
244 subscribers: Arc<Mutex<Vec<JobEventSender>>>,
245}
246
247impl JobTracker {
248 fn new(info: JobInfo, subscribers: Arc<Mutex<Vec<JobEventSender>>>) -> Self {
249 let id = info.id;
250 {
251 let mut subs = subscribers.lock();
252 subs.retain(|sender| {
253 sender
254 .unbounded_send(JobEvent::Started { info: info.clone() })
255 .is_ok()
256 });
257 }
258 Self { id, subscribers }
259 }
260}
261
262impl Drop for JobTracker {
263 fn drop(&mut self) {
264 let mut subs = self.subscribers.lock();
265 subs.retain(|sender| {
266 sender
267 .unbounded_send(JobEvent::Completed { id: self.id })
268 .is_ok()
269 });
270 }
271}
272
273impl MTime {
274 /// Conversion intended for persistence and testing.
275 pub fn from_seconds_and_nanos(secs: u64, nanos: u32) -> Self {
276 MTime(UNIX_EPOCH + Duration::new(secs, nanos))
277 }
278
279 /// Conversion intended for persistence.
280 pub fn to_seconds_and_nanos_for_persistence(self) -> Option<(u64, u32)> {
281 self.0
282 .duration_since(UNIX_EPOCH)
283 .ok()
284 .map(|duration| (duration.as_secs(), duration.subsec_nanos()))
285 }
286
287 /// Returns the value wrapped by this `MTime`, for presentation to the user. The name including
288 /// "_for_user" is to discourage misuse - this method should not be used when making decisions
289 /// about file dirtiness.
290 pub fn timestamp_for_user(self) -> SystemTime {
291 self.0
292 }
293
294 /// Temporary method to split out the behavior changes from introduction of this newtype.
295 pub fn bad_is_greater_than(self, other: MTime) -> bool {
296 self.0 > other.0
297 }
298}
299
300impl From<proto::Timestamp> for MTime {
301 fn from(timestamp: proto::Timestamp) -> Self {
302 MTime(timestamp.into())
303 }
304}
305
306impl From<MTime> for proto::Timestamp {
307 fn from(mtime: MTime) -> Self {
308 mtime.0.into()
309 }
310}
311
312pub struct RealFs {
313 bundled_git_binary_path: Option<PathBuf>,
314 executor: BackgroundExecutor,
315 next_job_id: Arc<AtomicUsize>,
316 job_event_subscribers: Arc<Mutex<Vec<JobEventSender>>>,
317}
318
319pub trait FileHandle: Send + Sync + std::fmt::Debug {
320 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf>;
321}
322
323impl FileHandle for std::fs::File {
324 #[cfg(target_os = "macos")]
325 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
326 use std::{
327 ffi::{CStr, OsStr},
328 os::unix::ffi::OsStrExt,
329 };
330
331 let fd = self.as_fd();
332 let mut path_buf = MaybeUninit::<[u8; libc::PATH_MAX as usize]>::uninit();
333
334 let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETPATH, path_buf.as_mut_ptr()) };
335 anyhow::ensure!(result != -1, "fcntl returned -1");
336
337 // SAFETY: `fcntl` will initialize the path buffer.
338 let c_str = unsafe { CStr::from_ptr(path_buf.as_ptr().cast()) };
339 anyhow::ensure!(!c_str.is_empty(), "Could find a path for the file handle");
340 let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
341 Ok(path)
342 }
343
344 #[cfg(target_os = "linux")]
345 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
346 let fd = self.as_fd();
347 let fd_path = format!("/proc/self/fd/{}", fd.as_raw_fd());
348 let new_path = std::fs::read_link(fd_path)?;
349 if new_path
350 .file_name()
351 .is_some_and(|f| f.to_string_lossy().ends_with(" (deleted)"))
352 {
353 anyhow::bail!("file was deleted")
354 };
355
356 Ok(new_path)
357 }
358
359 #[cfg(target_os = "freebsd")]
360 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
361 use std::{
362 ffi::{CStr, OsStr},
363 os::unix::ffi::OsStrExt,
364 };
365
366 let fd = self.as_fd();
367 let mut kif = MaybeUninit::<libc::kinfo_file>::uninit();
368 kif.kf_structsize = libc::KINFO_FILE_SIZE;
369
370 let result = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_KINFO, kif.as_mut_ptr()) };
371 anyhow::ensure!(result != -1, "fcntl returned -1");
372
373 // SAFETY: `fcntl` will initialize the kif.
374 let c_str = unsafe { CStr::from_ptr(kif.assume_init().kf_path.as_ptr()) };
375 anyhow::ensure!(!c_str.is_empty(), "Could find a path for the file handle");
376 let path = PathBuf::from(OsStr::from_bytes(c_str.to_bytes()));
377 Ok(path)
378 }
379
380 #[cfg(target_os = "windows")]
381 fn current_path(&self, _: &Arc<dyn Fs>) -> Result<PathBuf> {
382 use std::ffi::OsString;
383 use std::os::windows::ffi::OsStringExt;
384 use std::os::windows::io::AsRawHandle;
385
386 use windows::Win32::Foundation::HANDLE;
387 use windows::Win32::Storage::FileSystem::{
388 FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW,
389 };
390
391 let handle = HANDLE(self.as_raw_handle() as _);
392
393 // Query required buffer size (in wide chars)
394 let required_len =
395 unsafe { GetFinalPathNameByHandleW(handle, &mut [], FILE_NAME_NORMALIZED) };
396 anyhow::ensure!(
397 required_len != 0,
398 "GetFinalPathNameByHandleW returned 0 length"
399 );
400
401 // Allocate buffer and retrieve the path
402 let mut buf: Vec<u16> = vec![0u16; required_len as usize + 1];
403 let written = unsafe { GetFinalPathNameByHandleW(handle, &mut buf, FILE_NAME_NORMALIZED) };
404 anyhow::ensure!(
405 written != 0,
406 "GetFinalPathNameByHandleW failed to write path"
407 );
408
409 let os_str: OsString = OsString::from_wide(&buf[..written as usize]);
410 anyhow::ensure!(!os_str.is_empty(), "Could find a path for the file handle");
411 Ok(PathBuf::from(os_str))
412 }
413}
414
415pub struct RealWatcher {}
416
417impl RealFs {
418 pub fn new(git_binary_path: Option<PathBuf>, executor: BackgroundExecutor) -> Self {
419 Self {
420 bundled_git_binary_path: git_binary_path,
421 executor,
422 next_job_id: Arc::new(AtomicUsize::new(0)),
423 job_event_subscribers: Arc::new(Mutex::new(Vec::new())),
424 }
425 }
426
427 #[cfg(target_os = "windows")]
428 fn canonicalize(path: &Path) -> Result<PathBuf> {
429 let mut strip_prefix = None;
430
431 let mut new_path = PathBuf::new();
432 for component in path.components() {
433 match component {
434 std::path::Component::Prefix(_) => {
435 let component = component.as_os_str();
436 let canonicalized = if component
437 .to_str()
438 .map(|e| e.ends_with("\\"))
439 .unwrap_or(false)
440 {
441 std::fs::canonicalize(component)
442 } else {
443 let mut component = component.to_os_string();
444 component.push("\\");
445 std::fs::canonicalize(component)
446 }?;
447
448 let mut strip = PathBuf::new();
449 for component in canonicalized.components() {
450 match component {
451 Component::Prefix(prefix_component) => {
452 match prefix_component.kind() {
453 std::path::Prefix::Verbatim(os_str) => {
454 strip.push(os_str);
455 }
456 std::path::Prefix::VerbatimUNC(host, share) => {
457 strip.push("\\\\");
458 strip.push(host);
459 strip.push(share);
460 }
461 std::path::Prefix::VerbatimDisk(disk) => {
462 strip.push(format!("{}:", disk as char));
463 }
464 _ => strip.push(component),
465 };
466 }
467 _ => strip.push(component),
468 }
469 }
470 strip_prefix = Some(strip);
471 new_path.push(component);
472 }
473 std::path::Component::RootDir => {
474 new_path.push(component);
475 }
476 std::path::Component::CurDir => {
477 if strip_prefix.is_none() {
478 // unrooted path
479 new_path.push(component);
480 }
481 }
482 std::path::Component::ParentDir => {
483 if strip_prefix.is_some() {
484 // rooted path
485 new_path.pop();
486 } else {
487 new_path.push(component);
488 }
489 }
490 std::path::Component::Normal(_) => {
491 if let Ok(link) = std::fs::read_link(new_path.join(component)) {
492 let link = match &strip_prefix {
493 Some(e) => link.strip_prefix(e).unwrap_or(&link),
494 None => &link,
495 };
496 new_path.extend(link);
497 } else {
498 new_path.push(component);
499 }
500 }
501 }
502 }
503
504 Ok(new_path)
505 }
506}
507
508#[async_trait::async_trait]
509impl Fs for RealFs {
510 async fn create_dir(&self, path: &Path) -> Result<()> {
511 Ok(smol::fs::create_dir_all(path).await?)
512 }
513
514 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
515 #[cfg(unix)]
516 smol::fs::unix::symlink(target, path).await?;
517
518 #[cfg(windows)]
519 if smol::fs::metadata(&target).await?.is_dir() {
520 let status = new_smol_command("cmd")
521 .args(["/C", "mklink", "/J"])
522 .args([path, target.as_path()])
523 .status()
524 .await?;
525
526 if !status.success() {
527 return Err(anyhow::anyhow!(
528 "Failed to create junction from {:?} to {:?}",
529 path,
530 target
531 ));
532 }
533 } else {
534 smol::fs::windows::symlink_file(target, path).await?
535 }
536
537 Ok(())
538 }
539
540 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
541 let mut open_options = smol::fs::OpenOptions::new();
542 open_options.write(true).create(true);
543 if options.overwrite {
544 open_options.truncate(true);
545 } else if !options.ignore_if_exists {
546 open_options.create_new(true);
547 }
548 open_options
549 .open(path)
550 .await
551 .with_context(|| format!("Failed to create file at {:?}", path))?;
552 Ok(())
553 }
554
555 async fn create_file_with(
556 &self,
557 path: &Path,
558 content: Pin<&mut (dyn AsyncRead + Send)>,
559 ) -> Result<()> {
560 let mut file = smol::fs::File::create(&path)
561 .await
562 .with_context(|| format!("Failed to create file at {:?}", path))?;
563 futures::io::copy(content, &mut file).await?;
564 Ok(())
565 }
566
567 async fn extract_tar_file(
568 &self,
569 path: &Path,
570 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
571 ) -> Result<()> {
572 content.unpack(path).await?;
573 Ok(())
574 }
575
576 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
577 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
578 if options.ignore_if_exists {
579 return Ok(());
580 } else {
581 anyhow::bail!("{target:?} already exists");
582 }
583 }
584
585 smol::fs::copy(source, target).await?;
586 Ok(())
587 }
588
589 async fn rename(&self, source: &Path, target: &Path, options: RenameOptions) -> Result<()> {
590 if !options.overwrite && smol::fs::metadata(target).await.is_ok() {
591 if options.ignore_if_exists {
592 return Ok(());
593 } else {
594 anyhow::bail!("{target:?} already exists");
595 }
596 }
597
598 if options.create_parents {
599 if let Some(parent) = target.parent() {
600 self.create_dir(parent).await?;
601 }
602 }
603
604 smol::fs::rename(source, target).await?;
605 Ok(())
606 }
607
608 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
609 let result = if options.recursive {
610 smol::fs::remove_dir_all(path).await
611 } else {
612 smol::fs::remove_dir(path).await
613 };
614 match result {
615 Ok(()) => Ok(()),
616 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
617 Ok(())
618 }
619 Err(err) => Err(err)?,
620 }
621 }
622
623 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
624 #[cfg(windows)]
625 if let Ok(Some(metadata)) = self.metadata(path).await
626 && metadata.is_symlink
627 && metadata.is_dir
628 {
629 self.remove_dir(
630 path,
631 RemoveOptions {
632 recursive: false,
633 ignore_if_not_exists: true,
634 },
635 )
636 .await?;
637 return Ok(());
638 }
639
640 match smol::fs::remove_file(path).await {
641 Ok(()) => Ok(()),
642 Err(err) if err.kind() == io::ErrorKind::NotFound && options.ignore_if_not_exists => {
643 Ok(())
644 }
645 Err(err) => Err(err)?,
646 }
647 }
648
649 #[cfg(target_os = "macos")]
650 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
651 use cocoa::{
652 base::{id, nil},
653 foundation::{NSAutoreleasePool, NSString},
654 };
655 use objc::{class, msg_send, sel, sel_impl};
656
657 unsafe {
658 /// Allow NSString::alloc use here because it sets autorelease
659 #[allow(clippy::disallowed_methods)]
660 unsafe fn ns_string(string: &str) -> id {
661 unsafe { NSString::alloc(nil).init_str(string).autorelease() }
662 }
663
664 let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
665 let array: id = msg_send![class!(NSArray), arrayWithObject: url];
666 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
667
668 let _: id = msg_send![workspace, recycleURLs: array completionHandler: nil];
669 }
670 Ok(())
671 }
672
673 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
674 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
675 if let Ok(Some(metadata)) = self.metadata(path).await
676 && metadata.is_symlink
677 {
678 // TODO: trash_file does not support trashing symlinks yet - https://github.com/bilelmoussaoui/ashpd/issues/255
679 return self.remove_file(path, RemoveOptions::default()).await;
680 }
681 let file = smol::fs::File::open(path).await?;
682 match trash::trash_file(&file.as_fd()).await {
683 Ok(_) => Ok(()),
684 Err(err) => {
685 log::error!("Failed to trash file: {}", err);
686 // Trashing files can fail if you don't have a trashing dbus service configured.
687 // In that case, delete the file directly instead.
688 return self.remove_file(path, RemoveOptions::default()).await;
689 }
690 }
691 }
692
693 #[cfg(target_os = "windows")]
694 async fn trash_file(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
695 use util::paths::SanitizedPath;
696 use windows::{
697 Storage::{StorageDeleteOption, StorageFile},
698 core::HSTRING,
699 };
700 // todo(windows)
701 // When new version of `windows-rs` release, make this operation `async`
702 let path = path.canonicalize()?;
703 let path = SanitizedPath::new(&path);
704 let path_string = path.to_string();
705 let file = StorageFile::GetFileFromPathAsync(&HSTRING::from(path_string))?.get()?;
706 file.DeleteAsync(StorageDeleteOption::Default)?.get()?;
707 Ok(())
708 }
709
710 #[cfg(target_os = "macos")]
711 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
712 self.trash_file(path, options).await
713 }
714
715 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
716 async fn trash_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
717 self.trash_file(path, options).await
718 }
719
720 #[cfg(target_os = "windows")]
721 async fn trash_dir(&self, path: &Path, _options: RemoveOptions) -> Result<()> {
722 use util::paths::SanitizedPath;
723 use windows::{
724 Storage::{StorageDeleteOption, StorageFolder},
725 core::HSTRING,
726 };
727
728 // todo(windows)
729 // When new version of `windows-rs` release, make this operation `async`
730 let path = path.canonicalize()?;
731 let path = SanitizedPath::new(&path);
732 let path_string = path.to_string();
733 let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(path_string))?.get()?;
734 folder.DeleteAsync(StorageDeleteOption::Default)?.get()?;
735 Ok(())
736 }
737
738 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
739 Ok(Box::new(std::fs::File::open(path)?))
740 }
741
742 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
743 let mut options = std::fs::OpenOptions::new();
744 options.read(true);
745 #[cfg(windows)]
746 {
747 use std::os::windows::fs::OpenOptionsExt;
748 options.custom_flags(windows::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS.0);
749 }
750 Ok(Arc::new(options.open(path)?))
751 }
752
753 async fn load(&self, path: &Path) -> Result<String> {
754 let path = path.to_path_buf();
755 self.executor
756 .spawn(async move {
757 std::fs::read_to_string(&path)
758 .with_context(|| format!("Failed to read file {}", path.display()))
759 })
760 .await
761 }
762
763 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
764 let path = path.to_path_buf();
765 let bytes = self
766 .executor
767 .spawn(async move { std::fs::read(path) })
768 .await?;
769 Ok(bytes)
770 }
771
772 #[cfg(not(target_os = "windows"))]
773 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
774 smol::unblock(move || {
775 // Use the directory of the destination as temp dir to avoid
776 // invalid cross-device link error, and XDG_CACHE_DIR for fallback.
777 // See https://github.com/zed-industries/zed/pull/8437 for more details.
778 let mut tmp_file =
779 tempfile::NamedTempFile::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
780 tmp_file.write_all(data.as_bytes())?;
781 tmp_file.persist(path)?;
782 anyhow::Ok(())
783 })
784 .await?;
785
786 Ok(())
787 }
788
789 #[cfg(target_os = "windows")]
790 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
791 smol::unblock(move || {
792 // If temp dir is set to a different drive than the destination,
793 // we receive error:
794 //
795 // failed to persist temporary file:
796 // The system cannot move the file to a different disk drive. (os error 17)
797 //
798 // This is because `ReplaceFileW` does not support cross volume moves.
799 // See the remark section: "The backup file, replaced file, and replacement file must all reside on the same volume."
800 // https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-replacefilew#remarks
801 //
802 // So we use the directory of the destination as a temp dir to avoid it.
803 // https://github.com/zed-industries/zed/issues/16571
804 let temp_dir = TempDir::new_in(path.parent().unwrap_or(paths::temp_dir()))?;
805 let temp_file = {
806 let temp_file_path = temp_dir.path().join("temp_file");
807 let mut file = std::fs::File::create_new(&temp_file_path)?;
808 file.write_all(data.as_bytes())?;
809 temp_file_path
810 };
811 atomic_replace(path.as_path(), temp_file.as_path())?;
812 anyhow::Ok(())
813 })
814 .await?;
815 Ok(())
816 }
817
818 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
819 let buffer_size = text.summary().len.min(10 * 1024);
820 if let Some(path) = path.parent() {
821 self.create_dir(path)
822 .await
823 .with_context(|| format!("Failed to create directory at {:?}", path))?;
824 }
825 let file = smol::fs::File::create(path)
826 .await
827 .with_context(|| format!("Failed to create file at {:?}", path))?;
828 let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
829 for chunk in text::chunks_with_line_ending(text, line_ending) {
830 writer.write_all(chunk.as_bytes()).await?;
831 }
832 writer.flush().await?;
833 Ok(())
834 }
835
836 async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
837 if let Some(path) = path.parent() {
838 self.create_dir(path)
839 .await
840 .with_context(|| format!("Failed to create directory at {:?}", path))?;
841 }
842 let path = path.to_owned();
843 let contents = content.to_owned();
844 self.executor
845 .spawn(async move {
846 std::fs::write(path, contents)?;
847 Ok(())
848 })
849 .await
850 }
851
852 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
853 let path = path.to_owned();
854 self.executor
855 .spawn(async move {
856 #[cfg(target_os = "windows")]
857 let result = Self::canonicalize(&path);
858
859 #[cfg(not(target_os = "windows"))]
860 let result = std::fs::canonicalize(&path);
861
862 result.with_context(|| format!("canonicalizing {path:?}"))
863 })
864 .await
865 }
866
867 async fn is_file(&self, path: &Path) -> bool {
868 let path = path.to_owned();
869 self.executor
870 .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) })
871 .await
872 }
873
874 async fn is_dir(&self, path: &Path) -> bool {
875 let path = path.to_owned();
876 self.executor
877 .spawn(async move { std::fs::metadata(path).is_ok_and(|metadata| metadata.is_dir()) })
878 .await
879 }
880
881 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
882 let path_buf = path.to_owned();
883 let symlink_metadata = match self
884 .executor
885 .spawn(async move { std::fs::symlink_metadata(&path_buf) })
886 .await
887 {
888 Ok(metadata) => metadata,
889 Err(err) => {
890 return match err.kind() {
891 io::ErrorKind::NotFound | io::ErrorKind::NotADirectory => Ok(None),
892 _ => Err(anyhow::Error::new(err)),
893 };
894 }
895 };
896
897 let is_symlink = symlink_metadata.file_type().is_symlink();
898 let metadata = if is_symlink {
899 let path_buf = path.to_path_buf();
900 // Read target metadata, if the target exists
901 match self
902 .executor
903 .spawn(async move { std::fs::metadata(path_buf) })
904 .await
905 {
906 Ok(target_metadata) => target_metadata,
907 Err(err) => {
908 if err.kind() != io::ErrorKind::NotFound {
909 // TODO: Also FilesystemLoop when that's stable
910 log::warn!(
911 "Failed to read symlink target metadata for path {path:?}: {err}"
912 );
913 }
914 // For a broken or recursive symlink, return the symlink metadata. (Or
915 // as edge cases, a symlink into a directory we can't read, which is hard
916 // to distinguish from just being broken.)
917 symlink_metadata
918 }
919 }
920 } else {
921 symlink_metadata
922 };
923
924 #[cfg(unix)]
925 let inode = metadata.ino();
926
927 #[cfg(windows)]
928 let inode = file_id(path).await?;
929
930 #[cfg(windows)]
931 let is_fifo = false;
932
933 #[cfg(unix)]
934 let is_fifo = metadata.file_type().is_fifo();
935
936 let path_buf = path.to_path_buf();
937 let is_executable = self
938 .executor
939 .spawn(async move { path_buf.is_executable() })
940 .await;
941
942 Ok(Some(Metadata {
943 inode,
944 mtime: MTime(metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH)),
945 len: metadata.len(),
946 is_symlink,
947 is_dir: metadata.file_type().is_dir(),
948 is_fifo,
949 is_executable,
950 }))
951 }
952
953 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
954 let path = path.to_owned();
955 let path = self
956 .executor
957 .spawn(async move { std::fs::read_link(&path) })
958 .await?;
959 Ok(path)
960 }
961
962 async fn read_dir(
963 &self,
964 path: &Path,
965 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
966 let path = path.to_owned();
967 let result = iter(
968 self.executor
969 .spawn(async move { std::fs::read_dir(path) })
970 .await?,
971 )
972 .map(|entry| match entry {
973 Ok(entry) => Ok(entry.path()),
974 Err(error) => Err(anyhow!("failed to read dir entry {error:?}")),
975 });
976 Ok(Box::pin(result))
977 }
978
979 #[cfg(target_os = "macos")]
980 async fn watch(
981 &self,
982 path: &Path,
983 latency: Duration,
984 ) -> (
985 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
986 Arc<dyn Watcher>,
987 ) {
988 use fsevent::StreamFlags;
989
990 let (events_tx, events_rx) = smol::channel::unbounded();
991 let handles = Arc::new(parking_lot::Mutex::new(collections::BTreeMap::default()));
992 let watcher = Arc::new(mac_watcher::MacWatcher::new(
993 events_tx,
994 Arc::downgrade(&handles),
995 latency,
996 ));
997 watcher.add(path).expect("handles can't be dropped");
998
999 (
1000 Box::pin(
1001 events_rx
1002 .map(|events| {
1003 events
1004 .into_iter()
1005 .map(|event| {
1006 log::trace!("fs path event: {event:?}");
1007 let kind = if event.flags.contains(StreamFlags::ITEM_REMOVED) {
1008 Some(PathEventKind::Removed)
1009 } else if event.flags.contains(StreamFlags::ITEM_CREATED) {
1010 Some(PathEventKind::Created)
1011 } else if event.flags.contains(StreamFlags::ITEM_MODIFIED)
1012 | event.flags.contains(StreamFlags::ITEM_RENAMED)
1013 {
1014 Some(PathEventKind::Changed)
1015 } else {
1016 None
1017 };
1018 PathEvent {
1019 path: event.path,
1020 kind,
1021 }
1022 })
1023 .collect()
1024 })
1025 .chain(futures::stream::once(async move {
1026 drop(handles);
1027 vec![]
1028 })),
1029 ),
1030 watcher,
1031 )
1032 }
1033
1034 #[cfg(not(target_os = "macos"))]
1035 async fn watch(
1036 &self,
1037 path: &Path,
1038 latency: Duration,
1039 ) -> (
1040 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
1041 Arc<dyn Watcher>,
1042 ) {
1043 use util::{ResultExt as _, paths::SanitizedPath};
1044 let executor = self.executor.clone();
1045
1046 let (tx, rx) = smol::channel::unbounded();
1047 let pending_paths: Arc<Mutex<Vec<PathEvent>>> = Default::default();
1048 let watcher = Arc::new(fs_watcher::FsWatcher::new(tx, pending_paths.clone()));
1049
1050 // If the path doesn't exist yet (e.g. settings.json), watch the parent dir to learn when it's created.
1051 if let Err(e) = watcher.add(path)
1052 && let Some(parent) = path.parent()
1053 && let Err(parent_e) = watcher.add(parent)
1054 {
1055 log::warn!(
1056 "Failed to watch {} and its parent directory {}:\n{e}\n{parent_e}",
1057 path.display(),
1058 parent.display()
1059 );
1060 }
1061
1062 // Check if path is a symlink and follow the target parent
1063 if let Some(mut target) = self.read_link(path).await.ok() {
1064 log::trace!("watch symlink {path:?} -> {target:?}");
1065 // Check if symlink target is relative path, if so make it absolute
1066 if target.is_relative()
1067 && let Some(parent) = path.parent()
1068 {
1069 target = parent.join(target);
1070 if let Ok(canonical) = self.canonicalize(&target).await {
1071 target = SanitizedPath::new(&canonical).as_path().to_path_buf();
1072 }
1073 }
1074 watcher.add(&target).ok();
1075 if let Some(parent) = target.parent() {
1076 watcher.add(parent).log_err();
1077 }
1078 }
1079
1080 (
1081 Box::pin(rx.filter_map({
1082 let watcher = watcher.clone();
1083 let executor = executor.clone();
1084 move |_| {
1085 let _ = watcher.clone();
1086 let pending_paths = pending_paths.clone();
1087 let executor = executor.clone();
1088 async move {
1089 executor.timer(latency).await;
1090 let paths = std::mem::take(&mut *pending_paths.lock());
1091 (!paths.is_empty()).then_some(paths)
1092 }
1093 }
1094 })),
1095 watcher,
1096 )
1097 }
1098
1099 fn open_repo(
1100 &self,
1101 dotgit_path: &Path,
1102 system_git_binary_path: Option<&Path>,
1103 ) -> Option<Arc<dyn GitRepository>> {
1104 Some(Arc::new(RealGitRepository::new(
1105 dotgit_path,
1106 self.bundled_git_binary_path.clone(),
1107 system_git_binary_path.map(|path| path.to_path_buf()),
1108 self.executor.clone(),
1109 )?))
1110 }
1111
1112 async fn git_init(
1113 &self,
1114 abs_work_directory_path: &Path,
1115 fallback_branch_name: String,
1116 ) -> Result<()> {
1117 let config = new_smol_command("git")
1118 .current_dir(abs_work_directory_path)
1119 .args(&["config", "--global", "--get", "init.defaultBranch"])
1120 .output()
1121 .await?;
1122
1123 let branch_name;
1124
1125 if config.status.success() && !config.stdout.is_empty() {
1126 branch_name = String::from_utf8_lossy(&config.stdout);
1127 } else {
1128 branch_name = Cow::Borrowed(fallback_branch_name.as_str());
1129 }
1130
1131 new_smol_command("git")
1132 .current_dir(abs_work_directory_path)
1133 .args(&["init", "-b"])
1134 .arg(branch_name.trim())
1135 .output()
1136 .await?;
1137
1138 Ok(())
1139 }
1140
1141 async fn git_clone(&self, repo_url: &str, abs_work_directory: &Path) -> Result<()> {
1142 let job_id = self.next_job_id.fetch_add(1, Ordering::SeqCst);
1143 let job_info = JobInfo {
1144 id: job_id,
1145 start: Instant::now(),
1146 message: SharedString::from(format!("Cloning {}", repo_url)),
1147 };
1148
1149 let _job_tracker = JobTracker::new(job_info, self.job_event_subscribers.clone());
1150
1151 let output = new_smol_command("git")
1152 .current_dir(abs_work_directory)
1153 .args(&["clone", repo_url])
1154 .output()
1155 .await?;
1156
1157 if !output.status.success() {
1158 anyhow::bail!(
1159 "git clone failed: {}",
1160 String::from_utf8_lossy(&output.stderr)
1161 );
1162 }
1163
1164 Ok(())
1165 }
1166
1167 fn is_fake(&self) -> bool {
1168 false
1169 }
1170
1171 fn subscribe_to_jobs(&self) -> JobEventReceiver {
1172 let (sender, receiver) = futures::channel::mpsc::unbounded();
1173 self.job_event_subscribers.lock().push(sender);
1174 receiver
1175 }
1176
1177 /// Checks whether the file system is case sensitive by attempting to create two files
1178 /// that have the same name except for the casing.
1179 ///
1180 /// It creates both files in a temporary directory it removes at the end.
1181 async fn is_case_sensitive(&self) -> Result<bool> {
1182 let temp_dir = TempDir::new()?;
1183 let test_file_1 = temp_dir.path().join("case_sensitivity_test.tmp");
1184 let test_file_2 = temp_dir.path().join("CASE_SENSITIVITY_TEST.TMP");
1185
1186 let create_opts = CreateOptions {
1187 overwrite: false,
1188 ignore_if_exists: false,
1189 };
1190
1191 // Create file1
1192 self.create_file(&test_file_1, create_opts).await?;
1193
1194 // Now check whether it's possible to create file2
1195 let case_sensitive = match self.create_file(&test_file_2, create_opts).await {
1196 Ok(_) => Ok(true),
1197 Err(e) => {
1198 if let Some(io_error) = e.downcast_ref::<io::Error>() {
1199 if io_error.kind() == io::ErrorKind::AlreadyExists {
1200 Ok(false)
1201 } else {
1202 Err(e)
1203 }
1204 } else {
1205 Err(e)
1206 }
1207 }
1208 };
1209
1210 temp_dir.close()?;
1211 case_sensitive
1212 }
1213}
1214
1215#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
1216impl Watcher for RealWatcher {
1217 fn add(&self, _: &Path) -> Result<()> {
1218 Ok(())
1219 }
1220
1221 fn remove(&self, _: &Path) -> Result<()> {
1222 Ok(())
1223 }
1224}
1225
1226#[cfg(feature = "test-support")]
1227pub struct FakeFs {
1228 this: std::sync::Weak<Self>,
1229 // Use an unfair lock to ensure tests are deterministic.
1230 state: Arc<Mutex<FakeFsState>>,
1231 executor: gpui::BackgroundExecutor,
1232}
1233
1234#[cfg(feature = "test-support")]
1235struct FakeFsState {
1236 root: FakeFsEntry,
1237 next_inode: u64,
1238 next_mtime: SystemTime,
1239 git_event_tx: smol::channel::Sender<PathBuf>,
1240 event_txs: Vec<(PathBuf, smol::channel::Sender<Vec<PathEvent>>)>,
1241 events_paused: bool,
1242 buffered_events: Vec<PathEvent>,
1243 metadata_call_count: usize,
1244 read_dir_call_count: usize,
1245 path_write_counts: std::collections::HashMap<PathBuf, usize>,
1246 moves: std::collections::HashMap<u64, PathBuf>,
1247 job_event_subscribers: Arc<Mutex<Vec<JobEventSender>>>,
1248}
1249
1250#[cfg(feature = "test-support")]
1251#[derive(Clone, Debug)]
1252enum FakeFsEntry {
1253 File {
1254 inode: u64,
1255 mtime: MTime,
1256 len: u64,
1257 content: Vec<u8>,
1258 // The path to the repository state directory, if this is a gitfile.
1259 git_dir_path: Option<PathBuf>,
1260 },
1261 Dir {
1262 inode: u64,
1263 mtime: MTime,
1264 len: u64,
1265 entries: BTreeMap<String, FakeFsEntry>,
1266 git_repo_state: Option<Arc<Mutex<FakeGitRepositoryState>>>,
1267 },
1268 Symlink {
1269 target: PathBuf,
1270 },
1271}
1272
1273#[cfg(feature = "test-support")]
1274impl PartialEq for FakeFsEntry {
1275 fn eq(&self, other: &Self) -> bool {
1276 match (self, other) {
1277 (
1278 Self::File {
1279 inode: l_inode,
1280 mtime: l_mtime,
1281 len: l_len,
1282 content: l_content,
1283 git_dir_path: l_git_dir_path,
1284 },
1285 Self::File {
1286 inode: r_inode,
1287 mtime: r_mtime,
1288 len: r_len,
1289 content: r_content,
1290 git_dir_path: r_git_dir_path,
1291 },
1292 ) => {
1293 l_inode == r_inode
1294 && l_mtime == r_mtime
1295 && l_len == r_len
1296 && l_content == r_content
1297 && l_git_dir_path == r_git_dir_path
1298 }
1299 (
1300 Self::Dir {
1301 inode: l_inode,
1302 mtime: l_mtime,
1303 len: l_len,
1304 entries: l_entries,
1305 git_repo_state: l_git_repo_state,
1306 },
1307 Self::Dir {
1308 inode: r_inode,
1309 mtime: r_mtime,
1310 len: r_len,
1311 entries: r_entries,
1312 git_repo_state: r_git_repo_state,
1313 },
1314 ) => {
1315 let same_repo_state = match (l_git_repo_state.as_ref(), r_git_repo_state.as_ref()) {
1316 (Some(l), Some(r)) => Arc::ptr_eq(l, r),
1317 (None, None) => true,
1318 _ => false,
1319 };
1320 l_inode == r_inode
1321 && l_mtime == r_mtime
1322 && l_len == r_len
1323 && l_entries == r_entries
1324 && same_repo_state
1325 }
1326 (Self::Symlink { target: l_target }, Self::Symlink { target: r_target }) => {
1327 l_target == r_target
1328 }
1329 _ => false,
1330 }
1331 }
1332}
1333
1334#[cfg(feature = "test-support")]
1335impl FakeFsState {
1336 fn get_and_increment_mtime(&mut self) -> MTime {
1337 let mtime = self.next_mtime;
1338 self.next_mtime += FakeFs::SYSTEMTIME_INTERVAL;
1339 MTime(mtime)
1340 }
1341
1342 fn get_and_increment_inode(&mut self) -> u64 {
1343 let inode = self.next_inode;
1344 self.next_inode += 1;
1345 inode
1346 }
1347
1348 fn canonicalize(&self, target: &Path, follow_symlink: bool) -> Option<PathBuf> {
1349 let mut canonical_path = PathBuf::new();
1350 let mut path = target.to_path_buf();
1351 let mut entry_stack = Vec::new();
1352 'outer: loop {
1353 let mut path_components = path.components().peekable();
1354 let mut prefix = None;
1355 while let Some(component) = path_components.next() {
1356 match component {
1357 Component::Prefix(prefix_component) => prefix = Some(prefix_component),
1358 Component::RootDir => {
1359 entry_stack.clear();
1360 entry_stack.push(&self.root);
1361 canonical_path.clear();
1362 match prefix {
1363 Some(prefix_component) => {
1364 canonical_path = PathBuf::from(prefix_component.as_os_str());
1365 // Prefixes like `C:\\` are represented without their trailing slash, so we have to re-add it.
1366 canonical_path.push(std::path::MAIN_SEPARATOR_STR);
1367 }
1368 None => canonical_path = PathBuf::from(std::path::MAIN_SEPARATOR_STR),
1369 }
1370 }
1371 Component::CurDir => {}
1372 Component::ParentDir => {
1373 entry_stack.pop()?;
1374 canonical_path.pop();
1375 }
1376 Component::Normal(name) => {
1377 let current_entry = *entry_stack.last()?;
1378 if let FakeFsEntry::Dir { entries, .. } = current_entry {
1379 let entry = entries.get(name.to_str().unwrap())?;
1380 if (path_components.peek().is_some() || follow_symlink)
1381 && let FakeFsEntry::Symlink { target, .. } = entry
1382 {
1383 let mut target = target.clone();
1384 target.extend(path_components);
1385 path = target;
1386 continue 'outer;
1387 }
1388 entry_stack.push(entry);
1389 canonical_path = canonical_path.join(name);
1390 } else {
1391 return None;
1392 }
1393 }
1394 }
1395 }
1396 break;
1397 }
1398
1399 if entry_stack.is_empty() {
1400 None
1401 } else {
1402 Some(canonical_path)
1403 }
1404 }
1405
1406 fn try_entry(
1407 &mut self,
1408 target: &Path,
1409 follow_symlink: bool,
1410 ) -> Option<(&mut FakeFsEntry, PathBuf)> {
1411 let canonical_path = self.canonicalize(target, follow_symlink)?;
1412
1413 let mut components = canonical_path
1414 .components()
1415 .skip_while(|component| matches!(component, Component::Prefix(_)));
1416 let Some(Component::RootDir) = components.next() else {
1417 panic!(
1418 "the path {:?} was not canonicalized properly {:?}",
1419 target, canonical_path
1420 )
1421 };
1422
1423 let mut entry = &mut self.root;
1424 for component in components {
1425 match component {
1426 Component::Normal(name) => {
1427 if let FakeFsEntry::Dir { entries, .. } = entry {
1428 entry = entries.get_mut(name.to_str().unwrap())?;
1429 } else {
1430 return None;
1431 }
1432 }
1433 _ => {
1434 panic!(
1435 "the path {:?} was not canonicalized properly {:?}",
1436 target, canonical_path
1437 )
1438 }
1439 }
1440 }
1441
1442 Some((entry, canonical_path))
1443 }
1444
1445 fn entry(&mut self, target: &Path) -> Result<&mut FakeFsEntry> {
1446 Ok(self
1447 .try_entry(target, true)
1448 .ok_or_else(|| {
1449 anyhow!(io::Error::new(
1450 io::ErrorKind::NotFound,
1451 format!("not found: {target:?}")
1452 ))
1453 })?
1454 .0)
1455 }
1456
1457 fn write_path<Fn, T>(&mut self, path: &Path, callback: Fn) -> Result<T>
1458 where
1459 Fn: FnOnce(btree_map::Entry<String, FakeFsEntry>) -> Result<T>,
1460 {
1461 let path = normalize_path(path);
1462 let filename = path.file_name().context("cannot overwrite the root")?;
1463 let parent_path = path.parent().unwrap();
1464
1465 let parent = self.entry(parent_path)?;
1466 let new_entry = parent
1467 .dir_entries(parent_path)?
1468 .entry(filename.to_str().unwrap().into());
1469 callback(new_entry)
1470 }
1471
1472 fn emit_event<I, T>(&mut self, paths: I)
1473 where
1474 I: IntoIterator<Item = (T, Option<PathEventKind>)>,
1475 T: Into<PathBuf>,
1476 {
1477 self.buffered_events
1478 .extend(paths.into_iter().map(|(path, kind)| PathEvent {
1479 path: path.into(),
1480 kind,
1481 }));
1482
1483 if !self.events_paused {
1484 self.flush_events(self.buffered_events.len());
1485 }
1486 }
1487
1488 fn flush_events(&mut self, mut count: usize) {
1489 count = count.min(self.buffered_events.len());
1490 let events = self.buffered_events.drain(0..count).collect::<Vec<_>>();
1491 self.event_txs.retain(|(_, tx)| {
1492 let _ = tx.try_send(events.clone());
1493 !tx.is_closed()
1494 });
1495 }
1496}
1497
1498#[cfg(feature = "test-support")]
1499pub static FS_DOT_GIT: std::sync::LazyLock<&'static OsStr> =
1500 std::sync::LazyLock::new(|| OsStr::new(".git"));
1501
1502#[cfg(feature = "test-support")]
1503impl FakeFs {
1504 /// We need to use something large enough for Windows and Unix to consider this a new file.
1505 /// https://doc.rust-lang.org/nightly/std/time/struct.SystemTime.html#platform-specific-behavior
1506 const SYSTEMTIME_INTERVAL: Duration = Duration::from_nanos(100);
1507
1508 pub fn new(executor: gpui::BackgroundExecutor) -> Arc<Self> {
1509 let (tx, rx) = smol::channel::bounded::<PathBuf>(10);
1510
1511 let this = Arc::new_cyclic(|this| Self {
1512 this: this.clone(),
1513 executor: executor.clone(),
1514 state: Arc::new(Mutex::new(FakeFsState {
1515 root: FakeFsEntry::Dir {
1516 inode: 0,
1517 mtime: MTime(UNIX_EPOCH),
1518 len: 0,
1519 entries: Default::default(),
1520 git_repo_state: None,
1521 },
1522 git_event_tx: tx,
1523 next_mtime: UNIX_EPOCH + Self::SYSTEMTIME_INTERVAL,
1524 next_inode: 1,
1525 event_txs: Default::default(),
1526 buffered_events: Vec::new(),
1527 events_paused: false,
1528 read_dir_call_count: 0,
1529 metadata_call_count: 0,
1530 path_write_counts: Default::default(),
1531 moves: Default::default(),
1532 job_event_subscribers: Arc::new(Mutex::new(Vec::new())),
1533 })),
1534 });
1535
1536 executor.spawn({
1537 let this = this.clone();
1538 async move {
1539 while let Ok(git_event) = rx.recv().await {
1540 if let Some(mut state) = this.state.try_lock() {
1541 state.emit_event([(git_event, Some(PathEventKind::Changed))]);
1542 } else {
1543 panic!("Failed to lock file system state, this execution would have caused a test hang");
1544 }
1545 }
1546 }
1547 }).detach();
1548
1549 this
1550 }
1551
1552 pub fn set_next_mtime(&self, next_mtime: SystemTime) {
1553 let mut state = self.state.lock();
1554 state.next_mtime = next_mtime;
1555 }
1556
1557 pub fn get_and_increment_mtime(&self) -> MTime {
1558 let mut state = self.state.lock();
1559 state.get_and_increment_mtime()
1560 }
1561
1562 pub async fn touch_path(&self, path: impl AsRef<Path>) {
1563 let mut state = self.state.lock();
1564 let path = path.as_ref();
1565 let new_mtime = state.get_and_increment_mtime();
1566 let new_inode = state.get_and_increment_inode();
1567 state
1568 .write_path(path, move |entry| {
1569 match entry {
1570 btree_map::Entry::Vacant(e) => {
1571 e.insert(FakeFsEntry::File {
1572 inode: new_inode,
1573 mtime: new_mtime,
1574 content: Vec::new(),
1575 len: 0,
1576 git_dir_path: None,
1577 });
1578 }
1579 btree_map::Entry::Occupied(mut e) => match &mut *e.get_mut() {
1580 FakeFsEntry::File { mtime, .. } => *mtime = new_mtime,
1581 FakeFsEntry::Dir { mtime, .. } => *mtime = new_mtime,
1582 FakeFsEntry::Symlink { .. } => {}
1583 },
1584 }
1585 Ok(())
1586 })
1587 .unwrap();
1588 state.emit_event([(path.to_path_buf(), Some(PathEventKind::Changed))]);
1589 }
1590
1591 pub async fn insert_file(&self, path: impl AsRef<Path>, content: Vec<u8>) {
1592 self.write_file_internal(path, content, true).unwrap()
1593 }
1594
1595 pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
1596 let mut state = self.state.lock();
1597 let path = path.as_ref();
1598 let file = FakeFsEntry::Symlink { target };
1599 state
1600 .write_path(path.as_ref(), move |e| match e {
1601 btree_map::Entry::Vacant(e) => {
1602 e.insert(file);
1603 Ok(())
1604 }
1605 btree_map::Entry::Occupied(mut e) => {
1606 *e.get_mut() = file;
1607 Ok(())
1608 }
1609 })
1610 .unwrap();
1611 state.emit_event([(path, Some(PathEventKind::Created))]);
1612 }
1613
1614 fn write_file_internal(
1615 &self,
1616 path: impl AsRef<Path>,
1617 new_content: Vec<u8>,
1618 recreate_inode: bool,
1619 ) -> Result<()> {
1620 fn inner(
1621 this: &FakeFs,
1622 path: &Path,
1623 new_content: Vec<u8>,
1624 recreate_inode: bool,
1625 ) -> Result<()> {
1626 let mut state = this.state.lock();
1627 let path_buf = path.to_path_buf();
1628 *state.path_write_counts.entry(path_buf).or_insert(0) += 1;
1629 let new_inode = state.get_and_increment_inode();
1630 let new_mtime = state.get_and_increment_mtime();
1631 let new_len = new_content.len() as u64;
1632 let mut kind = None;
1633 state.write_path(path, |entry| {
1634 match entry {
1635 btree_map::Entry::Vacant(e) => {
1636 kind = Some(PathEventKind::Created);
1637 e.insert(FakeFsEntry::File {
1638 inode: new_inode,
1639 mtime: new_mtime,
1640 len: new_len,
1641 content: new_content,
1642 git_dir_path: None,
1643 });
1644 }
1645 btree_map::Entry::Occupied(mut e) => {
1646 kind = Some(PathEventKind::Changed);
1647 if let FakeFsEntry::File {
1648 inode,
1649 mtime,
1650 len,
1651 content,
1652 ..
1653 } = e.get_mut()
1654 {
1655 *mtime = new_mtime;
1656 *content = new_content;
1657 *len = new_len;
1658 if recreate_inode {
1659 *inode = new_inode;
1660 }
1661 } else {
1662 anyhow::bail!("not a file")
1663 }
1664 }
1665 }
1666 Ok(())
1667 })?;
1668 state.emit_event([(path, kind)]);
1669 Ok(())
1670 }
1671 inner(self, path.as_ref(), new_content, recreate_inode)
1672 }
1673
1674 pub fn read_file_sync(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1675 let path = path.as_ref();
1676 let path = normalize_path(path);
1677 let mut state = self.state.lock();
1678 let entry = state.entry(&path)?;
1679 entry.file_content(&path).cloned()
1680 }
1681
1682 async fn load_internal(&self, path: impl AsRef<Path>) -> Result<Vec<u8>> {
1683 let path = path.as_ref();
1684 let path = normalize_path(path);
1685 self.simulate_random_delay().await;
1686 let mut state = self.state.lock();
1687 let entry = state.entry(&path)?;
1688 entry.file_content(&path).cloned()
1689 }
1690
1691 pub fn pause_events(&self) {
1692 self.state.lock().events_paused = true;
1693 }
1694
1695 pub fn unpause_events_and_flush(&self) {
1696 self.state.lock().events_paused = false;
1697 self.flush_events(usize::MAX);
1698 }
1699
1700 pub fn buffered_event_count(&self) -> usize {
1701 self.state.lock().buffered_events.len()
1702 }
1703
1704 pub fn flush_events(&self, count: usize) {
1705 self.state.lock().flush_events(count);
1706 }
1707
1708 pub(crate) fn entry(&self, target: &Path) -> Result<FakeFsEntry> {
1709 self.state.lock().entry(target).cloned()
1710 }
1711
1712 pub(crate) fn insert_entry(&self, target: &Path, new_entry: FakeFsEntry) -> Result<()> {
1713 let mut state = self.state.lock();
1714 state.write_path(target, |entry| {
1715 match entry {
1716 btree_map::Entry::Vacant(vacant_entry) => {
1717 vacant_entry.insert(new_entry);
1718 }
1719 btree_map::Entry::Occupied(mut occupied_entry) => {
1720 occupied_entry.insert(new_entry);
1721 }
1722 }
1723 Ok(())
1724 })
1725 }
1726
1727 #[must_use]
1728 pub fn insert_tree<'a>(
1729 &'a self,
1730 path: impl 'a + AsRef<Path> + Send,
1731 tree: serde_json::Value,
1732 ) -> futures::future::BoxFuture<'a, ()> {
1733 use futures::FutureExt as _;
1734 use serde_json::Value::*;
1735
1736 fn inner<'a>(
1737 this: &'a FakeFs,
1738 path: Arc<Path>,
1739 tree: serde_json::Value,
1740 ) -> futures::future::BoxFuture<'a, ()> {
1741 async move {
1742 match tree {
1743 Object(map) => {
1744 this.create_dir(&path).await.unwrap();
1745 for (name, contents) in map {
1746 let mut path = PathBuf::from(path.as_ref());
1747 path.push(name);
1748 this.insert_tree(&path, contents).await;
1749 }
1750 }
1751 Null => {
1752 this.create_dir(&path).await.unwrap();
1753 }
1754 String(contents) => {
1755 this.insert_file(&path, contents.into_bytes()).await;
1756 }
1757 _ => {
1758 panic!("JSON object must contain only objects, strings, or null");
1759 }
1760 }
1761 }
1762 .boxed()
1763 }
1764 inner(self, Arc::from(path.as_ref()), tree)
1765 }
1766
1767 pub fn insert_tree_from_real_fs<'a>(
1768 &'a self,
1769 path: impl 'a + AsRef<Path> + Send,
1770 src_path: impl 'a + AsRef<Path> + Send,
1771 ) -> futures::future::BoxFuture<'a, ()> {
1772 use futures::FutureExt as _;
1773
1774 async move {
1775 let path = path.as_ref();
1776 if std::fs::metadata(&src_path).unwrap().is_file() {
1777 let contents = std::fs::read(src_path).unwrap();
1778 self.insert_file(path, contents).await;
1779 } else {
1780 self.create_dir(path).await.unwrap();
1781 for entry in std::fs::read_dir(&src_path).unwrap() {
1782 let entry = entry.unwrap();
1783 self.insert_tree_from_real_fs(path.join(entry.file_name()), entry.path())
1784 .await;
1785 }
1786 }
1787 }
1788 .boxed()
1789 }
1790
1791 pub fn with_git_state_and_paths<T, F>(
1792 &self,
1793 dot_git: &Path,
1794 emit_git_event: bool,
1795 f: F,
1796 ) -> Result<T>
1797 where
1798 F: FnOnce(&mut FakeGitRepositoryState, &Path, &Path) -> T,
1799 {
1800 let mut state = self.state.lock();
1801 let git_event_tx = state.git_event_tx.clone();
1802 let entry = state.entry(dot_git).context("open .git")?;
1803
1804 if let FakeFsEntry::Dir { git_repo_state, .. } = entry {
1805 let repo_state = git_repo_state.get_or_insert_with(|| {
1806 log::debug!("insert git state for {dot_git:?}");
1807 Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1808 });
1809 let mut repo_state = repo_state.lock();
1810
1811 let result = f(&mut repo_state, dot_git, dot_git);
1812
1813 drop(repo_state);
1814 if emit_git_event {
1815 state.emit_event([(dot_git, Some(PathEventKind::Changed))]);
1816 }
1817
1818 Ok(result)
1819 } else if let FakeFsEntry::File {
1820 content,
1821 git_dir_path,
1822 ..
1823 } = &mut *entry
1824 {
1825 let path = match git_dir_path {
1826 Some(path) => path,
1827 None => {
1828 let path = std::str::from_utf8(content)
1829 .ok()
1830 .and_then(|content| content.strip_prefix("gitdir:"))
1831 .context("not a valid gitfile")?
1832 .trim();
1833 git_dir_path.insert(normalize_path(&dot_git.parent().unwrap().join(path)))
1834 }
1835 }
1836 .clone();
1837 let Some((git_dir_entry, canonical_path)) = state.try_entry(&path, true) else {
1838 anyhow::bail!("pointed-to git dir {path:?} not found")
1839 };
1840 let FakeFsEntry::Dir {
1841 git_repo_state,
1842 entries,
1843 ..
1844 } = git_dir_entry
1845 else {
1846 anyhow::bail!("gitfile points to a non-directory")
1847 };
1848 let common_dir = if let Some(child) = entries.get("commondir") {
1849 Path::new(
1850 std::str::from_utf8(child.file_content("commondir".as_ref())?)
1851 .context("commondir content")?,
1852 )
1853 .to_owned()
1854 } else {
1855 canonical_path.clone()
1856 };
1857 let repo_state = git_repo_state.get_or_insert_with(|| {
1858 Arc::new(Mutex::new(FakeGitRepositoryState::new(git_event_tx)))
1859 });
1860 let mut repo_state = repo_state.lock();
1861
1862 let result = f(&mut repo_state, &canonical_path, &common_dir);
1863
1864 if emit_git_event {
1865 drop(repo_state);
1866 state.emit_event([(canonical_path, Some(PathEventKind::Changed))]);
1867 }
1868
1869 Ok(result)
1870 } else {
1871 anyhow::bail!("not a valid git repository");
1872 }
1873 }
1874
1875 pub fn with_git_state<T, F>(&self, dot_git: &Path, emit_git_event: bool, f: F) -> Result<T>
1876 where
1877 F: FnOnce(&mut FakeGitRepositoryState) -> T,
1878 {
1879 self.with_git_state_and_paths(dot_git, emit_git_event, |state, _, _| f(state))
1880 }
1881
1882 pub fn set_branch_name(&self, dot_git: &Path, branch: Option<impl Into<String>>) {
1883 self.with_git_state(dot_git, true, |state| {
1884 let branch = branch.map(Into::into);
1885 state.branches.extend(branch.clone());
1886 state.current_branch_name = branch
1887 })
1888 .unwrap();
1889 }
1890
1891 pub fn set_remote_for_repo(
1892 &self,
1893 dot_git: &Path,
1894 name: impl Into<String>,
1895 url: impl Into<String>,
1896 ) {
1897 self.with_git_state(dot_git, true, |state| {
1898 state.remotes.insert(name.into(), url.into());
1899 })
1900 .unwrap();
1901 }
1902
1903 pub fn insert_branches(&self, dot_git: &Path, branches: &[&str]) {
1904 self.with_git_state(dot_git, true, |state| {
1905 if let Some(first) = branches.first()
1906 && state.current_branch_name.is_none()
1907 {
1908 state.current_branch_name = Some(first.to_string())
1909 }
1910 state
1911 .branches
1912 .extend(branches.iter().map(ToString::to_string));
1913 })
1914 .unwrap();
1915 }
1916
1917 pub fn set_unmerged_paths_for_repo(
1918 &self,
1919 dot_git: &Path,
1920 unmerged_state: &[(RepoPath, UnmergedStatus)],
1921 ) {
1922 self.with_git_state(dot_git, true, |state| {
1923 state.unmerged_paths.clear();
1924 state.unmerged_paths.extend(
1925 unmerged_state
1926 .iter()
1927 .map(|(path, content)| (path.clone(), *content)),
1928 );
1929 })
1930 .unwrap();
1931 }
1932
1933 pub fn set_index_for_repo(&self, dot_git: &Path, index_state: &[(&str, String)]) {
1934 self.with_git_state(dot_git, true, |state| {
1935 state.index_contents.clear();
1936 state.index_contents.extend(
1937 index_state
1938 .iter()
1939 .map(|(path, content)| (repo_path(path), content.clone())),
1940 );
1941 })
1942 .unwrap();
1943 }
1944
1945 pub fn set_head_for_repo(
1946 &self,
1947 dot_git: &Path,
1948 head_state: &[(&str, String)],
1949 sha: impl Into<String>,
1950 ) {
1951 self.with_git_state(dot_git, true, |state| {
1952 state.head_contents.clear();
1953 state.head_contents.extend(
1954 head_state
1955 .iter()
1956 .map(|(path, content)| (repo_path(path), content.clone())),
1957 );
1958 state.refs.insert("HEAD".into(), sha.into());
1959 })
1960 .unwrap();
1961 }
1962
1963 pub fn set_head_and_index_for_repo(&self, dot_git: &Path, contents_by_path: &[(&str, String)]) {
1964 self.with_git_state(dot_git, true, |state| {
1965 state.head_contents.clear();
1966 state.head_contents.extend(
1967 contents_by_path
1968 .iter()
1969 .map(|(path, contents)| (repo_path(path), contents.clone())),
1970 );
1971 state.index_contents = state.head_contents.clone();
1972 })
1973 .unwrap();
1974 }
1975
1976 pub fn set_merge_base_content_for_repo(
1977 &self,
1978 dot_git: &Path,
1979 contents_by_path: &[(&str, String)],
1980 ) {
1981 self.with_git_state(dot_git, true, |state| {
1982 use git::Oid;
1983
1984 state.merge_base_contents.clear();
1985 let oids = (1..)
1986 .map(|n| n.to_string())
1987 .map(|n| Oid::from_bytes(n.repeat(20).as_bytes()).unwrap());
1988 for ((path, content), oid) in contents_by_path.iter().zip(oids) {
1989 state.merge_base_contents.insert(repo_path(path), oid);
1990 state.oids.insert(oid, content.clone());
1991 }
1992 })
1993 .unwrap();
1994 }
1995
1996 pub fn set_blame_for_repo(&self, dot_git: &Path, blames: Vec<(RepoPath, git::blame::Blame)>) {
1997 self.with_git_state(dot_git, true, |state| {
1998 state.blames.clear();
1999 state.blames.extend(blames);
2000 })
2001 .unwrap();
2002 }
2003
2004 pub fn set_graph_commits(&self, dot_git: &Path, commits: Vec<Arc<InitialGraphCommitData>>) {
2005 self.with_git_state(dot_git, true, |state| {
2006 state.graph_commits = commits;
2007 })
2008 .unwrap();
2009 }
2010
2011 /// Put the given git repository into a state with the given status,
2012 /// by mutating the head, index, and unmerged state.
2013 pub fn set_status_for_repo(&self, dot_git: &Path, statuses: &[(&str, FileStatus)]) {
2014 let workdir_path = dot_git.parent().unwrap();
2015 let workdir_contents = self.files_with_contents(workdir_path);
2016 self.with_git_state(dot_git, true, |state| {
2017 state.index_contents.clear();
2018 state.head_contents.clear();
2019 state.unmerged_paths.clear();
2020 for (path, content) in workdir_contents {
2021 use util::{paths::PathStyle, rel_path::RelPath};
2022
2023 let repo_path = RelPath::new(path.strip_prefix(&workdir_path).unwrap(), PathStyle::local()).unwrap();
2024 let repo_path = RepoPath::from_rel_path(&repo_path);
2025 let status = statuses
2026 .iter()
2027 .find_map(|(p, status)| (*p == repo_path.as_unix_str()).then_some(status));
2028 let mut content = String::from_utf8_lossy(&content).to_string();
2029
2030 let mut index_content = None;
2031 let mut head_content = None;
2032 match status {
2033 None => {
2034 index_content = Some(content.clone());
2035 head_content = Some(content);
2036 }
2037 Some(FileStatus::Untracked | FileStatus::Ignored) => {}
2038 Some(FileStatus::Unmerged(unmerged_status)) => {
2039 state
2040 .unmerged_paths
2041 .insert(repo_path.clone(), *unmerged_status);
2042 content.push_str(" (unmerged)");
2043 index_content = Some(content.clone());
2044 head_content = Some(content);
2045 }
2046 Some(FileStatus::Tracked(TrackedStatus {
2047 index_status,
2048 worktree_status,
2049 })) => {
2050 match worktree_status {
2051 StatusCode::Modified => {
2052 let mut content = content.clone();
2053 content.push_str(" (modified in working copy)");
2054 index_content = Some(content);
2055 }
2056 StatusCode::TypeChanged | StatusCode::Unmodified => {
2057 index_content = Some(content.clone());
2058 }
2059 StatusCode::Added => {}
2060 StatusCode::Deleted | StatusCode::Renamed | StatusCode::Copied => {
2061 panic!("cannot create these statuses for an existing file");
2062 }
2063 };
2064 match index_status {
2065 StatusCode::Modified => {
2066 let mut content = index_content.clone().expect(
2067 "file cannot be both modified in index and created in working copy",
2068 );
2069 content.push_str(" (modified in index)");
2070 head_content = Some(content);
2071 }
2072 StatusCode::TypeChanged | StatusCode::Unmodified => {
2073 head_content = Some(index_content.clone().expect("file cannot be both unmodified in index and created in working copy"));
2074 }
2075 StatusCode::Added => {}
2076 StatusCode::Deleted => {
2077 head_content = Some("".into());
2078 }
2079 StatusCode::Renamed | StatusCode::Copied => {
2080 panic!("cannot create these statuses for an existing file");
2081 }
2082 };
2083 }
2084 };
2085
2086 if let Some(content) = index_content {
2087 state.index_contents.insert(repo_path.clone(), content);
2088 }
2089 if let Some(content) = head_content {
2090 state.head_contents.insert(repo_path.clone(), content);
2091 }
2092 }
2093 }).unwrap();
2094 }
2095
2096 pub fn set_error_message_for_index_write(&self, dot_git: &Path, message: Option<String>) {
2097 self.with_git_state(dot_git, true, |state| {
2098 state.simulated_index_write_error_message = message;
2099 })
2100 .unwrap();
2101 }
2102
2103 pub fn paths(&self, include_dot_git: bool) -> Vec<PathBuf> {
2104 let mut result = Vec::new();
2105 let mut queue = collections::VecDeque::new();
2106 let state = &*self.state.lock();
2107 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2108 while let Some((path, entry)) = queue.pop_front() {
2109 if let FakeFsEntry::Dir { entries, .. } = entry {
2110 for (name, entry) in entries {
2111 queue.push_back((path.join(name), entry));
2112 }
2113 }
2114 if include_dot_git
2115 || !path
2116 .components()
2117 .any(|component| component.as_os_str() == *FS_DOT_GIT)
2118 {
2119 result.push(path);
2120 }
2121 }
2122 result
2123 }
2124
2125 pub fn directories(&self, include_dot_git: bool) -> Vec<PathBuf> {
2126 let mut result = Vec::new();
2127 let mut queue = collections::VecDeque::new();
2128 let state = &*self.state.lock();
2129 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2130 while let Some((path, entry)) = queue.pop_front() {
2131 if let FakeFsEntry::Dir { entries, .. } = entry {
2132 for (name, entry) in entries {
2133 queue.push_back((path.join(name), entry));
2134 }
2135 if include_dot_git
2136 || !path
2137 .components()
2138 .any(|component| component.as_os_str() == *FS_DOT_GIT)
2139 {
2140 result.push(path);
2141 }
2142 }
2143 }
2144 result
2145 }
2146
2147 pub fn files(&self) -> Vec<PathBuf> {
2148 let mut result = Vec::new();
2149 let mut queue = collections::VecDeque::new();
2150 let state = &*self.state.lock();
2151 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2152 while let Some((path, entry)) = queue.pop_front() {
2153 match entry {
2154 FakeFsEntry::File { .. } => result.push(path),
2155 FakeFsEntry::Dir { entries, .. } => {
2156 for (name, entry) in entries {
2157 queue.push_back((path.join(name), entry));
2158 }
2159 }
2160 FakeFsEntry::Symlink { .. } => {}
2161 }
2162 }
2163 result
2164 }
2165
2166 pub fn files_with_contents(&self, prefix: &Path) -> Vec<(PathBuf, Vec<u8>)> {
2167 let mut result = Vec::new();
2168 let mut queue = collections::VecDeque::new();
2169 let state = &*self.state.lock();
2170 queue.push_back((PathBuf::from(util::path!("/")), &state.root));
2171 while let Some((path, entry)) = queue.pop_front() {
2172 match entry {
2173 FakeFsEntry::File { content, .. } => {
2174 if path.starts_with(prefix) {
2175 result.push((path, content.clone()));
2176 }
2177 }
2178 FakeFsEntry::Dir { entries, .. } => {
2179 for (name, entry) in entries {
2180 queue.push_back((path.join(name), entry));
2181 }
2182 }
2183 FakeFsEntry::Symlink { .. } => {}
2184 }
2185 }
2186 result
2187 }
2188
2189 /// How many `read_dir` calls have been issued.
2190 pub fn read_dir_call_count(&self) -> usize {
2191 self.state.lock().read_dir_call_count
2192 }
2193
2194 pub fn watched_paths(&self) -> Vec<PathBuf> {
2195 let state = self.state.lock();
2196 state
2197 .event_txs
2198 .iter()
2199 .filter_map(|(path, tx)| Some(path.clone()).filter(|_| !tx.is_closed()))
2200 .collect()
2201 }
2202
2203 /// How many `metadata` calls have been issued.
2204 pub fn metadata_call_count(&self) -> usize {
2205 self.state.lock().metadata_call_count
2206 }
2207
2208 /// How many write operations have been issued for a specific path.
2209 pub fn write_count_for_path(&self, path: impl AsRef<Path>) -> usize {
2210 let path = path.as_ref().to_path_buf();
2211 self.state
2212 .lock()
2213 .path_write_counts
2214 .get(&path)
2215 .copied()
2216 .unwrap_or(0)
2217 }
2218
2219 pub fn emit_fs_event(&self, path: impl Into<PathBuf>, event: Option<PathEventKind>) {
2220 self.state.lock().emit_event(std::iter::once((path, event)));
2221 }
2222
2223 fn simulate_random_delay(&self) -> impl futures::Future<Output = ()> {
2224 self.executor.simulate_random_delay()
2225 }
2226}
2227
2228#[cfg(feature = "test-support")]
2229impl FakeFsEntry {
2230 fn is_file(&self) -> bool {
2231 matches!(self, Self::File { .. })
2232 }
2233
2234 fn is_symlink(&self) -> bool {
2235 matches!(self, Self::Symlink { .. })
2236 }
2237
2238 fn file_content(&self, path: &Path) -> Result<&Vec<u8>> {
2239 if let Self::File { content, .. } = self {
2240 Ok(content)
2241 } else {
2242 anyhow::bail!("not a file: {path:?}");
2243 }
2244 }
2245
2246 fn dir_entries(&mut self, path: &Path) -> Result<&mut BTreeMap<String, FakeFsEntry>> {
2247 if let Self::Dir { entries, .. } = self {
2248 Ok(entries)
2249 } else {
2250 anyhow::bail!("not a directory: {path:?}");
2251 }
2252 }
2253}
2254
2255#[cfg(feature = "test-support")]
2256struct FakeWatcher {
2257 tx: smol::channel::Sender<Vec<PathEvent>>,
2258 original_path: PathBuf,
2259 fs_state: Arc<Mutex<FakeFsState>>,
2260 prefixes: Mutex<Vec<PathBuf>>,
2261}
2262
2263#[cfg(feature = "test-support")]
2264impl Watcher for FakeWatcher {
2265 fn add(&self, path: &Path) -> Result<()> {
2266 if path.starts_with(&self.original_path) {
2267 return Ok(());
2268 }
2269 self.fs_state
2270 .try_lock()
2271 .unwrap()
2272 .event_txs
2273 .push((path.to_owned(), self.tx.clone()));
2274 self.prefixes.lock().push(path.to_owned());
2275 Ok(())
2276 }
2277
2278 fn remove(&self, _: &Path) -> Result<()> {
2279 Ok(())
2280 }
2281}
2282
2283#[cfg(feature = "test-support")]
2284#[derive(Debug)]
2285struct FakeHandle {
2286 inode: u64,
2287}
2288
2289#[cfg(feature = "test-support")]
2290impl FileHandle for FakeHandle {
2291 fn current_path(&self, fs: &Arc<dyn Fs>) -> Result<PathBuf> {
2292 let fs = fs.as_fake();
2293 let mut state = fs.state.lock();
2294 let Some(target) = state.moves.get(&self.inode).cloned() else {
2295 anyhow::bail!("fake fd not moved")
2296 };
2297
2298 if state.try_entry(&target, false).is_some() {
2299 return Ok(target);
2300 }
2301 anyhow::bail!("fake fd target not found")
2302 }
2303}
2304
2305#[cfg(feature = "test-support")]
2306#[async_trait::async_trait]
2307impl Fs for FakeFs {
2308 async fn create_dir(&self, path: &Path) -> Result<()> {
2309 self.simulate_random_delay().await;
2310
2311 let mut created_dirs = Vec::new();
2312 let mut cur_path = PathBuf::new();
2313 for component in path.components() {
2314 let should_skip = matches!(component, Component::Prefix(..) | Component::RootDir);
2315 cur_path.push(component);
2316 if should_skip {
2317 continue;
2318 }
2319 let mut state = self.state.lock();
2320
2321 let inode = state.get_and_increment_inode();
2322 let mtime = state.get_and_increment_mtime();
2323 state.write_path(&cur_path, |entry| {
2324 entry.or_insert_with(|| {
2325 created_dirs.push((cur_path.clone(), Some(PathEventKind::Created)));
2326 FakeFsEntry::Dir {
2327 inode,
2328 mtime,
2329 len: 0,
2330 entries: Default::default(),
2331 git_repo_state: None,
2332 }
2333 });
2334 Ok(())
2335 })?
2336 }
2337
2338 self.state.lock().emit_event(created_dirs);
2339 Ok(())
2340 }
2341
2342 async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
2343 self.simulate_random_delay().await;
2344 let mut state = self.state.lock();
2345 let inode = state.get_and_increment_inode();
2346 let mtime = state.get_and_increment_mtime();
2347 let file = FakeFsEntry::File {
2348 inode,
2349 mtime,
2350 len: 0,
2351 content: Vec::new(),
2352 git_dir_path: None,
2353 };
2354 let mut kind = Some(PathEventKind::Created);
2355 state.write_path(path, |entry| {
2356 match entry {
2357 btree_map::Entry::Occupied(mut e) => {
2358 if options.overwrite {
2359 kind = Some(PathEventKind::Changed);
2360 *e.get_mut() = file;
2361 } else if !options.ignore_if_exists {
2362 anyhow::bail!("path already exists: {path:?}");
2363 }
2364 }
2365 btree_map::Entry::Vacant(e) => {
2366 e.insert(file);
2367 }
2368 }
2369 Ok(())
2370 })?;
2371 state.emit_event([(path, kind)]);
2372 Ok(())
2373 }
2374
2375 async fn create_symlink(&self, path: &Path, target: PathBuf) -> Result<()> {
2376 let mut state = self.state.lock();
2377 let file = FakeFsEntry::Symlink { target };
2378 state
2379 .write_path(path.as_ref(), move |e| match e {
2380 btree_map::Entry::Vacant(e) => {
2381 e.insert(file);
2382 Ok(())
2383 }
2384 btree_map::Entry::Occupied(mut e) => {
2385 *e.get_mut() = file;
2386 Ok(())
2387 }
2388 })
2389 .unwrap();
2390 state.emit_event([(path, Some(PathEventKind::Created))]);
2391
2392 Ok(())
2393 }
2394
2395 async fn create_file_with(
2396 &self,
2397 path: &Path,
2398 mut content: Pin<&mut (dyn AsyncRead + Send)>,
2399 ) -> Result<()> {
2400 let mut bytes = Vec::new();
2401 content.read_to_end(&mut bytes).await?;
2402 self.write_file_internal(path, bytes, true)?;
2403 Ok(())
2404 }
2405
2406 async fn extract_tar_file(
2407 &self,
2408 path: &Path,
2409 content: Archive<Pin<&mut (dyn AsyncRead + Send)>>,
2410 ) -> Result<()> {
2411 let mut entries = content.entries()?;
2412 while let Some(entry) = entries.next().await {
2413 let mut entry = entry?;
2414 if entry.header().entry_type().is_file() {
2415 let path = path.join(entry.path()?.as_ref());
2416 let mut bytes = Vec::new();
2417 entry.read_to_end(&mut bytes).await?;
2418 self.create_dir(path.parent().unwrap()).await?;
2419 self.write_file_internal(&path, bytes, true)?;
2420 }
2421 }
2422 Ok(())
2423 }
2424
2425 async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
2426 self.simulate_random_delay().await;
2427
2428 let old_path = normalize_path(old_path);
2429 let new_path = normalize_path(new_path);
2430
2431 if options.create_parents {
2432 if let Some(parent) = new_path.parent() {
2433 self.create_dir(parent).await?;
2434 }
2435 }
2436
2437 let mut state = self.state.lock();
2438 let moved_entry = state.write_path(&old_path, |e| {
2439 if let btree_map::Entry::Occupied(e) = e {
2440 Ok(e.get().clone())
2441 } else {
2442 anyhow::bail!("path does not exist: {old_path:?}")
2443 }
2444 })?;
2445
2446 let inode = match moved_entry {
2447 FakeFsEntry::File { inode, .. } => inode,
2448 FakeFsEntry::Dir { inode, .. } => inode,
2449 _ => 0,
2450 };
2451
2452 state.moves.insert(inode, new_path.clone());
2453
2454 state.write_path(&new_path, |e| {
2455 match e {
2456 btree_map::Entry::Occupied(mut e) => {
2457 if options.overwrite {
2458 *e.get_mut() = moved_entry;
2459 } else if !options.ignore_if_exists {
2460 anyhow::bail!("path already exists: {new_path:?}");
2461 }
2462 }
2463 btree_map::Entry::Vacant(e) => {
2464 e.insert(moved_entry);
2465 }
2466 }
2467 Ok(())
2468 })?;
2469
2470 state
2471 .write_path(&old_path, |e| {
2472 if let btree_map::Entry::Occupied(e) = e {
2473 Ok(e.remove())
2474 } else {
2475 unreachable!()
2476 }
2477 })
2478 .unwrap();
2479
2480 state.emit_event([
2481 (old_path, Some(PathEventKind::Removed)),
2482 (new_path, Some(PathEventKind::Created)),
2483 ]);
2484 Ok(())
2485 }
2486
2487 async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
2488 self.simulate_random_delay().await;
2489
2490 let source = normalize_path(source);
2491 let target = normalize_path(target);
2492 let mut state = self.state.lock();
2493 let mtime = state.get_and_increment_mtime();
2494 let inode = state.get_and_increment_inode();
2495 let source_entry = state.entry(&source)?;
2496 let content = source_entry.file_content(&source)?.clone();
2497 let mut kind = Some(PathEventKind::Created);
2498 state.write_path(&target, |e| match e {
2499 btree_map::Entry::Occupied(e) => {
2500 if options.overwrite {
2501 kind = Some(PathEventKind::Changed);
2502 Ok(Some(e.get().clone()))
2503 } else if !options.ignore_if_exists {
2504 anyhow::bail!("{target:?} already exists");
2505 } else {
2506 Ok(None)
2507 }
2508 }
2509 btree_map::Entry::Vacant(e) => Ok(Some(
2510 e.insert(FakeFsEntry::File {
2511 inode,
2512 mtime,
2513 len: content.len() as u64,
2514 content,
2515 git_dir_path: None,
2516 })
2517 .clone(),
2518 )),
2519 })?;
2520 state.emit_event([(target, kind)]);
2521 Ok(())
2522 }
2523
2524 async fn remove_dir(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2525 self.simulate_random_delay().await;
2526
2527 let path = normalize_path(path);
2528 let parent_path = path.parent().context("cannot remove the root")?;
2529 let base_name = path.file_name().context("cannot remove the root")?;
2530
2531 let mut state = self.state.lock();
2532 let parent_entry = state.entry(parent_path)?;
2533 let entry = parent_entry
2534 .dir_entries(parent_path)?
2535 .entry(base_name.to_str().unwrap().into());
2536
2537 match entry {
2538 btree_map::Entry::Vacant(_) => {
2539 if !options.ignore_if_not_exists {
2540 anyhow::bail!("{path:?} does not exist");
2541 }
2542 }
2543 btree_map::Entry::Occupied(mut entry) => {
2544 {
2545 let children = entry.get_mut().dir_entries(&path)?;
2546 if !options.recursive && !children.is_empty() {
2547 anyhow::bail!("{path:?} is not empty");
2548 }
2549 }
2550 entry.remove();
2551 }
2552 }
2553 state.emit_event([(path, Some(PathEventKind::Removed))]);
2554 Ok(())
2555 }
2556
2557 async fn remove_file(&self, path: &Path, options: RemoveOptions) -> Result<()> {
2558 self.simulate_random_delay().await;
2559
2560 let path = normalize_path(path);
2561 let parent_path = path.parent().context("cannot remove the root")?;
2562 let base_name = path.file_name().unwrap();
2563 let mut state = self.state.lock();
2564 let parent_entry = state.entry(parent_path)?;
2565 let entry = parent_entry
2566 .dir_entries(parent_path)?
2567 .entry(base_name.to_str().unwrap().into());
2568 match entry {
2569 btree_map::Entry::Vacant(_) => {
2570 if !options.ignore_if_not_exists {
2571 anyhow::bail!("{path:?} does not exist");
2572 }
2573 }
2574 btree_map::Entry::Occupied(mut entry) => {
2575 entry.get_mut().file_content(&path)?;
2576 entry.remove();
2577 }
2578 }
2579 state.emit_event([(path, Some(PathEventKind::Removed))]);
2580 Ok(())
2581 }
2582
2583 async fn open_sync(&self, path: &Path) -> Result<Box<dyn io::Read + Send + Sync>> {
2584 let bytes = self.load_internal(path).await?;
2585 Ok(Box::new(io::Cursor::new(bytes)))
2586 }
2587
2588 async fn open_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>> {
2589 self.simulate_random_delay().await;
2590 let mut state = self.state.lock();
2591 let inode = match state.entry(path)? {
2592 FakeFsEntry::File { inode, .. } => *inode,
2593 FakeFsEntry::Dir { inode, .. } => *inode,
2594 _ => unreachable!(),
2595 };
2596 Ok(Arc::new(FakeHandle { inode }))
2597 }
2598
2599 async fn load(&self, path: &Path) -> Result<String> {
2600 let content = self.load_internal(path).await?;
2601 Ok(String::from_utf8(content)?)
2602 }
2603
2604 async fn load_bytes(&self, path: &Path) -> Result<Vec<u8>> {
2605 self.load_internal(path).await
2606 }
2607
2608 async fn atomic_write(&self, path: PathBuf, data: String) -> Result<()> {
2609 self.simulate_random_delay().await;
2610 let path = normalize_path(path.as_path());
2611 if let Some(path) = path.parent() {
2612 self.create_dir(path).await?;
2613 }
2614 self.write_file_internal(path, data.into_bytes(), true)?;
2615 Ok(())
2616 }
2617
2618 async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
2619 self.simulate_random_delay().await;
2620 let path = normalize_path(path);
2621 let content = text::chunks_with_line_ending(text, line_ending).collect::<String>();
2622 if let Some(path) = path.parent() {
2623 self.create_dir(path).await?;
2624 }
2625 self.write_file_internal(path, content.into_bytes(), false)?;
2626 Ok(())
2627 }
2628
2629 async fn write(&self, path: &Path, content: &[u8]) -> Result<()> {
2630 self.simulate_random_delay().await;
2631 let path = normalize_path(path);
2632 if let Some(path) = path.parent() {
2633 self.create_dir(path).await?;
2634 }
2635 self.write_file_internal(path, content.to_vec(), false)?;
2636 Ok(())
2637 }
2638
2639 async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
2640 let path = normalize_path(path);
2641 self.simulate_random_delay().await;
2642 let state = self.state.lock();
2643 let canonical_path = state
2644 .canonicalize(&path, true)
2645 .with_context(|| format!("path does not exist: {path:?}"))?;
2646 Ok(canonical_path)
2647 }
2648
2649 async fn is_file(&self, path: &Path) -> bool {
2650 let path = normalize_path(path);
2651 self.simulate_random_delay().await;
2652 let mut state = self.state.lock();
2653 if let Some((entry, _)) = state.try_entry(&path, true) {
2654 entry.is_file()
2655 } else {
2656 false
2657 }
2658 }
2659
2660 async fn is_dir(&self, path: &Path) -> bool {
2661 self.metadata(path)
2662 .await
2663 .is_ok_and(|metadata| metadata.is_some_and(|metadata| metadata.is_dir))
2664 }
2665
2666 async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
2667 self.simulate_random_delay().await;
2668 let path = normalize_path(path);
2669 let mut state = self.state.lock();
2670 state.metadata_call_count += 1;
2671 if let Some((mut entry, _)) = state.try_entry(&path, false) {
2672 let is_symlink = entry.is_symlink();
2673 if is_symlink {
2674 if let Some(e) = state.try_entry(&path, true).map(|e| e.0) {
2675 entry = e;
2676 } else {
2677 return Ok(None);
2678 }
2679 }
2680
2681 Ok(Some(match &*entry {
2682 FakeFsEntry::File {
2683 inode, mtime, len, ..
2684 } => Metadata {
2685 inode: *inode,
2686 mtime: *mtime,
2687 len: *len,
2688 is_dir: false,
2689 is_symlink,
2690 is_fifo: false,
2691 is_executable: false,
2692 },
2693 FakeFsEntry::Dir {
2694 inode, mtime, len, ..
2695 } => Metadata {
2696 inode: *inode,
2697 mtime: *mtime,
2698 len: *len,
2699 is_dir: true,
2700 is_symlink,
2701 is_fifo: false,
2702 is_executable: false,
2703 },
2704 FakeFsEntry::Symlink { .. } => unreachable!(),
2705 }))
2706 } else {
2707 Ok(None)
2708 }
2709 }
2710
2711 async fn read_link(&self, path: &Path) -> Result<PathBuf> {
2712 self.simulate_random_delay().await;
2713 let path = normalize_path(path);
2714 let mut state = self.state.lock();
2715 let (entry, _) = state
2716 .try_entry(&path, false)
2717 .with_context(|| format!("path does not exist: {path:?}"))?;
2718 if let FakeFsEntry::Symlink { target } = entry {
2719 Ok(target.clone())
2720 } else {
2721 anyhow::bail!("not a symlink: {path:?}")
2722 }
2723 }
2724
2725 async fn read_dir(
2726 &self,
2727 path: &Path,
2728 ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
2729 self.simulate_random_delay().await;
2730 let path = normalize_path(path);
2731 let mut state = self.state.lock();
2732 state.read_dir_call_count += 1;
2733 let entry = state.entry(&path)?;
2734 let children = entry.dir_entries(&path)?;
2735 let paths = children
2736 .keys()
2737 .map(|file_name| Ok(path.join(file_name)))
2738 .collect::<Vec<_>>();
2739 Ok(Box::pin(futures::stream::iter(paths)))
2740 }
2741
2742 async fn watch(
2743 &self,
2744 path: &Path,
2745 _: Duration,
2746 ) -> (
2747 Pin<Box<dyn Send + Stream<Item = Vec<PathEvent>>>>,
2748 Arc<dyn Watcher>,
2749 ) {
2750 self.simulate_random_delay().await;
2751 let (tx, rx) = smol::channel::unbounded();
2752 let path = path.to_path_buf();
2753 self.state.lock().event_txs.push((path.clone(), tx.clone()));
2754 let executor = self.executor.clone();
2755 let watcher = Arc::new(FakeWatcher {
2756 tx,
2757 original_path: path.to_owned(),
2758 fs_state: self.state.clone(),
2759 prefixes: Mutex::new(vec![path]),
2760 });
2761 (
2762 Box::pin(futures::StreamExt::filter(rx, {
2763 let watcher = watcher.clone();
2764 move |events| {
2765 let result = events.iter().any(|evt_path| {
2766 watcher
2767 .prefixes
2768 .lock()
2769 .iter()
2770 .any(|prefix| evt_path.path.starts_with(prefix))
2771 });
2772 let executor = executor.clone();
2773 async move {
2774 executor.simulate_random_delay().await;
2775 result
2776 }
2777 }
2778 })),
2779 watcher,
2780 )
2781 }
2782
2783 fn open_repo(
2784 &self,
2785 abs_dot_git: &Path,
2786 _system_git_binary: Option<&Path>,
2787 ) -> Option<Arc<dyn GitRepository>> {
2788 use util::ResultExt as _;
2789
2790 self.with_git_state_and_paths(
2791 abs_dot_git,
2792 false,
2793 |_, repository_dir_path, common_dir_path| {
2794 Arc::new(fake_git_repo::FakeGitRepository {
2795 fs: self.this.upgrade().unwrap(),
2796 executor: self.executor.clone(),
2797 dot_git_path: abs_dot_git.to_path_buf(),
2798 repository_dir_path: repository_dir_path.to_owned(),
2799 common_dir_path: common_dir_path.to_owned(),
2800 checkpoints: Arc::default(),
2801 }) as _
2802 },
2803 )
2804 .log_err()
2805 }
2806
2807 async fn git_init(
2808 &self,
2809 abs_work_directory_path: &Path,
2810 _fallback_branch_name: String,
2811 ) -> Result<()> {
2812 self.create_dir(&abs_work_directory_path.join(".git")).await
2813 }
2814
2815 async fn git_clone(&self, _repo_url: &str, _abs_work_directory: &Path) -> Result<()> {
2816 anyhow::bail!("Git clone is not supported in fake Fs")
2817 }
2818
2819 fn is_fake(&self) -> bool {
2820 true
2821 }
2822
2823 async fn is_case_sensitive(&self) -> Result<bool> {
2824 Ok(true)
2825 }
2826
2827 fn subscribe_to_jobs(&self) -> JobEventReceiver {
2828 let (sender, receiver) = futures::channel::mpsc::unbounded();
2829 self.state.lock().job_event_subscribers.lock().push(sender);
2830 receiver
2831 }
2832
2833 #[cfg(feature = "test-support")]
2834 fn as_fake(&self) -> Arc<FakeFs> {
2835 self.this.upgrade().unwrap()
2836 }
2837}
2838
2839pub fn normalize_path(path: &Path) -> PathBuf {
2840 let mut components = path.components().peekable();
2841 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
2842 components.next();
2843 PathBuf::from(c.as_os_str())
2844 } else {
2845 PathBuf::new()
2846 };
2847
2848 for component in components {
2849 match component {
2850 Component::Prefix(..) => unreachable!(),
2851 Component::RootDir => {
2852 ret.push(component.as_os_str());
2853 }
2854 Component::CurDir => {}
2855 Component::ParentDir => {
2856 ret.pop();
2857 }
2858 Component::Normal(c) => {
2859 ret.push(c);
2860 }
2861 }
2862 }
2863 ret
2864}
2865
2866pub async fn copy_recursive<'a>(
2867 fs: &'a dyn Fs,
2868 source: &'a Path,
2869 target: &'a Path,
2870 options: CopyOptions,
2871) -> Result<()> {
2872 for (item, is_dir) in read_dir_items(fs, source).await? {
2873 let Ok(item_relative_path) = item.strip_prefix(source) else {
2874 continue;
2875 };
2876 let target_item = if item_relative_path == Path::new("") {
2877 target.to_path_buf()
2878 } else {
2879 target.join(item_relative_path)
2880 };
2881 if is_dir {
2882 if !options.overwrite && fs.metadata(&target_item).await.is_ok_and(|m| m.is_some()) {
2883 if options.ignore_if_exists {
2884 continue;
2885 } else {
2886 anyhow::bail!("{target_item:?} already exists");
2887 }
2888 }
2889 let _ = fs
2890 .remove_dir(
2891 &target_item,
2892 RemoveOptions {
2893 recursive: true,
2894 ignore_if_not_exists: true,
2895 },
2896 )
2897 .await;
2898 fs.create_dir(&target_item).await?;
2899 } else {
2900 fs.copy_file(&item, &target_item, options).await?;
2901 }
2902 }
2903 Ok(())
2904}
2905
2906/// Recursively reads all of the paths in the given directory.
2907///
2908/// Returns a vector of tuples of (path, is_dir).
2909pub async fn read_dir_items<'a>(fs: &'a dyn Fs, source: &'a Path) -> Result<Vec<(PathBuf, bool)>> {
2910 let mut items = Vec::new();
2911 read_recursive(fs, source, &mut items).await?;
2912 Ok(items)
2913}
2914
2915fn read_recursive<'a>(
2916 fs: &'a dyn Fs,
2917 source: &'a Path,
2918 output: &'a mut Vec<(PathBuf, bool)>,
2919) -> BoxFuture<'a, Result<()>> {
2920 use futures::future::FutureExt;
2921
2922 async move {
2923 let metadata = fs
2924 .metadata(source)
2925 .await?
2926 .with_context(|| format!("path does not exist: {source:?}"))?;
2927
2928 if metadata.is_dir {
2929 output.push((source.to_path_buf(), true));
2930 let mut children = fs.read_dir(source).await?;
2931 while let Some(child_path) = children.next().await {
2932 if let Ok(child_path) = child_path {
2933 read_recursive(fs, &child_path, output).await?;
2934 }
2935 }
2936 } else {
2937 output.push((source.to_path_buf(), false));
2938 }
2939 Ok(())
2940 }
2941 .boxed()
2942}
2943
2944// todo(windows)
2945// can we get file id not open the file twice?
2946// https://github.com/rust-lang/rust/issues/63010
2947#[cfg(target_os = "windows")]
2948async fn file_id(path: impl AsRef<Path>) -> Result<u64> {
2949 use std::os::windows::io::AsRawHandle;
2950
2951 use smol::fs::windows::OpenOptionsExt;
2952 use windows::Win32::{
2953 Foundation::HANDLE,
2954 Storage::FileSystem::{
2955 BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS, GetFileInformationByHandle,
2956 },
2957 };
2958
2959 let file = smol::fs::OpenOptions::new()
2960 .read(true)
2961 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS.0)
2962 .open(path)
2963 .await?;
2964
2965 let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
2966 // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfileinformationbyhandle
2967 // This function supports Windows XP+
2968 smol::unblock(move || {
2969 unsafe { GetFileInformationByHandle(HANDLE(file.as_raw_handle() as _), &mut info)? };
2970
2971 Ok(((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64))
2972 })
2973 .await
2974}
2975
2976#[cfg(target_os = "windows")]
2977fn atomic_replace<P: AsRef<Path>>(
2978 replaced_file: P,
2979 replacement_file: P,
2980) -> windows::core::Result<()> {
2981 use windows::{
2982 Win32::Storage::FileSystem::{REPLACE_FILE_FLAGS, ReplaceFileW},
2983 core::HSTRING,
2984 };
2985
2986 // If the file does not exist, create it.
2987 let _ = std::fs::File::create_new(replaced_file.as_ref());
2988
2989 unsafe {
2990 ReplaceFileW(
2991 &HSTRING::from(replaced_file.as_ref().to_string_lossy().into_owned()),
2992 &HSTRING::from(replacement_file.as_ref().to_string_lossy().into_owned()),
2993 None,
2994 REPLACE_FILE_FLAGS::default(),
2995 None,
2996 None,
2997 )
2998 }
2999}