1use std::io::Write;
4
5use gix_object::{Kind, WriteTo};
6
7use ring::digest::Digest;
8
9mod blob;
10mod commit;
11mod tag;
12mod tree;
13
14pub use blob::Blob;
15pub use commit::Commit;
16pub use tag::Tag;
17pub use tree::{Tree, TreeEntry};
18
19use crate::{Error, WithError};
20
21#[derive(Debug)]
22pub enum Object {
23 Commit(Box<Commit>),
24 Tree(Tree),
25 Blob(Blob),
26 Tag(Tag),
27}
28
29impl Object {
30 #[must_use]
31 pub fn hash(&self) -> Digest {
32 match self {
33 Self::Commit(data) => data.hash,
34 Self::Tree(tree) => tree.hash,
35 Self::Blob(blob) => blob.hash,
36 Self::Tag(tag) => tag.hash,
37 }
38 }
39
40 #[must_use]
41 pub fn kind(&self) -> Kind {
42 match self {
43 Self::Commit(_) => Kind::Commit,
44 Self::Tree(_) => Kind::Tree,
45 Self::Blob(_) => Kind::Blob,
46 Self::Tag(_) => Kind::Tag,
47 }
48 }
49
50 pub fn write_to<W: Write>(&self, mut writer: W) -> Result<(), Error> {
52 match self {
53 Object::Commit(commit) => {
54 let size = commit.size();
55 write!(writer, "commit {size}\x00")?;
56
57 commit
58 .commit
59 .write_to(&mut writer)
60 .with_err_msg("could not write commit")
61 }
62 Object::Tree(tree) => {
63 let size = tree.size();
64 write!(writer, "tree {size}\x00")?;
65
66 tree.write_to(writer).with_err_msg("could not write tree")
67 }
68 Object::Blob(blob) => {
69 let size = blob.content.len();
70 write!(writer, "blob {size}\x00")?;
71
72 writer
73 .write_all(&blob.content)
74 .with_err_msg("could not write blob")
75 }
76 Object::Tag(tag) => {
77 let size = tag.tag.size();
78 write!(writer, "tag {size}\x00")?;
79
80 tag.tag
81 .write_to(&mut writer)
82 .with_err_msg("could not write tag")
83 }
84 }
85 }
86
87 #[must_use]
88 pub fn size(&self) -> u64 {
89 match self {
90 Self::Commit(commit) => commit.size(),
91 Self::Tree(tree) => tree.size(),
92 Self::Blob(blob) => blob.size(),
93 Self::Tag(tag) => tag.size(),
94 }
95 }
96}