Skip to main content

oven_cli/git/
mod.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{Context, Result};
4use tokio::process::Command;
5
6/// A git worktree created for an issue pipeline.
7#[derive(Debug, Clone)]
8pub struct Worktree {
9    pub path: PathBuf,
10    pub branch: String,
11    pub issue_number: u32,
12}
13
14/// Info about an existing worktree from `git worktree list`.
15#[derive(Debug, Clone)]
16pub struct WorktreeInfo {
17    pub path: PathBuf,
18    pub branch: Option<String>,
19}
20
21/// Generate a branch name for an issue: `oven/issue-{number}-{short_hex}`.
22fn branch_name(issue_number: u32) -> String {
23    let short_hex = &uuid::Uuid::new_v4().to_string()[..8];
24    format!("oven/issue-{issue_number}-{short_hex}")
25}
26
27/// Create a worktree for the given issue, branching from `base_branch`.
28pub async fn create_worktree(
29    repo_dir: &Path,
30    issue_number: u32,
31    base_branch: &str,
32) -> Result<Worktree> {
33    let branch = branch_name(issue_number);
34    let worktree_path =
35        repo_dir.join(".oven").join("worktrees").join(format!("issue-{issue_number}"));
36
37    // Ensure parent directory exists
38    if let Some(parent) = worktree_path.parent() {
39        tokio::fs::create_dir_all(parent).await.context("creating worktree parent directory")?;
40    }
41
42    run_git(
43        repo_dir,
44        &["worktree", "add", "-b", &branch, &worktree_path.to_string_lossy(), base_branch],
45    )
46    .await
47    .context("creating worktree")?;
48
49    Ok(Worktree { path: worktree_path, branch, issue_number })
50}
51
52/// Remove a worktree by path.
53pub async fn remove_worktree(repo_dir: &Path, worktree_path: &Path) -> Result<()> {
54    run_git(repo_dir, &["worktree", "remove", "--force", &worktree_path.to_string_lossy()])
55        .await
56        .context("removing worktree")?;
57    Ok(())
58}
59
60/// List all worktrees in the repository.
61pub async fn list_worktrees(repo_dir: &Path) -> Result<Vec<WorktreeInfo>> {
62    let output = run_git(repo_dir, &["worktree", "list", "--porcelain"])
63        .await
64        .context("listing worktrees")?;
65
66    let mut worktrees = Vec::new();
67    let mut current_path: Option<PathBuf> = None;
68    let mut current_branch: Option<String> = None;
69
70    for line in output.lines() {
71        if let Some(path_str) = line.strip_prefix("worktree ") {
72            // Save previous worktree if we have one
73            if let Some(path) = current_path.take() {
74                worktrees.push(WorktreeInfo { path, branch: current_branch.take() });
75            }
76            current_path = Some(PathBuf::from(path_str));
77        } else if let Some(branch_ref) = line.strip_prefix("branch ") {
78            // Extract branch name from refs/heads/...
79            current_branch =
80                Some(branch_ref.strip_prefix("refs/heads/").unwrap_or(branch_ref).to_string());
81        }
82    }
83
84    // Don't forget the last one
85    if let Some(path) = current_path {
86        worktrees.push(WorktreeInfo { path, branch: current_branch });
87    }
88
89    Ok(worktrees)
90}
91
92/// Prune stale worktrees and return the count pruned.
93pub async fn clean_worktrees(repo_dir: &Path) -> Result<u32> {
94    let before = list_worktrees(repo_dir).await?;
95    run_git(repo_dir, &["worktree", "prune"]).await.context("pruning worktrees")?;
96    let after = list_worktrees(repo_dir).await?;
97
98    let pruned = if before.len() > after.len() { before.len() - after.len() } else { 0 };
99    Ok(u32::try_from(pruned).unwrap_or(u32::MAX))
100}
101
102/// Delete a local branch.
103pub async fn delete_branch(repo_dir: &Path, branch: &str) -> Result<()> {
104    run_git(repo_dir, &["branch", "-D", branch]).await.context("deleting branch")?;
105    Ok(())
106}
107
108/// List merged branches matching `oven/*`.
109pub async fn list_merged_branches(repo_dir: &Path, base: &str) -> Result<Vec<String>> {
110    let output = run_git(repo_dir, &["branch", "--merged", base])
111        .await
112        .context("listing merged branches")?;
113
114    let branches = output
115        .lines()
116        .map(|l| l.trim().trim_start_matches("* ").to_string())
117        .filter(|b| b.starts_with("oven/"))
118        .collect();
119
120    Ok(branches)
121}
122
123/// Create an empty commit (used to seed a branch before PR creation).
124pub async fn empty_commit(repo_dir: &Path, message: &str) -> Result<()> {
125    run_git(repo_dir, &["commit", "--allow-empty", "-m", message])
126        .await
127        .context("creating empty commit")?;
128    Ok(())
129}
130
131/// Push a branch to origin.
132pub async fn push_branch(repo_dir: &Path, branch: &str) -> Result<()> {
133    run_git(repo_dir, &["push", "origin", branch]).await.context("pushing branch")?;
134    Ok(())
135}
136
137/// Force-push a branch to origin using `--force-with-lease` for safety.
138///
139/// Used after rebasing a pipeline branch onto the updated base branch.
140pub async fn force_push_branch(repo_dir: &Path, branch: &str) -> Result<()> {
141    let lease = format!("--force-with-lease=refs/heads/{branch}");
142    run_git(repo_dir, &["push", &lease, "origin", branch]).await.context("force-pushing branch")?;
143    Ok(())
144}
145
146/// Outcome of a rebase attempt.
147#[derive(Debug)]
148pub enum RebaseOutcome {
149    /// Rebase succeeded cleanly.
150    Clean,
151    /// Rebase had conflicts. The working tree is left in a mid-rebase state
152    /// so the caller can attempt agent-assisted resolution via
153    /// [`rebase_continue`] / [`abort_rebase`].
154    RebaseConflicts(Vec<String>),
155    /// Agent resolved the rebase conflicts.
156    AgentResolved,
157    /// Unrecoverable failure (e.g. fetch failed).
158    Failed(String),
159}
160
161/// Start a rebase of the current branch onto the latest `origin/<base_branch>`.
162///
163/// If the rebase succeeds cleanly, returns `Clean`. If it hits conflicts, the
164/// working tree is left in a mid-rebase state and `RebaseConflicts` is returned
165/// with the list of conflicting files. The caller should resolve them and call
166/// [`rebase_continue`], or [`abort_rebase`] to give up.
167pub async fn start_rebase(repo_dir: &Path, base_branch: &str) -> RebaseOutcome {
168    if let Err(e) = run_git(repo_dir, &["fetch", "origin", base_branch]).await {
169        return RebaseOutcome::Failed(format!("failed to fetch {base_branch}: {e}"));
170    }
171
172    let target = format!("origin/{base_branch}");
173
174    let no_editor = [("GIT_EDITOR", "true")];
175    if run_git_with_env(repo_dir, &["rebase", &target], &no_editor).await.is_ok() {
176        return RebaseOutcome::Clean;
177    }
178
179    // Rebase stopped with conflicts -- leave the tree in mid-rebase state.
180    let conflicting = conflicting_files(repo_dir).await;
181    RebaseOutcome::RebaseConflicts(conflicting)
182}
183
184/// List files with unresolved merge conflicts.
185pub async fn conflicting_files(repo_dir: &Path) -> Vec<String> {
186    run_git(repo_dir, &["diff", "--name-only", "--diff-filter=U"])
187        .await
188        .map_or_else(|_| vec![], |output| output.lines().map(String::from).collect())
189}
190
191/// Abort an in-progress rebase.
192pub async fn abort_rebase(repo_dir: &Path) {
193    let _ = run_git(repo_dir, &["rebase", "--abort"]).await;
194}
195
196/// Stage resolved conflict files and continue the in-progress rebase.
197///
198/// Returns `Ok(None)` if the rebase completed successfully after continuing.
199/// Returns `Ok(Some(files))` if continuing hit new conflicts on the next commit.
200/// Returns `Err` on unexpected failures.
201pub async fn rebase_continue(
202    repo_dir: &Path,
203    conflicting: &[String],
204) -> Result<Option<Vec<String>>> {
205    for file in conflicting {
206        run_git(repo_dir, &["add", "--", file]).await.with_context(|| format!("staging {file}"))?;
207    }
208
209    let no_editor = [("GIT_EDITOR", "true")];
210    if run_git_with_env(repo_dir, &["rebase", "--continue"], &no_editor).await.is_ok() {
211        return Ok(None);
212    }
213
214    // rebase --continue stopped again -- new conflicts on the next commit.
215    let new_conflicts = conflicting_files(repo_dir).await;
216    if new_conflicts.is_empty() {
217        anyhow::bail!("rebase --continue failed but no conflicting files found");
218    }
219    Ok(Some(new_conflicts))
220}
221
222/// Get the default branch name (main or master).
223pub async fn default_branch(repo_dir: &Path) -> Result<String> {
224    // Try symbolic-ref first
225    if let Ok(output) = run_git(repo_dir, &["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
226        if let Some(branch) = output.strip_prefix("refs/remotes/origin/") {
227            return Ok(branch.to_string());
228        }
229    }
230
231    // Fallback: check if main exists, otherwise master
232    if run_git(repo_dir, &["rev-parse", "--verify", "main"]).await.is_ok() {
233        return Ok("main".to_string());
234    }
235    if run_git(repo_dir, &["rev-parse", "--verify", "master"]).await.is_ok() {
236        return Ok("master".to_string());
237    }
238
239    // Last resort: whatever HEAD points to
240    let output = run_git(repo_dir, &["rev-parse", "--abbrev-ref", "HEAD"])
241        .await
242        .context("detecting default branch")?;
243    Ok(output)
244}
245
246/// Get the current HEAD commit SHA.
247pub async fn head_sha(repo_dir: &Path) -> Result<String> {
248    run_git(repo_dir, &["rev-parse", "HEAD"]).await.context("getting HEAD sha")
249}
250
251/// Count commits between a ref and HEAD.
252pub async fn commit_count_since(repo_dir: &Path, since_ref: &str) -> Result<u32> {
253    let output = run_git(repo_dir, &["rev-list", "--count", &format!("{since_ref}..HEAD")])
254        .await
255        .context("counting commits since ref")?;
256    output.parse::<u32>().context("parsing commit count")
257}
258
259/// List files changed between a ref and HEAD.
260pub async fn changed_files_since(repo_dir: &Path, since_ref: &str) -> Result<Vec<String>> {
261    let output = run_git(repo_dir, &["diff", "--name-only", since_ref, "HEAD"])
262        .await
263        .context("listing changed files since ref")?;
264    Ok(output.lines().filter(|l| !l.is_empty()).map(String::from).collect())
265}
266
267async fn run_git(repo_dir: &Path, args: &[&str]) -> Result<String> {
268    run_git_with_env(repo_dir, args, &[]).await
269}
270
271async fn run_git_with_env(repo_dir: &Path, args: &[&str], env: &[(&str, &str)]) -> Result<String> {
272    let mut cmd = Command::new("git");
273    cmd.args(args).current_dir(repo_dir).kill_on_drop(true);
274    for (k, v) in env {
275        cmd.env(k, v);
276    }
277    let output = cmd.output().await.context("spawning git")?;
278
279    if !output.status.success() {
280        let stderr = String::from_utf8_lossy(&output.stderr);
281        anyhow::bail!("git {} failed: {}", args.join(" "), stderr.trim());
282    }
283
284    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    async fn init_temp_repo() -> tempfile::TempDir {
292        let dir = tempfile::tempdir().unwrap();
293
294        // Init a repo with an initial commit so we have a branch to work from
295        Command::new("git").args(["init"]).current_dir(dir.path()).output().await.unwrap();
296
297        Command::new("git")
298            .args(["config", "user.email", "test@test.com"])
299            .current_dir(dir.path())
300            .output()
301            .await
302            .unwrap();
303
304        Command::new("git")
305            .args(["config", "user.name", "Test"])
306            .current_dir(dir.path())
307            .output()
308            .await
309            .unwrap();
310
311        tokio::fs::write(dir.path().join("README.md"), "hello").await.unwrap();
312
313        Command::new("git").args(["add", "."]).current_dir(dir.path()).output().await.unwrap();
314
315        Command::new("git")
316            .args(["commit", "-m", "initial"])
317            .current_dir(dir.path())
318            .output()
319            .await
320            .unwrap();
321
322        dir
323    }
324
325    #[tokio::test]
326    async fn create_and_remove_worktree() {
327        let dir = init_temp_repo().await;
328
329        // Detect the current branch name
330        let branch = run_git(dir.path(), &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap();
331
332        let wt = create_worktree(dir.path(), 42, &branch).await.unwrap();
333        assert!(wt.path.exists());
334        assert!(wt.branch.starts_with("oven/issue-42-"));
335        assert_eq!(wt.issue_number, 42);
336
337        remove_worktree(dir.path(), &wt.path).await.unwrap();
338        assert!(!wt.path.exists());
339    }
340
341    #[tokio::test]
342    async fn list_worktrees_includes_created() {
343        let dir = init_temp_repo().await;
344        let branch = run_git(dir.path(), &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap();
345
346        let _wt = create_worktree(dir.path(), 99, &branch).await.unwrap();
347
348        let worktrees = list_worktrees(dir.path()).await.unwrap();
349        // Should have at least the main worktree + the one we created
350        assert!(worktrees.len() >= 2);
351        assert!(
352            worktrees
353                .iter()
354                .any(|w| { w.branch.as_deref().is_some_and(|b| b.starts_with("oven/issue-99-")) })
355        );
356    }
357
358    #[tokio::test]
359    async fn branch_naming_convention() {
360        let name = branch_name(123);
361        assert!(name.starts_with("oven/issue-123-"));
362        assert_eq!(name.len(), "oven/issue-123-".len() + 8);
363        // The hex part should be valid hex
364        let hex_part = &name["oven/issue-123-".len()..];
365        assert!(hex_part.chars().all(|c| c.is_ascii_hexdigit()));
366    }
367
368    #[tokio::test]
369    async fn default_branch_detection() {
370        let dir = init_temp_repo().await;
371        let branch = default_branch(dir.path()).await.unwrap();
372        // git init creates "main" or "master" depending on config
373        assert!(branch == "main" || branch == "master", "got: {branch}");
374    }
375
376    #[tokio::test]
377    async fn error_on_non_git_dir() {
378        let dir = tempfile::tempdir().unwrap();
379        let result = list_worktrees(dir.path()).await;
380        assert!(result.is_err());
381    }
382
383    #[tokio::test]
384    async fn force_push_branch_works() {
385        let dir = init_temp_repo().await;
386
387        // Set up a bare remote to push to
388        let remote_dir = tempfile::tempdir().unwrap();
389        Command::new("git")
390            .args(["clone", "--bare", &dir.path().to_string_lossy(), "."])
391            .current_dir(remote_dir.path())
392            .output()
393            .await
394            .unwrap();
395
396        run_git(dir.path(), &["remote", "add", "origin", &remote_dir.path().to_string_lossy()])
397            .await
398            .unwrap();
399
400        // Create a branch, push it, then amend and force-push
401        run_git(dir.path(), &["checkout", "-b", "test-branch"]).await.unwrap();
402        tokio::fs::write(dir.path().join("new.txt"), "v1").await.unwrap();
403        run_git(dir.path(), &["add", "."]).await.unwrap();
404        run_git(dir.path(), &["commit", "-m", "v1"]).await.unwrap();
405        push_branch(dir.path(), "test-branch").await.unwrap();
406
407        // Amend the commit (simulating a rebase)
408        tokio::fs::write(dir.path().join("new.txt"), "v2").await.unwrap();
409        run_git(dir.path(), &["add", "."]).await.unwrap();
410        run_git(dir.path(), &["commit", "--amend", "-m", "v2"]).await.unwrap();
411
412        // Regular push should fail, force push should succeed
413        assert!(push_branch(dir.path(), "test-branch").await.is_err());
414        assert!(force_push_branch(dir.path(), "test-branch").await.is_ok());
415    }
416
417    #[tokio::test]
418    async fn start_rebase_clean() {
419        let dir = init_temp_repo().await;
420        let branch = run_git(dir.path(), &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap();
421
422        run_git(dir.path(), &["checkout", "-b", "feature"]).await.unwrap();
423        tokio::fs::write(dir.path().join("feature.txt"), "feature work").await.unwrap();
424        run_git(dir.path(), &["add", "."]).await.unwrap();
425        run_git(dir.path(), &["commit", "-m", "feature commit"]).await.unwrap();
426
427        run_git(dir.path(), &["checkout", &branch]).await.unwrap();
428        tokio::fs::write(dir.path().join("base.txt"), "base work").await.unwrap();
429        run_git(dir.path(), &["add", "."]).await.unwrap();
430        run_git(dir.path(), &["commit", "-m", "base commit"]).await.unwrap();
431
432        run_git(dir.path(), &["checkout", "feature"]).await.unwrap();
433        run_git(dir.path(), &["remote", "add", "origin", &dir.path().to_string_lossy()])
434            .await
435            .unwrap();
436
437        let outcome = start_rebase(dir.path(), &branch).await;
438        assert!(matches!(outcome, RebaseOutcome::Clean));
439        assert!(dir.path().join("feature.txt").exists());
440        assert!(dir.path().join("base.txt").exists());
441    }
442
443    #[tokio::test]
444    async fn start_rebase_conflicts() {
445        let dir = init_temp_repo().await;
446        let branch = run_git(dir.path(), &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap();
447
448        // Create a feature branch that modifies README.md
449        run_git(dir.path(), &["checkout", "-b", "feature"]).await.unwrap();
450        tokio::fs::write(dir.path().join("README.md"), "feature version").await.unwrap();
451        run_git(dir.path(), &["add", "."]).await.unwrap();
452        run_git(dir.path(), &["commit", "-m", "feature change"]).await.unwrap();
453
454        // Create a conflicting change on the base branch
455        run_git(dir.path(), &["checkout", &branch]).await.unwrap();
456        tokio::fs::write(dir.path().join("README.md"), "base version").await.unwrap();
457        run_git(dir.path(), &["add", "."]).await.unwrap();
458        run_git(dir.path(), &["commit", "-m", "base change"]).await.unwrap();
459
460        run_git(dir.path(), &["checkout", "feature"]).await.unwrap();
461        run_git(dir.path(), &["remote", "add", "origin", &dir.path().to_string_lossy()])
462            .await
463            .unwrap();
464
465        let outcome = start_rebase(dir.path(), &branch).await;
466        assert!(
467            matches!(outcome, RebaseOutcome::RebaseConflicts(_)),
468            "expected RebaseConflicts, got {outcome:?}"
469        );
470
471        // Tree should be in mid-rebase state
472        assert!(
473            dir.path().join(".git/rebase-merge").exists()
474                || dir.path().join(".git/rebase-apply").exists()
475        );
476
477        // Clean up
478        abort_rebase(dir.path()).await;
479    }
480
481    #[tokio::test]
482    async fn start_rebase_no_remote_fails() {
483        let dir = init_temp_repo().await;
484        // No remote configured, so fetch will fail
485        let outcome = start_rebase(dir.path(), "main").await;
486        assert!(matches!(outcome, RebaseOutcome::Failed(_)));
487    }
488
489    #[tokio::test]
490    async fn rebase_continue_resolves_conflict() {
491        let dir = init_temp_repo().await;
492        let branch = run_git(dir.path(), &["rev-parse", "--abbrev-ref", "HEAD"]).await.unwrap();
493
494        run_git(dir.path(), &["checkout", "-b", "feature"]).await.unwrap();
495        tokio::fs::write(dir.path().join("README.md"), "feature version").await.unwrap();
496        run_git(dir.path(), &["add", "."]).await.unwrap();
497        run_git(dir.path(), &["commit", "-m", "feature change"]).await.unwrap();
498
499        run_git(dir.path(), &["checkout", &branch]).await.unwrap();
500        tokio::fs::write(dir.path().join("README.md"), "base version").await.unwrap();
501        run_git(dir.path(), &["add", "."]).await.unwrap();
502        run_git(dir.path(), &["commit", "-m", "base change"]).await.unwrap();
503
504        run_git(dir.path(), &["checkout", "feature"]).await.unwrap();
505        run_git(dir.path(), &["remote", "add", "origin", &dir.path().to_string_lossy()])
506            .await
507            .unwrap();
508
509        let outcome = start_rebase(dir.path(), &branch).await;
510        let files = match outcome {
511            RebaseOutcome::RebaseConflicts(f) => f,
512            other => panic!("expected RebaseConflicts, got {other:?}"),
513        };
514
515        // Manually resolve the conflict
516        tokio::fs::write(dir.path().join("README.md"), "resolved version").await.unwrap();
517
518        let result = rebase_continue(dir.path(), &files).await.unwrap();
519        assert!(result.is_none(), "expected rebase to complete, got more conflicts");
520
521        // Verify rebase completed (no rebase-merge dir)
522        assert!(!dir.path().join(".git/rebase-merge").exists());
523        assert!(!dir.path().join(".git/rebase-apply").exists());
524    }
525}