use crate::error::SpriteError;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;
#[allow(dead_code)]
pub fn get_git_root() -> Result<PathBuf> {
let output = Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.output()
.with_context(|| "Failed to execute git command. Is git installed?")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to get git repository root",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let root_str = String::from_utf8_lossy(&output.stdout);
Ok(PathBuf::from(root_str.trim()))
}
#[allow(dead_code)]
pub fn get_current_branch() -> Result<String> {
get_current_branch_at(&std::env::current_dir()?)
}
pub fn get_current_branch_at(path: &Path) -> Result<String> {
let output = Command::new("git")
.current_dir(path)
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.output()
.with_context(|| format!("Failed to get current git branch at {}", path.display()))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to get current branch at {}", path.display()),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(branch)
}
pub fn branch_exists(branch: &str) -> Result<bool> {
let output = Command::new("git")
.args(["rev-parse", "--verify", &format!("refs/heads/{}", branch)])
.output()
.with_context(|| "Failed to check if branch exists")?;
Ok(output.status.success())
}
pub fn create_branch(branch: &str) -> Result<()> {
create_branch_from(branch, "HEAD")
}
pub fn create_branch_from(branch: &str, from: &str) -> Result<()> {
if branch_exists(branch)? {
return Err(SpriteError::git(format!("Branch '{}' already exists", branch)).into());
}
let output = Command::new("git")
.args(["checkout", "-b", branch, from])
.output()
.with_context(|| format!("Failed to create branch '{}' from '{}'", branch, from))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to create branch '{}' from '{}'", branch, from),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn switch_branch(branch: &str) -> Result<()> {
switch_branch_at(&std::env::current_dir()?, branch)
}
pub fn switch_branch_at(path: &Path, branch: &str) -> Result<()> {
if !branch_exists(branch)? {
return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
}
let output = Command::new("git")
.current_dir(path)
.args(["checkout", branch])
.output()
.with_context(|| {
format!(
"Failed to switch to branch '{}' at {}",
branch,
path.display()
)
})?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!(
"Failed to switch to branch '{}' at {}",
branch,
path.display()
),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
pub fn checkout_branch(path: &Path, branch: &str) -> Result<()> {
switch_branch_at(path, branch)
}
pub fn create_worktree(path: &Path, branch: &str) -> Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!(
"Failed to create parent directory for worktree: {}",
parent.display()
)
})?;
}
if !branch_exists(branch)? {
create_branch(branch)?;
}
let output = Command::new("git")
.args(["worktree", "add", path.to_string_lossy().as_ref(), branch])
.output()
.with_context(|| format!("Failed to create worktree at '{}'", path.display()))?;
if output.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("already exists") || stderr.contains("a branch named") {
prune_worktrees()?;
let force_output = Command::new("git")
.args([
"worktree",
"add",
"--force",
path.to_string_lossy().as_ref(),
branch,
])
.output()
.with_context(|| {
format!(
"Failed to create worktree with force at '{}'",
path.display()
)
})?;
if force_output.status.success() {
return Ok(());
}
}
Err(SpriteError::git_with_source(
format!("Failed to create worktree at '{}'", path.display()),
stderr,
)
.into())
}
pub fn remove_worktree(path: &Path) -> Result<()> {
if !path.exists() {
return Err(
SpriteError::git(format!("Worktree path does not exist: {}", path.display())).into(),
);
}
let output = Command::new("git")
.args(["worktree", "remove", path.to_string_lossy().as_ref()])
.output()
.with_context(|| format!("Failed to remove worktree at '{}'", path.display()))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to remove worktree at '{}'", path.display()),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
if path.exists() {
std::fs::remove_dir_all(path)
.with_context(|| format!("Failed to remove worktree directory: {}", path.display()))?;
}
Ok(())
}
pub fn list_worktrees() -> Result<Vec<WorktreeInfo>> {
let output = Command::new("git")
.args(["worktree", "list"])
.output()
.with_context(|| "Failed to list worktrees")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to list worktrees",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let worktrees_str = String::from_utf8_lossy(&output.stdout);
parse_worktree_list(&worktrees_str)
}
#[derive(Debug, Clone)]
pub struct WorktreeInfo {
pub path: PathBuf,
#[allow(dead_code)]
pub branch: String,
#[allow(dead_code)]
pub bare: bool,
#[allow(dead_code)]
pub id: Option<String>,
}
fn parse_worktree_list(output: &str) -> Result<Vec<WorktreeInfo>> {
let mut worktrees = Vec::new();
for line in output.lines() {
if line.trim().is_empty() {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.is_empty() {
continue;
}
let path = PathBuf::from(parts[0]);
let (branch, id, bare) = if parts.len() > 1 {
if parts.len() == 2 && parts[1].starts_with('(') && parts[1].ends_with(')') {
(String::new(), None, true)
} else if parts.len() >= 3 {
if parts[2].starts_with('(') {
(parts[1].to_string(), None, parts[2].contains("bare"))
} else {
(parts[1].to_string(), Some(parts[2].to_string()), false)
}
} else {
let branch_part = parts[1];
let (branch, id_part) = branch_part.split_once(' ').unwrap_or((branch_part, ""));
let id = if !id_part.is_empty() {
Some(id_part.to_string())
} else {
None
};
(branch.trim().to_string(), id, false)
}
} else {
(String::new(), None, false)
};
worktrees.push(WorktreeInfo {
path,
branch,
bare,
id,
});
}
Ok(worktrees)
}
pub fn is_git_repository() -> Result<bool> {
is_git_repository_at(&std::env::current_dir()?)
}
pub fn is_git_repository_at(path: &Path) -> Result<bool> {
let output = Command::new("git")
.current_dir(path)
.args(["rev-parse", "--git-dir"])
.output()
.with_context(|| format!("Failed to execute git command at {}", path.display()))?;
Ok(output.status.success())
}
pub fn validate_git_repository() -> Result<()> {
if !is_git_repository()? {
return Err(SpriteError::config(
"Not a git repository. Sprite must be run from within a git repository.",
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn get_status() -> Result<GitStatus> {
get_status_at(&std::env::current_dir()?)
}
#[allow(dead_code)]
pub fn get_status_string() -> Result<String> {
get_status_string_at(&std::env::current_dir()?)
}
#[allow(dead_code)]
pub fn get_status_at(path: &Path) -> Result<GitStatus> {
let output = Command::new("git")
.current_dir(path)
.args(["status", "--porcelain"])
.output()
.with_context(|| format!("Failed to get git status at {}", path.display()))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to get git status at {}", path.display()),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let status_str = String::from_utf8_lossy(&output.stdout);
parse_git_status(&status_str)
}
pub fn get_status_string_at(path: &Path) -> Result<String> {
let output = Command::new("git")
.current_dir(path)
.args(["status", "--porcelain"])
.output()
.with_context(|| format!("Failed to get git status string at {}", path.display()))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to get git status string at {}", path.display()),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let status_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(status_str)
}
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GitStatus {
pub modified: usize,
pub added: usize,
pub deleted: usize,
pub untracked: usize,
pub has_changes: bool,
}
#[allow(dead_code)]
fn parse_git_status(output: &str) -> Result<GitStatus> {
let mut status = GitStatus {
modified: 0,
added: 0,
deleted: 0,
untracked: 0,
has_changes: false,
};
for line in output.lines() {
if line.trim().is_empty() {
continue;
}
let first_char = line.chars().next().unwrap_or(' ');
let second_char = line.chars().nth(1).unwrap_or(' ');
match (first_char, second_char) {
('M', _) | ('A', 'M') | ('R', 'M') => status.modified += 1,
(' ', 'M') => status.modified += 1, ('A', _) | ('R', 'A') | ('C', 'A') => status.added += 1,
('D', _) | ('C', 'D') => status.deleted += 1,
(' ', 'D') => status.deleted += 1, ('?', _) => status.untracked += 1,
_ => {}
}
}
status.has_changes = status.modified + status.added + status.deleted + status.untracked > 0;
Ok(status)
}
#[allow(dead_code)]
pub fn pull() -> Result<()> {
let output = Command::new("git")
.args(["pull"])
.output()
.with_context(|| "Failed to pull changes")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to pull changes",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn push(branch: Option<&str>) -> Result<()> {
let mut args = vec!["push"];
if let Some(b) = branch {
args.extend(&["origin", b]);
}
let output = Command::new("git")
.args(&args)
.output()
.with_context(|| "Failed to push changes")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to push changes",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn commit(message: &str) -> Result<()> {
let output = Command::new("git")
.args(["commit", "-m", message])
.output()
.with_context(|| "Failed to commit changes")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to commit changes",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn add(files: &[&Path]) -> Result<()> {
let mut args: Vec<String> = vec!["add".to_string()];
for file in files {
args.push(file.to_string_lossy().into_owned());
}
let output = Command::new("git")
.args(&args)
.output()
.with_context(|| "Failed to add files to git")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to add files to git",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
#[allow(dead_code)]
pub fn has_uncommitted_changes(path: &Path) -> Result<bool> {
let output = Command::new("git")
.args([
"diff",
"--quiet",
"--exit-code",
path.to_string_lossy().as_ref(),
])
.output()
.with_context(|| "Failed to check for uncommitted changes")?;
Ok(output.status.code() == Some(1))
}
#[allow(dead_code)]
pub fn get_current_commit() -> Result<String> {
let output = Command::new("git")
.args(["rev-parse", "HEAD"])
.output()
.with_context(|| "Failed to get current commit hash")?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
"Failed to get current commit hash",
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(commit)
}
#[allow(dead_code)]
pub fn get_remote_url(remote: Option<&str>) -> Result<String> {
let remote_name = remote.unwrap_or("origin");
let output = Command::new("git")
.args(["remote", "get-url", remote_name])
.output()
.with_context(|| format!("Failed to get remote URL for '{}'", remote_name))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to get remote URL for '{}'", remote_name),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(url)
}
pub fn delete_branch(branch: &str, force: bool) -> Result<()> {
if !branch_exists(branch)? {
return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
}
let mut args = vec!["branch", "-d"];
if force {
args.push("-D");
}
args.push(branch);
let output = Command::new("git")
.args(&args)
.output()
.with_context(|| format!("Failed to delete branch '{}'", branch))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to delete branch '{}'", branch),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
pub fn is_branch_merged(branch: &str) -> Result<bool> {
let output = Command::new("git")
.args(["merge-base", "--is-ancestor", branch, "HEAD"])
.output()
.with_context(|| format!("Failed to check if branch '{}' is merged", branch))?;
Ok(output.status.success())
}
#[allow(dead_code)]
pub fn get_branches_containing_commit(commit: &str) -> Result<Vec<String>> {
let output = Command::new("git")
.args(["branch", "--contains", commit])
.output()
.with_context(|| format!("Failed to get branches containing commit '{}'", commit))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to get branches containing commit '{}'", commit),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let branches_str = String::from_utf8_lossy(&output.stdout);
let branches: Vec<String> = branches_str
.lines()
.map(|line| line.trim().trim_start_matches("* ").to_string())
.filter(|s| !s.is_empty())
.collect();
Ok(branches)
}
#[allow(dead_code)]
pub fn force_delete_branch(branch: &str) -> Result<()> {
delete_branch(branch, true)
}
#[allow(dead_code)]
pub fn safe_delete_branch(branch: &str) -> Result<()> {
if !is_branch_merged(branch)? {
return Err(SpriteError::git(format!(
"Branch '{}' has unmerged changes. Use --force to delete anyway.",
branch
))
.into());
}
delete_branch(branch, false)
}
#[allow(dead_code)]
pub fn get_branch_commit(branch: &str) -> Result<String> {
let output = Command::new("git")
.args(["rev-parse", &format!("refs/heads/{}", branch)])
.output()
.with_context(|| format!("Failed to get commit hash for branch '{}'", branch))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to get commit hash for branch '{}'", branch),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(commit)
}
pub fn merge_branch(branch: &str) -> Result<()> {
if !branch_exists(branch)? {
return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
}
let output = Command::new("git")
.args(["merge", "--no-ff", branch])
.output()
.with_context(|| format!("Failed to merge branch '{}'", branch))?;
if !output.status.success() {
return Err(SpriteError::git_with_source(
format!("Failed to merge branch '{}'", branch),
String::from_utf8_lossy(&output.stderr),
)
.into());
}
Ok(())
}
pub fn has_merge_conflicts() -> Result<bool> {
let output = Command::new("git")
.args(["diff", "--name-only", "--diff-filter=U"])
.output()
.with_context(|| "Failed to check for merge conflicts")?;
let conflicts_str = String::from_utf8_lossy(&output.stdout);
Ok(!conflicts_str.trim().is_empty())
}
pub fn prune_worktrees() -> Result<()> {
let output = Command::new("git")
.args(["worktree", "prune"])
.output()
.with_context(|| "Failed to prune worktrees")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("⚠️ Warning: Failed to prune worktrees: {}", stderr);
}
Ok(())
}
pub fn remove_worktree_reference(path: &Path) -> Result<()> {
let output = Command::new("git")
.args([
"worktree",
"remove",
"--force",
path.to_string_lossy().as_ref(),
])
.output()
.with_context(|| {
format!(
"Failed to remove worktree reference at '{}'",
path.display()
)
})?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!(
"⚠️ Warning: Failed to remove worktree reference: {}. Trying prune...",
stderr
);
prune_worktrees()?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_worktree_list() {
let input = r#"
/path/to/worktree feature/branch
/path/to/another main abc123
/path/to/bare (bare)
"#;
let worktrees = parse_worktree_list(input).unwrap();
assert_eq!(worktrees.len(), 3);
assert_eq!(worktrees[0].path, PathBuf::from("/path/to/worktree"));
assert_eq!(worktrees[0].branch, "feature/branch");
assert!(!worktrees[0].bare);
assert_eq!(worktrees[0].id, None);
assert_eq!(worktrees[1].path, PathBuf::from("/path/to/another"));
assert_eq!(worktrees[1].branch, "main");
assert!(!worktrees[1].bare);
assert_eq!(worktrees[1].id, Some("abc123".to_string()));
assert_eq!(worktrees[2].path, PathBuf::from("/path/to/bare"));
assert!(worktrees[2].bare);
}
#[test]
fn test_parse_git_status() {
let input = r#"
M src/main.rs
A src/new_file.rs
D src/old_file.rs
?? untracked.txt
"#;
let status = parse_git_status(input).unwrap();
assert_eq!(status.modified, 1);
assert_eq!(status.added, 1);
assert_eq!(status.deleted, 1);
assert_eq!(status.untracked, 1);
assert!(status.has_changes);
}
#[test]
fn test_validate_git_repository() {
let _result = is_git_repository();
}
}