Skip to main content

ostrya_core/
objname.rs

1//! The name of an object: a checksum and an object type.
2//!
3//! Traversal, prune, and fsck use sets of object names, so the checksum and the
4//! type of a loose object stay together.
5
6use crate::checksum::Checksum;
7use crate::loosepath::loose_path;
8use crate::mode::RepoMode;
9use crate::objtype::ObjectType;
10
11/// A checksum and the type of the object that it identifies.
12///
13/// The [`Display`](std::fmt::Display) form is `<hexchecksum>.<typestr>`. The
14/// `ostree` command prints an object reference in this form. The type string
15/// comes from [`ObjectType::type_str`] and does not depend on the repository
16/// mode. In archive mode, a content object is also `file`, and its loose path
17/// has the `z` suffix that [`ObjectType::extension`] adds.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub struct ObjectName {
20    /// The SHA-256 checksum of the object.
21    pub checksum: Checksum,
22    /// The object type.
23    pub ty: ObjectType,
24}
25
26impl ObjectName {
27    /// Creates an object name from a checksum and an object type.
28    pub fn new(checksum: Checksum, ty: ObjectType) -> ObjectName {
29        ObjectName { checksum, ty }
30    }
31
32    /// Returns the loose path of this object for a repository mode.
33    ///
34    /// The path is relative to the `objects/` directory and has the layout of
35    /// [`loose_path`].
36    pub fn loose_path(&self, mode: RepoMode) -> String {
37        loose_path(&self.checksum, self.ty, mode)
38    }
39}
40
41impl std::fmt::Display for ObjectName {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "{}.{}", self.checksum.to_hex(), self.ty.type_str())
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn string_form_uses_the_mode_independent_type() {
53        let c =
54            Checksum::from_hex("b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89")
55                .unwrap();
56        // A content object is `.file` in the string form regardless of mode.
57        assert_eq!(
58            ObjectName::new(c, ObjectType::File).to_string(),
59            "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89.file"
60        );
61        assert_eq!(
62            ObjectName::new(c, ObjectType::DirTree).to_string(),
63            "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89.dirtree"
64        );
65        // The loose path is mode-aware: archive content carries the z suffix.
66        assert_eq!(
67            ObjectName::new(c, ObjectType::File).loose_path(RepoMode::Archive),
68            "b3/c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89.filez"
69        );
70    }
71}