Skip to content

Commit

Permalink
refactor git.rs (#1003)
Browse files Browse the repository at this point in the history
  • Loading branch information
jdx authored Nov 16, 2023
1 parent f9ac9b0 commit 5372bef
Showing 1 changed file with 24 additions and 33 deletions.
57 changes: 24 additions & 33 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fs::create_dir_all;
use std::path::PathBuf;

use color_eyre::eyre::{eyre, Result};
use duct::Expression;

use crate::cmd;
use crate::file::touch_dir;
Expand All @@ -16,7 +17,7 @@ macro_rules! git_cmd {
let safe = format!("safe.directory={}", $dir.display());
cmd!("git", "-C", $dir, "-c", safe $(, $arg)*)
}
};
}
}

impl Git {
Expand All @@ -31,23 +32,39 @@ impl Git {
pub fn update(&self, gitref: Option<String>) -> Result<(String, String)> {
let gitref = gitref.map_or_else(|| self.current_branch(), Ok)?;
debug!("updating {} to {}", self.dir.display(), gitref);
self.run_git_command(&[
let exec = |cmd: Expression| match cmd.stderr_to_stdout().stdout_capture().unchecked().run()
{
Ok(res) => {
if res.status.success() {
Ok(())
} else {
Err(eyre!(
"git failed: {cmd:?} {}",
String::from_utf8(res.stdout).unwrap()
))
}
}
Err(err) => Err(eyre!("git failed: {cmd:?} {err:#}")),
};
exec(git_cmd!(
&self.dir,
"fetch",
"--prune",
"--update-head-ok",
"origin",
format!("{}:{}", gitref, gitref).as_str(),
])?;
&format!("{}:{}", gitref, gitref),
))?;
let prev_rev = self.current_sha()?;
self.run_git_command(&[
exec(git_cmd!(
&self.dir,
"-c",
"advice.detachedHead=false",
"-c",
"advice.objectNameWarning=false",
"checkout",
"--force",
gitref.as_str(),
])?;
&gitref
))?;
let post_rev = self.current_sha()?;
touch_dir(&self.dir)?;

Expand Down Expand Up @@ -120,32 +137,6 @@ impl Git {
None => (url.to_string(), None),
}
}

pub fn run_git_command(&self, args: &[&str]) -> Result<()> {
let dir = self.dir.to_string_lossy();
let safe = format!("safe.directory={}", dir);
let mut cmd_args = vec!["-C", &dir, "-c", &safe];
cmd_args.extend(args.iter().cloned());
match cmd::cmd("git", &cmd_args)
.stderr_to_stdout()
.stdout_capture()
.unchecked()
.run()
{
Ok(res) => {
if res.status.success() {
Ok(())
} else {
Err(eyre!(
"git failed: {:?} {}",
cmd_args,
String::from_utf8(res.stdout).unwrap()
))
}
}
Err(err) => Err(eyre!("git failed: {:?} {:#}", cmd_args, err)),
}
}
}

fn get_git_version() -> Result<String> {
Expand Down

0 comments on commit 5372bef

Please sign in to comment.