Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 134 additions & 2 deletions src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl Blob {
}
}

#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub struct Tree {
pub files: Vec<File>,
}
Expand All @@ -34,6 +34,20 @@ impl Tree {
pub fn new(files: Vec<File>) -> Tree {
Tree { files }
}

// Format (one per file/folder/tree/submodule):
// [mode] [object name]\0[SHA-1 in binary format (20 bytes)]
pub fn to_bytes(&self) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
for file in &self.files {
bytes.extend(file.mode.mode_str().as_bytes());
bytes.push(b' ');
bytes.extend(file.name.as_bytes());
bytes.push(0);
bytes.extend(hex::decode(&file.hash).context("Invalid hash")?);
}
Ok(bytes)
}
}

#[derive(Debug, PartialEq)]
Expand Down Expand Up @@ -87,7 +101,7 @@ impl File {
}
}

#[derive(Debug, Default)]
#[derive(Debug, Default, PartialEq)]
pub struct Commit {
// Git seems to only consider the following standard headers:
// https://github.com/git/git/blob/7b0defb3915eaa0bd118f0996e8c00b4eb2dc1ca/commit.c#L1442
Expand All @@ -101,6 +115,33 @@ pub struct Commit {
pub message: String,
}

impl Commit {
// Format is:
// [key] [value]
// ...
// <empty line>
// [commit message]
pub fn to_bytes(&self) -> Vec<u8> {
let mut headers = vec![("tree", &self.tree)];
if !self.parent.is_empty() {
headers.push(("parent", &self.parent));
}
headers.push(("author", &self.author));
headers.push(("committer", &self.committer));
if !self.encoding.is_empty() {
headers.push(("encoding", &self.encoding));
}

let mut content = String::new();
for (key, value) in headers {
content.push_str(&format!("{key} {value}\n"));
}
content.push('\n');
content.push_str(&self.message);
content.into_bytes()
}
}

#[derive(Debug)]
pub enum Object {
Blob(Blob),
Expand Down Expand Up @@ -320,11 +361,102 @@ mod tests {
use crate::object::File;

use super::Blob;
use super::Commit;
use super::Mode;
use super::Object;
use super::Tree;
use super::hash;
use super::write_object;
use crate::repo::Repo;

#[test]
fn test_tree_to_bytes() {
let tree = Tree::new(vec![
File {
mode: Mode::NormalFile,
name: "a.txt".to_string(),
hash: "78981922613b2afb6025042ff6bd878ac1994e85".to_string(),
},
File {
mode: Mode::Tree,
name: "dir".to_string(),
hash: "ce013625030ba8dba906f756967f9e9ca394464a".to_string(),
},
]);
let content = tree.to_bytes().unwrap();
let expected = [
b"100644 a.txt\0".as_slice(),
&hex::decode("78981922613b2afb6025042ff6bd878ac1994e85").unwrap(),
b"40000 dir\0",
&hex::decode("ce013625030ba8dba906f756967f9e9ca394464a").unwrap(),
]
.concat();
assert_eq!(content, expected);

let data = [format!("tree {}\0", content.len()).into_bytes(), content].concat();
let Object::Tree(parsed) = Object::from_bytes(&data).unwrap() else {
panic!("expected a tree");
};
assert_eq!(parsed, tree);
}

fn test_commit() -> Commit {
Commit {
tree: "1234567890abcdef1234567890abcdef12345678".to_string(),
parent: "aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb".to_string(),
author: "Bob <bob@bob.test>".to_string(),
committer: "Alice <alice@alice.test>".to_string(),
encoding: String::new(),
message: "hello".to_string(),
}
}

#[test]
fn test_commit_to_bytes() {
assert_eq!(
std::str::from_utf8(&test_commit().to_bytes()).unwrap(),
"tree 1234567890abcdef1234567890abcdef12345678\n\
parent aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb\n\
author Bob <bob@bob.test>\n\
committer Alice <alice@alice.test>\n\
\nhello"
);
}

#[test]
fn test_commit_to_bytes_no_parent_with_encoding() {
let commit = Commit {
parent: String::new(),
encoding: "UTF-8".to_string(),
..test_commit()
};
let bytes = commit.to_bytes();
let text = std::str::from_utf8(&bytes).unwrap();
assert!(!text.contains("parent"));
assert!(text.contains("committer Alice <alice@alice.test>\nencoding UTF-8\n\nhello"));
}

#[test]
fn test_commit_to_bytes_from_bytes() {
let commit = test_commit();
let content = commit.to_bytes();
let data = [format!("commit {}\0", content.len()).into_bytes(), content].concat();
let Object::Commit(parsed) = Object::from_bytes(&data).unwrap() else {
panic!("expected a commit");
};
assert_eq!(parsed, commit);
}

#[test]
fn test_tree_to_bytes_invalid_hash() {
let tree = Tree::new(vec![File {
mode: Mode::NormalFile,
name: "a".to_string(),
hash: "zz".to_string(),
}]);
assert!(tree.to_bytes().is_err());
}

#[test]
fn test_object_parse_header() {
assert_eq!(
Expand Down
38 changes: 2 additions & 36 deletions tests/git_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,7 @@ fn create_blob(dir: PathBuf, hash: &str, content: &str) {
}

fn create_tree(dir: PathBuf, hash: &str, tree: &Tree) {
// Format (one per file/folder/tree/submodule):
// [mode] [object name]\0[SHA-1 in binary format (20 bytes)]
let tree_content: Vec<u8> = tree
.files
.iter()
.flat_map(|file| {
let mut bytes = file.mode.mode_str().as_bytes().to_vec();
bytes.push(b' ');
bytes.extend(file.name.as_bytes());
bytes.push(0);
bytes.extend(&hex::decode(&file.hash).unwrap());
bytes
})
.collect();
let tree_content = tree.to_bytes().unwrap();

let tree_header = format!("tree {}\0", tree_content.len()).into_bytes();
let full_bytes = [tree_header, tree_content].concat();
Expand All @@ -49,28 +36,7 @@ fn create_tree(dir: PathBuf, hash: &str, tree: &Tree) {
}

fn create_commit(dir: PathBuf, hash: &str, commit: &Commit) {
// Format is:
// [key] [value]
// ...
// <empty line>
// [commit message]
let content = format!(
"\
tree {}
encoding {}
committer {}
author {}
parent {}

{}",
commit.tree,
commit.encoding,
commit.committer,
commit.author,
commit.parent,
commit.message
)
.into_bytes();
let content = commit.to_bytes();

let header = format!("commit {}\0", content.len()).into_bytes();
let full_bytes = [header, content].concat();
Expand Down
Loading