use std::collections::BTreeMap;
use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
use crate::port::kind::EntryKind;
use crate::port::tree::FileTree;
#[derive(Debug, Clone)]
enum Node {
File(Vec<u8>),
Dir,
Symlink,
Special,
Unreadable,
UnlistableDir,
Uninspectable,
}
#[derive(Debug, Clone)]
pub struct FakeFileTree {
root: PathBuf,
nodes: BTreeMap<PathBuf, Node>,
}
impl FakeFileTree {
pub fn new(root: impl Into<PathBuf>) -> Self {
let mut nodes = BTreeMap::new();
nodes.insert(PathBuf::new(), Node::Dir);
Self {
root: root.into(),
nodes,
}
}
pub fn missing(root: impl Into<PathBuf>) -> Self {
Self {
root: root.into(),
nodes: BTreeMap::new(),
}
}
#[must_use]
pub fn file(self, rel: impl AsRef<Path>, bytes: &[u8]) -> Self {
self.with(rel.as_ref(), Node::File(bytes.to_vec()))
}
#[must_use]
pub fn dir(self, rel: impl AsRef<Path>) -> Self {
self.with(rel.as_ref(), Node::Dir)
}
#[must_use]
pub fn symlink(self, rel: impl AsRef<Path>) -> Self {
self.with(rel.as_ref(), Node::Symlink)
}
#[must_use]
pub fn special(self, rel: impl AsRef<Path>) -> Self {
self.with(rel.as_ref(), Node::Special)
}
#[must_use]
pub fn unreadable(self, rel: impl AsRef<Path>) -> Self {
self.with(rel.as_ref(), Node::Unreadable)
}
#[must_use]
pub fn unlistable_dir(self, rel: impl AsRef<Path>) -> Self {
self.with(rel.as_ref(), Node::UnlistableDir)
}
#[must_use]
pub fn uninspectable(self, rel: impl AsRef<Path>) -> Self {
self.with(rel.as_ref(), Node::Uninspectable)
}
#[must_use]
pub fn denied() -> io::Error {
io::Error::new(io::ErrorKind::PermissionDenied, "permission denied")
}
#[must_use]
pub fn not_found() -> io::Error {
io::Error::new(io::ErrorKind::NotFound, "no such file or directory")
}
fn with(mut self, rel: &Path, node: Node) -> Self {
let mut parent = rel.parent();
while let Some(dir) = parent {
if dir.as_os_str().is_empty() {
break;
}
self.nodes.entry(dir.to_path_buf()).or_insert(Node::Dir);
parent = dir.parent();
}
self.nodes.insert(rel.to_path_buf(), node);
self
}
fn node(&self, rel: &Path) -> io::Result<&Node> {
self.nodes.get(rel).ok_or_else(Self::not_found)
}
}
impl FileTree for FakeFileTree {
fn root(&self) -> &Path {
&self.root
}
fn kind(&self, rel: &Path) -> io::Result<EntryKind> {
match self.node(rel)? {
Node::File(_) | Node::Unreadable => Ok(EntryKind::File),
Node::Dir | Node::UnlistableDir => Ok(EntryKind::Dir),
Node::Symlink => Ok(EntryKind::Symlink),
Node::Special => Ok(EntryKind::Other),
Node::Uninspectable => Err(Self::denied()),
}
}
fn read_dir(&self, rel: &Path) -> io::Result<Vec<OsString>> {
match self.node(rel)? {
Node::Dir => Ok(self
.nodes
.keys()
.filter(|path| path.as_os_str() != "" && path.parent() == Some(rel))
.filter_map(|path| path.file_name().map(OsString::from))
.collect()),
Node::UnlistableDir => Err(Self::denied()),
_ => Err(io::Error::new(
io::ErrorKind::NotADirectory,
"not a directory",
)),
}
}
fn read_file(&self, rel: &Path) -> io::Result<Vec<u8>> {
match self.node(rel)? {
Node::File(bytes) => Ok(bytes.clone()),
Node::Unreadable => Err(Self::denied()),
_ => Err(io::Error::new(io::ErrorKind::InvalidInput, "not a file")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error;
type TestResult = Result<(), Box<dyn Error>>;
fn names(tree: &FakeFileTree, rel: &str) -> io::Result<Vec<String>> {
let mut names: Vec<String> = tree
.read_dir(Path::new(rel))?
.iter()
.map(|name| name.to_string_lossy().into_owned())
.collect();
names.sort();
Ok(names)
}
#[test]
fn the_root_is_the_display_path() {
assert_eq!(
FakeFileTree::new("packs/core").root(),
Path::new("packs/core")
);
}
#[test]
fn a_file_creates_the_directories_above_it() -> TestResult {
let tree = FakeFileTree::new("r").file("a/b/c.md", b"x");
assert_eq!(tree.kind(Path::new("a"))?, EntryKind::Dir);
assert_eq!(tree.kind(Path::new("a/b"))?, EntryKind::Dir);
assert_eq!(tree.kind(Path::new("a/b/c.md"))?, EntryKind::File);
assert_eq!(tree.read_file(Path::new("a/b/c.md"))?, b"x");
Ok(())
}
#[test]
fn read_dir_lists_direct_children_only() -> TestResult {
let tree = FakeFileTree::new("r")
.file("a.md", b"")
.file("d/e.md", b"")
.file("d/f/g.md", b"");
assert_eq!(names(&tree, "")?, ["a.md", "d"]);
assert_eq!(names(&tree, "d")?, ["e.md", "f"]);
Ok(())
}
#[test]
fn each_builder_reports_its_kind() -> TestResult {
let tree = FakeFileTree::new("r")
.dir("d")
.symlink("l")
.special("s")
.unreadable("u")
.unlistable_dir("x");
assert_eq!(tree.kind(Path::new("d"))?, EntryKind::Dir);
assert_eq!(tree.kind(Path::new("l"))?, EntryKind::Symlink);
assert_eq!(tree.kind(Path::new("s"))?, EntryKind::Other);
assert_eq!(tree.kind(Path::new("u"))?, EntryKind::File);
assert_eq!(tree.kind(Path::new("x"))?, EntryKind::Dir);
Ok(())
}
#[test]
fn the_failing_entries_return_an_io_error() {
let tree = FakeFileTree::new("r")
.unreadable("u")
.unlistable_dir("x")
.uninspectable("i");
let kinds = [
tree.read_file(Path::new("u")).err().map(|e| e.kind()),
tree.read_dir(Path::new("x")).err().map(|e| e.kind()),
tree.kind(Path::new("i")).err().map(|e| e.kind()),
];
assert_eq!(kinds, [Some(io::ErrorKind::PermissionDenied); 3]);
}
#[test]
fn a_path_that_is_not_in_the_tree_is_not_found() {
let tree = FakeFileTree::new("r");
let kind = tree.kind(Path::new("nope")).err().map(|e| e.kind());
assert_eq!(kind, Some(io::ErrorKind::NotFound));
}
#[test]
fn a_missing_root_cannot_be_listed() {
let tree = FakeFileTree::missing("gone");
let kind = tree.read_dir(Path::new("")).err().map(|e| e.kind());
assert_eq!(kind, Some(io::ErrorKind::NotFound));
}
#[test]
fn a_file_is_not_a_directory_and_a_directory_is_not_a_file() {
let tree = FakeFileTree::new("r").file("a.md", b"").dir("d");
assert!(tree.read_dir(Path::new("a.md")).is_err());
assert!(tree.read_file(Path::new("d")).is_err());
}
#[cfg(unix)]
#[test]
fn a_non_utf8_name_is_listed() -> TestResult {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let bad = OsStr::from_bytes(&[0x66, 0xFF]);
let tree = FakeFileTree::new("r").file(bad, b"");
assert_eq!(tree.read_dir(Path::new(""))?, [bad.to_os_string()]);
Ok(())
}
}