Skip to main content

git2db/
branch.rs

1//! Branch management for tracked repositories
2//!
3//! Provides git-native branch operations similar to `git branch`
4
5use crate::errors::{Git2DBError, Git2DBResult};
6use crate::references::{GitRef, IntoGitRef};
7use crate::registry::{Git2DB, RepoId};
8use crate::repo_accessor::RepositoryAccessor;
9use git2::{BranchType, Oid, Repository};
10
11/// Manager for repository branches
12///
13/// Provides operations similar to `git branch` commands.
14///
15/// # Examples
16///
17/// ```rust,ignore
18/// let repo = registry.repo(repo_id)?;
19/// let branch_mgr = repo.branch();
20///
21/// // List branches
22/// for branch in branch_mgr.list().await? {
23///     let marker = if branch.is_head { "*" } else { " " };
24///     println!("{} {}", marker, branch.name);
25/// }
26///
27/// // Get current branch
28/// if let Some(current) = branch_mgr.current().await? {
29///     println!("On branch: {}", current.name);
30/// }
31///
32/// // Create new branch
33/// branch_mgr.create("feature", Some("main")).await?;
34///
35/// // Checkout branch
36/// branch_mgr.checkout("feature").await?;
37///
38/// // Remove branch
39/// branch_mgr.remove("old-feature", false).await?;
40/// ```
41pub struct BranchManager<'a> {
42    registry: &'a Git2DB,
43    repo_id: RepoId,
44}
45
46impl<'a> RepositoryAccessor for BranchManager<'a> {
47    fn registry(&self) -> &Git2DB {
48        self.registry
49    }
50
51    fn repo_id(&self) -> &RepoId {
52        &self.repo_id
53    }
54}
55
56impl<'a> BranchManager<'a> {
57    /// Create a new branch manager
58    pub(crate) fn new(registry: &'a Git2DB, repo_id: RepoId) -> Self {
59        Self { registry, repo_id }
60    }
61
62    /// List all branches (local and remote)
63    ///
64    /// Similar to `git branch -a`
65    pub async fn list(&self) -> Git2DBResult<Vec<Branch>> {
66        let path = self.repo_path()?;
67
68        tokio::task::spawn_blocking(move || {
69            let repo = Repository::open(&path).map_err(|e| {
70                Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
71            })?;
72
73            let mut branches = Vec::new();
74
75            // Get HEAD for comparison
76            let head_ref = repo.head().ok();
77            let head_name = head_ref
78                .as_ref()
79                .and_then(|h| h.shorthand())
80                .map(std::borrow::ToOwned::to_owned);
81
82            // List local branches
83            for (branch, _) in (repo.branches(Some(BranchType::Local)).map_err(|e| {
84                Git2DBError::internal(format!("Failed to list local branches: {e}"))
85            })?)
86            .flatten()
87            {
88                if let Some(name) = branch.name().ok().flatten() {
89                    let is_head = head_name.as_deref() == Some(name);
90                    let oid = branch.get().target();
91
92                    branches.push(Branch {
93                        name: name.to_owned(),
94                        branch_type: BranchKind::Local,
95                        is_head,
96                        oid,
97                        tracking: branch.upstream().ok().and_then(|u| {
98                            u.name().ok().flatten().map(std::borrow::ToOwned::to_owned)
99                        }),
100                    });
101                }
102            }
103
104            // List remote branches
105            for (branch, _) in (repo.branches(Some(BranchType::Remote)).map_err(|e| {
106                Git2DBError::internal(format!("Failed to list remote branches: {e}"))
107            })?)
108            .flatten()
109            {
110                if let Some(name) = branch.name().ok().flatten() {
111                    let oid = branch.get().target();
112
113                    branches.push(Branch {
114                        name: name.to_owned(),
115                        branch_type: BranchKind::Remote,
116                        is_head: false,
117                        oid,
118                        tracking: None,
119                    });
120                }
121            }
122
123            Ok(branches)
124        })
125        .await
126        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
127    }
128
129    /// Get the current branch (HEAD)
130    ///
131    /// Returns None if HEAD is detached
132    pub async fn current(&self) -> Git2DBResult<Option<Branch>> {
133        let path = self.repo_path()?;
134
135        tokio::task::spawn_blocking(move || {
136            let repo = Repository::open(&path).map_err(|e| {
137                Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
138            })?;
139
140            let head = repo
141                .head()
142                .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
143
144            // Check if HEAD is a branch
145            if !head.is_branch() {
146                return Ok(None);
147            }
148
149            let name = head
150                .shorthand()
151                .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD has no name"))?
152                .to_owned();
153
154            let oid = head.target();
155
156            // Try to find the branch to get tracking info
157            let tracking = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
158                branch
159                    .upstream()
160                    .ok()
161                    .and_then(|u| u.name().ok().flatten().map(std::borrow::ToOwned::to_owned))
162            } else {
163                None
164            };
165
166            Ok(Some(Branch {
167                name,
168                branch_type: BranchKind::Local,
169                is_head: true,
170                oid,
171                tracking,
172            }))
173        })
174        .await
175        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
176    }
177
178    /// Create a new branch
179    ///
180    /// Similar to `git branch <name> [from]`
181    ///
182    /// Accepts strings, GitRef enums, or direct Oids for the base reference.
183    /// If `from` is None, creates from HEAD.
184    ///
185    /// # Examples
186    ///
187    /// ```rust,ignore
188    /// // Create from HEAD
189    /// repo.branch().create("feature", None).await?;
190    ///
191    /// // Create from string reference
192    /// repo.branch().create("feature", Some("main")).await?;
193    ///
194    /// // Create from explicit GitRef
195    /// repo.branch().create("hotfix", Some(git2db::GitRef::Tag("v1.0.0".into()))).await?;
196    ///
197    /// // Create from specific commit (type-safe)
198    /// let oid = git2::Oid::from_str("abc123...")?;
199    /// repo.branch().create("from-commit", Some(oid)).await?;
200    /// ```
201    pub async fn create<R: IntoGitRef>(&self, name: &str, from: Option<R>) -> Git2DBResult<()> {
202        let path = self.repo_path()?;
203        let name = name.to_owned();
204        let from_ref = from.map(super::references::IntoGitRef::into_git_ref);
205
206        tokio::task::spawn_blocking(move || {
207            let repo = Repository::open(&path).map_err(|e| {
208                Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
209            })?;
210
211            // Resolve the starting point
212            let commit = if let Some(git_ref) = from_ref {
213                let ref_str = git_ref.display_name();
214
215                // Resolve GitRef to commit
216                let oid = match git_ref {
217                    GitRef::DefaultBranch => {
218                        let head = repo.head().map_err(|e| {
219                            Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
220                        })?;
221                        head.peel_to_commit()
222                            .map_err(|e| {
223                                Git2DBError::reference("HEAD", format!("HEAD is not a commit: {e}"))
224                            })?
225                            .id()
226                    }
227                    GitRef::Commit(oid) => oid,
228                    GitRef::Branch(branch_name)
229                    | GitRef::Tag(branch_name)
230                    | GitRef::Revspec(branch_name) => {
231                        let obj = repo.revparse_single(&branch_name).map_err(|e| {
232                            Git2DBError::reference(
233                                &ref_str,
234                                format!("Failed to resolve reference: {e}"),
235                            )
236                        })?;
237                        obj.peel_to_commit()
238                            .map_err(|e| {
239                                Git2DBError::reference(&ref_str, format!("Not a commit: {e}"))
240                            })?
241                            .id()
242                    }
243                };
244
245                repo.find_commit(oid).map_err(|e| {
246                    Git2DBError::reference(&ref_str, format!("Failed to find commit: {e}"))
247                })?
248            } else {
249                // Use HEAD
250                let head = repo.head().map_err(|e| {
251                    Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
252                })?;
253                head.peel_to_commit().map_err(|e| {
254                    Git2DBError::reference("HEAD", format!("HEAD is not a commit: {e}"))
255                })?
256            };
257
258            // Create the branch
259            repo.branch(&name, &commit, false).map_err(|e| {
260                Git2DBError::reference(&name, format!("Failed to create branch: {e}"))
261            })?;
262
263            Ok(())
264        })
265        .await
266        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
267    }
268
269    /// Checkout a branch
270    ///
271    /// Similar to `git checkout <name>`
272    pub async fn checkout(&self, name: &str) -> Git2DBResult<()> {
273        let path = self.repo_path()?;
274        let name = name.to_owned();
275
276        tokio::task::spawn_blocking(move || {
277            let repo = Repository::open(&path).map_err(|e| {
278                Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
279            })?;
280
281            // Find the branch
282            let branch = repo
283                .find_branch(&name, BranchType::Local)
284                .map_err(|_| Git2DBError::reference(&name, "Branch not found"))?;
285
286            let reference = branch.into_reference();
287            let commit = reference
288                .peel_to_commit()
289                .map_err(|e| Git2DBError::reference(&name, format!("Failed to get commit: {e}")))?;
290
291            // Checkout the branch
292            repo.checkout_tree(commit.as_object(), None)
293                .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
294
295            // Set HEAD to the branch
296            repo.set_head(&format!("refs/heads/{name}"))
297                .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
298
299            Ok(())
300        })
301        .await
302        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
303    }
304
305    /// Remove a branch
306    ///
307    /// Similar to `git branch -d <name>` (or `-D` if force=true)
308    pub async fn remove(&self, name: &str, force: bool) -> Git2DBResult<()> {
309        // Check if this is the current branch
310        if let Ok(Some(current)) = self.current().await {
311            if current.name == name {
312                return Err(Git2DBError::configuration(format!(
313                    "Cannot delete current branch '{name}'"
314                )));
315            }
316        }
317
318        let path = self.repo_path()?;
319        let name = name.to_owned();
320
321        tokio::task::spawn_blocking(move || {
322            let repo = Repository::open(&path).map_err(|e| {
323                Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
324            })?;
325
326            // Find and delete the branch
327            let mut branch = repo
328                .find_branch(&name, BranchType::Local)
329                .map_err(|_| Git2DBError::reference(&name, "Branch not found"))?;
330
331            if !force {
332                // Check if branch is fully merged
333                let branch_oid = branch
334                    .get()
335                    .target()
336                    .ok_or_else(|| Git2DBError::reference(&name, "Branch has no target"))?;
337
338                // Check if reachable from HEAD
339                let head = repo.head().map_err(|e| {
340                    Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
341                })?;
342                let head_oid = head
343                    .target()
344                    .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD has no target"))?;
345
346                if !repo
347                    .graph_descendant_of(head_oid, branch_oid)
348                    .unwrap_or(false)
349                {
350                    return Err(Git2DBError::configuration(format!(
351                        "Branch '{name}' is not fully merged. Use force=true to delete anyway."
352                    )));
353                }
354            }
355
356            branch.delete().map_err(|e| {
357                Git2DBError::reference(&name, format!("Failed to delete branch: {e}"))
358            })?;
359
360            Ok(())
361        })
362        .await
363        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
364    }
365
366    /// Rename current branch or a specific branch
367    ///
368    /// Similar to `git branch -m [old] <new>`
369    pub async fn rename(&self, old_name: Option<&str>, new_name: &str) -> Git2DBResult<()> {
370        let branch_name = if let Some(name) = old_name {
371            name.to_owned()
372        } else {
373            // Get current branch name
374            self.current()
375                .await?
376                .ok_or_else(|| Git2DBError::reference("HEAD", "Not on a branch (detached HEAD)"))?
377                .name
378        };
379
380        let path = self.repo_path()?;
381        let new_name = new_name.to_owned();
382
383        tokio::task::spawn_blocking(move || {
384            let repo = Repository::open(&path).map_err(|e| {
385                Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
386            })?;
387
388            // Find and rename the branch
389            let mut branch = repo
390                .find_branch(&branch_name, BranchType::Local)
391                .map_err(|_| Git2DBError::reference(&branch_name, "Branch not found"))?;
392
393            branch.rename(&new_name, false).map_err(|e| {
394                Git2DBError::reference(&new_name, format!("Failed to rename branch: {e}"))
395            })?;
396
397            Ok(())
398        })
399        .await
400        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
401    }
402}
403
404/// Branch information
405#[derive(Debug, Clone)]
406pub struct Branch {
407    pub name: String,
408    pub branch_type: BranchKind,
409    pub is_head: bool,
410    pub oid: Option<Oid>,
411    pub tracking: Option<String>,
412}
413
414impl Branch {
415    /// Check if this is a local branch
416    pub fn is_local(&self) -> bool {
417        matches!(self.branch_type, BranchKind::Local)
418    }
419
420    /// Check if this is a remote branch
421    pub fn is_remote(&self) -> bool {
422        matches!(self.branch_type, BranchKind::Remote)
423    }
424
425    /// Get short commit hash (first 7 chars)
426    pub fn short_oid(&self) -> Option<String> {
427        self.oid.map(|oid| format!("{oid:.7}"))
428    }
429}
430
431/// Branch type
432#[derive(Debug, Clone, Copy, PartialEq, Eq)]
433pub enum BranchKind {
434    Local,
435    Remote,
436}