diff --git a/src/git.rs b/src/git.rs index 1c091d3..14908c9 100644 --- a/src/git.rs +++ b/src/git.rs @@ -3,6 +3,25 @@ use anyhow::{Context, Result as AnyResult}; use git2::{Repository, StashFlags, StatusOptions}; pub(crate) trait GitBackend: Sized { + fn run_in(&mut self, id: &str, f: F) -> AnyResult + where + F: FnOnce() -> O, + { + self.switch_to(id) + .with_context(|| format!("Failed to checkout to {}", id))?; + + let rslt = f(); + + self.switch_back().with_context(|| { + format!( + "Failed to switch back to {}", + self.previous_branch().unwrap() + ) + })?; + + Ok(rslt) + } + fn switch_to(&mut self, id: &str) -> AnyResult<()> { if self.needs_stash() { self.stash_push().context("Failed to stash changes")?; diff --git a/src/lib.rs b/src/lib.rs index fb2e4ad..e579ec5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,16 +19,13 @@ pub fn run() -> AnyResult<()> { let mut repo = CrateRepo::current().context("Failed to fetch repository data")?; - let current_api = glue::extract_api().context("Failed to get crate API")?; let version = manifest::get_crate_version().context("Failed to get crate version")?; - repo.switch_to(config.comparaison_ref.as_str()) - .with_context(|| format!("Failed to checkout to `{}`", config.comparaison_ref))?; - - let previous_api = glue::extract_api().context("Failed to get crate API")?; + let current_api = glue::extract_api().context("Failed to get crate API")?; - repo.switch_back() - .context("Failed to go back to initial branch")?; + let previous_api = repo.run_in(config.comparaison_ref.as_str(), || { + glue::extract_api().context("Failed to get crate API") + })??; let api_comparator = ApiComparator::new(previous_api, current_api);