Skip to main content

git_internal/internal/object/
tree.rs

1//! In Git, a tree object is used to represent the state of a directory at a specific point in time.
2//! It stores information about the files and directories within that directory, including their names,
3//! permissions, and the IDs of the objects that represent their contents.
4//!
5//! A tree object can contain other tree objects as well as blob objects, which represent the contents
6//! of individual files. The object IDs of these child objects are stored within the tree object itself.
7//!
8//! When you make a commit in Git, you create a new tree object that represents the state of the
9//! repository at that point in time. The parent of the new commit is typically the tree object
10//! representing the previous state of the repository.
11//!
12//! Git uses the tree object to efficiently store and manage the contents of a repository. By
13//! representing the contents of a directory as a tree object, Git can quickly determine which files
14//! have been added, modified, or deleted between two points in time. This allows Git to perform
15//! operations like merging and rebasing more quickly and accurately.
16//!
17use std::fmt::Display;
18
19use colored::Colorize;
20use encoding_rs::GBK;
21
22use crate::{
23    errors::GitError,
24    hash::{HashKind, ObjectHash},
25    internal::object::{ObjectTrait, ObjectType},
26};
27
28/// In Git, the mode field in a tree object's entry specifies the type of the object represented by
29/// that entry. The mode is a three-digit octal number that encodes both the permissions and the
30/// type of the object. The first digit specifies the object type, and the remaining two digits
31/// specify the file mode or permissions.
32#[derive(
33    PartialEq,
34    Eq,
35    Debug,
36    Clone,
37    Copy,
38    serde::Serialize,
39    serde::Deserialize,
40    Hash,
41    rkyv::Archive,
42    rkyv::Serialize,
43    rkyv::Deserialize,
44)]
45pub enum TreeItemMode {
46    Blob,
47    BlobExecutable,
48    Tree,
49    Commit,
50    Link,
51}
52
53impl Display for TreeItemMode {
54    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
55        let _print = match *self {
56            TreeItemMode::Blob => "blob",
57            TreeItemMode::BlobExecutable => "blob executable",
58            TreeItemMode::Tree => "tree",
59            TreeItemMode::Commit => "commit",
60            TreeItemMode::Link => "link",
61        };
62
63        write!(f, "{}", String::from(_print).blue())
64    }
65}
66
67impl TreeItemMode {
68    /// Convert a 32-bit mode to a TreeItemType
69    ///
70    /// |0100000000000000| (040000)| Directory|
71    /// |1000000110100100| (100644)| Regular non-executable file|
72    /// |1000000110110100| (100664)| Regular non-executable group-writeable file|
73    /// |1000000111101101| (100755)| Regular executable file|
74    /// |1010000000000000| (120000)| Symbolic link|
75    /// |1110000000000000| (160000)| Gitlink|
76    /// ---
77    /// # GitLink
78    /// Gitlink, also known as a submodule, is a feature in Git that allows you to include a Git
79    /// repository as a subdirectory within another Git repository. This is useful when you want to
80    /// incorporate code from another project into your own project, without having to manually copy
81    /// the code into your repository.
82    ///
83    /// When you add a submodule to your Git repository, Git stores a reference to the other
84    /// repository at a specific commit. This means that your repository will always point to a
85    /// specific version of the other repository, even if changes are made to the submodule's code
86    /// in the future.
87    ///
88    /// To work with a submodule in Git, you use commands like git submodule add, git submodule
89    /// update, and git submodule init. These commands allow you to add a submodule to your repository,
90    /// update it to the latest version, and initialize it for use.
91    ///
92    /// Submodules can be a powerful tool for managing dependencies between different projects and
93    /// components. However, they can also add complexity to your workflow, so it's important to
94    /// understand how they work and when to use them.
95    pub fn tree_item_type_from_bytes(mode: &[u8]) -> Result<TreeItemMode, GitError> {
96        Ok(match mode {
97            b"40000" => TreeItemMode::Tree,
98            b"100644" => TreeItemMode::Blob,
99            b"100755" => TreeItemMode::BlobExecutable,
100            b"120000" => TreeItemMode::Link,
101            b"160000" => TreeItemMode::Commit,
102            b"100664" => TreeItemMode::Blob,
103            b"100640" => TreeItemMode::Blob,
104            _ => {
105                // Non-UTF-8 modes are reported lossily instead of panicking.
106                return Err(GitError::InvalidTreeItem(
107                    String::from_utf8_lossy(mode).into_owned(),
108                ));
109            }
110        })
111    }
112
113    /// 32-bit mode, split into (high to low bits):
114    /// - 4-bit object type: valid values in binary are 1000 (regular file), 1010 (symbolic link) and 1110 (gitlink)
115    /// - 3-bit unused
116    /// - 9-bit unix permission: Only 0755 and 0644 are valid for regular files. Symbolic links and gitlink have value 0 in this field.
117    pub fn to_bytes(self) -> &'static [u8] {
118        match self {
119            TreeItemMode::Blob => b"100644",
120            TreeItemMode::BlobExecutable => b"100755",
121            TreeItemMode::Link => b"120000",
122            TreeItemMode::Tree => b"40000",
123            TreeItemMode::Commit => b"160000",
124        }
125    }
126}
127
128/// A tree object contains a list of entries, one for each file or directory in the tree. Each entry
129/// in the file represents an entry in the tree, and each entry has the following format:
130///
131/// ```bash
132/// <mode> <name>\0<binary object ID>
133/// ```
134/// - `<mode>` is the mode of the object, represented as a six-digit octal number. The first digit
135///   represents the object type (tree, blob, etc.), and the remaining digits represent the file mode or permissions.
136/// - `<name>` is the name of the object.
137/// - `\0` is a null byte separator.
138/// - `<binary object ID>` is the ID of the object that represents the contents of the file or
139///   directory, represented as a binary SHA-1 hash.
140///
141/// # Example
142/// ```bash
143/// 100644 hello-world\0<blob object ID>
144/// 040000 data\0<tree object ID>
145/// ```
146#[derive(
147    PartialEq,
148    Eq,
149    Debug,
150    Clone,
151    serde::Serialize,
152    serde::Deserialize,
153    Hash,
154    rkyv::Archive,
155    rkyv::Serialize,
156    rkyv::Deserialize,
157)]
158pub struct TreeItem {
159    pub mode: TreeItemMode,
160    pub id: ObjectHash,
161    pub name: String,
162}
163
164impl Display for TreeItem {
165    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
166        write!(
167            f,
168            "{} {} {}",
169            self.mode,
170            self.name,
171            self.id.to_string().blue()
172        )
173    }
174}
175
176impl TreeItem {
177    /// Creates a new [`TreeItem`] with the given mode, object ID, and name.
178    pub fn new(mode: TreeItemMode, id: ObjectHash, name: String) -> Self {
179        TreeItem { mode, id, name }
180    }
181
182    /// Parse one `<mode> <name>\0<binary object ID>` entry whose ID belongs to an
183    /// explicit repository `kind`.
184    ///
185    /// Does not consult the thread-local [`HashKind`]. Fails closed (never
186    /// panics) on a malformed entry or an ID of the wrong width.
187    pub fn from_bytes_with_kind(bytes: &[u8], kind: HashKind) -> Result<Self, GitError> {
188        let malformed = |what: &str| {
189            GitError::InvalidTreeItem(format!(
190                "tree entry is missing its {what} ({} bytes, expected {} mode/name bytes + 1 NUL + {}-byte {kind} id)",
191                bytes.len(),
192                bytes.len().saturating_sub(kind.size() + 1),
193                kind.size()
194            ))
195        };
196        let space = memchr::memchr(b' ', bytes).ok_or_else(|| malformed("mode"))?;
197        let (mode, rest) = (&bytes[..space], &bytes[space + 1..]);
198        let nul = memchr::memchr(0, rest).ok_or_else(|| malformed("NUL separator"))?;
199        let (raw_name, id) = (&rest[..nul], &rest[nul + 1..]);
200
201        let name = match String::from_utf8(raw_name.to_vec()) {
202            Ok(name) => name,
203            Err(_) => {
204                let (decoded, _, had_errors) = GBK.decode(raw_name);
205                if had_errors {
206                    return Err(GitError::InvalidTreeItem(format!(
207                        "Unsupported raw format: {raw_name:?}"
208                    )));
209                }
210                decoded.to_string()
211            }
212        };
213        Ok(TreeItem {
214            mode: TreeItemMode::tree_item_type_from_bytes(mode)?,
215            id: ObjectHash::from_bytes_for_kind(kind, id)?,
216            name,
217        })
218    }
219
220    /// Create a new TreeItem from a byte vector, split into a mode, id and name, the TreeItem format is:
221    ///
222    /// ```bash
223    /// <mode> <name>\0<binary object ID>
224    /// ```
225    ///
226    /// Legacy entry point: the ID width comes from the thread-local
227    /// [`HashKind`]. Prefer [`TreeItem::from_bytes_with_kind`].
228    pub fn from_bytes(bytes: &[u8]) -> Result<Self, GitError> {
229        let mut parts = bytes.splitn(2, |b| *b == b' ');
230        let mode = parts.next().unwrap();
231        let rest = parts.next().unwrap();
232        let mut parts = rest.splitn(2, |b| *b == b'\0');
233        let raw_name = parts.next().unwrap();
234        let id = parts.next().unwrap();
235
236        let name = if String::from_utf8(raw_name.to_vec()).is_ok() {
237            String::from_utf8(raw_name.to_vec()).unwrap()
238        } else {
239            let (decoded, _, had_errors) = GBK.decode(raw_name);
240            if had_errors {
241                return Err(GitError::InvalidTreeItem(format!(
242                    "Unsupported raw format: {raw_name:?}"
243                )));
244            } else {
245                decoded.to_string()
246            }
247        };
248        Ok(TreeItem {
249            mode: TreeItemMode::tree_item_type_from_bytes(mode)?,
250            id: ObjectHash::from_bytes(id).unwrap(),
251            name,
252        })
253    }
254
255    /// Convert a TreeItem to a byte vector
256    /// ```rust
257    /// use git_internal::internal::object::tree::{TreeItem, TreeItemMode};
258    /// use git_internal::hash::{HashKind, ObjectHash};
259    ///
260    /// let tree_item = TreeItem::new(
261    ///     TreeItemMode::Blob,
262    ///     ObjectHash::from_hex_for_kind(HashKind::Sha1, "8ab686eafeb1f44702738c8b0f24f2567c36da6d")
263    ///         .unwrap(),
264    ///     "hello-world".to_string(),
265    /// );
266    ///
267    //  let bytes = tree_item.to_bytes();
268    /// ```
269    pub fn to_data(&self) -> Vec<u8> {
270        let mut bytes = Vec::new();
271
272        bytes.extend_from_slice(self.mode.to_bytes());
273        bytes.push(b' ');
274        bytes.extend_from_slice(self.name.as_bytes());
275        bytes.push(b'\0');
276        bytes.extend_from_slice(&self.id.to_data());
277
278        bytes
279    }
280
281    /// Returns `true` if this item represents a subdirectory (tree).
282    pub fn is_tree(&self) -> bool {
283        self.mode == TreeItemMode::Tree
284    }
285
286    /// Returns `true` if this item represents a regular file (blob).
287    pub fn is_blob(&self) -> bool {
288        self.mode == TreeItemMode::Blob
289    }
290}
291
292/// A tree object is a Git object that represents a directory. It contains a list of entries, one
293/// for each file or directory in the tree.
294#[derive(
295    Eq,
296    Debug,
297    Clone,
298    serde::Serialize,
299    serde::Deserialize,
300    rkyv::Archive,
301    rkyv::Serialize,
302    rkyv::Deserialize,
303)]
304pub struct Tree {
305    pub id: ObjectHash,
306    pub tree_items: Vec<TreeItem>,
307}
308
309impl PartialEq for Tree {
310    fn eq(&self, other: &Self) -> bool {
311        self.id == other.id
312    }
313}
314
315impl Display for Tree {
316    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
317        writeln!(f, "Tree: {}", self.id.to_string().blue())?;
318        for item in &self.tree_items {
319            writeln!(f, "{item}")?;
320        }
321        Ok(())
322    }
323}
324
325impl Tree {
326    /// Serialize `items` and verify every entry ID belongs to `kind`.
327    fn items_data_for_kind(kind: HashKind, items: &[TreeItem]) -> Result<Vec<u8>, GitError> {
328        let mut data = Vec::new();
329        for item in items {
330            item.id.ensure_kind(kind)?;
331            data.extend_from_slice(item.to_data().as_slice());
332        }
333        Ok(data)
334    }
335
336    /// Create a new Tree from a list of TreeItems, hashing with an explicit repository `kind`.
337    ///
338    /// Does not consult the thread-local [`HashKind`]. Every entry ID must
339    /// belong to `kind`; a cross-kind reference fails closed with
340    /// [`GitError::InvalidHashValue`].
341    pub fn from_tree_items_with_kind(
342        kind: HashKind,
343        tree_items: Vec<TreeItem>,
344    ) -> Result<Self, GitError> {
345        if tree_items.is_empty() {
346            return Err(GitError::EmptyTreeItems(
347                "When export tree object to meta, the items is empty".to_string(),
348            ));
349        }
350        let data = Self::items_data_for_kind(kind, &tree_items)?;
351        Ok(Tree {
352            id: ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Tree, &data)?,
353            tree_items,
354        })
355    }
356
357    /// Create a new Tree from a list of TreeItems
358    ///
359    /// Uses the thread-local [`HashKind`]; see [`Tree::from_tree_items_with_kind`].
360    pub fn from_tree_items(tree_items: Vec<TreeItem>) -> Result<Self, GitError> {
361        if tree_items.is_empty() {
362            return Err(GitError::EmptyTreeItems(
363                "When export tree object to meta, the items is empty"
364                    .parse()
365                    .unwrap(),
366            ));
367        }
368        let mut data = Vec::new();
369        for item in &tree_items {
370            data.extend_from_slice(item.to_data().as_slice());
371        }
372
373        Ok(Tree {
374            id: ObjectHash::from_type_and_data(ObjectType::Tree, &data),
375            tree_items,
376        })
377    }
378
379    /// Recalculate the tree ID for an explicit repository `kind` after the entries changed.
380    ///
381    /// Every entry ID must belong to `kind`; on failure the ID is left unchanged.
382    pub fn rehash_with_kind(&mut self, kind: HashKind) -> Result<(), GitError> {
383        let data = Self::items_data_for_kind(kind, &self.tree_items)?;
384        self.id = ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Tree, &data)?;
385        Ok(())
386    }
387
388    /// After the subdirectory is changed, the hash value of the tree is recalculated.
389    ///
390    /// Uses the thread-local [`HashKind`]; see [`Tree::rehash_with_kind`].
391    pub fn rehash(&mut self) {
392        let mut data = Vec::new();
393        for item in &self.tree_items {
394            data.extend_from_slice(item.to_data().as_slice());
395        }
396        self.id = ObjectHash::from_type_and_data(ObjectType::Tree, &data);
397    }
398}
399
400impl TryFrom<&[u8]> for Tree {
401    type Error = GitError;
402    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
403        let h = ObjectHash::from_type_and_data(ObjectType::Tree, data);
404        Tree::from_bytes(data, h)
405    }
406}
407impl ObjectTrait for Tree {
408    /// Parse a tree body. Entry IDs are sliced with the width of `hash.kind()` —
409    /// the repository kind of the tree being loaded — never the thread-local
410    /// kind, so an explicit-kind loader works on any thread.
411    fn from_bytes(data: &[u8], hash: ObjectHash) -> Result<Self, GitError>
412    where
413        Self: Sized,
414    {
415        let kind = hash.kind();
416        let mut tree_items = Vec::new();
417        let mut i = 0;
418        while i < data.len() {
419            // Find the position of the null byte (0x00)
420            if let Some(index) = memchr::memchr(0x00, &data[i..]) {
421                // Calculate the next position
422                let next = i + index + kind.size() + 1; // +1 for the null byte
423                if next > data.len() {
424                    return Err(GitError::InvalidTreeObject);
425                } //check bounds before slicing the fixed-width id
426                // Extract the bytes and create a TreeItem
427                let item_data = &data[i..next];
428                let tree_item = TreeItem::from_bytes_with_kind(item_data, kind)?;
429
430                tree_items.push(tree_item);
431
432                i = next;
433            } else {
434                // If no null byte is found, return an error
435                return Err(GitError::InvalidTreeObject);
436            }
437        }
438
439        Ok(Tree {
440            id: hash,
441            tree_items,
442        })
443    }
444
445    fn get_type(&self) -> ObjectType {
446        ObjectType::Tree
447    }
448
449    fn get_size(&self) -> usize {
450        self.to_data().map(|data| data.len()).unwrap_or(0)
451    }
452
453    fn to_data(&self) -> Result<Vec<u8>, GitError> {
454        let mut data: Vec<u8> = Vec::new();
455
456        for item in &self.tree_items {
457            data.extend_from_slice(item.to_data().as_slice());
458            //data.push(b'\0');
459        }
460
461        Ok(data)
462    }
463}
464
465#[cfg(test)]
466mod tests {
467
468    use std::str::FromStr;
469
470    use crate::{
471        errors::GitError,
472        hash::{HashKind, ObjectHash, set_hash_kind_for_test},
473        internal::object::tree::{Tree, TreeItem, TreeItemMode},
474    };
475
476    /// Helper: roundtrip a single TreeItem under a given hash kind.
477    fn tree_item_round_trip(kind: HashKind, id_hex: &str) {
478        let _guard = set_hash_kind_for_test(kind);
479        let item = TreeItem::new(
480            TreeItemMode::Blob,
481            ObjectHash::from_str(id_hex).unwrap(),
482            "hello-world".to_string(),
483        );
484
485        let bytes = item.to_data();
486        let parsed = TreeItem::from_bytes(&bytes).unwrap();
487
488        assert_eq!(parsed.mode, TreeItemMode::Blob);
489        assert_eq!(parsed.id, item.id);
490        assert_eq!(parsed.name, item.name);
491    }
492
493    /// TreeItem new/to_data/from_bytes roundtrip with SHA-1.
494    #[test]
495    fn tree_item_round_trip_sha1() {
496        tree_item_round_trip(HashKind::Sha1, "8ab686eafeb1f44702738c8b0f24f2567c36da6d");
497    }
498
499    /// TreeItem new/to_data/from_bytes roundtrip with SHA-256.
500    #[test]
501    fn tree_item_round_trip_sha256() {
502        tree_item_round_trip(
503            HashKind::Sha256,
504            "2cf8d83d9ee29543b34a87727421fdecb7e3f3a183d337639025de576db9ebb4",
505        );
506    }
507
508    /// Helper: build a tree from items and assert the resulting ID.
509    fn tree_round_trip(kind: HashKind, items: Vec<(&str, &str)>, expected_id: &str) {
510        let _guard = set_hash_kind_for_test(kind);
511        let tree_items = items
512            .into_iter()
513            .map(|(name, id_hex)| {
514                TreeItem::new(
515                    TreeItemMode::Blob,
516                    ObjectHash::from_str(id_hex).unwrap(),
517                    name.to_string(),
518                )
519            })
520            .collect::<Vec<_>>();
521        let tree = Tree::from_tree_items(tree_items).unwrap();
522        assert_eq!(tree.id.to_string(), expected_id);
523    }
524
525    /// Tree construction from items (SHA-1).
526    /// Explicit-kind entry parsing fails closed on malformed input (never panics).
527    #[test]
528    fn tree_item_from_bytes_with_kind_rejects_malformed() {
529        let _guard = set_hash_kind_for_test(HashKind::Sha256);
530        let id = [0x11u8; 20];
531
532        // Non-UTF-8 mode bytes: reported lossily, not a panic.
533        let mut bad_mode = b"\xff\xfe name\0".to_vec();
534        bad_mode.extend_from_slice(&id);
535        assert!(matches!(
536            TreeItem::from_bytes_with_kind(&bad_mode, HashKind::Sha1),
537            Err(GitError::InvalidTreeItem(_))
538        ));
539
540        // Missing NUL separator / missing space.
541        assert!(matches!(
542            TreeItem::from_bytes_with_kind(b"100644 name", HashKind::Sha1),
543            Err(GitError::InvalidTreeItem(_))
544        ));
545        assert!(matches!(
546            TreeItem::from_bytes_with_kind(b"100644", HashKind::Sha1),
547            Err(GitError::InvalidTreeItem(_))
548        ));
549
550        // Wrong id width for the requested kind (20 bytes offered as SHA-256).
551        let mut short_id = b"100644 name\0".to_vec();
552        short_id.extend_from_slice(&id);
553        match TreeItem::from_bytes_with_kind(&short_id, HashKind::Sha256) {
554            Err(GitError::InvalidHashValue(msg)) => {
555                assert!(
556                    msg.contains("sha256") && msg.contains("32") && msg.contains("20"),
557                    "{msg}"
558                )
559            }
560            other => panic!("unexpected: {other:?}"),
561        }
562
563        // Correct width parses regardless of the thread-local kind (20 bytes as SHA-1 while the
564        // thread-local is SHA-256, and 32 bytes as SHA-256 while the thread-local is SHA-1).
565        let item = TreeItem::from_bytes_with_kind(&short_id, HashKind::Sha1).unwrap();
566        assert_eq!(item.id, ObjectHash::Sha1(id));
567        assert_eq!(item.name, "name");
568        {
569            let _guard = set_hash_kind_for_test(HashKind::Sha1);
570            let wide_id = [0x22u8; 32];
571            let mut wide = b"100755 wide\0".to_vec();
572            wide.extend_from_slice(&wide_id);
573            let item = TreeItem::from_bytes_with_kind(&wide, HashKind::Sha256).unwrap();
574            assert_eq!(item.id, ObjectHash::Sha256(wide_id));
575            assert_eq!(item.mode, TreeItemMode::BlobExecutable);
576            assert_eq!(item.name, "wide");
577            assert!(TreeItem::from_bytes_with_kind(&wide, HashKind::Sha1).is_err());
578        }
579    }
580
581    #[test]
582    fn tree_from_items_sha1() {
583        tree_round_trip(
584            HashKind::Sha1,
585            vec![("hello-world", "17288789afffb273c8c394bc65e87d899b92897b")],
586            "cf99336fa61439a2f074c7e6de1c1a05579550e2",
587        );
588    }
589
590    /// Tree construction from items (SHA-256).
591    #[test]
592    fn tree_from_items_sha256() {
593        tree_round_trip(
594            HashKind::Sha256,
595            vec![
596                (
597                    "a.txt",
598                    "2cf8d83d9ee29543b34a87727421fdecb7e3f3a183d337639025de576db9ebb4",
599                ),
600                (
601                    "b.txt",
602                    "fc2593998f8e1dec9c3a8be11557888134dad90ef5c7a2d6236ed75534c7698e",
603                ),
604                (
605                    "c.txt",
606                    "21513dcb4d6f9eb247db3b4c52158395d94f809cbaa2630bd2a7a474d9b39fab",
607                ),
608                (
609                    "hello-world",
610                    "2cf8d83d9ee29543b34a87727421fdecb7e3f3a183d337639025de576db9ebb4",
611                ),
612                (
613                    "message.txt",
614                    "9ba9ae56288652bf32f074f922e37d3e95df8920b3cdfc053309595b8f86cbc6",
615                ),
616            ],
617            "d712a36aadfb47cabc7aaa90cf9e515773ba3bfc1fe3783730b387ce15c49261",
618        );
619    }
620}