Use synchronous locks in FakeFs

This way, the state can be accessed without running the deterministic
executor.
This commit is contained in:
Max Brunsfeld 2023-04-03 18:15:07 -07:00
parent f95732e981
commit 5ecc9606af
3 changed files with 149 additions and 171 deletions

View File

@ -624,7 +624,7 @@ async fn apply_client_operation(
); );
ensure_project_shared(&project, client, cx).await; ensure_project_shared(&project, client, cx).await;
if !client.fs.paths().await.contains(&new_root_path) { if !client.fs.paths().contains(&new_root_path) {
client.fs.create_dir(&new_root_path).await.unwrap(); client.fs.create_dir(&new_root_path).await.unwrap();
} }
project project
@ -1350,7 +1350,6 @@ impl TestPlan {
return None; return None;
} }
let executor = cx.background();
self.operation_ix += 1; self.operation_ix += 1;
let call = cx.read(ActiveCall::global); let call = cx.read(ActiveCall::global);
Some(loop { Some(loop {
@ -1467,7 +1466,7 @@ impl TestPlan {
.choose(&mut self.rng) .choose(&mut self.rng)
.cloned() else { continue }; .cloned() else { continue };
let project_root_name = root_name_for_project(&project, cx); let project_root_name = root_name_for_project(&project, cx);
let mut paths = executor.block(client.fs.paths()); let mut paths = client.fs.paths();
paths.remove(0); paths.remove(0);
let new_root_path = if paths.is_empty() || self.rng.gen() { let new_root_path = if paths.is_empty() || self.rng.gen() {
Path::new("/").join(&self.next_root_dir_name(user_id)) Path::new("/").join(&self.next_root_dir_name(user_id))
@ -1637,14 +1636,16 @@ impl TestPlan {
// Update a git index // Update a git index
91..=95 => { 91..=95 => {
let repo_path = executor let repo_path = client
.block(client.fs.directories()) .fs
.directories()
.choose(&mut self.rng) .choose(&mut self.rng)
.unwrap() .unwrap()
.clone(); .clone();
let mut file_paths = executor let mut file_paths = client
.block(client.fs.files()) .fs
.files()
.into_iter() .into_iter()
.filter(|path| path.starts_with(&repo_path)) .filter(|path| path.starts_with(&repo_path))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -1673,7 +1674,7 @@ impl TestPlan {
let is_dir = self.rng.gen::<bool>(); let is_dir = self.rng.gen::<bool>();
let content; let content;
let mut path; let mut path;
let dir_paths = cx.background().block(client.fs.directories()); let dir_paths = client.fs.directories();
if is_dir { if is_dir {
content = String::new(); content = String::new();
@ -1683,7 +1684,7 @@ impl TestPlan {
content = Alphanumeric.sample_string(&mut self.rng, 16); content = Alphanumeric.sample_string(&mut self.rng, 16);
// Create a new file or overwrite an existing file // Create a new file or overwrite an existing file
let file_paths = cx.background().block(client.fs.files()); let file_paths = client.fs.files();
if file_paths.is_empty() || self.rng.gen_bool(0.5) { if file_paths.is_empty() || self.rng.gen_bool(0.5) {
path = dir_paths.choose(&mut self.rng).unwrap().clone(); path = dir_paths.choose(&mut self.rng).unwrap().clone();
path.push(gen_file_name(&mut self.rng)); path.push(gen_file_name(&mut self.rng));
@ -1789,7 +1790,7 @@ async fn simulate_client(
let fs = fs.clone(); let fs = fs.clone();
let plan = plan.clone(); let plan = plan.clone();
async move { async move {
let files = fs.files().await; let files = fs.files();
let count = plan.lock().rng.gen_range::<usize, _>(1..3); let count = plan.lock().rng.gen_range::<usize, _>(1..3);
let files = (0..count) let files = (0..count)
.map(|_| files.choose(&mut plan.lock().rng).unwrap()) .map(|_| files.choose(&mut plan.lock().rng).unwrap())

View File

@ -5,7 +5,7 @@ use fsevent::EventStream;
use futures::{future::BoxFuture, Stream, StreamExt}; use futures::{future::BoxFuture, Stream, StreamExt};
use git2::Repository as LibGitRepository; use git2::Repository as LibGitRepository;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use parking_lot::Mutex as SyncMutex; use parking_lot::Mutex;
use regex::Regex; use regex::Regex;
use repository::GitRepository; use repository::GitRepository;
use rope::Rope; use rope::Rope;
@ -27,8 +27,6 @@ use util::ResultExt;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use collections::{btree_map, BTreeMap}; use collections::{btree_map, BTreeMap};
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use futures::lock::Mutex;
#[cfg(any(test, feature = "test-support"))]
use repository::FakeGitRepositoryState; use repository::FakeGitRepositoryState;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
use std::sync::Weak; use std::sync::Weak;
@ -117,7 +115,7 @@ pub trait Fs: Send + Sync {
path: &Path, path: &Path,
latency: Duration, latency: Duration,
) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>; ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>>;
fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<SyncMutex<dyn GitRepository>>>; fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>>;
fn is_fake(&self) -> bool; fn is_fake(&self) -> bool;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
fn as_fake(&self) -> &FakeFs; fn as_fake(&self) -> &FakeFs;
@ -350,11 +348,11 @@ impl Fs for RealFs {
}))) })))
} }
fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<SyncMutex<dyn GitRepository>>> { fn open_repo(&self, dotgit_path: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
LibGitRepository::open(&dotgit_path) LibGitRepository::open(&dotgit_path)
.log_err() .log_err()
.and_then::<Arc<SyncMutex<dyn GitRepository>>, _>(|libgit_repository| { .and_then::<Arc<Mutex<dyn GitRepository>>, _>(|libgit_repository| {
Some(Arc::new(SyncMutex::new(libgit_repository))) Some(Arc::new(Mutex::new(libgit_repository)))
}) })
} }
@ -396,7 +394,7 @@ enum FakeFsEntry {
inode: u64, inode: u64,
mtime: SystemTime, mtime: SystemTime,
entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>, entries: BTreeMap<String, Arc<Mutex<FakeFsEntry>>>,
git_repo_state: Option<Arc<SyncMutex<repository::FakeGitRepositoryState>>>, git_repo_state: Option<Arc<Mutex<repository::FakeGitRepositoryState>>>,
}, },
Symlink { Symlink {
target: PathBuf, target: PathBuf,
@ -405,18 +403,14 @@ enum FakeFsEntry {
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
impl FakeFsState { impl FakeFsState {
async fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> { fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
Ok(self Ok(self
.try_read_path(target) .try_read_path(target)
.await
.ok_or_else(|| anyhow!("path does not exist: {}", target.display()))? .ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
.0) .0)
} }
async fn try_read_path<'a>( fn try_read_path<'a>(&'a self, target: &Path) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
&'a self,
target: &Path,
) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
let mut path = target.to_path_buf(); let mut path = target.to_path_buf();
let mut real_path = PathBuf::new(); let mut real_path = PathBuf::new();
let mut entry_stack = Vec::new(); let mut entry_stack = Vec::new();
@ -438,10 +432,10 @@ impl FakeFsState {
} }
Component::Normal(name) => { Component::Normal(name) => {
let current_entry = entry_stack.last().cloned()?; let current_entry = entry_stack.last().cloned()?;
let current_entry = current_entry.lock().await; let current_entry = current_entry.lock();
if let FakeFsEntry::Dir { entries, .. } = &*current_entry { if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
let entry = entries.get(name.to_str().unwrap()).cloned()?; let entry = entries.get(name.to_str().unwrap()).cloned()?;
let _entry = entry.lock().await; let _entry = entry.lock();
if let FakeFsEntry::Symlink { target, .. } = &*_entry { if let FakeFsEntry::Symlink { target, .. } = &*_entry {
let mut target = target.clone(); let mut target = target.clone();
target.extend(path_components); target.extend(path_components);
@ -462,7 +456,7 @@ impl FakeFsState {
entry_stack.pop().map(|entry| (entry, real_path)) entry_stack.pop().map(|entry| (entry, real_path))
} }
async fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T> fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
where where
Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>, Fn: FnOnce(btree_map::Entry<String, Arc<Mutex<FakeFsEntry>>>) -> Result<T>,
{ {
@ -472,8 +466,8 @@ impl FakeFsState {
.ok_or_else(|| anyhow!("cannot overwrite the root"))?; .ok_or_else(|| anyhow!("cannot overwrite the root"))?;
let parent_path = path.parent().unwrap(); let parent_path = path.parent().unwrap();
let parent = self.read_path(parent_path).await?; let parent = self.read_path(parent_path)?;
let mut parent = parent.lock().await; let mut parent = parent.lock();
let new_entry = parent let new_entry = parent
.dir_entries(parent_path)? .dir_entries(parent_path)?
.entry(filename.to_str().unwrap().into()); .entry(filename.to_str().unwrap().into());
@ -529,7 +523,7 @@ impl FakeFs {
} }
pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) { pub async fn insert_file(&self, path: impl AsRef<Path>, content: String) {
let mut state = self.state.lock().await; let mut state = self.state.lock();
let path = path.as_ref(); let path = path.as_ref();
let inode = state.next_inode; let inode = state.next_inode;
let mtime = state.next_mtime; let mtime = state.next_mtime;
@ -552,13 +546,12 @@ impl FakeFs {
} }
Ok(()) Ok(())
}) })
.await
.unwrap(); .unwrap();
state.emit_event(&[path]); state.emit_event(&[path]);
} }
pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) { pub async fn insert_symlink(&self, path: impl AsRef<Path>, target: PathBuf) {
let mut state = self.state.lock().await; let mut state = self.state.lock();
let path = path.as_ref(); let path = path.as_ref();
let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target })); let file = Arc::new(Mutex::new(FakeFsEntry::Symlink { target }));
state state
@ -572,21 +565,20 @@ impl FakeFs {
Ok(()) Ok(())
} }
}) })
.await
.unwrap(); .unwrap();
state.emit_event(&[path]); state.emit_event(&[path]);
} }
pub async fn pause_events(&self) { pub async fn pause_events(&self) {
self.state.lock().await.events_paused = true; self.state.lock().events_paused = true;
} }
pub async fn buffered_event_count(&self) -> usize { pub async fn buffered_event_count(&self) -> usize {
self.state.lock().await.buffered_events.len() self.state.lock().buffered_events.len()
} }
pub async fn flush_events(&self, count: usize) { pub async fn flush_events(&self, count: usize) {
self.state.lock().await.flush_events(count); self.state.lock().flush_events(count);
} }
#[must_use] #[must_use]
@ -625,9 +617,9 @@ impl FakeFs {
} }
pub async fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) { pub async fn set_index_for_repo(&self, dot_git: &Path, head_state: &[(&Path, String)]) {
let mut state = self.state.lock().await; let mut state = self.state.lock();
let entry = state.read_path(dot_git).await.unwrap(); let entry = state.read_path(dot_git).unwrap();
let mut entry = entry.lock().await; let mut entry = entry.lock();
if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry { if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
let repo_state = git_repo_state.get_or_insert_with(Default::default); let repo_state = git_repo_state.get_or_insert_with(Default::default);
@ -646,12 +638,12 @@ impl FakeFs {
} }
} }
pub async fn paths(&self) -> Vec<PathBuf> { pub fn paths(&self) -> Vec<PathBuf> {
let mut result = Vec::new(); let mut result = Vec::new();
let mut queue = collections::VecDeque::new(); let mut queue = collections::VecDeque::new();
queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone())); queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
while let Some((path, entry)) = queue.pop_front() { while let Some((path, entry)) = queue.pop_front() {
if let FakeFsEntry::Dir { entries, .. } = &*entry.lock().await { if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
for (name, entry) in entries { for (name, entry) in entries {
queue.push_back((path.join(name), entry.clone())); queue.push_back((path.join(name), entry.clone()));
} }
@ -661,12 +653,12 @@ impl FakeFs {
result result
} }
pub async fn directories(&self) -> Vec<PathBuf> { pub fn directories(&self) -> Vec<PathBuf> {
let mut result = Vec::new(); let mut result = Vec::new();
let mut queue = collections::VecDeque::new(); let mut queue = collections::VecDeque::new();
queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone())); queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
while let Some((path, entry)) = queue.pop_front() { while let Some((path, entry)) = queue.pop_front() {
if let FakeFsEntry::Dir { entries, .. } = &*entry.lock().await { if let FakeFsEntry::Dir { entries, .. } = &*entry.lock() {
for (name, entry) in entries { for (name, entry) in entries {
queue.push_back((path.join(name), entry.clone())); queue.push_back((path.join(name), entry.clone()));
} }
@ -676,12 +668,12 @@ impl FakeFs {
result result
} }
pub async fn files(&self) -> Vec<PathBuf> { pub fn files(&self) -> Vec<PathBuf> {
let mut result = Vec::new(); let mut result = Vec::new();
let mut queue = collections::VecDeque::new(); let mut queue = collections::VecDeque::new();
queue.push_back((PathBuf::from("/"), self.state.lock().await.root.clone())); queue.push_back((PathBuf::from("/"), self.state.lock().root.clone()));
while let Some((path, entry)) = queue.pop_front() { while let Some((path, entry)) = queue.pop_front() {
let e = entry.lock().await; let e = entry.lock();
match &*e { match &*e {
FakeFsEntry::File { .. } => result.push(path), FakeFsEntry::File { .. } => result.push(path),
FakeFsEntry::Dir { entries, .. } => { FakeFsEntry::Dir { entries, .. } => {
@ -745,11 +737,11 @@ impl FakeFsEntry {
impl Fs for FakeFs { impl Fs for FakeFs {
async fn create_dir(&self, path: &Path) -> Result<()> { async fn create_dir(&self, path: &Path) -> Result<()> {
self.simulate_random_delay().await; self.simulate_random_delay().await;
let mut state = self.state.lock().await;
let mut created_dirs = Vec::new(); let mut created_dirs = Vec::new();
let mut cur_path = PathBuf::new(); let mut cur_path = PathBuf::new();
for component in path.components() { for component in path.components() {
let mut state = self.state.lock();
cur_path.push(component); cur_path.push(component);
if cur_path == Path::new("/") { if cur_path == Path::new("/") {
continue; continue;
@ -759,29 +751,27 @@ impl Fs for FakeFs {
let mtime = state.next_mtime; let mtime = state.next_mtime;
state.next_mtime += Duration::from_nanos(1); state.next_mtime += Duration::from_nanos(1);
state.next_inode += 1; state.next_inode += 1;
state state.write_path(&cur_path, |entry| {
.write_path(&cur_path, |entry| { entry.or_insert_with(|| {
entry.or_insert_with(|| { created_dirs.push(cur_path.clone());
created_dirs.push(cur_path.clone()); Arc::new(Mutex::new(FakeFsEntry::Dir {
Arc::new(Mutex::new(FakeFsEntry::Dir { inode,
inode, mtime,
mtime, entries: Default::default(),
entries: Default::default(), git_repo_state: None,
git_repo_state: None, }))
})) });
}); Ok(())
Ok(()) })?
})
.await?;
} }
state.emit_event(&created_dirs); self.state.lock().emit_event(&created_dirs);
Ok(()) Ok(())
} }
async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> { async fn create_file(&self, path: &Path, options: CreateOptions) -> Result<()> {
self.simulate_random_delay().await; self.simulate_random_delay().await;
let mut state = self.state.lock().await; let mut state = self.state.lock();
let inode = state.next_inode; let inode = state.next_inode;
let mtime = state.next_mtime; let mtime = state.next_mtime;
state.next_mtime += Duration::from_nanos(1); state.next_mtime += Duration::from_nanos(1);
@ -791,23 +781,21 @@ impl Fs for FakeFs {
mtime, mtime,
content: String::new(), content: String::new(),
})); }));
state state.write_path(path, |entry| {
.write_path(path, |entry| { match entry {
match entry { btree_map::Entry::Occupied(mut e) => {
btree_map::Entry::Occupied(mut e) => { if options.overwrite {
if options.overwrite { *e.get_mut() = file;
*e.get_mut() = file; } else if !options.ignore_if_exists {
} else if !options.ignore_if_exists { return Err(anyhow!("path already exists: {}", path.display()));
return Err(anyhow!("path already exists: {}", path.display()));
}
}
btree_map::Entry::Vacant(e) => {
e.insert(file);
} }
} }
Ok(()) btree_map::Entry::Vacant(e) => {
}) e.insert(file);
.await?; }
}
Ok(())
})?;
state.emit_event(&[path]); state.emit_event(&[path]);
Ok(()) Ok(())
} }
@ -815,33 +803,29 @@ impl Fs for FakeFs {
async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> { async fn rename(&self, old_path: &Path, new_path: &Path, options: RenameOptions) -> Result<()> {
let old_path = normalize_path(old_path); let old_path = normalize_path(old_path);
let new_path = normalize_path(new_path); let new_path = normalize_path(new_path);
let mut state = self.state.lock().await; let mut state = self.state.lock();
let moved_entry = state let moved_entry = state.write_path(&old_path, |e| {
.write_path(&old_path, |e| { if let btree_map::Entry::Occupied(e) = e {
if let btree_map::Entry::Occupied(e) = e { Ok(e.remove())
Ok(e.remove()) } else {
} else { Err(anyhow!("path does not exist: {}", &old_path.display()))
Err(anyhow!("path does not exist: {}", &old_path.display())) }
} })?;
}) state.write_path(&new_path, |e| {
.await?; match e {
state btree_map::Entry::Occupied(mut e) => {
.write_path(&new_path, |e| { if options.overwrite {
match e { *e.get_mut() = moved_entry;
btree_map::Entry::Occupied(mut e) => { } else if !options.ignore_if_exists {
if options.overwrite { return Err(anyhow!("path already exists: {}", new_path.display()));
*e.get_mut() = moved_entry;
} else if !options.ignore_if_exists {
return Err(anyhow!("path already exists: {}", new_path.display()));
}
}
btree_map::Entry::Vacant(e) => {
e.insert(moved_entry);
} }
} }
Ok(()) btree_map::Entry::Vacant(e) => {
}) e.insert(moved_entry);
.await?; }
}
Ok(())
})?;
state.emit_event(&[old_path, new_path]); state.emit_event(&[old_path, new_path]);
Ok(()) Ok(())
} }
@ -849,35 +833,33 @@ impl Fs for FakeFs {
async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> { async fn copy_file(&self, source: &Path, target: &Path, options: CopyOptions) -> Result<()> {
let source = normalize_path(source); let source = normalize_path(source);
let target = normalize_path(target); let target = normalize_path(target);
let mut state = self.state.lock().await; let mut state = self.state.lock();
let mtime = state.next_mtime; let mtime = state.next_mtime;
let inode = util::post_inc(&mut state.next_inode); let inode = util::post_inc(&mut state.next_inode);
state.next_mtime += Duration::from_nanos(1); state.next_mtime += Duration::from_nanos(1);
let source_entry = state.read_path(&source).await?; let source_entry = state.read_path(&source)?;
let content = source_entry.lock().await.file_content(&source)?.clone(); let content = source_entry.lock().file_content(&source)?.clone();
let entry = state let entry = state.write_path(&target, |e| match e {
.write_path(&target, |e| match e { btree_map::Entry::Occupied(e) => {
btree_map::Entry::Occupied(e) => { if options.overwrite {
if options.overwrite { Ok(Some(e.get().clone()))
Ok(Some(e.get().clone())) } else if !options.ignore_if_exists {
} else if !options.ignore_if_exists { return Err(anyhow!("{target:?} already exists"));
return Err(anyhow!("{target:?} already exists")); } else {
} else { Ok(None)
Ok(None)
}
} }
btree_map::Entry::Vacant(e) => Ok(Some( }
e.insert(Arc::new(Mutex::new(FakeFsEntry::File { btree_map::Entry::Vacant(e) => Ok(Some(
inode, e.insert(Arc::new(Mutex::new(FakeFsEntry::File {
mtime, inode,
content: String::new(), mtime,
}))) content: String::new(),
.clone(), })))
)), .clone(),
}) )),
.await?; })?;
if let Some(entry) = entry { if let Some(entry) = entry {
entry.lock().await.set_file_content(&target, content)?; entry.lock().set_file_content(&target, content)?;
} }
state.emit_event(&[target]); state.emit_event(&[target]);
Ok(()) Ok(())
@ -890,9 +872,9 @@ impl Fs for FakeFs {
.ok_or_else(|| anyhow!("cannot remove the root"))?; .ok_or_else(|| anyhow!("cannot remove the root"))?;
let base_name = path.file_name().unwrap(); let base_name = path.file_name().unwrap();
let mut state = self.state.lock().await; let mut state = self.state.lock();
let parent_entry = state.read_path(parent_path).await?; let parent_entry = state.read_path(parent_path)?;
let mut parent_entry = parent_entry.lock().await; let mut parent_entry = parent_entry.lock();
let entry = parent_entry let entry = parent_entry
.dir_entries(parent_path)? .dir_entries(parent_path)?
.entry(base_name.to_str().unwrap().into()); .entry(base_name.to_str().unwrap().into());
@ -905,7 +887,7 @@ impl Fs for FakeFs {
} }
btree_map::Entry::Occupied(e) => { btree_map::Entry::Occupied(e) => {
{ {
let mut entry = e.get().lock().await; let mut entry = e.get().lock();
let children = entry.dir_entries(&path)?; let children = entry.dir_entries(&path)?;
if !options.recursive && !children.is_empty() { if !options.recursive && !children.is_empty() {
return Err(anyhow!("{path:?} is not empty")); return Err(anyhow!("{path:?} is not empty"));
@ -924,9 +906,9 @@ impl Fs for FakeFs {
.parent() .parent()
.ok_or_else(|| anyhow!("cannot remove the root"))?; .ok_or_else(|| anyhow!("cannot remove the root"))?;
let base_name = path.file_name().unwrap(); let base_name = path.file_name().unwrap();
let mut state = self.state.lock().await; let mut state = self.state.lock();
let parent_entry = state.read_path(parent_path).await?; let parent_entry = state.read_path(parent_path)?;
let mut parent_entry = parent_entry.lock().await; let mut parent_entry = parent_entry.lock();
let entry = parent_entry let entry = parent_entry
.dir_entries(parent_path)? .dir_entries(parent_path)?
.entry(base_name.to_str().unwrap().into()); .entry(base_name.to_str().unwrap().into());
@ -937,7 +919,7 @@ impl Fs for FakeFs {
} }
} }
btree_map::Entry::Occupied(e) => { btree_map::Entry::Occupied(e) => {
e.get().lock().await.file_content(&path)?; e.get().lock().file_content(&path)?;
e.remove(); e.remove();
} }
} }
@ -953,9 +935,9 @@ impl Fs for FakeFs {
async fn load(&self, path: &Path) -> Result<String> { async fn load(&self, path: &Path) -> Result<String> {
let path = normalize_path(path); let path = normalize_path(path);
self.simulate_random_delay().await; self.simulate_random_delay().await;
let state = self.state.lock().await; let state = self.state.lock();
let entry = state.read_path(&path).await?; let entry = state.read_path(&path)?;
let entry = entry.lock().await; let entry = entry.lock();
entry.file_content(&path).cloned() entry.file_content(&path).cloned()
} }
@ -978,8 +960,8 @@ impl Fs for FakeFs {
async fn canonicalize(&self, path: &Path) -> Result<PathBuf> { async fn canonicalize(&self, path: &Path) -> Result<PathBuf> {
let path = normalize_path(path); let path = normalize_path(path);
self.simulate_random_delay().await; self.simulate_random_delay().await;
let state = self.state.lock().await; let state = self.state.lock();
if let Some((_, real_path)) = state.try_read_path(&path).await { if let Some((_, real_path)) = state.try_read_path(&path) {
Ok(real_path) Ok(real_path)
} else { } else {
Err(anyhow!("path does not exist: {}", path.display())) Err(anyhow!("path does not exist: {}", path.display()))
@ -989,9 +971,9 @@ impl Fs for FakeFs {
async fn is_file(&self, path: &Path) -> bool { async fn is_file(&self, path: &Path) -> bool {
let path = normalize_path(path); let path = normalize_path(path);
self.simulate_random_delay().await; self.simulate_random_delay().await;
let state = self.state.lock().await; let state = self.state.lock();
if let Some((entry, _)) = state.try_read_path(&path).await { if let Some((entry, _)) = state.try_read_path(&path) {
entry.lock().await.is_file() entry.lock().is_file()
} else { } else {
false false
} }
@ -1000,9 +982,9 @@ impl Fs for FakeFs {
async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> { async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
self.simulate_random_delay().await; self.simulate_random_delay().await;
let path = normalize_path(path); let path = normalize_path(path);
let state = self.state.lock().await; let state = self.state.lock();
if let Some((entry, real_path)) = state.try_read_path(&path).await { if let Some((entry, real_path)) = state.try_read_path(&path) {
let entry = entry.lock().await; let entry = entry.lock();
let is_symlink = real_path != path; let is_symlink = real_path != path;
Ok(Some(match &*entry { Ok(Some(match &*entry {
@ -1031,9 +1013,9 @@ impl Fs for FakeFs {
) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> { ) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
self.simulate_random_delay().await; self.simulate_random_delay().await;
let path = normalize_path(path); let path = normalize_path(path);
let state = self.state.lock().await; let state = self.state.lock();
let entry = state.read_path(&path).await?; let entry = state.read_path(&path)?;
let mut entry = entry.lock().await; let mut entry = entry.lock();
let children = entry.dir_entries(&path)?; let children = entry.dir_entries(&path)?;
let paths = children let paths = children
.keys() .keys()
@ -1047,10 +1029,9 @@ impl Fs for FakeFs {
path: &Path, path: &Path,
_: Duration, _: Duration,
) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> { ) -> Pin<Box<dyn Send + Stream<Item = Vec<fsevent::Event>>>> {
let mut state = self.state.lock().await;
self.simulate_random_delay().await; self.simulate_random_delay().await;
let (tx, rx) = smol::channel::unbounded(); let (tx, rx) = smol::channel::unbounded();
state.event_txs.push(tx); self.state.lock().event_txs.push(tx);
let path = path.to_path_buf(); let path = path.to_path_buf();
let executor = self.executor.clone(); let executor = self.executor.clone();
Box::pin(futures::StreamExt::filter(rx, move |events| { Box::pin(futures::StreamExt::filter(rx, move |events| {
@ -1065,22 +1046,18 @@ impl Fs for FakeFs {
})) }))
} }
fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<SyncMutex<dyn GitRepository>>> { fn open_repo(&self, abs_dot_git: &Path) -> Option<Arc<Mutex<dyn GitRepository>>> {
smol::block_on(async move { let state = self.state.lock();
let state = self.state.lock().await; let entry = state.read_path(abs_dot_git).unwrap();
let entry = state.read_path(abs_dot_git).await.unwrap(); let mut entry = entry.lock();
let mut entry = entry.lock().await; if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry {
if let FakeFsEntry::Dir { git_repo_state, .. } = &mut *entry { let state = git_repo_state
let state = git_repo_state .get_or_insert_with(|| Arc::new(Mutex::new(FakeGitRepositoryState::default())))
.get_or_insert_with(|| { .clone();
Arc::new(SyncMutex::new(FakeGitRepositoryState::default())) Some(repository::FakeGitRepository::open(state))
}) } else {
.clone(); None
Some(repository::FakeGitRepository::open(state)) }
} else {
None
}
})
} }
fn is_fake(&self) -> bool { fn is_fake(&self) -> bool {
@ -1213,7 +1190,7 @@ mod tests {
.await; .await;
assert_eq!( assert_eq!(
fs.files().await, fs.files(),
vec![ vec![
PathBuf::from("/root/dir1/a"), PathBuf::from("/root/dir1/a"),
PathBuf::from("/root/dir1/b"), PathBuf::from("/root/dir1/b"),

View File

@ -3729,7 +3729,7 @@ mod tests {
) { ) {
let mut files = Vec::new(); let mut files = Vec::new();
let mut dirs = Vec::new(); let mut dirs = Vec::new();
for path in fs.as_fake().paths().await { for path in fs.as_fake().paths() {
if path.starts_with(root_path) { if path.starts_with(root_path) {
if fs.is_file(&path).await { if fs.is_file(&path).await {
files.push(path); files.push(path);