use std::path::{Path, PathBuf};
use crate::error::{Result, Context};
use super::objects::{Blob, Tree, TreeEntry, Commit, ObjectId, object_path, hash_object, ObjectType};
use super::refs::RefManager;
use super::index::Index;
#[derive(Clone)]
pub struct Repository {
root: PathBuf,
refs: RefManager,
}
impl Repository {
pub fn init(path: &Path) -> Result<Self> {
let codetree_dir = path.join(".codetree");
if codetree_dir.exists() {
bail!("Repository already exists at {}", codetree_dir.display());
}
std::fs::create_dir_all(codetree_dir.join("objects"))?;
std::fs::create_dir_all(codetree_dir.join("refs").join("heads"))?;
let repo = Self {
root: codetree_dir.clone(),
refs: RefManager::new(codetree_dir.clone()),
};
let empty_tree = Tree::new(vec![]);
repo.write_object(ObjectType::Tree, &empty_tree.serialize())?;
let tree_id = empty_tree.id();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![],
"CodeTree <init@codetree>".to_string(),
"Initial commit".to_string(),
timestamp,
);
repo.write_object(ObjectType::Commit, &commit.serialize())?;
let commit_id = commit.id();
repo.refs.set_branch("main", &commit_id)?;
repo.refs.set_head("main")?;
Index::new(codetree_dir.clone()).save()?;
Ok(repo)
}
pub fn open(path: &Path) -> Result<Self> {
let codetree_dir = path.join(".codetree");
if !codetree_dir.exists() {
bail!("No CodeTree repository found at {}", path.display());
}
Ok(Self {
root: codetree_dir.clone(),
refs: RefManager::new(codetree_dir),
})
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn refs(&self) -> &RefManager {
&self.refs
}
pub fn write_object(&self, obj_type: ObjectType, data: &[u8]) -> Result<ObjectId> {
let id = hash_object(obj_type.clone(), data);
let path = object_path(&self.root, &id);
if !path.exists() {
let tmp = crate::atomic::temp_sibling(&path);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&tmp, data)?;
std::fs::rename(&tmp, &path)?;
}
Ok(id)
}
pub fn read_object(&self, id: &ObjectId) -> Result<Vec<u8>> {
let path = object_path(&self.root, id);
std::fs::read(&path).context("Object not found")
}
pub fn has_object(&self, id: &str) -> bool {
object_path(&self.root, id).exists()
}
pub fn write_blob(&self, content: &[u8]) -> Result<ObjectId> {
self.write_object(ObjectType::Blob, content)
}
pub fn read_blob(&self, id: &ObjectId) -> Result<Blob> {
let data = self.read_object(id)?;
Ok(Blob::deserialize(&data))
}
pub fn write_tree(&self, tree: &Tree) -> Result<ObjectId> {
self.write_object(ObjectType::Tree, &tree.serialize())
}
pub fn read_tree(&self, id: &ObjectId) -> Result<Tree> {
let data = self.read_object(id)?;
Ok(Tree::deserialize(&data))
}
pub fn write_commit(&self, commit: &Commit) -> Result<ObjectId> {
self.write_object(ObjectType::Commit, &commit.serialize())
}
pub fn read_commit(&self, id: &ObjectId) -> Result<Commit> {
let data = self.read_object(id)?;
Ok(Commit::deserialize(&data))
}
pub fn load_index(&self) -> Result<Index> {
Index::load(self.root.clone())
}
pub fn commit(&self, message: &str, author: &str) -> Result<ObjectId> {
let index = self.load_index()?;
let entries: Vec<TreeEntry> = index.entries_sorted().into_iter().map(|(path, blob_id)| {
TreeEntry { mode: 0o100644, name: path, id: blob_id }
}).collect();
let tree = Tree::new(entries);
let tree_id = self.write_tree(&tree)?;
let parent = self.refs.resolve_head()?;
let parents = parent.into_iter().collect();
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(tree_id, parents, author.to_string(), message.to_string(), timestamp);
let commit_id = self.write_commit(&commit)?;
if let Some(branch) = self.refs.current_branch()? {
self.refs.set_branch(&branch, &commit_id)?;
}
Ok(commit_id)
}
pub fn commit_with_meta(&self, message: &str, author: &str, timestamp: u64) -> Result<ObjectId> {
let index = self.load_index()?;
let entries: Vec<TreeEntry> = index.entries_sorted().into_iter().map(|(path, blob_id)| {
TreeEntry { mode: 0o100644, name: path, id: blob_id }
}).collect();
let tree = Tree::new(entries);
let tree_id = self.write_tree(&tree)?;
let parent = self.refs.resolve_head()?;
let parents = parent.into_iter().collect();
let commit = Commit::new(tree_id, parents, author.to_string(), message.to_string(), timestamp);
let commit_id = self.write_commit(&commit)?;
if let Some(branch) = self.refs.current_branch()? {
self.refs.set_branch(&branch, &commit_id)?;
}
Ok(commit_id)
}
pub fn create_branch(&self, name: &str) -> Result<()> {
let head = self.refs.resolve_head()?
.context("HEAD does not point to a commit")?;
self.refs.set_branch(name, &head)?;
Ok(())
}
pub fn checkout(&self, branch: &str) -> Result<()> {
let commit_id = self.refs.get_branch(branch)?
.context(format!("Branch '{}' not found", branch))?;
self.refs.set_head(branch)?;
let _ = commit_id;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn init_repo() -> (TempDir, Repository) {
let tmp = TempDir::new().unwrap();
let repo = Repository::init(tmp.path()).unwrap();
(tmp, repo)
}
#[test]
fn test_init_creates_structure() {
let (tmp, repo) = init_repo();
assert!(tmp.path().join(".codetree").exists());
assert!(tmp.path().join(".codetree/objects").exists());
assert!(tmp.path().join(".codetree/refs/heads").exists());
assert!(tmp.path().join(".codetree/HEAD").exists());
assert!(tmp.path().join(".codetree/index").exists());
let branches = repo.refs().list_branches().unwrap();
assert!(branches.contains(&"main".to_string()));
assert_eq!(repo.refs().current_branch().unwrap(), Some("main".to_string()));
}
#[test]
fn test_init_fails_if_already_exists() {
let tmp = TempDir::new().unwrap();
Repository::init(tmp.path()).unwrap();
let result = Repository::init(tmp.path());
assert!(result.is_err());
}
#[test]
fn test_open_existing_repo() {
let tmp = TempDir::new().unwrap();
Repository::init(tmp.path()).unwrap();
let repo = Repository::open(tmp.path()).unwrap();
assert_eq!(repo.refs().current_branch().unwrap(), Some("main".to_string()));
}
#[test]
fn test_open_fails_if_no_repo() {
let tmp = TempDir::new().unwrap();
let result = Repository::open(tmp.path());
assert!(result.is_err());
}
#[test]
fn test_write_and_read_blob() {
let (_tmp, repo) = init_repo();
let id = repo.write_blob(b"hello world").unwrap();
let blob = repo.read_blob(&id).unwrap();
assert_eq!(blob.content, b"hello world");
}
#[test]
fn test_write_and_read_tree() {
let (_tmp, repo) = init_repo();
let blob_id = repo.write_blob(b"content").unwrap();
let tree = Tree::new(vec![
TreeEntry { mode: 0o100644, name: "file.txt".to_string(), id: blob_id.clone() },
]);
let tree_id = repo.write_tree(&tree).unwrap();
let read_tree = repo.read_tree(&tree_id).unwrap();
assert_eq!(read_tree.entries.len(), 1);
assert_eq!(read_tree.entries[0].name, "file.txt");
assert_eq!(read_tree.entries[0].id, blob_id);
}
#[test]
fn test_write_and_read_commit() {
let (_tmp, repo) = init_repo();
let tree = Tree::new(vec![]);
let tree_id = repo.write_tree(&tree).unwrap();
let commit = Commit::new(
tree_id,
vec![],
"test".to_string(),
"test commit".to_string(),
12345,
);
let commit_id = repo.write_commit(&commit).unwrap();
let read_commit = repo.read_commit(&commit_id).unwrap();
assert_eq!(read_commit.message, "test commit");
assert_eq!(read_commit.author, "test");
}
#[test]
fn test_has_object() {
let (_tmp, repo) = init_repo();
let id = repo.write_blob(b"data").unwrap();
assert!(repo.has_object(&id));
assert!(!repo.has_object("0000000000000000000000000000000000000000"));
}
#[test]
fn test_create_branch() {
let (_tmp, repo) = init_repo();
repo.create_branch("feature").unwrap();
let branches = repo.refs().list_branches().unwrap();
assert!(branches.contains(&"feature".to_string()));
let main_commit = repo.refs().get_branch("main").unwrap().unwrap();
let feature_commit = repo.refs().get_branch("feature").unwrap().unwrap();
assert_eq!(main_commit, feature_commit);
}
#[test]
fn test_commit_updates_branch_ref() {
let (_tmp, repo) = init_repo();
let mut index = repo.load_index().unwrap();
let blob_id = repo.write_blob(b"hello").unwrap();
index.add("hello.txt", &blob_id);
index.save().unwrap();
let commit_id = repo.commit("Add hello.txt", "agent").unwrap();
let main_commit = repo.refs().get_branch("main").unwrap().unwrap();
assert_eq!(main_commit, commit_id);
let commit = repo.read_commit(&commit_id).unwrap();
assert_eq!(commit.parents.len(), 1);
}
#[test]
fn test_checkout() {
let (_tmp, repo) = init_repo();
repo.create_branch("feature").unwrap();
repo.checkout("feature").unwrap();
assert_eq!(repo.refs().current_branch().unwrap(), Some("feature".to_string()));
}
}