From 6013e84892100f3a692a6699cef1cc5efb2f838e Mon Sep 17 00:00:00 2001 From: PgBiel <9021226+PgBiel@users.noreply.github.com> Date: Tue, 5 Nov 2024 22:19:38 -0300 Subject: [PATCH] ensure imfs has root --- compiler-core/src/io/memory.rs | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/compiler-core/src/io/memory.rs b/compiler-core/src/io/memory.rs index 989993a1ec4..3910c8d4c31 100644 --- a/compiler-core/src/io/memory.rs +++ b/compiler-core/src/io/memory.rs @@ -19,15 +19,27 @@ use camino::{Utf8Path, Utf8PathBuf}; /// /// Not thread safe. The compiler is single threaded, so that's OK. /// -/// Only supports absolute paths. Additionally, the filesystem is fully empty -/// until the first file is created, so, in particular, the root directory -/// ("/") is not always guaranteed to exist. +/// Only supports absolute paths. The root directory ("/") is always guaranteed +/// to exist. /// -#[derive(Clone, Default, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub struct InMemoryFileSystem { files: Rc>>, } +impl Default for InMemoryFileSystem { + fn default() -> Self { + let mut files = HashMap::new(); + + // Ensure root directory always exists. + let _ = files.insert(Utf8PathBuf::from("/"), InMemoryFile::directory()); + + Self { + files: Rc::new(RefCell::new(files)), + } + } +} + impl InMemoryFileSystem { pub fn new() -> Self { Self::default() @@ -110,7 +122,11 @@ impl FileSystemWriter for InMemoryFileSystem { }); } - let _ = files.remove(path); + if path != Utf8Path::new("/") { + // Ensure the root path always exists. + // Deleting other files is fine. + let _ = files.remove(path); + } // Remove any files in the directory while let Some(file) = files.keys().find(|file| file.starts_with(path)) { @@ -428,6 +444,13 @@ impl BeamCompiler for InMemoryFileSystem { } } +#[test] +fn test_empty_in_memory_fs_has_root() { + let imfs = InMemoryFileSystem::new(); + + assert!(imfs.exists(Utf8Path::new("/"))); +} + #[test] fn test_subpaths_exclude_root() -> Result<(), Error> { let imfs = InMemoryFileSystem::new();