use crate::cmd::cmd;
use color_eyre::Result;
use std::path::{Path, PathBuf};
pub struct Repository {
path: Option<PathBuf>,
dirty: bool,
}
impl Repository {
pub fn new(path: Option<PathBuf>) -> Self {
Repository { path, dirty: false }
}
pub fn add(&mut self, path: &Path) -> Result<()> {
let changed = !cmd!([git diff] ["-s" "--exit-code" "--" (path)] -> bool in &self.path)?;
if changed {
self.dirty = true;
cmd!([git add] [(path)] in &self.path)?;
}
Ok(())
}
pub fn current_commit(&self) -> Result<String> {
cmd!([git "rev-parse"] [HEAD] -> String in &self.path)
}
pub fn commit(&mut self, message: &str) -> Result<Option<String>> {
if !self.dirty {
return Ok(None);
}
cmd!([git commit] ["-m" (message)] in &self.path)?;
self.dirty = false;
Ok(Some(self.current_commit()?))
}
pub fn current_branch_or_commit(&self) -> Result<String> {
let branch = cmd!([git branch] ["--show-current"] -> String in &self.path)?;
if !branch.is_empty() {
Ok(branch)
} else {
Ok(self.current_commit()?)
}
}
pub fn checkout(&mut self, target: &str) -> Result<()> {
cmd!([git "checkout"] [(target)] in &self.path)
}
}