use xshell::Shell;
use crate::environment::quiet_println;
use crate::quiet_cmd;
pub struct GitSwitchGuard<'a> {
sh: &'a Shell,
}
impl<'a> GitSwitchGuard<'a> {
pub fn new(sh: &'a Shell, git_ref: &str) -> Result<Self, Box<dyn std::error::Error>> {
quiet_println(&format!("Switching to ref: {}", git_ref));
quiet_cmd!(sh, "git switch --detach {git_ref}").run()?;
Ok(Self { sh })
}
}
impl Drop for GitSwitchGuard<'_> {
fn drop(&mut self) {
quiet_println("Returning to previous ref...");
quiet_cmd!(self.sh, "git switch --detach -")
.run()
.expect("Failed to switch back to previous git ref");
}
}
pub fn list_commits(sh: &Shell, base: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let range_base = quiet_cmd!(sh, "git merge-base HEAD {base}").read()?;
let range_base = range_base.trim();
let output = quiet_cmd!(sh, "git log --reverse --format=%H {range_base}..HEAD").read()?;
let commits = output.lines().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect();
Ok(commits)
}