use alloc::vec::Vec;
use relative_path::{RelativePath, RelativePathBuf};
use crate::FileSystem;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct File {
pub path: RelativePathBuf,
pub contents: Vec<u8>,
pub new: bool,
}
impl File {
pub fn new(path: RelativePathBuf, contents: Vec<u8>, new: bool) -> Self {
Self {
path,
contents,
new,
}
}
pub fn update<F>(mut self, f: F) -> Self
where
F: FnOnce(&mut Vec<u8>),
{
f(&mut self.contents);
self
}
pub fn save(self, fs: &mut FileSystem) -> anyhow::Result<()> {
fs.save(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FilePath {
pub path: RelativePathBuf,
pub len: usize,
}
impl FilePath {
pub fn new(path: RelativePathBuf, len: usize) -> Self {
Self { path, len }
}
pub fn open(&self, fs: &mut FileSystem) -> anyhow::Result<File> {
fs.open(&self.path)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Dir {
pub path: RelativePathBuf,
}
impl Dir {
pub fn new(path: RelativePathBuf) -> Self {
Self { path }
}
pub fn ls(&self, fs: &mut FileSystem) -> anyhow::Result<Vec<DirOrFile>> {
fs.ls(&self.path)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum DirOrFile {
Dir(Dir),
File(FilePath),
}
impl DirOrFile {
pub fn path(&self) -> &RelativePath {
match self {
DirOrFile::Dir(p) => p.path.as_relative_path(),
DirOrFile::File(p) => p.path.as_relative_path(),
}
}
pub fn as_dir(&self) -> Option<&Dir> {
match self {
DirOrFile::Dir(dir) => Some(dir),
_ => None,
}
}
pub fn as_file(&self) -> Option<&FilePath> {
match self {
DirOrFile::File(file) => Some(file),
_ => None,
}
}
}
impl From<Dir> for DirOrFile {
fn from(dir: Dir) -> Self {
Self::Dir(dir)
}
}
impl From<FilePath> for DirOrFile {
fn from(file: FilePath) -> Self {
Self::File(file)
}
}