use std::error::Error;
use std::fmt::{self, Display, Formatter};
use crate::domain::{ObjectId, RepoPath};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TreeKind {
Directory,
File,
Symlink,
Submodule,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum GitTreeMode {
Directory,
RegularFile,
ExecutableFile,
Symlink,
Submodule,
}
impl GitTreeMode {
pub fn parse(object_type: &str, mode: &str) -> Result<Self, GitTreeModeError> {
match (object_type, mode) {
("tree", "040000") => Ok(Self::Directory),
("blob", "100644") => Ok(Self::RegularFile),
("blob", "100755") => Ok(Self::ExecutableFile),
("blob", "120000") => Ok(Self::Symlink),
("commit", "160000") => Ok(Self::Submodule),
_ => Err(GitTreeModeError {
object_type: object_type.to_owned(),
mode: mode.to_owned(),
}),
}
}
#[must_use]
pub const fn kind(self) -> TreeKind {
match self {
Self::Directory => TreeKind::Directory,
Self::RegularFile | Self::ExecutableFile => TreeKind::File,
Self::Symlink => TreeKind::Symlink,
Self::Submodule => TreeKind::Submodule,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Directory => "040000",
Self::RegularFile => "100644",
Self::ExecutableFile => "100755",
Self::Symlink => "120000",
Self::Submodule => "160000",
}
}
}
impl Display for GitTreeMode {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GitTreeModeError {
object_type: String,
mode: String,
}
impl GitTreeModeError {
#[must_use]
pub fn object_type(&self) -> &str {
&self.object_type
}
#[must_use]
pub fn mode(&self) -> &str {
&self.mode
}
}
impl Display for GitTreeModeError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
write!(
formatter,
"unsupported tree entry type {:?} with mode {:?}",
self.object_type, self.mode
)
}
}
impl Error for GitTreeModeError {}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TreeEntry {
object_id: ObjectId,
mode: GitTreeMode,
name: RepoPath,
}
impl TreeEntry {
#[must_use]
pub fn new(object_id: ObjectId, mode: GitTreeMode, name: RepoPath) -> Self {
Self {
object_id,
mode,
name,
}
}
#[must_use]
pub fn object_id(&self) -> &ObjectId {
&self.object_id
}
#[must_use]
pub fn mode(&self) -> GitTreeMode {
self.mode
}
#[must_use]
pub fn kind(&self) -> TreeKind {
self.mode.kind()
}
#[must_use]
pub fn name(&self) -> &RepoPath {
&self.name
}
}