Skip to main content

vvv_engine/vfs/
disk.rs

1use std::path::{Path, PathBuf};
2
3use super::{EntryKind, MoveError, MoveState, ParentCreation, Stamp, Vfs, VfsError};
4
5/// Real file system. Walks respect `.gitignore` and skip hidden entries.
6#[derive(Debug, Default, Clone)]
7pub struct DiskVfs;
8
9impl DiskVfs {
10    pub fn new() -> Self {
11        Self
12    }
13
14    fn io(path: &Path, source: std::io::Error) -> VfsError {
15        match source.kind() {
16            std::io::ErrorKind::NotFound => VfsError::NotFound(path.to_path_buf()),
17            std::io::ErrorKind::AlreadyExists => VfsError::Exists(path.to_path_buf()),
18            _ => VfsError::Io {
19                path: path.to_path_buf(),
20                source,
21            },
22        }
23    }
24}
25
26impl Vfs for DiskVfs {
27    fn read_bytes(&self, path: &Path) -> Result<Vec<u8>, VfsError> {
28        std::fs::read(path).map_err(|error| Self::io(path, error))
29    }
30    fn read(&self, path: &Path) -> Result<String, VfsError> {
31        let bytes = std::fs::read(path).map_err(|e| Self::io(path, e))?;
32        String::from_utf8(bytes).map_err(|_| VfsError::InvalidUtf8 {
33            path: path.to_path_buf(),
34        })
35    }
36
37    fn stamp(&self, path: &Path) -> Result<Stamp, VfsError> {
38        let meta = std::fs::metadata(path).map_err(|e| Self::io(path, e))?;
39        let modified = meta
40            .modified()
41            .ok()
42            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
43            .map_or(0, |d| d.as_nanos());
44        Ok(Stamp::new(modified, meta.len()))
45    }
46
47    fn write(&self, path: &Path, contents: &str) -> Result<(), VfsError> {
48        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
49            std::fs::create_dir_all(parent).map_err(|e| Self::io(parent, e))?;
50        }
51        std::fs::write(path, contents).map_err(|e| Self::io(path, e))
52    }
53
54    fn exists(&self, path: &Path) -> bool {
55        path.exists()
56    }
57
58    fn entry_kind(&self, path: &Path) -> Result<Option<EntryKind>, VfsError> {
59        match std::fs::symlink_metadata(path) {
60            Ok(meta) => Ok(Some(if meta.is_file() {
61                EntryKind::File
62            } else if meta.is_dir() {
63                EntryKind::Directory
64            } else {
65                EntryKind::Other
66            })),
67            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
68            Err(error) => Err(Self::io(path, error)),
69        }
70    }
71
72    fn entry_path(&self, path: &Path) -> Result<Option<PathBuf>, VfsError> {
73        let Some(kind) = self.entry_kind(path)? else {
74            return Ok(None);
75        };
76        let Some(name) = path.file_name() else {
77            return std::fs::canonicalize(path)
78                .map(Some)
79                .map_err(|error| Self::io(path, error));
80        };
81        let parent = path
82            .parent()
83            .filter(|p| !p.as_os_str().is_empty())
84            .unwrap_or(Path::new("."));
85        let requested_parent = parent;
86        let parent = std::fs::canonicalize(parent).map_err(|error| Self::io(parent, error))?;
87        let entries = std::fs::read_dir(&parent)
88            .map_err(|error| Self::io(&parent, error))?
89            .collect::<Result<Vec<_>, _>>()
90            .map_err(|error| Self::io(&parent, error))?;
91        if let Some(entry) = entries.iter().find(|entry| entry.file_name() == name) {
92            return Ok(Some(requested_parent.join(entry.file_name())));
93        }
94        if kind != EntryKind::File {
95            return Err(Self::io(
96                path,
97                std::io::Error::other("cannot determine directory-entry spelling"),
98            ));
99        }
100        let handle = same_file::Handle::from_path(path).map_err(|error| Self::io(path, error))?;
101        let mut matches = Vec::new();
102        let mut folded = Vec::new();
103        for entry in entries {
104            if entry
105                .file_type()
106                .map_err(|error| Self::io(&entry.path(), error))?
107                .is_file()
108                && same_file::Handle::from_path(entry.path())
109                    .is_ok_and(|candidate| candidate == handle)
110            {
111                if entry.file_name().to_string_lossy().to_lowercase()
112                    == name.to_string_lossy().to_lowercase()
113                {
114                    folded.push(requested_parent.join(entry.file_name()));
115                }
116                matches.push(requested_parent.join(entry.file_name()));
117            }
118        }
119        let mut candidates = if folded.is_empty() { matches } else { folded };
120        if candidates.len() == 1 {
121            return Ok(candidates.pop());
122        }
123        Err(Self::io(
124            path,
125            std::io::Error::other("ambiguous directory-entry spelling"),
126        ))
127    }
128
129    fn same_entry(&self, from: &Path, to: &Path) -> Result<bool, VfsError> {
130        let (Some(from), Some(to)) = (self.entry_path(from)?, self.entry_path(to)?) else {
131            return Ok(false);
132        };
133        if from.file_name() != to.file_name() {
134            return Ok(false);
135        }
136        let from_parent = from.parent().unwrap_or(Path::new("."));
137        let to_parent = to.parent().unwrap_or(Path::new("."));
138        let from_handle = same_file::Handle::from_path(from_parent)
139            .map_err(|error| Self::io(from_parent, error))?;
140        let to_handle =
141            same_file::Handle::from_path(to_parent).map_err(|error| Self::io(to_parent, error))?;
142        Ok(from_handle == to_handle)
143    }
144
145    fn names_alias(&self, from: &Path, to: &Path) -> Result<bool, VfsError> {
146        if from == to {
147            return Ok(true);
148        }
149        let (Some(from_name), Some(to_name)) = (from.file_name(), to.file_name()) else {
150            return Ok(false);
151        };
152        if from_name.to_string_lossy().to_lowercase() != to_name.to_string_lossy().to_lowercase() {
153            return Ok(false);
154        }
155        let from_parent = from.parent().unwrap_or(Path::new("."));
156        let to_parent = to.parent().unwrap_or(Path::new("."));
157        // Existing aliases resolve directly. An absent staged name needs the
158        // directory's name policy, read from a real entry without creating a probe.
159        let from_entry = self.entry_path(from)?;
160        let to_entry = self.entry_path(to)?;
161        if from_entry.is_some() || to_entry.is_some() {
162            return self.same_entry(from, to);
163        }
164        let mut parent = from_parent;
165        if from_parent != to_parent
166            && !(same_file::Handle::from_path(from_parent)
167                .ok()
168                .zip(same_file::Handle::from_path(to_parent).ok())
169                .is_some_and(|(from, to)| from == to))
170        {
171            return Ok(false);
172        }
173        while !parent.exists() {
174            parent = parent.parent().ok_or_else(|| {
175                Self::io(
176                    from,
177                    std::io::Error::other("no existing ancestor for name policy"),
178                )
179            })?;
180        }
181        let entries = std::fs::read_dir(parent)
182            .map_err(|error| Self::io(parent, error))?
183            .collect::<Result<Vec<_>, _>>()
184            .map_err(|error| Self::io(parent, error))?;
185        for entry in &entries {
186            let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
187                continue;
188            };
189            let alternative: String = name
190                .chars()
191                .map(|ch| {
192                    if ch.is_ascii_lowercase() {
193                        ch.to_ascii_uppercase()
194                    } else {
195                        ch.to_ascii_lowercase()
196                    }
197                })
198                .collect();
199            if name == alternative {
200                continue;
201            }
202            // An actual second directory entry (including a hard link) proves
203            // these spellings are distinct; inode identity alone is insufficient.
204            if entries
205                .iter()
206                .any(|candidate| candidate.file_name() == std::ffi::OsStr::new(&alternative))
207            {
208                return Ok(false);
209            }
210            return parent
211                .join(alternative)
212                .try_exists()
213                .map_err(|error| Self::io(parent, error));
214        }
215        Err(Self::io(
216            parent,
217            std::io::Error::new(
218                std::io::ErrorKind::Unsupported,
219                "cannot determine directory name policy without an existing cased entry",
220            ),
221        ))
222    }
223
224    fn prepare_parent(&self, path: &Path) -> ParentCreation {
225        let mut created = Vec::new();
226        let parents: Vec<_> = path
227            .parent()
228            .into_iter()
229            .flat_map(Path::ancestors)
230            .filter(|parent| !parent.as_os_str().is_empty())
231            .collect();
232        for parent in parents.into_iter().rev() {
233            // Windows can return AccessDenied when asked to create an existing
234            // drive root. Existing ancestors are not directories we own.
235            match std::fs::metadata(parent) {
236                Ok(meta) if meta.is_dir() => continue,
237                Ok(_) => {
238                    return ParentCreation::new(
239                        created,
240                        Err(VfsError::Exists(parent.to_path_buf())),
241                    );
242                }
243                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
244                Err(error) => return ParentCreation::new(created, Err(Self::io(parent, error))),
245            }
246            match std::fs::create_dir(parent) {
247                Ok(()) => created.push(parent.to_path_buf()),
248                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
249                    match std::fs::metadata(parent) {
250                        Ok(meta) if meta.is_dir() => {}
251                        Ok(_) => return ParentCreation::new(created, Err(Self::io(parent, error))),
252                        Err(error) => {
253                            return ParentCreation::new(created, Err(Self::io(parent, error)));
254                        }
255                    }
256                }
257                Err(error) => return ParentCreation::new(created, Err(Self::io(parent, error))),
258            }
259        }
260        ParentCreation::new(created, Ok(()))
261    }
262
263    fn create_dir(&self, path: &Path) -> Result<(), VfsError> {
264        std::fs::create_dir(path).map_err(|error| Self::io(path, error))
265    }
266
267    fn remove_file(&self, path: &Path) -> Result<(), VfsError> {
268        std::fs::remove_file(path).map_err(|error| Self::io(path, error))
269    }
270
271    fn remove_empty_dir(&self, path: &Path) -> Result<(), VfsError> {
272        std::fs::remove_dir(path).map_err(|error| Self::io(path, error))
273    }
274
275    fn move_if_absent(&self, from: &Path, to: &Path) -> Result<(), MoveError> {
276        DiskMove::new(from, to)?.apply()
277    }
278
279    fn walk(&self, root: &Path) -> Result<Vec<PathBuf>, VfsError> {
280        // The parallel walker is what makes ripgrep's traversal fast; on a
281        // large tree the serial one costs more than reading every file.
282        // Each thread collects into its own buffer and hands it over once.
283        let all = std::sync::Mutex::new(Vec::new());
284        ignore::WalkBuilder::new(root).build_parallel().run(|| {
285            let mut mine = Buffer {
286                paths: Vec::new(),
287                all: &all,
288            };
289            Box::new(move |entry| {
290                if let Ok(entry) = entry
291                    && entry.file_type().is_some_and(|t| t.is_file())
292                {
293                    mine.paths.push(entry.into_path());
294                }
295                ignore::WalkState::Continue
296            })
297        });
298        let mut files = all.into_inner().expect("walk lock");
299        files.sort();
300        Ok(files)
301    }
302}
303
304/// Owns the paths and source identity of one destination-preserving disk move.
305struct DiskMove<'a> {
306    from: &'a Path,
307    to: &'a Path,
308    source: same_file::Handle,
309}
310
311impl<'a> DiskMove<'a> {
312    fn new(from: &'a Path, to: &'a Path) -> Result<Self, MoveError> {
313        let metadata = std::fs::symlink_metadata(from)
314            .map_err(|error| MoveError::new(DiskVfs::io(from, error), MoveState::Unchanged))?;
315        if !metadata.is_file() {
316            return Err(MoveError::new(
317                DiskVfs::io(
318                    from,
319                    std::io::Error::new(
320                        std::io::ErrorKind::InvalidInput,
321                        "moves require a regular file",
322                    ),
323                ),
324                MoveState::Unchanged,
325            ));
326        }
327        let source = same_file::Handle::from_path(from)
328            .map_err(|error| MoveError::new(DiskVfs::io(from, error), MoveState::Unchanged))?;
329        Ok(Self { from, to, source })
330    }
331
332    fn apply(&self) -> Result<(), MoveError> {
333        // Some native rename implementations accept distinct hard links to the
334        // same file as a successful no-op. They are still occupied destinations.
335        match std::fs::symlink_metadata(self.to) {
336            Ok(_) => {
337                return Err(MoveError::new(
338                    VfsError::Exists(self.to.to_path_buf()),
339                    MoveState::Unchanged,
340                ));
341            }
342            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
343            Err(error) => return Err(self.failure(error)),
344        }
345        match self.native() {
346            Ok(()) => self.verify_moved(),
347            Err(error) if self.unsupported(&error) => self.link()?.finish(),
348            Err(error) => Err(self.failure(error)),
349        }
350    }
351
352    fn verify_moved(&self) -> Result<(), MoveError> {
353        // The native operation protects against destinations created after the
354        // check above. A racing hard link can also produce a successful no-op;
355        // only source removal satisfies the Vfs success contract.
356        match std::fs::symlink_metadata(self.from) {
357            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
358            Ok(_) => Err(self.failure(std::io::Error::other(
359                "native move returned success without removing the source",
360            ))),
361            Err(error) => Err(self.failure(error)),
362        }
363    }
364
365    #[cfg(any(
366        target_os = "linux",
367        target_os = "android",
368        target_os = "macos",
369        target_os = "ios"
370    ))]
371    fn native(&self) -> std::io::Result<()> {
372        rustix::fs::renameat_with(
373            rustix::fs::CWD,
374            self.from,
375            rustix::fs::CWD,
376            self.to,
377            rustix::fs::RenameFlags::NOREPLACE,
378        )
379        .map_err(Into::into)
380    }
381
382    #[cfg(windows)]
383    fn native(&self) -> std::io::Result<()> {
384        use std::os::windows::ffi::OsStrExt;
385        if self
386            .from
387            .as_os_str()
388            .encode_wide()
389            .chain(self.to.as_os_str().encode_wide())
390            .any(|unit| unit == 0)
391        {
392            return Err(std::io::Error::new(
393                std::io::ErrorKind::InvalidInput,
394                "a path contains NUL",
395            ));
396        }
397        // Canonical parents retain lossless OS spelling and the extended-length
398        // prefix, without canonicalizing away the requested destination name.
399        let absolute = |path: &Path| -> std::io::Result<PathBuf> {
400            let parent = path
401                .parent()
402                .filter(|parent| !parent.as_os_str().is_empty())
403                .unwrap_or(Path::new("."));
404            let name = path.file_name().ok_or_else(|| {
405                std::io::Error::new(
406                    std::io::ErrorKind::InvalidInput,
407                    "a move requires a file name",
408                )
409            })?;
410            Ok(std::fs::canonicalize(parent)?.join(name))
411        };
412        atomicwrites::move_atomic(&absolute(self.from)?, &absolute(self.to)?)
413    }
414
415    #[cfg(not(any(
416        target_os = "linux",
417        target_os = "android",
418        target_os = "macos",
419        target_os = "ios",
420        windows
421    )))]
422    fn native(&self) -> std::io::Result<()> {
423        Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
424    }
425
426    fn unsupported(&self, error: &std::io::Error) -> bool {
427        #[cfg(any(
428            target_os = "linux",
429            target_os = "android",
430            target_os = "macos",
431            target_os = "ios"
432        ))]
433        {
434            let Some(raw) = error.raw_os_error() else {
435                return false;
436            };
437            let code = rustix::io::Errno::from_raw_os_error(raw);
438            code == rustix::io::Errno::NOSYS
439                || code == rustix::io::Errno::NOTSUP
440                || code == rustix::io::Errno::INVAL
441        }
442        #[cfg(not(any(
443            target_os = "linux",
444            target_os = "android",
445            target_os = "macos",
446            target_os = "ios"
447        )))]
448        {
449            error.kind() == std::io::ErrorKind::Unsupported
450        }
451    }
452
453    fn failure(&self, error: std::io::Error) -> MoveError {
454        let unchanged =
455            same_file::Handle::from_path(self.from).is_ok_and(|handle| handle == self.source);
456        if unchanged && std::fs::symlink_metadata(self.to).is_ok() {
457            return MoveError::new(
458                VfsError::Exists(self.to.to_path_buf()),
459                MoveState::Unchanged,
460            );
461        }
462        let destination_is_source =
463            same_file::Handle::from_path(self.to).is_ok_and(|handle| handle == self.source);
464        let state = if !unchanged
465            && destination_is_source
466            && error.kind() != std::io::ErrorKind::AlreadyExists
467        {
468            MoveState::Moved
469        } else if unchanged {
470            MoveState::Unchanged
471        } else {
472            MoveState::Unknown
473        };
474        let path = if error.kind() == std::io::ErrorKind::AlreadyExists {
475            self.to
476        } else {
477            self.from
478        };
479        MoveError::new(DiskVfs::io(path, error), state)
480    }
481
482    fn link(&self) -> Result<LinkedMove<'_>, MoveError> {
483        std::fs::hard_link(self.from, self.to).map_err(|error| {
484            // A link error may have completed remotely. If the destination now
485            // names the source inode, retain uncertainty instead of claiming no effect.
486            if same_file::Handle::from_path(self.to).is_ok_and(|handle| handle == self.source) {
487                MoveError::new(DiskVfs::io(self.to, error), MoveState::Unknown)
488            } else {
489                self.failure(error)
490            }
491        })?;
492        Ok(LinkedMove { from: self.from })
493    }
494}
495
496struct LinkedMove<'a> {
497    from: &'a Path,
498}
499
500impl LinkedMove<'_> {
501    fn finish(self) -> Result<(), MoveError> {
502        std::fs::remove_file(self.from).map_err(|error| {
503            MoveError::new(DiskVfs::io(self.from, error), MoveState::DestinationLinked)
504        })
505    }
506}
507
508/// One walker thread's paths, merged into the shared list when the thread
509/// is done with them.
510struct Buffer<'a> {
511    paths: Vec<PathBuf>,
512    all: &'a std::sync::Mutex<Vec<PathBuf>>,
513}
514
515impl Drop for Buffer<'_> {
516    fn drop(&mut self) {
517        self.all.lock().expect("walk lock").append(&mut self.paths);
518    }
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    struct Fixture {
526        root: PathBuf,
527    }
528    impl Fixture {
529        fn new() -> Self {
530            static IDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
531            let root = std::env::temp_dir().join(format!(
532                "vvv-disk-move-{}-{}",
533                std::process::id(),
534                IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
535            ));
536            std::fs::create_dir_all(&root).unwrap();
537            Self { root }
538        }
539        fn path(&self, name: &str) -> PathBuf {
540            self.root.join(name)
541        }
542    }
543    impl Drop for Fixture {
544        fn drop(&mut self) {
545            std::fs::remove_dir_all(&self.root).unwrap();
546        }
547    }
548
549    #[test]
550    fn disk_moves_preserve_occupied_files_and_directories() {
551        let fixture = Fixture::new();
552        let source = fixture.path("source");
553        let file = fixture.path("file");
554        let dir = fixture.path("dir");
555        std::fs::write(&source, "source").unwrap();
556        std::fs::write(&file, "foreign").unwrap();
557        std::fs::create_dir(&dir).unwrap();
558        for destination in [&file, &dir] {
559            let error = DiskVfs.move_if_absent(&source, destination).unwrap_err();
560            assert_eq!(error.state, MoveState::Unchanged);
561            assert!(matches!(error.source, VfsError::Exists(_)));
562            assert_eq!(std::fs::read_to_string(&source).unwrap(), "source");
563        }
564        assert_eq!(std::fs::read_to_string(file).unwrap(), "foreign");
565        assert!(dir.is_dir());
566    }
567
568    #[test]
569    fn disk_moves_refuse_a_distinct_hard_link_to_the_source() {
570        let fixture = Fixture::new();
571        let source = fixture.path("source");
572        let destination = fixture.path("destination");
573        std::fs::write(&source, "source").unwrap();
574        std::fs::hard_link(&source, &destination).unwrap();
575        let error = DiskVfs.move_if_absent(&source, &destination).unwrap_err();
576        assert_eq!(error.state, MoveState::Unchanged);
577        assert!(matches!(error.source, VfsError::Exists(_)));
578        assert!(source.exists() && destination.exists());
579    }
580
581    #[test]
582    fn a_native_noop_preserves_a_racing_hard_link_and_reports_an_error() {
583        let fixture = Fixture::new();
584        let source = fixture.path("source");
585        let destination = fixture.path("destination");
586        std::fs::write(&source, "source").unwrap();
587        let request = DiskMove::new(&source, &destination).unwrap();
588        std::fs::hard_link(&source, &destination).unwrap();
589        let error = request.verify_moved().unwrap_err();
590        assert_eq!(error.state, MoveState::Unchanged);
591        assert!(matches!(error.source, VfsError::Exists(_)));
592        assert_eq!(std::fs::read_to_string(source).unwrap(), "source");
593        assert_eq!(std::fs::read_to_string(destination).unwrap(), "source");
594    }
595
596    #[test]
597    fn parent_preparation_records_only_new_directories() {
598        let fixture = Fixture::new();
599        let vfs = DiskVfs;
600        let existing = vfs.prepare_parent(&fixture.path("file"));
601        existing.result.unwrap();
602        assert!(existing.created.is_empty());
603
604        let nested = vfs.prepare_parent(&fixture.path("a/b/file"));
605        nested.result.unwrap();
606        assert_eq!(nested.created, vec![fixture.path("a"), fixture.path("a/b")]);
607        let repeated = vfs.prepare_parent(&fixture.path("a/b/other"));
608        repeated.result.unwrap();
609        assert!(repeated.created.is_empty());
610    }
611
612    #[test]
613    fn parent_preparation_preserves_a_file_in_its_ancestry() {
614        let fixture = Fixture::new();
615        let occupied = fixture.path("occupied");
616        std::fs::write(&occupied, "foreign").unwrap();
617        let outcome = DiskVfs.prepare_parent(&occupied.join("child"));
618        assert!(outcome.created.is_empty());
619        assert!(matches!(outcome.result, Err(VfsError::Exists(path)) if path == occupied));
620        assert_eq!(std::fs::read_to_string(occupied).unwrap(), "foreign");
621    }
622
623    #[cfg(unix)]
624    #[test]
625    fn disk_moves_preserve_a_dangling_destination_symlink() {
626        let fixture = Fixture::new();
627        let source = fixture.path("source");
628        let destination = fixture.path("destination");
629        let target = fixture.path("missing");
630        std::fs::write(&source, "source").unwrap();
631        std::os::unix::fs::symlink(&target, &destination).unwrap();
632        assert!(matches!(
633            DiskVfs
634                .move_if_absent(&source, &destination)
635                .unwrap_err()
636                .source,
637            VfsError::Exists(_)
638        ));
639        assert_eq!(std::fs::read_link(destination).unwrap(), target);
640        assert_eq!(std::fs::read_to_string(source).unwrap(), "source");
641    }
642
643    #[test]
644    fn fallback_links_preserve_an_occupied_destination() {
645        let fixture = Fixture::new();
646        let source = fixture.path("source");
647        let destination = fixture.path("destination");
648        std::fs::write(&source, "source").unwrap();
649        std::fs::write(&destination, "foreign").unwrap();
650        let error = DiskMove::new(&source, &destination)
651            .unwrap()
652            .link()
653            .err()
654            .unwrap();
655        assert_eq!(error.state, MoveState::Unchanged);
656        assert_eq!(std::fs::read_to_string(source).unwrap(), "source");
657        assert_eq!(std::fs::read_to_string(destination).unwrap(), "foreign");
658    }
659
660    #[test]
661    fn fallback_moves_transfer_the_source_without_replacing_a_destination() {
662        let fixture = Fixture::new();
663        let source = fixture.path("source");
664        let destination = fixture.path("destination");
665        std::fs::write(&source, "source").unwrap();
666        DiskMove::new(&source, &destination)
667            .unwrap()
668            .link()
669            .unwrap()
670            .finish()
671            .unwrap();
672        assert!(!source.exists());
673        assert_eq!(std::fs::read_to_string(destination).unwrap(), "source");
674    }
675
676    #[test]
677    fn fallback_reports_both_names_when_source_removal_fails() {
678        let fixture = Fixture::new();
679        let source = fixture.path("source");
680        let destination = fixture.path("destination");
681        std::fs::write(&source, "source").unwrap();
682        let request = DiskMove::new(&source, &destination).unwrap();
683        let linked = request.link().unwrap();
684        std::fs::remove_file(&source).unwrap();
685        std::fs::create_dir(&source).unwrap();
686        let error = linked.finish().unwrap_err();
687        assert_eq!(error.state, MoveState::DestinationLinked);
688        assert_eq!(std::fs::read_to_string(destination).unwrap(), "source");
689        assert!(source.is_dir());
690    }
691
692    #[test]
693    fn write_and_rename_create_parent_directories() {
694        let root = std::env::temp_dir().join(format!("vvv-disk-vfs-{}", std::process::id()));
695        let vfs = DiskVfs::new();
696        let deep = root.join("a/b/c.txt");
697        vfs.write(&deep, "hi").unwrap();
698        assert_eq!(vfs.read(&deep).unwrap(), "hi");
699        let moved = root.join("x/y/z.txt");
700        vfs.prepare_parent(&moved).result.unwrap();
701        vfs.move_if_absent(&deep, &moved).unwrap();
702        assert!(!vfs.exists(&deep));
703        assert_eq!(vfs.read(&moved).unwrap(), "hi");
704        std::fs::remove_dir_all(&root).unwrap();
705    }
706}