use sha1::{Sha1, Digest};
use std::path::{Path, PathBuf};
pub type ObjectId = String;
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectType {
Blob,
Tree,
Commit,
}
impl ObjectType {
fn as_str(&self) -> &'static str {
match self {
ObjectType::Blob => "blob",
ObjectType::Tree => "tree",
ObjectType::Commit => "commit",
}
}
}
#[derive(Debug, Clone)]
pub struct Blob {
pub content: Vec<u8>,
}
impl Blob {
pub fn new(content: Vec<u8>) -> Self {
Self { content }
}
pub fn id(&self) -> ObjectId {
hash_object(ObjectType::Blob, &self.content)
}
pub fn serialize(&self) -> Vec<u8> {
self.content.clone()
}
pub fn deserialize(data: &[u8]) -> Self {
Self {
content: data.to_vec(),
}
}
}
#[derive(Debug, Clone)]
pub struct TreeEntry {
pub mode: u32,
pub name: String,
pub id: ObjectId,
}
#[derive(Debug, Clone)]
pub struct Tree {
pub entries: Vec<TreeEntry>,
}
impl Tree {
pub fn new(entries: Vec<TreeEntry>) -> Self {
Self { entries }
}
pub fn id(&self) -> ObjectId {
let data = self.serialize();
hash_object(ObjectType::Tree, &data)
}
pub fn serialize(&self) -> Vec<u8> {
let mut out = Vec::new();
for entry in &self.entries {
out.extend_from_slice(format!("{} {}\0", entry.mode, entry.name).as_bytes());
let bytes = hex_decode(&entry.id);
out.extend_from_slice(&bytes);
}
out
}
pub fn deserialize(data: &[u8]) -> Self {
let mut entries = Vec::new();
let mut pos = 0;
while pos < data.len() {
let null_pos = match data[pos..].iter().position(|&b| b == 0) {
Some(p) => pos + p,
None => break,
};
let header = String::from_utf8_lossy(&data[pos..null_pos]);
let mut parts = header.splitn(2, ' ');
let mode: u32 = parts.next().unwrap_or("0").parse().unwrap_or(0);
let name = parts.next().unwrap_or("").to_string();
pos = null_pos + 1;
if pos + 20 > data.len() {
break;
}
let hash_bytes = &data[pos..pos + 20];
let id = hex_encode(hash_bytes);
pos += 20;
entries.push(TreeEntry { mode, name, id });
}
Self { entries }
}
}
#[derive(Debug, Clone)]
pub struct Commit {
pub tree: ObjectId,
pub parents: Vec<ObjectId>,
pub author: String,
pub message: String,
pub timestamp: u64,
}
impl Commit {
pub fn new(tree: ObjectId, parents: Vec<ObjectId>, author: String, message: String, timestamp: u64) -> Self {
Self { tree, parents, author, message, timestamp }
}
pub fn id(&self) -> ObjectId {
let data = self.serialize();
hash_object(ObjectType::Commit, &data)
}
pub fn serialize(&self) -> Vec<u8> {
let mut out = String::new();
out.push_str(&format!("tree {}\n", self.tree));
for p in &self.parents {
out.push_str(&format!("parent {}\n", p));
}
out.push_str(&format!("author {} {}\n", self.author, self.timestamp));
out.push_str(&format!("committer {} {}\n", self.author, self.timestamp));
out.push('\n');
out.push_str(&self.message);
out.into_bytes()
}
pub fn deserialize(data: &[u8]) -> Self {
let text = String::from_utf8_lossy(data);
let mut tree = String::new();
let mut parents = Vec::new();
let mut author = String::new();
let mut timestamp = 0u64;
let mut message = String::new();
let mut in_header = true;
for line in text.lines() {
if in_header {
if line.is_empty() {
in_header = false;
continue;
}
if let Some(rest) = line.strip_prefix("tree ") {
tree = rest.to_string();
} else if let Some(rest) = line.strip_prefix("parent ") {
parents.push(rest.to_string());
} else if let Some(rest) = line.strip_prefix("author ") {
let mut parts = rest.rsplitn(2, ' ');
if let Some(ts) = parts.next() {
timestamp = ts.parse().unwrap_or(0);
}
if let Some(name) = parts.next() {
author = name.to_string();
}
}
} else {
if !message.is_empty() {
message.push('\n');
}
message.push_str(line);
}
}
Self { tree, parents, author, message, timestamp }
}
}
pub fn hash_object(obj_type: ObjectType, content: &[u8]) -> ObjectId {
let header = format!("{} {}\0", obj_type.as_str(), content.len());
let mut hasher = Sha1::new();
hasher.update(header.as_bytes());
hasher.update(content);
let result = hasher.finalize();
hex_encode(&result)
}
pub fn hex_encode(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
pub fn hex_decode(hex: &str) -> Vec<u8> {
(0..hex.len())
.step_by(2)
.filter_map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok())
.collect()
}
pub fn object_path(store_root: &Path, id: &str) -> PathBuf {
let (dir, file) = id.split_at(2);
store_root.join("objects").join(dir).join(file)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_blob_hash_deterministic() {
let blob1 = Blob::new(b"hello world".to_vec());
let blob2 = Blob::new(b"hello world".to_vec());
assert_eq!(blob1.id(), blob2.id());
}
#[test]
fn test_blob_hash_differs_for_different_content() {
let blob1 = Blob::new(b"hello".to_vec());
let blob2 = Blob::new(b"world".to_vec());
assert_ne!(blob1.id(), blob2.id());
}
#[test]
fn test_blob_roundtrip() {
let blob = Blob::new(b"test content".to_vec());
let serialized = blob.serialize();
let deserialized = Blob::deserialize(&serialized);
assert_eq!(blob.content, deserialized.content);
assert_eq!(blob.id(), deserialized.id());
}
#[test]
fn test_tree_roundtrip() {
let tree = Tree::new(vec![
TreeEntry { mode: 0o100644, name: "file.txt".to_string(), id: "abcdef1234567890abcdef1234567890abcdef12".to_string() },
TreeEntry { mode: 0o100644, name: "src/main.rs".to_string(), id: "1234567890abcdef1234567890abcdef12345678".to_string() },
]);
let serialized = tree.serialize();
let deserialized = Tree::deserialize(&serialized);
assert_eq!(tree.entries.len(), deserialized.entries.len());
for (a, b) in tree.entries.iter().zip(deserialized.entries.iter()) {
assert_eq!(a.mode, b.mode);
assert_eq!(a.name, b.name);
assert_eq!(a.id, b.id);
}
}
#[test]
fn test_commit_roundtrip() {
let commit = Commit::new(
"abc123".to_string(),
vec!["parent1".to_string()],
"agent".to_string(),
"Fix bug".to_string(),
1700000000,
);
let serialized = commit.serialize();
let deserialized = Commit::deserialize(&serialized);
assert_eq!(commit.tree, deserialized.tree);
assert_eq!(commit.parents, deserialized.parents);
assert_eq!(commit.author, deserialized.author);
assert_eq!(commit.message, deserialized.message);
assert_eq!(commit.timestamp, deserialized.timestamp);
}
#[test]
fn test_commit_hash_deterministic() {
let c1 = Commit::new("tree1".to_string(), vec![], "agent".to_string(), "msg".to_string(), 100);
let c2 = Commit::new("tree1".to_string(), vec![], "agent".to_string(), "msg".to_string(), 100);
assert_eq!(c1.id(), c2.id());
}
#[test]
fn test_hex_encode_decode() {
let bytes = [0xab, 0xcd, 0xef];
let hex = hex_encode(&bytes);
assert_eq!(hex, "abcdef");
let decoded = hex_decode(&hex);
assert_eq!(decoded, bytes.to_vec());
}
#[test]
fn test_object_path() {
let root = PathBuf::from("/repo/.codetree");
let path = object_path(&root, "abcdef1234567890abcdef1234567890abcdef12");
assert_eq!(path, PathBuf::from("/repo/.codetree/objects/ab/cdef1234567890abcdef1234567890abcdef12"));
}
}