use std::path::Path;
use std::process::Command;
#[derive(Debug, Clone)]
pub struct RepoStatus {
pub branch: String,
pub clean: bool,
pub ahead: u32,
pub behind: u32,
pub last_commit: String,
}
fn git_in_dir(dir: &Path, args: &[&str]) -> Result<(String, String), String> {
let output = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.map_err(|e| format!("failed to run git: {}", e))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if !output.status.success() {
return Err(if stderr.is_empty() { stdout } else { stderr });
}
Ok((stdout, stderr))
}
pub fn is_git_repo(path: &Path) -> bool {
path.join(".git").is_dir()
}
pub fn current_branch(dir: &Path) -> Result<String, String> {
let (out, _) = git_in_dir(dir, &["branch", "--show-current"])?;
if out.is_empty() {
let (out, _) = git_in_dir(dir, &["rev-parse", "--short", "HEAD"])?;
return Ok(format!("(HEAD at {})", out));
}
Ok(out)
}
pub fn ahead_behind(dir: &Path) -> Result<(u32, u32), String> {
let result = git_in_dir(dir, &["rev-list", "--count", "--left-right", "@{u}...HEAD"]);
match result {
Ok((out, _)) => {
let parts: Vec<&str> = out.split_whitespace().collect();
let ahead: u32 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
let behind: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
Ok((ahead, behind))
}
Err(_) => Ok((0, 0)), }
}
pub fn is_clean(dir: &Path) -> bool {
git_in_dir(dir, &["status", "--porcelain"])
.map(|(out, _)| out.is_empty())
.unwrap_or(false)
}
pub fn last_commit(dir: &Path) -> Result<String, String> {
let (hash, _) = git_in_dir(dir, &["rev-parse", "--short", "HEAD"])?;
let (subject, _) = git_in_dir(dir, &["log", "-1", "--format=%s"])?;
Ok(format!("{} {}", hash, truncate_str(&subject, 40)))
}
pub fn status(dir: &Path) -> Result<RepoStatus, String> {
if !is_git_repo(dir) {
return Err("not a git repository".into());
}
let branch = current_branch(dir)?;
let clean = is_clean(dir);
let (ahead, behind) = ahead_behind(dir)?;
let last_commit = last_commit(dir).unwrap_or_else(|_| "N/A".into());
Ok(RepoStatus {
branch,
clean,
ahead,
behind,
last_commit,
})
}
pub fn clone(url: &str, dest: &Path, token: Option<&str>) -> Result<CloneResult, String> {
if dest.join(".git").is_dir() {
return Ok(CloneResult::Skipped);
}
if dest.exists() {
return Err(format!(
"{} exists but is not a git repo — remove it manually",
dest.display()
));
}
let auth_url = if let Some(t) = token {
url.replace("https://", &format!("https://x-access-token:{}@", t))
} else {
url.to_string()
};
let output = Command::new("git")
.args(["clone", &auth_url])
.arg(dest)
.output()
.map_err(|e| format!("git clone failed: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let safe_err = if let Some(t) = token {
stderr.replace(t, "***")
} else {
stderr.to_string()
};
return Err(safe_err.trim().to_string());
}
Ok(CloneResult::Cloned)
}
#[derive(Debug, PartialEq)]
pub enum CloneResult {
Cloned,
Skipped,
}
pub fn pull(dir: &Path) -> Result<PullResult, String> {
if !is_git_repo(dir) {
return Err("not a git repository".into());
}
git_in_dir(dir, &["fetch", "origin"])?;
let result = git_in_dir(dir, &["merge", "--ff-only", "origin/main"]);
match result {
Ok((out, _)) => {
if out.contains("Already up to date") {
Ok(PullResult::UpToDate)
} else {
Ok(PullResult::Updated(out))
}
}
Err(e) => Err(e),
}
}
#[derive(Debug)]
pub enum PullResult {
Updated(String),
UpToDate,
}
pub fn push(dir: &Path) -> Result<String, String> {
if !is_git_repo(dir) {
return Err("not a git repository".into());
}
let (out, _) = git_in_dir(dir, &["push", "origin", "main"])?;
Ok(out)
}
pub fn fetch_upstream(dir: &Path, upstream_url: &str) -> Result<(), String> {
if !is_git_repo(dir) {
return Err("not a git repository".into());
}
let has_upstream = git_in_dir(dir, &["remote", "get-url", "upstream"]).is_ok();
if !has_upstream {
git_in_dir(dir, &["remote", "add", "upstream", upstream_url])?;
}
git_in_dir(dir, &["fetch", "upstream"])?;
Ok(())
}
fn truncate_str(s: &str, max: usize) -> String {
if s.len() <= max {
s.to_string()
} else {
format!("{}...", &s[..max - 3])
}
}