use git2::{build::CheckoutBuilder, Error, Repository};
use macro_log::*;
pub fn repo_switch(
repo: &Repository,
remote_name: &str,
branch_name: &str,
force_checkout: bool,
) -> Result<(), Error> {
repo.set_head(&format!("refs/remotes/{remote_name}/{branch_name}"))?;
let mut opts = CheckoutBuilder::new();
if force_checkout {
opts.force();
}
repo.checkout_head(Some(&mut opts))?;
Ok(())
}
pub fn repo_checkout(
repo: &Repository,
remote_name: &str,
branch_name: &str,
force_checkout: bool,
) -> Result<(), Error> {
let obj = repo.revparse_single(&format!("refs/remotes/{remote_name}/{branch_name}"))?;
let Some(commit) = obj.as_commit() else {
return Err(Error::from_str("Failed revparse_single commit"));
};
repo.set_head(&format!("refs/remotes/{remote_name}/{branch_name}"))?;
if let Ok(mut branch) = repo.find_branch(branch_name, git2::BranchType::Local) {
w!("分支 {branch_name} 已存在,更新");
branch.delete()?;
}
let _branch = repo.branch(branch_name, commit, false)?;
repo.set_head(&format!("refs/heads/{branch_name}"))?;
let mut opts = CheckoutBuilder::new();
if force_checkout {
opts.force();
}
repo.checkout_head(Some(&mut opts))?;
Ok(())
}