use std::path::Path; use std::process::{Command, Output}; use crate::error::{Error, Result}; pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result { let mut cmd = Command::new("git"); if let Some(c) = cwd { cmd.current_dir(c); } cmd.args(args); cmd.env("GIT_TERMINAL_PROMPT", "0"); cmd.env("GIT_CONFIG_NOSYSTEM", "1"); cmd.env("LC_ALL", "C"); let out = cmd.output().map_err(|e| Error::git(format!("git {args:?}: {e}")))?; ok(out, args) } fn ok(out: Output, args: &[&str]) -> Result { if !out.status.success() { return Err(Error::git(format!( "git {args:?} exited {}: {}", out.status, String::from_utf8_lossy(&out.stderr).trim() ))); } Ok(String::from_utf8_lossy(&out.stdout).to_string()) } pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool { git(cwd, args).is_ok() } pub fn ls_remote_head(url: &str) -> Result> { match git(None, &["ls-remote", url, "HEAD"]) { Ok(out) => { let sha = out .split_whitespace() .next() .filter(|s| s.len() >= 7) .map(|s| s.to_string()); Ok(sha) } Err(e) if is_missing_remote(&e) => Ok(None), Err(e) => Err(e), } } pub fn ls_remote_heads(url: &str) -> Result> { let out = git(None, &["ls-remote", "--heads", url])?; let mut v = Vec::new(); for line in out.lines() { let mut it = line.split_whitespace(); if let (Some(sha), Some(name)) = (it.next(), it.next()) { v.push((name.to_string(), sha.to_string())); } } Ok(v) } pub fn ls_remote_ref(url: &str, refname: &str) -> Result> { match git(None, &["ls-remote", url, refname]) { Ok(out) => Ok(out .lines() .next() .and_then(|l| l.split_whitespace().next()) .map(|s| s.to_string())), Err(e) if is_missing_remote(&e) => Ok(None), Err(e) => Err(e), } } fn is_missing_remote(e: &Error) -> bool { let s = e.to_string(); s.contains("not found") || s.contains("does not appear to be a git repository") || s.contains("Repository not found") || s.contains("404") } pub fn clone(url: &str, dest: &Path) -> Result<()> { if dest.exists() { return Ok(()); } if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; } git(None, &["clone", "--quiet", "--mirror", url, &dest.display().to_string()])?; Ok(()) } pub fn clone_bare(url: &str, dest: &Path) -> Result<()> { if dest.exists() { return Ok(()); } if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; } git( None, &["clone", "--quiet", "--bare", url, &dest.display().to_string()], )?; Ok(()) } pub fn fetch_head(mirror: &Path) -> Result { git(Some(mirror), &["fetch", "--quiet", "--no-prune", "origin"])?; head(mirror) } pub fn head(mirror: &Path) -> Result { Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string()) } pub fn has_commit(mirror: &Path, commit: &str) -> bool { git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")]) } pub fn ls_tree(mirror: &Path, commit: &str) -> Result> { let out = git(Some(mirror), &["ls-tree", "-r", commit])?; let mut v = Vec::new(); for line in out.lines() { if let Some(rest) = line.strip_prefix("100644 blob ").or_else(|| line.strip_prefix("100755 blob ")) { if let Some((sha, path)) = rest.split_once('\t') { v.push((path.to_string(), sha.to_string())); } } } Ok(v) } pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result> { let spec = format!("{commit}:{path}"); let out = Command::new("git") .current_dir(mirror) .env("GIT_TERMINAL_PROMPT", "0") .env("GIT_CONFIG_NOSYSTEM", "1") .args(["cat-file", "blob", &spec]) .output() .map_err(|e| Error::git(e.to_string()))?; if !out.status.success() { return Err(Error::not_found(format!("{spec} not in mirror"))); } Ok(out.stdout) } pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { std::fs::create_dir_all(dest)?; let out = Command::new("git") .current_dir(mirror) .env("GIT_TERMINAL_PROMPT", "0") .env("GIT_CONFIG_NOSYSTEM", "1") .args(["archive", "--format=tar", commit]) .output() .map_err(|e| Error::git(e.to_string()))?; if !out.status.success() { return Err(Error::git(format!( "git archive {commit}: {}", String::from_utf8_lossy(&out.stderr).trim() ))); } let mut ar = tar::Archive::new(std::io::Cursor::new(&out.stdout)); ar.set_preserve_permissions(true); ar.unpack(dest) .map_err(|e| Error::git(format!("unpack {commit}: {e}")))?; Ok(()) } pub fn log_oneline(mirror: &Path, range: &str) -> Result> { let out = git(Some(mirror), &["log", "--oneline", range])?; Ok(out.lines().map(|l| l.to_string()).collect()) } pub fn diff(mirror: &Path, range: &str, paths: &[&str]) -> Result { let mut args: Vec<&str> = vec!["diff", "--no-color", range, "--"]; args.extend(paths); git(Some(mirror), &args) } pub fn count_commits(mirror: &Path, range: &str) -> Result { let out = git(Some(mirror), &["rev-list", "--count", range])?; Ok(out.trim().parse().unwrap_or(0)) } pub fn clone_source(url: &str, dest: &Path, depth: Option, branch: Option<&str>) -> Result<()> { if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; } let mut args: Vec = vec!["clone".into(), "--quiet".into()]; if let Some(d) = depth { args.push(format!("--depth={d}")); } if let Some(b) = branch { args.push(format!("--branch={b}")); } args.push(url.to_string()); args.push(dest.display().to_string()); let refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect(); git(None, &refs)?; Ok(()) } pub fn fetch_and_head(repo: &Path) -> Result { git(Some(repo), &["fetch", "--quiet", "--no-prune", "origin"])?; head(repo) }