Skip to main content

lit/commands/
branch.rs

1use crate::core::{
2    delete_ref, find_repo_root, get_current_branch, list_refs, read_head, write_ref,
3};
4use crate::response::{BranchEntry, BranchResponse};
5
6pub fn execute(
7    name: Option<String>,
8    delete: bool,
9    _all: bool,
10) -> Result<BranchResponse, crate::errors::LitError> {
11    let repo_root = find_repo_root()?;
12
13    if delete {
14        if let Some(branch_name) = name {
15            // Check if trying to delete current branch
16            if let Ok(current) = get_current_branch(&repo_root) {
17                if current == branch_name {
18                    return Err("Cannot delete the currently checked out branch".into());
19                }
20            }
21            delete_ref(&repo_root, &format!("heads/{}", branch_name))?;
22            Ok(BranchResponse::Delete { name: branch_name })
23        } else {
24            Err("Branch name required for deletion".into())
25        }
26    } else if let Some(branch_name) = name {
27        let head_hash = read_head(&repo_root)?;
28        write_ref(&repo_root, &format!("heads/{}", branch_name), &head_hash)?;
29        Ok(BranchResponse::Create { name: branch_name })
30    } else {
31        let refs = list_refs(&repo_root, "heads")?;
32        let current = get_current_branch(&repo_root).ok();
33        let branches = refs
34            .into_iter()
35            .map(|r| BranchEntry {
36                name: r.name.clone(),
37                is_current: Some(&r.name) == current.as_ref(),
38            })
39            .collect();
40        Ok(BranchResponse::List { branches })
41    }
42}