use std::collections::BTreeMap;
use std::fmt;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DirEntry {
pub name: String,
pub is_dir: bool,
}
pub trait SourceFs: Send + Sync {
fn read_file(&self, path: &str) -> Option<String>;
fn read_dir(&self, path: &str) -> Option<Vec<DirEntry>>;
fn join(&self, parts: &[&str]) -> String;
fn dir(&self, path: &str) -> String;
fn canon(&self, path: &str) -> String;
fn real_path(&self, path: &str) -> Option<String> {
Some(self.canon(path))
}
fn native_paths(&self) -> bool {
false
}
}
impl fmt::Debug for dyn SourceFs {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("<SourceFs>")
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct OsFs;
impl SourceFs for OsFs {
fn read_file(&self, path: &str) -> Option<String> {
std::fs::read(path)
.ok()
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
}
fn read_dir(&self, path: &str) -> Option<Vec<DirEntry>> {
let mut entries = Vec::new();
for entry in std::fs::read_dir(path).ok()? {
let Ok(entry) = entry else { continue };
let is_dir = entry.file_type().map(|kind| kind.is_dir()).unwrap_or(false);
entries.push(DirEntry {
name: entry.file_name().to_string_lossy().into_owned(),
is_dir,
});
}
entries.sort_by(|left, right| left.name.cmp(&right.name));
Some(entries)
}
fn join(&self, parts: &[&str]) -> String {
let mut joined = PathBuf::new();
for part in parts {
joined.push(part);
}
lexical(&joined).to_string_lossy().into_owned()
}
fn dir(&self, path: &str) -> String {
match Path::new(path).parent() {
Some(parent) => parent.to_string_lossy().into_owned(),
None => path.to_string(),
}
}
fn native_paths(&self) -> bool {
true
}
fn canon(&self, path: &str) -> String {
lexical(&absolute(path)).to_string_lossy().into_owned()
}
fn real_path(&self, path: &str) -> Option<String> {
let absolute = lexical(&absolute(path));
if let Ok(real) = std::fs::canonicalize(&absolute) {
return Some(real.to_string_lossy().into_owned());
}
let mut prefix = absolute.clone();
let mut rest: Vec<std::ffi::OsString> = Vec::new();
loop {
if let Ok(real) = std::fs::canonicalize(&prefix) {
let mut resolved = real;
for name in rest.iter().rev() {
resolved.push(name);
}
return Some(resolved.to_string_lossy().into_owned());
}
if std::fs::symlink_metadata(&prefix).is_ok() {
return None;
}
let (Some(parent), Some(name)) = (prefix.parent(), prefix.file_name()) else {
return Some(absolute.to_string_lossy().into_owned());
};
rest.push(name.to_os_string());
prefix = parent.to_path_buf();
}
}
}
fn absolute(path: &str) -> PathBuf {
let candidate = Path::new(path);
if candidate.is_absolute() {
candidate.to_path_buf()
} else {
match std::env::current_dir() {
Ok(cwd) => cwd.join(candidate),
Err(_) => candidate.to_path_buf(),
}
}
}
#[derive(Clone, Debug, Default)]
pub struct MapFs {
files: BTreeMap<String, String>,
}
impl MapFs {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, path: impl AsRef<str>, content: impl Into<String>) -> &mut Self {
self.files.insert(clean(path.as_ref()), content.into());
self
}
pub fn with(mut self, path: impl AsRef<str>, content: impl Into<String>) -> Self {
self.insert(path, content);
self
}
pub fn paths(&self) -> Vec<&str> {
self.files.keys().map(String::as_str).collect()
}
}
impl<K, V> FromIterator<(K, V)> for MapFs
where
K: AsRef<str>,
V: Into<String>,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(entries: T) -> Self {
let mut filesystem = MapFs::new();
for (path, content) in entries {
filesystem.insert(path, content);
}
filesystem
}
}
impl<K, V, const N: usize> From<[(K, V); N]> for MapFs
where
K: AsRef<str>,
V: Into<String>,
{
fn from(entries: [(K, V); N]) -> Self {
entries.into_iter().collect()
}
}
impl SourceFs for MapFs {
fn read_file(&self, path: &str) -> Option<String> {
self.files.get(&clean(path)).cloned()
}
fn read_dir(&self, path: &str) -> Option<Vec<DirEntry>> {
let folder = clean(path);
let prefix = if folder == "." {
String::new()
} else {
format!("{folder}/")
};
let mut entries: BTreeMap<String, bool> = BTreeMap::new();
for key in self.files.keys() {
let Some(rest) = key.strip_prefix(prefix.as_str()) else {
continue;
};
if rest.is_empty() {
continue;
}
match rest.split_once('/') {
Some((head, _)) => {
entries.insert(head.to_string(), true);
}
None => {
entries.insert(rest.to_string(), false);
}
}
}
if entries.is_empty() && folder != "." {
return None;
}
Some(
entries
.into_iter()
.map(|(name, is_dir)| DirEntry { name, is_dir })
.collect(),
)
}
fn join(&self, parts: &[&str]) -> String {
clean(&parts.join("/"))
}
fn dir(&self, path: &str) -> String {
let cleaned = clean(path);
match cleaned.rsplit_once('/') {
Some((head, _)) if !head.is_empty() => head.to_string(),
Some(_) => ".".to_string(),
None => ".".to_string(),
}
}
fn canon(&self, path: &str) -> String {
clean(path)
}
}
pub(crate) fn clean(path: &str) -> String {
let unified = path.replace('\\', "/");
let mut parts: Vec<&str> = Vec::new();
for segment in unified.split('/') {
match segment {
"" | "." => {}
".." => {
parts.pop();
}
other => parts.push(other),
}
}
if parts.is_empty() {
".".to_string()
} else {
parts.join("/")
}
}
fn lexical(path: &Path) -> PathBuf {
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
if !out.pop() {
out.push("..");
}
}
other => out.push(other.as_os_str()),
}
}
if out.as_os_str().is_empty() {
out.push(".");
}
out
}
pub(crate) fn within_root(candidate: &str, root: &str, os_paths: bool) -> bool {
let (candidate, root) = if os_paths {
(
lexical(Path::new(candidate)).to_string_lossy().into_owned(),
lexical(Path::new(root)).to_string_lossy().into_owned(),
)
} else {
(clean(candidate), clean(root))
};
if root.is_empty() || root == "." {
return true;
}
if candidate == root {
return true;
}
let separator = if os_paths {
std::path::MAIN_SEPARATOR
} else {
'/'
};
let mut prefix = root;
if !prefix.ends_with(separator) {
prefix.push(separator);
}
candidate.starts_with(&prefix)
}
pub type SharedFs = Arc<dyn SourceFs>;
pub fn os_fs() -> SharedFs {
Arc::new(OsFs)
}