1use std::ffi::OsStr;
2use std::io::Write;
3use std::path::Path;
4use std::process::{Command, Output, Stdio};
5use thiserror::Error;
6
7#[derive(Debug, Error)]
8pub enum GitError {
9 #[error("failed to spawn `git {args}`: {source}")]
10 Spawn { args: String, source: std::io::Error },
11 #[error("`git {args}` failed: {stderr}")]
12 Failed { args: String, stderr: String },
13}
14
15pub fn git<T: AsRef<OsStr>>(repo: Option<&Path>, args: &[T]) -> Result<Vec<u8>, GitError> {
16 git_with_env(repo, args, &[])
17}
18
19pub fn git_with_env<T: AsRef<OsStr>>(
20 repo: Option<&Path>,
21 args: &[T],
22 env: &[(&str, &OsStr)],
23) -> Result<Vec<u8>, GitError> {
24 let output = command(repo, args).envs(env.iter().copied()).output().map_err(|source| spawn_error(args, source))?;
25 stdout(args, output)
26}
27
28pub fn git_text<T: AsRef<OsStr>>(repo: Option<&Path>, args: &[T]) -> Result<String, GitError> {
29 git(repo, args).map(|stdout| String::from_utf8_lossy(&stdout).trim().to_string())
30}
31
32pub fn current_ref(repo: &Path) -> Option<String> {
34 git_text(Some(repo), &["branch", "--show-current"])
35 .ok()
36 .filter(|name| !name.is_empty())
37 .or_else(|| git_text(Some(repo), &["rev-parse", "--short", "HEAD"]).ok())
38}
39
40pub fn git_with_stdin<T: AsRef<OsStr>>(repo: Option<&Path>, args: &[T], stdin: &[u8]) -> Result<Vec<u8>, GitError> {
41 let mut child = command(repo, args)
42 .stdin(Stdio::piped())
43 .stdout(Stdio::piped())
44 .stderr(Stdio::piped())
45 .spawn()
46 .map_err(|source| spawn_error(args, source))?;
47 child.stdin.take().expect("stdin is piped").write_all(stdin).map_err(|source| spawn_error(args, source))?;
48 let output = child.wait_with_output().map_err(|source| spawn_error(args, source))?;
49 stdout(args, output)
50}
51
52fn command<T: AsRef<OsStr>>(repo: Option<&Path>, args: &[T]) -> Command {
53 let mut command = Command::new("git");
54 if let Some(repo) = repo {
55 command.arg("-C").arg(repo);
56 }
57 command.args(args);
58 command
59}
60
61fn stdout<T: AsRef<OsStr>>(args: &[T], output: Output) -> Result<Vec<u8>, GitError> {
62 if output.status.success() {
63 Ok(output.stdout)
64 } else {
65 Err(GitError::Failed {
66 args: display(args),
67 stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
68 })
69 }
70}
71
72fn spawn_error<T: AsRef<OsStr>>(args: &[T], source: std::io::Error) -> GitError {
73 GitError::Spawn { args: display(args), source }
74}
75
76fn display<T: AsRef<OsStr>>(args: &[T]) -> String {
77 args.iter().map(|arg| arg.as_ref().to_string_lossy()).collect::<Vec<_>>().join(" ")
78}