47 lines
1.5 KiB
Rust
47 lines
1.5 KiB
Rust
//! chrs-code-edit: Autonomous Git-based code editing for CHORUS.
|
|
|
|
use git2::{Repository, BranchType};
|
|
use std::path::Path;
|
|
use thiserror::Error;
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum EditError {
|
|
#[error("Git error: {0}")]
|
|
Git(#[from] git2::Error),
|
|
#[error("IO error: {0}")]
|
|
Io(#[from] std::io::Error),
|
|
}
|
|
|
|
/// Manages isolated Git worktrees/branches for agent tasks.
|
|
pub struct WorktreeManager {
|
|
repo: Repository,
|
|
}
|
|
|
|
impl WorktreeManager {
|
|
/// Open an existing repository.
|
|
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, EditError> {
|
|
let repo = Repository::open(path)?;
|
|
Ok(Self { repo })
|
|
}
|
|
|
|
/// Create a new branch for a specific task.
|
|
///
|
|
/// **Why**: Isolation ensures that agents do not conflict with each other
|
|
/// or the main branch while performing autonomous edits.
|
|
pub fn spawn_task_branch(&self, task_id: &str) -> Result<String, EditError> {
|
|
let branch_name = format!("task/{}", task_id);
|
|
let head = self.repo.head()?.peel_to_commit()?;
|
|
self.repo.branch(&branch_name, &head, false)?;
|
|
println!("[CODE-EDIT] Spawned branch: {}", branch_name);
|
|
Ok(branch_name)
|
|
}
|
|
|
|
/// Checkout a specific branch.
|
|
pub fn checkout_branch(&self, branch_name: &str) -> Result<(), EditError> {
|
|
let obj = self.repo.revparse_single(&format!("refs/heads/{}", branch_name))?;
|
|
self.repo.checkout_tree(&obj, None)?;
|
|
self.repo.set_head(&format!("refs/heads/{}", branch_name))?;
|
|
Ok(())
|
|
}
|
|
}
|