rcom/src/fs/local.rs
2026-12-05 23:30:06 +03:00

113 lines
3.6 KiB
Rust

use std::path::Path;
use async_trait::async_trait;
use tokio::io::AsyncReadExt;
use crate::domain::{Entry, EntryKind, Location, SourceId};
use super::{FsError, ReadFileSystem, ReadPrefix};
#[derive(Clone, Copy, Debug, Default)]
pub struct LocalFs;
impl LocalFs {
pub fn new() -> Self {
Self
}
fn path(location: &Location) -> Result<&Path, FsError> {
match location.source {
SourceId::Local => Ok(location.path()),
SourceId::Ssh(_) => Err(FsError::Other(
"local filesystem cannot access an SSH location".into(),
)),
}
}
async fn entry(path: &Path, name: std::ffi::OsString) -> Result<Entry, FsError> {
let metadata = tokio::fs::symlink_metadata(path)
.await
.map_err(FsError::from)?;
let file_type = metadata.file_type();
let kind = if file_type.is_dir() {
EntryKind::Directory
} else if file_type.is_file() {
EntryKind::File
} else if file_type.is_symlink() {
EntryKind::Symlink
} else {
EntryKind::Other
};
let size = file_type.is_file().then_some(metadata.len());
let modified = metadata.modified().ok();
#[cfg(unix)]
let permissions = {
use std::os::unix::fs::PermissionsExt;
Some(metadata.permissions().mode() & 0o7777)
};
#[cfg(not(unix))]
let permissions = None;
let mut entry = Entry::new(name, kind).with_metadata(size, modified, permissions);
if file_type.is_symlink() {
entry.link_target = tokio::fs::read_link(path).await.map_err(FsError::from).ok();
}
Ok(entry)
}
}
#[async_trait]
impl ReadFileSystem for LocalFs {
async fn list(&self, location: &Location) -> Result<Vec<Entry>, FsError> {
self.list_prefix(location, usize::MAX).await
}
async fn list_prefix(&self, location: &Location, limit: usize) -> Result<Vec<Entry>, FsError> {
let path = Self::path(location)?;
let mut directory = tokio::fs::read_dir(path).await.map_err(FsError::from)?;
let mut entries = Vec::new();
while entries.len() < limit {
let Some(child) = directory.next_entry().await.map_err(FsError::from)? else {
break;
};
entries.push(Self::entry(&child.path(), child.file_name()).await?);
}
Ok(entries)
}
async fn canonicalize(&self, location: &Location) -> Result<Location, FsError> {
let path = tokio::fs::canonicalize(Self::path(location)?)
.await
.map_err(FsError::from)?;
Ok(Location::local(path))
}
async fn metadata(&self, location: &Location) -> Result<Entry, FsError> {
let path = Self::path(location)?;
let name = path
.file_name()
.map(std::ffi::OsStr::to_os_string)
.unwrap_or_else(|| path.as_os_str().to_os_string());
Self::entry(path, name).await
}
async fn read_prefix(&self, location: &Location, limit: usize) -> Result<ReadPrefix, FsError> {
let file = tokio::fs::File::open(Self::path(location)?)
.await
.map_err(FsError::from)?;
let read_limit = u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1);
let mut data = Vec::new();
file.take(read_limit)
.read_to_end(&mut data)
.await
.map_err(FsError::from)?;
let truncated = data.len() > limit;
data.truncate(limit);
Ok(ReadPrefix { data, truncated })
}
}