Skip to main content

gitflow_core/
git_ops.rs

1//! Git operations for branch and worktree management.
2//!
3//! Provides low-level git operations used by [`CleanupService`](crate::cleanup::CleanupService).
4//! All operations are local git commands — no platform API calls.
5
6use tokio::process::Command;
7
8use crate::Result;
9
10/// Delete a local git branch.
11///
12/// Uses `git branch -d <branch>` for merged branches, or `git branch -D <branch>`
13/// if `force` is true.
14///
15/// # Errors
16///
17/// Returns an error if:
18/// - The git command fails
19/// - The branch does not exist
20/// - The branch is not fully merged (unless `force` is true)
21/// - The branch is currently checked out
22pub async fn delete_local_branch(branch: &str, force: bool) -> Result<()> {
23    let flag = if force { "-D" } else { "-d" };
24    let output = Command::new("git")
25        .args(["branch", flag, branch])
26        .output()
27        .await
28        .map_err(|e| crate::CoreError::App(format!("Failed to execute git branch: {e}")))?;
29
30    if !output.status.success() {
31        let stderr = String::from_utf8_lossy(&output.stderr);
32        return Err(crate::CoreError::App(format!(
33            "Failed to delete local branch '{branch}': {stderr}"
34        )));
35    }
36
37    Ok(())
38}
39
40/// Delete a remote git branch.
41///
42/// Uses `git push origin --delete <branch>`.
43///
44/// # Errors
45///
46/// Returns an error if:
47/// - The git command fails
48/// - The remote branch does not exist
49/// - Authentication fails
50pub async fn delete_remote_branch(branch: &str) -> Result<()> {
51    let output = Command::new("git")
52        .args(["push", "origin", "--delete", branch])
53        .output()
54        .await
55        .map_err(|e| crate::CoreError::App(format!("Failed to execute git push: {e}")))?;
56
57    if !output.status.success() {
58        let stderr = String::from_utf8_lossy(&output.stderr);
59        return Err(crate::CoreError::App(format!(
60            "Failed to delete remote branch '{branch}': {stderr}"
61        )));
62    }
63
64    Ok(())
65}
66
67/// Check if the current directory is inside a git worktree.
68///
69/// A worktree is detected by checking if `.git` is a file (not a directory).
70/// In a regular repo, `.git` is a directory; in a worktree, it's a file
71/// containing a pointer to the main repo's git directory.
72///
73/// # Errors
74///
75/// Returns an error if the `.git` path cannot be accessed.
76#[allow(
77    clippy::unused_async,
78    reason = "Consistent async API with other git_ops functions"
79)]
80pub async fn is_in_worktree() -> Result<bool> {
81    let git_path = std::path::Path::new(".git");
82    if !git_path.exists() {
83        return Err(crate::CoreError::App("Not in a git repository".to_string()));
84    }
85    Ok(git_path.is_file())
86}
87
88/// Get the path to the main repository from a worktree.
89///
90/// Uses `git rev-parse --git-common-dir` to find the main repo's git directory,
91/// then returns its parent (the main repo root).
92///
93/// # Errors
94///
95/// Returns an error if:
96/// - Not in a git worktree
97/// - The git command fails
98pub async fn get_main_repo_path() -> Result<std::path::PathBuf> {
99    let output = Command::new("git")
100        .args(["rev-parse", "--git-common-dir"])
101        .output()
102        .await
103        .map_err(|e| crate::CoreError::App(format!("Failed to execute git: {e}")))?;
104
105    if !output.status.success() {
106        return Err(crate::CoreError::App(
107            "Failed to get main repo path".to_string(),
108        ));
109    }
110
111    let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();
112    let git_path = std::path::PathBuf::from(&git_dir);
113
114    // git-common-dir returns the .git directory; parent is the repo root
115    git_path
116        .parent()
117        .map(std::path::Path::to_path_buf)
118        .ok_or_else(|| {
119            crate::CoreError::App("Cannot determine parent of git directory".to_string())
120        })
121}
122
123/// Get the path to the current worktree.
124///
125/// Uses `git rev-parse --show-toplevel` to get the worktree root.
126///
127/// # Errors
128///
129/// Returns an error if:
130/// - Not in a git worktree
131/// - The git command fails
132pub async fn get_current_worktree_path() -> Result<std::path::PathBuf> {
133    let output = Command::new("git")
134        .args(["rev-parse", "--show-toplevel"])
135        .output()
136        .await
137        .map_err(|e| crate::CoreError::App(format!("Failed to execute git: {e}")))?;
138
139    if !output.status.success() {
140        return Err(crate::CoreError::App(
141            "Failed to get current worktree path".to_string(),
142        ));
143    }
144
145    let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
146    Ok(std::path::PathBuf::from(path))
147}
148
149/// Remove a git worktree.
150///
151/// Uses `git worktree remove <path>`.
152///
153/// # Errors
154///
155/// Returns an error if:
156/// - The worktree does not exist
157/// - The worktree contains uncommitted changes
158/// - The git command fails
159pub async fn remove_worktree(path: &str) -> Result<()> {
160    let output = Command::new("git")
161        .args(["worktree", "remove", path])
162        .output()
163        .await
164        .map_err(|e| {
165            crate::CoreError::App(format!("Failed to execute git worktree remove: {e}"))
166        })?;
167
168    if !output.status.success() {
169        let stderr = String::from_utf8_lossy(&output.stderr);
170        return Err(crate::CoreError::App(format!(
171            "Failed to remove worktree '{path}': {stderr}"
172        )));
173    }
174
175    Ok(())
176}
177
178/// Exit the current worktree and return to the main repository.
179///
180/// Changes the current directory to the main repository root.
181///
182/// # Errors
183///
184/// Returns an error if:
185/// - Not in a worktree
186/// - Cannot determine main repo path
187/// - Cannot change directory
188pub async fn exit_worktree() -> Result<std::path::PathBuf> {
189    if !is_in_worktree().await? {
190        return Err(crate::CoreError::App("Not in a worktree".to_string()));
191    }
192
193    let main_repo = get_main_repo_path().await?;
194    std::env::set_current_dir(&main_repo).map_err(|e| {
195        crate::CoreError::App(format!(
196            "Failed to change directory to {}: {e}",
197            main_repo.display()
198        ))
199    })?;
200
201    Ok(main_repo)
202}
203
204#[cfg(test)]
205mod tests {
206    // Branch deletion operations are tested via integration tests
207    // since they require a real git repository and remote.
208    // Unit tests would require mocking Command execution, which
209    // adds complexity disproportionate to the simple git wrapper logic.
210}