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])
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
use std::process::Command;
fn temp_dir(tag: &str) -> PathBuf {
let mut dir = std::env::temp_dir();
dir.push(format!(
"pets-git-test-{}-{}-{}",
tag,
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
dir
}
fn git(dir: &Path, args: &[&str]) {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.expect("git should run");
assert!(
out.status.success(),
"git {:?} failed: {}",
args,
String::from_utf8_lossy(&out.stderr)
);
}
fn init_repo(dir: &Path) {
std::fs::create_dir_all(dir).unwrap();
git(dir, &["init", "-q"]);
git(dir, &["config", "user.email", "pets-test@example.com"]);
git(dir, &["config", "user.name", "Pets Test"]);
git(dir, &["config", "core.autocrlf", "false"]);
std::fs::write(dir.join("a.txt"), "hello\n").unwrap();
git(dir, &["add", "a.txt"]);
git(dir, &["commit", "-q", "-m", "initial commit"]);
}
#[test]
fn truncate_long_and_short() {
assert_eq!(truncate_str("short", 40), "short");
let long = "x".repeat(100);
let cut = truncate_str(&long, 40);
assert_eq!(cut.len(), 40);
assert!(cut.ends_with("..."));
}
#[test]
fn status_on_fresh_repo() {
let dir = temp_dir("status");
init_repo(&dir);
assert!(is_git_repo(&dir));
assert!(is_clean(&dir));
let branch = current_branch(&dir).unwrap();
assert!(!branch.is_empty());
assert_eq!(ahead_behind(&dir).unwrap(), (0, 0));
assert!(last_commit(&dir).unwrap().contains("initial commit"));
let s = status(&dir).unwrap();
assert_eq!(s.branch, branch);
assert!(s.clean);
assert_eq!(s.ahead, 0);
assert!(s.last_commit.contains("initial commit"));
std::fs::write(dir.join("a.txt"), "dirty\n").unwrap();
assert!(!is_clean(&dir));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn clone_is_idempotent() {
let dir = temp_dir("clone");
let src = dir.join("src");
let bare = dir.join("remote.git");
let dest = dir.join("work");
init_repo(&src);
let out = Command::new("git")
.args(["clone", "--bare", "-q"])
.arg(&src)
.arg(&bare)
.output()
.expect("git clone --bare should run");
assert!(
out.status.success(),
"bare clone failed: {}",
String::from_utf8_lossy(&out.stderr)
);
let url = bare.to_string_lossy().to_string();
assert_eq!(clone(&url, &dest, None).unwrap(), CloneResult::Cloned);
assert!(is_git_repo(&dest));
assert_eq!(clone(&url, &dest, None).unwrap(), CloneResult::Skipped);
let _ = std::fs::remove_dir_all(&dir);
}
}