use std::{io::ErrorKind, path::Path};
use rho_protocol::methods::{FsGitCheckout, FsListing, FsResolved, FsSubfolder};
use super::{canonical, host_path, parse_head, project_root};
pub(super) fn resolve_folder(path: &Path) -> FsResolved {
let folder = || {
let real = canonical(path).ok().filter(|real| can_enter(real))?;
Some(FsResolved::Folder {
project: host_path(&project_root(&real)).ok()?,
real: host_path(&real).ok()?,
})
};
folder().unwrap_or(FsResolved::NotFolder)
}
pub(super) fn list_folder(folder: &Path) -> FsListing {
match std::fs::metadata(folder) {
Err(error) if error.kind() == ErrorKind::NotFound => return FsListing::Gone,
Ok(metadata) if !metadata.is_dir() => return FsListing::NotFolder,
_ => {}
}
let entries = match std::fs::read_dir(folder) {
Ok(entries) => entries,
Err(error) => {
return match error.kind() {
ErrorKind::NotFound => FsListing::Gone,
ErrorKind::PermissionDenied => FsListing::Denied,
_ => FsListing::Failed {
message: error.to_string(),
},
}
}
};
let subfolders = entries
.flatten()
.filter_map(|entry| {
let path = entry.path();
if !path.is_dir() {
return None;
}
let name = entry.file_name().into_string().ok()?;
Some(FsSubfolder::new(name, git_checkout(&path)))
})
.collect();
FsListing::Listed {
real: canonical(folder)
.ok()
.filter(|real| can_enter(real))
.and_then(|real| host_path(&real).ok()),
subfolders,
}
}
fn can_enter(dir: &Path) -> bool {
#[cfg(unix)]
{
std::fs::metadata(dir.join(".")).is_ok_and(|metadata| metadata.is_dir())
}
#[cfg(not(unix))]
{
std::fs::read_dir(dir).is_ok()
}
}
fn git_checkout(dir: &Path) -> Option<FsGitCheckout> {
let git_dir = crate::git::git_dir_at(dir)?;
let head = crate::git::read_small(&git_dir.join("HEAD"));
Some(FsGitCheckout::new(head.as_deref().and_then(parse_head)))
}