use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use super::error::GitError;
use super::merge::SquashMergeOutcome;
use super::rebase::{InProgressGitOperation, RebaseStepResult};
#[cfg(test)]
use super::sync;
use super::sync::{BranchTrackingMap, PullRebaseResult, SingleCommitMessageStrategy};
use super::{
abort_rebase, branch_tracking_statuses, commit_all, commit_all_preserving_single_commit,
create_worktree, current_upstream_reference, delete_branch, detect_git_info, diff,
fetch_remote, find_git_repo_root, get_ahead_behind, get_ref_ahead_behind, has_commits_since,
has_unmerged_paths, head_commit_message, head_hash, head_short_hash, in_progress_operation,
is_rebase_in_progress, is_worktree_clean, list_conflicted_files, list_local_commit_titles,
list_staged_conflict_marker_files, list_upstream_commit_titles, main_repo_root, pull_rebase,
push_current_branch, push_current_branch_to_remote_branch, rebase, rebase_continue,
rebase_onto_start, rebase_start, ref_hash, remote_branch_exists, remove_worktree, repo_url,
squash_merge, squash_merge_diff, stage_all, tracked_worktree_status, worktree_status,
};
pub type GitFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
pub trait GitClient: Send + Sync {
fn detect_git_info(&self, dir: PathBuf) -> GitFuture<Option<String>>;
fn find_git_repo_root(&self, dir: PathBuf) -> GitFuture<Option<PathBuf>>;
fn create_worktree(
&self,
repo_path: PathBuf,
worktree_path: PathBuf,
branch_name: String,
start_ref: String,
) -> GitFuture<Result<(), GitError>>;
fn remove_worktree(&self, worktree_path: PathBuf) -> GitFuture<Result<(), GitError>>;
fn squash_merge_diff(
&self,
repo_path: PathBuf,
source_branch: String,
target_branch: String,
) -> GitFuture<Result<String, GitError>>;
fn squash_merge(
&self,
repo_path: PathBuf,
source_branch: String,
target_branch: String,
commit_message: String,
) -> GitFuture<Result<SquashMergeOutcome, GitError>>;
fn rebase(&self, repo_path: PathBuf, target_branch: String) -> GitFuture<Result<(), GitError>>;
fn rebase_start(
&self,
repo_path: PathBuf,
target_branch: String,
) -> GitFuture<Result<RebaseStepResult, GitError>>;
fn rebase_onto_start(
&self,
repo_path: PathBuf,
new_base: String,
old_base: String,
) -> GitFuture<Result<RebaseStepResult, GitError>>;
fn rebase_continue(&self, repo_path: PathBuf) -> GitFuture<Result<RebaseStepResult, GitError>>;
fn abort_rebase(&self, repo_path: PathBuf) -> GitFuture<Result<(), GitError>>;
fn is_rebase_in_progress(&self, repo_path: PathBuf) -> GitFuture<Result<bool, GitError>>;
fn in_progress_operation(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Option<InProgressGitOperation>, GitError>>;
fn has_unmerged_paths(&self, repo_path: PathBuf) -> GitFuture<Result<bool, GitError>>;
fn list_staged_conflict_marker_files(
&self,
repo_path: PathBuf,
paths: Vec<String>,
) -> GitFuture<Result<Vec<String>, GitError>>;
fn list_conflicted_files(&self, repo_path: PathBuf)
-> GitFuture<Result<Vec<String>, GitError>>;
fn commit_all(
&self,
repo_path: PathBuf,
message: String,
no_verify: bool,
) -> GitFuture<Result<(), GitError>>;
fn commit_all_preserving_single_commit(
&self,
repo_path: PathBuf,
base_branch: String,
commit_message: String,
message_strategy: SingleCommitMessageStrategy,
no_verify: bool,
) -> GitFuture<Result<(), GitError>>;
fn stage_all(&self, repo_path: PathBuf) -> GitFuture<Result<(), GitError>>;
fn head_short_hash(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>>;
fn head_hash(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>>;
fn ref_hash(
&self,
repo_path: PathBuf,
reference: String,
) -> GitFuture<Result<String, GitError>>;
fn head_commit_message(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Option<String>, GitError>>;
fn delete_branch(
&self,
repo_path: PathBuf,
branch_name: String,
) -> GitFuture<Result<(), GitError>>;
fn diff(&self, repo_path: PathBuf, base_branch: String) -> GitFuture<Result<String, GitError>>;
fn is_worktree_clean(&self, repo_path: PathBuf) -> GitFuture<Result<bool, GitError>>;
fn worktree_status(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>>;
fn tracked_worktree_status(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>>;
fn has_commits_since(
&self,
repo_path: PathBuf,
base_branch: String,
) -> GitFuture<Result<bool, GitError>>;
fn pull_rebase(&self, repo_path: PathBuf) -> GitFuture<Result<PullRebaseResult, GitError>>;
fn push_current_branch(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>>;
fn push_current_branch_to_remote_branch(
&self,
repo_path: PathBuf,
remote_branch_name: String,
) -> GitFuture<Result<String, GitError>>;
fn remote_branch_exists(
&self,
repo_path: PathBuf,
remote_branch_name: String,
) -> GitFuture<Result<bool, GitError>>;
fn current_upstream_reference(&self, repo_path: PathBuf)
-> GitFuture<Result<String, GitError>>;
fn fetch_remote(&self, repo_path: PathBuf) -> GitFuture<Result<(), GitError>>;
fn get_ahead_behind(&self, repo_path: PathBuf) -> GitFuture<Result<(u32, u32), GitError>>;
fn get_ref_ahead_behind(
&self,
repo_path: PathBuf,
left_ref: String,
right_ref: String,
) -> GitFuture<Result<(u32, u32), GitError>>;
fn branch_tracking_statuses(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<BranchTrackingMap, GitError>>;
fn list_upstream_commit_titles(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Vec<String>, GitError>>;
fn list_local_commit_titles(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Vec<String>, GitError>>;
fn repo_url(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>>;
fn main_repo_root(&self, repo_path: PathBuf) -> GitFuture<Result<PathBuf, GitError>>;
}
pub struct RealGitClient;
impl GitClient for RealGitClient {
fn detect_git_info(&self, dir: PathBuf) -> GitFuture<Option<String>> {
Box::pin(async move { detect_git_info(dir).await })
}
fn find_git_repo_root(&self, dir: PathBuf) -> GitFuture<Option<PathBuf>> {
Box::pin(async move { find_git_repo_root(dir).await })
}
fn create_worktree(
&self,
repo_path: PathBuf,
worktree_path: PathBuf,
branch_name: String,
start_ref: String,
) -> GitFuture<Result<(), GitError>> {
Box::pin(
async move { create_worktree(repo_path, worktree_path, branch_name, start_ref).await },
)
}
fn remove_worktree(&self, worktree_path: PathBuf) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { remove_worktree(worktree_path).await })
}
fn squash_merge_diff(
&self,
repo_path: PathBuf,
source_branch: String,
target_branch: String,
) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { squash_merge_diff(repo_path, source_branch, target_branch).await })
}
fn squash_merge(
&self,
repo_path: PathBuf,
source_branch: String,
target_branch: String,
commit_message: String,
) -> GitFuture<Result<SquashMergeOutcome, GitError>> {
Box::pin(async move {
squash_merge(repo_path, source_branch, target_branch, commit_message).await
})
}
fn rebase(&self, repo_path: PathBuf, target_branch: String) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { rebase::rebase(repo_path, target_branch).await })
}
fn rebase_start(
&self,
repo_path: PathBuf,
target_branch: String,
) -> GitFuture<Result<RebaseStepResult, GitError>> {
Box::pin(async move { rebase_start(repo_path, target_branch).await })
}
fn rebase_onto_start(
&self,
repo_path: PathBuf,
new_base: String,
old_base: String,
) -> GitFuture<Result<RebaseStepResult, GitError>> {
Box::pin(async move { rebase_onto_start(repo_path, new_base, old_base).await })
}
fn rebase_continue(&self, repo_path: PathBuf) -> GitFuture<Result<RebaseStepResult, GitError>> {
Box::pin(async move { rebase_continue(repo_path).await })
}
fn abort_rebase(&self, repo_path: PathBuf) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { abort_rebase(repo_path).await })
}
fn is_rebase_in_progress(&self, repo_path: PathBuf) -> GitFuture<Result<bool, GitError>> {
Box::pin(async move { is_rebase_in_progress(repo_path).await })
}
fn in_progress_operation(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Option<InProgressGitOperation>, GitError>> {
Box::pin(async move { in_progress_operation(repo_path).await })
}
fn has_unmerged_paths(&self, repo_path: PathBuf) -> GitFuture<Result<bool, GitError>> {
Box::pin(async move { has_unmerged_paths(repo_path).await })
}
fn list_staged_conflict_marker_files(
&self,
repo_path: PathBuf,
paths: Vec<String>,
) -> GitFuture<Result<Vec<String>, GitError>> {
Box::pin(async move { list_staged_conflict_marker_files(repo_path, paths).await })
}
fn list_conflicted_files(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Vec<String>, GitError>> {
Box::pin(async move { list_conflicted_files(repo_path).await })
}
fn commit_all(
&self,
repo_path: PathBuf,
message: String,
no_verify: bool,
) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { commit_all(repo_path, message, no_verify).await })
}
fn commit_all_preserving_single_commit(
&self,
repo_path: PathBuf,
base_branch: String,
commit_message: String,
message_strategy: SingleCommitMessageStrategy,
no_verify: bool,
) -> GitFuture<Result<(), GitError>> {
Box::pin(async move {
commit_all_preserving_single_commit(
repo_path,
base_branch,
commit_message,
message_strategy,
no_verify,
)
.await
})
}
fn stage_all(&self, repo_path: PathBuf) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { stage_all(repo_path).await })
}
fn head_short_hash(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { head_short_hash(repo_path).await })
}
fn head_hash(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { head_hash(repo_path).await })
}
fn ref_hash(
&self,
repo_path: PathBuf,
reference: String,
) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { ref_hash(repo_path, reference).await })
}
fn head_commit_message(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Option<String>, GitError>> {
Box::pin(async move { head_commit_message(repo_path).await })
}
fn delete_branch(
&self,
repo_path: PathBuf,
branch_name: String,
) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { delete_branch(repo_path, branch_name).await })
}
fn diff(&self, repo_path: PathBuf, base_branch: String) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { diff(repo_path, base_branch).await })
}
fn is_worktree_clean(&self, repo_path: PathBuf) -> GitFuture<Result<bool, GitError>> {
Box::pin(async move { is_worktree_clean(repo_path).await })
}
fn worktree_status(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { worktree_status(repo_path).await })
}
fn tracked_worktree_status(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { tracked_worktree_status(repo_path).await })
}
fn has_commits_since(
&self,
repo_path: PathBuf,
base_branch: String,
) -> GitFuture<Result<bool, GitError>> {
Box::pin(async move { has_commits_since(repo_path, base_branch).await })
}
fn pull_rebase(&self, repo_path: PathBuf) -> GitFuture<Result<PullRebaseResult, GitError>> {
Box::pin(async move { pull_rebase(repo_path).await })
}
fn push_current_branch(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { push_current_branch(repo_path).await })
}
fn push_current_branch_to_remote_branch(
&self,
repo_path: PathBuf,
remote_branch_name: String,
) -> GitFuture<Result<String, GitError>> {
Box::pin(async move {
push_current_branch_to_remote_branch(repo_path, remote_branch_name).await
})
}
fn remote_branch_exists(
&self,
repo_path: PathBuf,
remote_branch_name: String,
) -> GitFuture<Result<bool, GitError>> {
Box::pin(async move { remote_branch_exists(repo_path, remote_branch_name).await })
}
fn current_upstream_reference(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { current_upstream_reference(repo_path).await })
}
fn fetch_remote(&self, repo_path: PathBuf) -> GitFuture<Result<(), GitError>> {
Box::pin(async move { fetch_remote(repo_path).await })
}
fn get_ahead_behind(&self, repo_path: PathBuf) -> GitFuture<Result<(u32, u32), GitError>> {
Box::pin(async move { get_ahead_behind(repo_path).await })
}
fn get_ref_ahead_behind(
&self,
repo_path: PathBuf,
left_ref: String,
right_ref: String,
) -> GitFuture<Result<(u32, u32), GitError>> {
Box::pin(async move { get_ref_ahead_behind(repo_path, left_ref, right_ref).await })
}
fn branch_tracking_statuses(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<BranchTrackingMap, GitError>> {
Box::pin(async move { branch_tracking_statuses(repo_path).await })
}
fn list_upstream_commit_titles(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Vec<String>, GitError>> {
Box::pin(async move { list_upstream_commit_titles(repo_path).await })
}
fn list_local_commit_titles(
&self,
repo_path: PathBuf,
) -> GitFuture<Result<Vec<String>, GitError>> {
Box::pin(async move { list_local_commit_titles(repo_path).await })
}
fn repo_url(&self, repo_path: PathBuf) -> GitFuture<Result<String, GitError>> {
Box::pin(async move { repo_url(repo_path).await })
}
fn main_repo_root(&self, repo_path: PathBuf) -> GitFuture<Result<PathBuf, GitError>> {
Box::pin(async move { main_repo_root(repo_path).await })
}
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use std::{fs, thread};
use tempfile::tempdir;
use super::*;
fn canonicalize_test_path(path: &Path) -> PathBuf {
fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
fn run_git_command(repo_path: &Path, args: &[&str]) {
let output = Command::new("git")
.args(args)
.current_dir(repo_path)
.output()
.expect("failed to run git command");
assert!(
output.status.success(),
"git command {:?} failed: {}",
args,
String::from_utf8_lossy(&output.stderr)
);
}
fn run_git_command_stdout(repo_path: &Path, args: &[&str]) -> String {
let output = Command::new("git")
.args(args)
.current_dir(repo_path)
.output()
.expect("failed to run git command");
assert!(
output.status.success(),
"git command {:?} failed: {}",
args,
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
fn setup_test_git_repo(repo_path: &Path) {
run_git_command(repo_path, &["init", "-b", "main"]);
run_git_command(repo_path, &["config", "user.name", "Test User"]);
run_git_command(repo_path, &["config", "user.email", "test@example.com"]);
fs::write(repo_path.join("README.md"), "test repo").expect("failed to write file");
run_git_command(repo_path, &["add", "README.md"]);
run_git_command(repo_path, &["commit", "-m", "Initial commit"]);
}
#[tokio::test]
async fn test_squash_merge_returns_committed_when_changes_exist() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "feature-branch"]);
fs::write(dir.path().join("feature.txt"), "feature content").expect("failed to write file");
run_git_command(dir.path(), &["add", "feature.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Add feature"]);
run_git_command(dir.path(), &["checkout", "main"]);
let result = squash_merge(
dir.path().to_path_buf(),
"feature-branch".to_string(),
"main".to_string(),
"Squash merge feature".to_string(),
)
.await;
assert_eq!(
result.expect("squash merge should succeed"),
SquashMergeOutcome::Committed,
);
}
#[tokio::test]
async fn test_squash_merge_returns_already_present_when_changes_exist_in_target() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
fs::write(dir.path().join("session.txt"), "session change").expect("failed to write file");
run_git_command(dir.path(), &["add", "session.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Session change"]);
run_git_command(dir.path(), &["checkout", "main"]);
fs::write(dir.path().join("session.txt"), "session change").expect("failed to write file");
run_git_command(dir.path(), &["add", "session.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Apply same change on main"]);
let result = squash_merge(
dir.path().to_path_buf(),
"session-branch".to_string(),
"main".to_string(),
"Merge session".to_string(),
)
.await;
assert_eq!(
result.expect("squash merge should succeed"),
SquashMergeOutcome::AlreadyPresentInTarget,
);
}
#[tokio::test]
async fn test_commit_all_preserving_single_commit_creates_first_commit() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
let commit_message = "Session commit".to_string();
fs::write(dir.path().join("work.txt"), "first change").expect("failed to write file");
let result = commit_all_preserving_single_commit(
dir.path().to_path_buf(),
"main".to_string(),
commit_message.clone(),
SingleCommitMessageStrategy::Replace,
false,
)
.await;
let commit_count = run_git_command_stdout(dir.path(), &["rev-list", "--count", "HEAD"]);
let head_message = run_git_command_stdout(dir.path(), &["log", "-1", "--pretty=%B"]);
assert!(
result.is_ok(),
"commit_all_preserving_single_commit should succeed: {result:?}"
);
assert_eq!(commit_count, "2");
assert_eq!(head_message, commit_message);
}
#[tokio::test]
async fn test_commit_all_preserving_single_commit_amends_existing_session_commit() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
let commit_message = "Session commit".to_string();
fs::write(dir.path().join("work.txt"), "first change").expect("failed to write file");
commit_all_preserving_single_commit(
dir.path().to_path_buf(),
"main".to_string(),
commit_message.clone(),
SingleCommitMessageStrategy::Replace,
false,
)
.await
.expect("failed to create first session commit");
let first_hash = run_git_command_stdout(dir.path(), &["rev-parse", "HEAD"]);
let first_count = run_git_command_stdout(dir.path(), &["rev-list", "--count", "HEAD"]);
fs::write(dir.path().join("work.txt"), "second change").expect("failed to write file");
let result = commit_all_preserving_single_commit(
dir.path().to_path_buf(),
"main".to_string(),
commit_message.clone(),
SingleCommitMessageStrategy::Replace,
false,
)
.await;
let second_hash = run_git_command_stdout(dir.path(), &["rev-parse", "HEAD"]);
let second_count = run_git_command_stdout(dir.path(), &["rev-list", "--count", "HEAD"]);
assert!(result.is_ok(), "amend commit should succeed: {result:?}");
assert_ne!(first_hash, second_hash);
assert_eq!(first_count, second_count);
}
#[tokio::test]
async fn test_commit_all_preserving_single_commit_replaces_amended_message() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
fs::write(dir.path().join("work.txt"), "first change").expect("failed to write file");
commit_all_preserving_single_commit(
dir.path().to_path_buf(),
"main".to_string(),
"First session message".to_string(),
SingleCommitMessageStrategy::Replace,
false,
)
.await
.expect("failed to create first session commit");
fs::write(dir.path().join("work.txt"), "second change").expect("failed to write file");
let result = commit_all_preserving_single_commit(
dir.path().to_path_buf(),
"main".to_string(),
"Refined session message".to_string(),
SingleCommitMessageStrategy::Replace,
false,
)
.await;
let head_message = run_git_command_stdout(dir.path(), &["log", "-1", "--pretty=%B"]);
assert!(
result.is_ok(),
"replace amended message should succeed: {result:?}"
);
assert_eq!(head_message, "Refined session message");
}
#[tokio::test]
async fn test_commit_all_preserving_single_commit_retries_index_lock_and_succeeds() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
let commit_message = "Session commit".to_string();
fs::write(dir.path().join("work.txt"), "locked change").expect("failed to write file");
let index_lock_path = dir.path().join(".git").join("index.lock");
fs::write(&index_lock_path, "stale lock").expect("failed to write lock file");
let lock_cleanup = thread::spawn(move || {
thread::sleep(Duration::from_millis(250));
let _ = fs::remove_file(index_lock_path);
});
let result = commit_all_preserving_single_commit(
dir.path().to_path_buf(),
"main".to_string(),
commit_message.clone(),
SingleCommitMessageStrategy::Replace,
false,
)
.await;
lock_cleanup
.join()
.expect("failed to join lock cleanup thread");
let head_message = run_git_command_stdout(dir.path(), &["log", "-1", "--pretty=%B"]);
assert!(
result.is_ok(),
"retry with index lock should succeed: {result:?}"
);
assert_eq!(head_message, commit_message);
}
#[tokio::test]
async fn test_diff_hides_leading_squash_merged_commit_for_non_rebased_session() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
fs::write(dir.path().join("merged.txt"), "already merged change")
.expect("failed to write merged file");
run_git_command(dir.path(), &["add", "merged.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Session change"]);
run_git_command(dir.path(), &["checkout", "main"]);
run_git_command(dir.path(), &["merge", "--squash", "session-branch"]);
run_git_command(dir.path(), &["commit", "-m", "Squash merge session change"]);
run_git_command(dir.path(), &["checkout", "session-branch"]);
let diff_output = diff(dir.path().to_path_buf(), "main".to_string())
.await
.expect("failed to load diff");
assert!(
diff_output.trim().is_empty(),
"expected no diff, got: {diff_output}"
);
}
#[tokio::test]
async fn test_diff_keeps_new_commits_after_leading_squash_merged_commit() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
fs::write(dir.path().join("merged.txt"), "already merged change")
.expect("failed to write merged file");
run_git_command(dir.path(), &["add", "merged.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Session change"]);
run_git_command(dir.path(), &["checkout", "main"]);
run_git_command(dir.path(), &["merge", "--squash", "session-branch"]);
run_git_command(dir.path(), &["commit", "-m", "Squash merge session change"]);
run_git_command(dir.path(), &["checkout", "session-branch"]);
fs::write(dir.path().join("new.txt"), "new session-only change")
.expect("failed to write new file");
run_git_command(dir.path(), &["add", "new.txt"]);
run_git_command(dir.path(), &["commit", "-m", "New session change"]);
let diff_output = diff(dir.path().to_path_buf(), "main".to_string())
.await
.expect("failed to load diff");
assert!(diff_output.contains("new.txt"));
assert!(!diff_output.contains("merged.txt"));
}
#[tokio::test]
async fn test_diff_does_not_include_base_only_commits() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "session-branch"]);
fs::write(dir.path().join("session.txt"), "session change").expect("failed to write file");
run_git_command(dir.path(), &["add", "session.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Session change"]);
run_git_command(dir.path(), &["checkout", "main"]);
fs::write(dir.path().join("main-only.txt"), "base branch only")
.expect("failed to write base-only file");
run_git_command(dir.path(), &["add", "main-only.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Main branch change"]);
run_git_command(dir.path(), &["checkout", "session-branch"]);
let diff_output = diff(dir.path().to_path_buf(), "main".to_string())
.await
.expect("failed to load diff");
assert!(diff_output.contains("session.txt"));
assert!(!diff_output.contains("main-only.txt"));
}
#[tokio::test]
async fn test_is_worktree_clean_returns_true_for_clean_repo() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let is_clean = is_worktree_clean(dir.path().to_path_buf())
.await
.expect("failed to check worktree cleanliness");
assert!(is_clean);
}
#[tokio::test]
async fn test_is_worktree_clean_returns_false_for_dirty_repo() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
fs::write(dir.path().join("README.md"), "dirty change").expect("failed to write change");
let is_clean = is_worktree_clean(dir.path().to_path_buf())
.await
.expect("failed to check worktree cleanliness");
assert!(!is_clean);
}
#[tokio::test]
async fn test_worktree_status_reports_dirty_repo_paths() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
fs::write(dir.path().join("README.md"), "dirty change").expect("failed to write change");
fs::write(dir.path().join("new-file.txt"), "new").expect("failed to write new file");
let status = worktree_status(dir.path().to_path_buf())
.await
.expect("failed to read worktree status");
assert!(status.contains("README.md"));
assert!(status.contains("new-file.txt"));
}
#[tokio::test]
async fn test_tracked_worktree_status_ignores_untracked_repo_paths() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
fs::write(dir.path().join("README.md"), "dirty change").expect("failed to write change");
fs::write(dir.path().join("new-file.txt"), "new").expect("failed to write new file");
let status = tracked_worktree_status(dir.path().to_path_buf())
.await
.expect("failed to read tracked worktree status");
assert!(status.contains("README.md"));
assert!(!status.contains("new-file.txt"));
}
#[tokio::test]
async fn test_main_repo_root_returns_repo_root_for_main_worktree() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let repo_root = main_repo_root(dir.path().to_path_buf())
.await
.expect("failed to resolve main repo root");
assert_eq!(
canonicalize_test_path(&repo_root),
canonicalize_test_path(dir.path())
);
}
#[tokio::test]
async fn test_main_repo_root_returns_shared_repo_root_for_linked_worktree() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let linked_worktree = dir.path().join("linked-worktree");
create_worktree(
dir.path().to_path_buf(),
linked_worktree.clone(),
"wt/main-repo-root-test".to_string(),
"main".to_string(),
)
.await
.expect("failed to create linked worktree");
let repo_root = main_repo_root(linked_worktree)
.await
.expect("failed to resolve shared repo root");
assert_eq!(
canonicalize_test_path(&repo_root),
canonicalize_test_path(dir.path())
);
}
#[tokio::test]
async fn test_abort_rebase_cleans_stale_rebase_merge_metadata() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let stale_rebase_dir = dir.path().join(".git/rebase-merge");
fs::create_dir_all(&stale_rebase_dir).expect("failed to create stale rebase metadata");
fs::write(stale_rebase_dir.join("head-name"), "refs/heads/main")
.expect("failed to write stale rebase metadata");
let result = abort_rebase(dir.path().to_path_buf()).await;
assert!(result.is_ok(), "abort_rebase should succeed: {result:?}");
assert!(!stale_rebase_dir.exists());
}
#[tokio::test]
async fn test_abort_rebase_returns_error_without_rebase_state_or_stale_metadata() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let result = abort_rebase(dir.path().to_path_buf()).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_ref_hash_resolves_branch_head() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let expected_hash = run_git_command_stdout(dir.path(), &["rev-parse", "main"]);
let resolved_hash = ref_hash(dir.path().to_path_buf(), "main".to_string())
.await
.expect("failed to resolve main hash");
assert_eq!(resolved_hash, expected_hash);
}
#[tokio::test]
async fn test_rebase_onto_start_replays_commits_after_old_base() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "parent"]);
fs::write(dir.path().join("parent.txt"), "parent").expect("failed to write parent file");
run_git_command(dir.path(), &["add", "parent.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Parent change"]);
let parent_tip = run_git_command_stdout(dir.path(), &["rev-parse", "HEAD"]);
run_git_command(dir.path(), &["checkout", "-b", "child"]);
fs::write(dir.path().join("child.txt"), "child").expect("failed to write child file");
run_git_command(dir.path(), &["add", "child.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Child change"]);
run_git_command(dir.path(), &["checkout", "main"]);
fs::write(dir.path().join("main.txt"), "main").expect("failed to write main file");
run_git_command(dir.path(), &["add", "main.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Main change"]);
run_git_command(dir.path(), &["checkout", "child"]);
let result = rebase_onto_start(dir.path().to_path_buf(), "main".to_string(), parent_tip)
.await
.expect("failed to start rebase --onto");
let child_only_subjects = run_git_command_stdout(
dir.path(),
&["log", "--format=%s", "--reverse", "main..HEAD"],
);
assert_eq!(result, RebaseStepResult::Completed);
assert_eq!(child_only_subjects, "Child change");
assert!(!dir.path().join("parent.txt").exists());
assert!(dir.path().join("child.txt").exists());
}
#[tokio::test]
async fn test_pull_rebase_returns_error_without_upstream() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let result = pull_rebase(dir.path().to_path_buf()).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_pull_rebase_targets_single_upstream_when_merge_targets_are_ambiguous() {
let dir = tempdir().expect("failed to create temp dir");
let remote_dir = tempdir().expect("failed to create remote temp dir");
setup_test_git_repo(dir.path());
run_git_command(remote_dir.path(), &["init", "--bare"]);
let remote_path = remote_dir.path().to_string_lossy().to_string();
run_git_command(dir.path(), &["remote", "add", "origin", &remote_path]);
run_git_command(dir.path(), &["push", "-u", "origin", "main"]);
run_git_command(dir.path(), &["checkout", "-b", "feature"]);
fs::write(dir.path().join("feature.txt"), "feature change").expect("failed to write file");
run_git_command(dir.path(), &["add", "feature.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Add feature branch"]);
run_git_command(dir.path(), &["push", "-u", "origin", "feature"]);
run_git_command(dir.path(), &["checkout", "main"]);
run_git_command(
dir.path(),
&["config", "--add", "branch.main.merge", "refs/heads/feature"],
);
let pull_without_explicit_target = Command::new("git")
.args(["pull", "--rebase"])
.current_dir(dir.path())
.output()
.expect("failed to run pull --rebase");
assert!(
!pull_without_explicit_target.status.success(),
"expected plain pull --rebase to fail in ambiguous merge-target setup"
);
assert!(
String::from_utf8_lossy(&pull_without_explicit_target.stderr)
.contains("Cannot rebase onto multiple branches"),
"expected ambiguous merge-target failure"
);
let result = pull_rebase(dir.path().to_path_buf()).await;
assert!(
matches!(result, Ok(PullRebaseResult::Completed)),
"pull_rebase should complete: {result:?}"
);
}
#[tokio::test]
async fn test_pull_rebase_targets_local_upstream_when_upstream_name_has_no_remote_prefix() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
run_git_command(dir.path(), &["checkout", "-b", "feature"]);
fs::write(dir.path().join("feature.txt"), "feature change").expect("failed to write file");
run_git_command(dir.path(), &["add", "feature.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Add feature branch"]);
run_git_command(dir.path(), &["checkout", "main"]);
run_git_command(dir.path(), &["config", "branch.main.remote", "."]);
run_git_command(
dir.path(),
&[
"config",
"--replace-all",
"branch.main.merge",
"refs/heads/main",
],
);
run_git_command(
dir.path(),
&["config", "--add", "branch.main.merge", "refs/heads/feature"],
);
let pull_without_explicit_target = Command::new("git")
.args(["pull", "--rebase"])
.current_dir(dir.path())
.output()
.expect("failed to run pull --rebase");
assert!(
!pull_without_explicit_target.status.success(),
"expected plain pull --rebase to fail in ambiguous merge-target setup"
);
assert!(
String::from_utf8_lossy(&pull_without_explicit_target.stderr)
.contains("Cannot rebase onto multiple branches"),
"expected ambiguous merge-target failure"
);
let result = pull_rebase(dir.path().to_path_buf()).await;
assert!(
matches!(result, Ok(PullRebaseResult::Completed)),
"pull_rebase with local upstream should complete: {result:?}"
);
}
#[tokio::test]
async fn test_list_upstream_commit_titles_returns_error_without_upstream() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let result = list_upstream_commit_titles(dir.path().to_path_buf()).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_list_upstream_commit_titles_returns_new_upstream_commit_titles() {
let dir = tempdir().expect("failed to create temp dir");
let remote_dir = tempdir().expect("failed to create remote temp dir");
let contributor_dir = tempdir().expect("failed to create contributor temp dir");
let contributor_clone_path = contributor_dir.path().join("clone");
setup_test_git_repo(dir.path());
run_git_command(remote_dir.path(), &["init", "--bare"]);
let remote_path = remote_dir.path().to_string_lossy().to_string();
let contributor_clone_path_text = contributor_clone_path.to_string_lossy().to_string();
run_git_command(dir.path(), &["remote", "add", "origin", &remote_path]);
run_git_command(dir.path(), &["push", "-u", "origin", "main"]);
run_git_command(
contributor_dir.path(),
&["clone", &remote_path, &contributor_clone_path_text],
);
run_git_command(
&contributor_clone_path,
&["config", "user.name", "Contributor User"],
);
run_git_command(
&contributor_clone_path,
&["config", "user.email", "contributor@example.com"],
);
run_git_command(
&contributor_clone_path,
&["checkout", "-B", "main", "origin/main"],
);
fs::write(contributor_clone_path.join("remote.txt"), "remote change")
.expect("failed to write remote change");
run_git_command(&contributor_clone_path, &["add", "remote.txt"]);
run_git_command(
&contributor_clone_path,
&["commit", "-m", "Remote commit title"],
);
run_git_command(&contributor_clone_path, &["push", "origin", "main"]);
run_git_command(dir.path(), &["fetch", "origin"]);
let titles = list_upstream_commit_titles(dir.path().to_path_buf())
.await
.expect("failed to list upstream commit titles");
assert_eq!(titles, vec!["Remote commit title".to_string()]);
}
#[tokio::test]
async fn test_list_local_commit_titles_returns_error_without_upstream() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let result = list_local_commit_titles(dir.path().to_path_buf()).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_list_local_commit_titles_returns_new_local_commit_titles() {
let dir = tempdir().expect("failed to create temp dir");
let remote_dir = tempdir().expect("failed to create remote temp dir");
setup_test_git_repo(dir.path());
run_git_command(remote_dir.path(), &["init", "--bare"]);
let remote_path = remote_dir.path().to_string_lossy().to_string();
run_git_command(dir.path(), &["remote", "add", "origin", &remote_path]);
run_git_command(dir.path(), &["push", "-u", "origin", "main"]);
fs::write(dir.path().join("local_1.txt"), "local change 1")
.expect("failed to write local change 1");
run_git_command(dir.path(), &["add", "local_1.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Local commit title one"]);
fs::write(dir.path().join("local_2.txt"), "local change 2")
.expect("failed to write local change 2");
run_git_command(dir.path(), &["add", "local_2.txt"]);
run_git_command(dir.path(), &["commit", "-m", "Local commit title two"]);
let titles = list_local_commit_titles(dir.path().to_path_buf())
.await
.expect("failed to list local commit titles");
assert_eq!(
titles,
vec![
"Local commit title one".to_string(),
"Local commit title two".to_string(),
]
);
}
#[tokio::test]
async fn test_push_current_branch_returns_error_without_remote() {
let dir = tempdir().expect("failed to create temp dir");
setup_test_git_repo(dir.path());
let result = push_current_branch(dir.path().to_path_buf()).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_push_current_branch_returns_upstream_reference() {
let dir = tempdir().expect("failed to create temp dir");
let remote_dir = tempdir().expect("failed to create remote temp dir");
setup_test_git_repo(dir.path());
run_git_command(remote_dir.path(), &["init", "--bare"]);
let remote_path = remote_dir.path().to_string_lossy().to_string();
run_git_command(dir.path(), &["remote", "add", "origin", &remote_path]);
let upstream_reference = push_current_branch(dir.path().to_path_buf())
.await
.expect("push should set upstream");
assert_eq!(upstream_reference, "origin/main");
}
#[tokio::test]
async fn test_push_current_branch_to_remote_branch_returns_upstream_reference() {
let dir = tempdir().expect("failed to create temp dir");
let remote_dir = tempdir().expect("failed to create remote temp dir");
setup_test_git_repo(dir.path());
run_git_command(remote_dir.path(), &["init", "--bare"]);
let remote_path = remote_dir.path().to_string_lossy().to_string();
run_git_command(dir.path(), &["remote", "add", "origin", &remote_path]);
let upstream_reference = push_current_branch_to_remote_branch(
dir.path().to_path_buf(),
"review/custom-branch".to_string(),
)
.await
.expect("push should set a custom upstream");
assert_eq!(upstream_reference, "origin/review/custom-branch");
}
#[test]
fn test_is_no_upstream_error_detects_upstream_hint() {
let detail = "fatal: The current branch main has no upstream branch.";
let is_no_upstream = sync::is_no_upstream_error(detail);
assert!(is_no_upstream);
}
#[test]
fn test_is_rebase_conflict_detects_conflict_keyword() {
let detail = "CONFLICT (content): Merge conflict in src/main.rs";
assert!(rebase::is_rebase_conflict(detail));
}
#[test]
fn test_is_rebase_conflict_detects_could_not_apply() {
let detail = "error: could not apply abc1234... Update handler";
assert!(rebase::is_rebase_conflict(detail));
}
#[test]
fn test_is_rebase_conflict_detects_mark_as_resolved() {
let detail = "hint: mark them as resolved using git add";
assert!(rebase::is_rebase_conflict(detail));
}
#[test]
fn test_is_rebase_conflict_detects_unresolved_conflict() {
let detail = "fatal: Exiting because of an unresolved conflict.";
assert!(rebase::is_rebase_conflict(detail));
}
#[test]
fn test_is_rebase_conflict_detects_committing_not_possible() {
let detail = "error: Committing is not possible because you have unmerged files.";
assert!(rebase::is_rebase_conflict(detail));
}
#[test]
fn test_is_rebase_conflict_returns_false_for_unrelated_error() {
let detail = "fatal: not a git repository (or any parent up to mount point /)";
assert!(!rebase::is_rebase_conflict(detail));
}
#[test]
fn test_is_rebase_conflict_returns_false_for_index_lock_error() {
let detail = "fatal: Unable to create '.git/index.lock': File exists.";
assert!(!rebase::is_rebase_conflict(detail));
}
}