Skip to main content

objects/object/
tree_types.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Tree entry type definitions.
3
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8/// Error type for tree operations.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum TreeError {
11    /// Invalid entry name.
12    InvalidName(String),
13    /// Invalid tree structure.
14    InvalidStructure(String),
15}
16
17impl std::error::Error for TreeError {}
18
19impl fmt::Display for TreeError {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        match self {
22            TreeError::InvalidName(msg) => write!(f, "invalid tree entry name: {}", msg),
23            TreeError::InvalidStructure(msg) => write!(f, "invalid tree structure: {}", msg),
24        }
25    }
26}
27
28/// File mode for tree entries.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
30pub enum FileMode {
31    /// Regular file (0644)
32    Normal,
33    /// Executable file (0755)
34    Executable,
35    /// Symbolic link
36    Symlink,
37}
38
39impl FileMode {
40    /// Convert to a byte for serialization.
41    pub fn to_byte(&self) -> u8 {
42        match self {
43            FileMode::Normal => 0,
44            FileMode::Executable => 1,
45            FileMode::Symlink => 2,
46        }
47    }
48
49    /// Parse from a byte.
50    pub fn from_byte(b: u8) -> Option<Self> {
51        match b {
52            0 => Some(FileMode::Normal),
53            1 => Some(FileMode::Executable),
54            2 => Some(FileMode::Symlink),
55            _ => None,
56        }
57    }
58
59    /// Convert to Unix mode bits.
60    pub fn to_unix_mode(&self) -> u32 {
61        match self {
62            FileMode::Normal => 0o100644,
63            FileMode::Executable => 0o100755,
64            FileMode::Symlink => 0o120000,
65        }
66    }
67}
68
69/// Entry type in a tree (blob or subtree).
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
71pub enum EntryType {
72    /// A file (blob)
73    Blob,
74    /// A directory (subtree)
75    Tree,
76    /// A symlink
77    Symlink,
78}
79
80impl EntryType {
81    /// Convert to a byte for serialization.
82    pub fn to_byte(&self) -> u8 {
83        match self {
84            EntryType::Blob => 0,
85            EntryType::Tree => 1,
86            EntryType::Symlink => 2,
87        }
88    }
89
90    /// Parse from a byte.
91    pub fn from_byte(b: u8) -> Option<Self> {
92        match b {
93            0 => Some(EntryType::Blob),
94            1 => Some(EntryType::Tree),
95            2 => Some(EntryType::Symlink),
96            _ => None,
97        }
98    }
99}