use crate::error::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::fs;
pub(crate) fn now_ts() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangeGroup {
pub files: Vec<String>,
pub description: String,
pub created_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchInfo {
pub name: String,
pub created_at: u64,
pub updated_at: u64,
pub change_group: ChangeGroup,
pub status: BranchStatus,
#[serde(default)]
pub template: Option<String>,
#[serde(default)]
pub worktree: Option<std::path::PathBuf>,
#[serde(default)]
pub branchless: bool,
#[serde(default)]
pub depends_on: Vec<String>,
#[serde(default)]
pub last_commit: Option<String>,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub parent_branch: Option<String>,
#[serde(default)]
pub agent_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BranchStatus {
Active,
Merged,
Archived,
}
impl BranchStatus {
pub fn as_str(&self) -> &str {
match self {
BranchStatus::Active => "active",
BranchStatus::Merged => "merged",
BranchStatus::Archived => "archived",
}
}
}
pub struct BranchManager {
pub branches: HashMap<String, BranchInfo>,
data_file: std::path::PathBuf,
}
impl BranchManager {
pub async fn new(data_file: std::path::PathBuf) -> Result<Self> {
let mut manager = Self {
branches: HashMap::new(),
data_file,
};
if let Err(e) = manager.load_branches().await {
warn!("Failed to load existing branches: {}", e);
}
Ok(manager)
}
pub async fn save(&self) -> Result<()> {
self.save_branches().await
}
pub async fn get_all_branches(&self) -> Result<Vec<(String, BranchStatus)>> {
Ok(self.branches.values()
.map(|branch| (branch.name.clone(), branch.status.clone()))
.collect())
}
pub async fn update_branch_status(&mut self, branch_name: &str, status: BranchStatus) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.status = status;
branch.updated_at = now_ts();
self.save_branches().await?;
}
Ok(())
}
pub async fn update_branch_files(&mut self, branch_name: &str, files: &[String]) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
for f in files {
if !branch.change_group.files.contains(f) {
branch.change_group.files.push(f.clone());
}
}
branch.updated_at = now_ts();
self.save_branches().await?;
}
Ok(())
}
pub async fn set_branch_last_commit(&mut self, branch_name: &str, commit_hash: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.last_commit = Some(commit_hash.to_string());
branch.updated_at = now_ts();
self.save_branches().await?;
}
Ok(())
}
pub async fn remove_branch(&mut self, branch_name: &str) -> Result<()> {
self.branches.remove(branch_name);
self.save_branches().await
}
pub async fn register_branch(&mut self, branch_name: &str, files: Vec<String>, description: String) -> Result<()> {
self.register_branch_with_template(branch_name, files, description, Vec::new(), None).await
}
pub async fn register_branch_with_template(&mut self, branch_name: &str, files: Vec<String>, description: String, depends_on: Vec<String>, template: Option<String>) -> Result<()> {
self.register_branch_full(branch_name, files, description, depends_on, template, Vec::new(), None).await
}
#[allow(clippy::too_many_arguments)]
pub async fn register_branch_full(&mut self, branch_name: &str, files: Vec<String>, description: String, depends_on: Vec<String>, template: Option<String>, tags: Vec<String>, agent_id: Option<String>) -> Result<()> {
self.register_branch_full_no_save(branch_name, files, description, depends_on, template, tags, agent_id).await?;
self.save_branches().await
}
#[allow(clippy::too_many_arguments)]
pub async fn register_branch_full_no_save(&mut self, branch_name: &str, files: Vec<String>, description: String, depends_on: Vec<String>, template: Option<String>, tags: Vec<String>, agent_id: Option<String>) -> Result<()> {
info!("Registering branch: {}", branch_name);
let change_group = ChangeGroup {
files,
description,
created_at: now_ts(),
};
let branch_info = BranchInfo {
name: branch_name.to_string(),
created_at: now_ts(),
updated_at: now_ts(),
change_group,
status: BranchStatus::Active,
template,
worktree: None,
branchless: false,
depends_on,
last_commit: None,
tags,
parent_branch: None,
agent_id,
};
self.branches.insert(branch_name.to_string(), branch_info);
Ok(())
}
pub async fn set_branch_worktree(&mut self, branch_name: &str, path: std::path::PathBuf) -> Result<()> {
self.set_branch_worktree_no_save(branch_name, path).await?;
self.save_branches().await
}
pub async fn set_branch_worktree_no_save(&mut self, branch_name: &str, path: std::path::PathBuf) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.worktree = Some(path);
branch.updated_at = now_ts();
}
Ok(())
}
pub async fn set_parent_branch(&mut self, branch_name: &str, parent: &str) -> Result<()> {
self.set_parent_branch_no_save(branch_name, parent).await?;
self.save_branches().await
}
pub async fn set_parent_branch_no_save(&mut self, branch_name: &str, parent: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.parent_branch = Some(parent.to_string());
branch.updated_at = now_ts();
}
Ok(())
}
pub fn get_parent_branch(&self, branch_name: &str) -> Option<&str> {
self.branches.get(branch_name)
.and_then(|b| b.parent_branch.as_deref())
}
pub async fn clear_branch_worktree(&mut self, branch_name: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.worktree = None;
branch.updated_at = now_ts();
self.save_branches().await?;
}
Ok(())
}
pub fn get_branch(&self, branch_name: &str) -> Option<&BranchInfo> {
self.branches.get(branch_name)
}
pub fn list_branches(&self) -> Vec<&BranchInfo> {
self.branches.values().collect()
}
pub fn list_branches_by_status(&self, status: BranchStatus) -> Vec<&BranchInfo> {
self.branches.values()
.filter(|branch| branch.status == status)
.collect()
}
pub fn list_branches_by_agent(&self, agent_id: &str) -> Vec<&BranchInfo> {
self.branches.values()
.filter(|b| b.agent_id.as_deref() == Some(agent_id))
.collect()
}
pub fn list_branches_by_tag(&self, tag: &str) -> Vec<&BranchInfo> {
self.branches.values()
.filter(|branch| branch.tags.iter().any(|t| t == tag))
.collect()
}
pub async fn add_tag(&mut self, branch_name: &str, tag: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name)
&& !branch.tags.iter().any(|t| t == tag)
{
branch.tags.push(tag.to_string());
branch.updated_at = now_ts();
self.save_branches().await?;
}
Ok(())
}
pub async fn remove_tag(&mut self, branch_name: &str, tag: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.tags.retain(|t| t != tag);
branch.updated_at = now_ts();
self.save_branches().await?;
}
Ok(())
}
pub async fn mark_branch_merged(&mut self, branch_name: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.status = BranchStatus::Merged;
branch.updated_at = now_ts();
self.save_branches().await?;
info!("Branch '{}' marked as merged", branch_name);
} else {
bail!("Branch '{}' not found", branch_name);
}
Ok(())
}
pub async fn archive_branch(&mut self, branch_name: &str) -> Result<()> {
if let Some(branch) = self.branches.get_mut(branch_name) {
branch.status = BranchStatus::Archived;
branch.updated_at = now_ts();
self.save_branches().await?;
info!("Branch '{}' archived", branch_name);
} else {
bail!("Branch '{}' not found", branch_name);
}
Ok(())
}
pub async fn archive_old_branches(&mut self, days_old: u32) -> Result<Vec<String>> {
let cutoff = now_ts().saturating_sub(days_old as u64 * 86400);
let mut archived = Vec::new();
for (name, branch) in self.branches.iter_mut() {
if branch.updated_at < cutoff &&
matches!(branch.status, BranchStatus::Active | BranchStatus::Merged) {
branch.status = BranchStatus::Archived;
archived.push(name.clone());
}
}
if !archived.is_empty() {
self.save_branches().await?;
info!("Archived {} old branches", archived.len());
}
Ok(archived)
}
async fn load_branches(&mut self) -> Result<()> {
if !self.data_file.exists() {
return Ok(());
}
let content = fs::read_to_string(&self.data_file).await
.context("Failed to read branches file")?;
self.branches = serde_json::from_str(&content)
.context("Failed to parse branches file")?;
debug!("Loaded {} branches from disk", self.branches.len());
Ok(())
}
async fn save_branches(&self) -> Result<()> {
if let Some(parent) = self.data_file.parent() {
fs::create_dir_all(parent).await
.context("Failed to create data directory")?;
}
let content = serde_json::to_string_pretty(&self.branches)
.context("Failed to serialize branches")?;
crate::atomic::write_atomic(&self.data_file, content.as_bytes())
.context("Failed to write branches file")?;
debug!("Saved {} branches to disk", self.branches.len());
Ok(())
}
pub async fn cleanup(&self) -> Result<()> {
if self.data_file.exists() {
fs::remove_file(&self.data_file).await
.context("Failed to remove branches file")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
async fn create_test_branch_manager() -> (BranchManager, TempDir) {
let temp_dir = TempDir::new().unwrap();
let db_path = temp_dir.path().join("test_branches.json");
let manager = BranchManager::new(db_path).await.unwrap();
(manager, temp_dir)
}
#[tokio::test]
async fn test_branch_manager_creation() {
let temp_dir = TempDir::new().unwrap();
let db_path = temp_dir.path().join("branches.json");
let branch_manager = BranchManager::new(db_path.clone()).await;
assert!(branch_manager.is_ok());
let branch_manager = branch_manager.unwrap();
branch_manager.save().await.unwrap();
assert!(db_path.exists());
}
#[tokio::test]
async fn test_branch_registration() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
let result = branch_manager.register_branch(
"feature-test",
vec!["src/main.rs".to_string()],
"Test feature".to_string()
).await;
assert!(result.is_ok());
let branch_info = branch_manager.get_branch("feature-test").unwrap();
assert_eq!(branch_info.name, "feature-test");
assert_eq!(branch_info.status, BranchStatus::Active);
}
#[tokio::test]
async fn test_branch_status_transitions() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"feature-status",
vec!["src/test.rs".to_string()],
"Status test".to_string()
).await.unwrap();
let info = branch_manager.get_branch("feature-status").unwrap();
assert_eq!(info.status, BranchStatus::Active);
let result = branch_manager.mark_branch_merged("feature-status").await;
assert!(result.is_ok());
let info = branch_manager.get_branch("feature-status").unwrap();
assert_eq!(info.status, BranchStatus::Merged);
}
#[tokio::test]
async fn test_branch_listing() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
let branches = vec!["feature-1", "feature-2", "bugfix-1"];
for branch_name in &branches {
branch_manager.register_branch(
branch_name,
vec![format!("src/{}.rs", branch_name)],
format!("{} branch", branch_name)
).await.unwrap();
}
let all_branches = branch_manager.get_all_branches().await.unwrap();
assert_eq!(all_branches.len(), 3);
let active_branches = branch_manager.list_branches_by_status(BranchStatus::Active);
assert_eq!(active_branches.len(), 3);
let merged_branches = branch_manager.list_branches_by_status(BranchStatus::Merged);
assert_eq!(merged_branches.len(), 0);
}
#[tokio::test]
async fn test_branch_cleanup() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"old-feature",
vec!["src/old.rs".to_string()],
"Old feature".to_string()
).await.unwrap();
if let Some(branch) = branch_manager.branches.get_mut("old-feature") {
branch.updated_at = now_ts() - 40 * 86400;
}
branch_manager.register_branch(
"recent-feature",
vec!["src/recent.rs".to_string()],
"Recent feature".to_string()
).await.unwrap();
let cleaned = branch_manager.archive_old_branches(30).await.unwrap();
assert_eq!(cleaned.len(), 1);
assert!(cleaned.contains(&"old-feature".to_string()));
let old_info = branch_manager.get_branch("old-feature").unwrap();
assert_eq!(old_info.status, BranchStatus::Archived);
let recent_info = branch_manager.get_branch("recent-feature").unwrap();
assert_eq!(recent_info.status, BranchStatus::Active);
}
#[test]
fn test_branch_status_enum() {
let active_status = BranchStatus::Active;
let merged_status = BranchStatus::Merged;
assert_ne!(active_status, merged_status);
assert_eq!(active_status, BranchStatus::Active);
}
#[tokio::test]
async fn test_update_branch_status() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"feature-update",
vec!["src/test.rs".to_string()],
"Update test".to_string()
).await.unwrap();
let result = branch_manager.update_branch_status("feature-update", BranchStatus::Merged).await;
assert!(result.is_ok());
let info = branch_manager.get_branch("feature-update").unwrap();
assert_eq!(info.status, BranchStatus::Merged);
}
#[tokio::test]
async fn test_update_branch_files() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"feature-files",
vec!["src/a.rs".to_string()],
"Files test".to_string()
).await.unwrap();
let new_files = vec!["src/a.rs".to_string(), "src/b.rs".to_string()];
let result = branch_manager.update_branch_files("feature-files", &new_files).await;
assert!(result.is_ok());
let info = branch_manager.get_branch("feature-files").unwrap();
assert_eq!(info.change_group.files, new_files);
}
#[tokio::test]
async fn test_remove_branch() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"feature-remove",
vec!["src/test.rs".to_string()],
"Remove test".to_string()
).await.unwrap();
assert!(branch_manager.get_branch("feature-remove").is_some());
let result = branch_manager.remove_branch("feature-remove").await;
assert!(result.is_ok());
assert!(branch_manager.get_branch("feature-remove").is_none());
}
#[tokio::test]
async fn test_remove_nonexistent_branch() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
let result = branch_manager.remove_branch("nonexistent").await;
assert!(result.is_ok()); }
#[tokio::test]
async fn test_get_all_branches_empty() {
let (branch_manager, _temp_dir) = create_test_branch_manager().await;
let branches = branch_manager.get_all_branches().await.unwrap();
assert!(branches.is_empty());
}
#[tokio::test]
async fn test_branchless_bookmark() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"bookmark-1",
vec!["src/main.rs".to_string()],
"Branchless test".to_string()
).await.unwrap();
let info = branch_manager.get_branch("bookmark-1").unwrap();
assert!(!info.branchless);
if let Some(branch) = branch_manager.branches.get_mut("bookmark-1") {
branch.branchless = true;
branch_manager.save().await.unwrap();
}
let info = branch_manager.get_branch("bookmark-1").unwrap();
assert!(info.branchless);
}
#[tokio::test]
async fn test_cleanup_no_old_branches() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch(
"recent",
vec!["src/test.rs".to_string()],
"Recent branch".to_string()
).await.unwrap();
let cleaned = branch_manager.archive_old_branches(30).await.unwrap();
assert!(cleaned.is_empty());
let info = branch_manager.get_branch("recent").unwrap();
assert_eq!(info.status, BranchStatus::Active);
}
#[tokio::test]
async fn test_load_and_save_persistence() {
let temp_dir = TempDir::new().unwrap();
let db_path = temp_dir.path().join("branches.json");
let mut manager = BranchManager::new(db_path.clone()).await.unwrap();
manager.register_branch("persist-test", vec!["src/main.rs".to_string()], "Test".to_string()).await.unwrap();
manager.save().await.unwrap();
let loaded_manager = BranchManager::new(db_path).await.unwrap();
let branch = loaded_manager.get_branch("persist-test").unwrap();
assert_eq!(branch.name, "persist-test");
assert_eq!(branch.status, BranchStatus::Active);
}
#[tokio::test]
async fn test_load_nonexistent_file_creates_empty() {
let temp_dir = TempDir::new().unwrap();
let db_path = temp_dir.path().join("nonexistent.json");
let manager = BranchManager::new(db_path).await.unwrap();
let branches = manager.get_all_branches().await.unwrap();
assert!(branches.is_empty());
}
#[tokio::test]
async fn test_tags_add_remove_list() {
let (mut branch_manager, _temp_dir) = create_test_branch_manager().await;
branch_manager.register_branch_full(
"tagged-op",
vec!["src/main.rs".to_string()],
"Tagged operation".to_string(),
Vec::new(),
None,
vec!["sprint-42".to_string(), "bugfix-week".to_string()],
None,
).await.unwrap();
let info = branch_manager.get_branch("tagged-op").unwrap();
assert_eq!(info.tags.len(), 2);
assert!(info.tags.contains(&"sprint-42".to_string()));
let sprint_branches = branch_manager.list_branches_by_tag("sprint-42");
assert_eq!(sprint_branches.len(), 1);
let bugfix_branches = branch_manager.list_branches_by_tag("bugfix-week");
assert_eq!(bugfix_branches.len(), 1);
let none_branches = branch_manager.list_branches_by_tag("nonexistent");
assert_eq!(none_branches.len(), 0);
branch_manager.remove_tag("tagged-op", "bugfix-week").await.unwrap();
let info = branch_manager.get_branch("tagged-op").unwrap();
assert_eq!(info.tags.len(), 1);
assert!(!info.tags.contains(&"bugfix-week".to_string()));
branch_manager.add_tag("tagged-op", "hotfix").await.unwrap();
let info = branch_manager.get_branch("tagged-op").unwrap();
assert!(info.tags.contains(&"hotfix".to_string()));
branch_manager.add_tag("tagged-op", "hotfix").await.unwrap();
let info = branch_manager.get_branch("tagged-op").unwrap();
assert_eq!(info.tags.iter().filter(|t| *t == "hotfix").count(), 1);
}
}