#![deny(unsafe_code)]
use std::path::Path;
use super::git2_to_io_error;
pub fn is_main_or_master_branch() -> std::io::Result<bool> {
let repo = git2::Repository::discover(".").map_err(|e| git2_to_io_error(&e))?;
is_main_or_master_branch_impl(&repo)
}
fn is_main_or_master_branch_impl(repo: &git2::Repository) -> std::io::Result<bool> {
let head = repo.head().map_err(|e| git2_to_io_error(&e))?;
let reference_name = head.shorthand().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
"Could not determine branch name from HEAD",
)
})?;
Ok(reference_name == "main" || reference_name == "master")
}
pub fn get_default_branch() -> std::io::Result<String> {
let repo = git2::Repository::discover(".").map_err(|e| git2_to_io_error(&e))?;
Ok(get_default_branch_impl(&repo))
}
pub fn get_default_branch_at(repo_root: &Path) -> std::io::Result<String> {
let repo = git2::Repository::open(repo_root).map_err(|e| git2_to_io_error(&e))?;
Ok(get_default_branch_impl(&repo))
}
fn determine_default_branch(repo: &git2::Repository) -> String {
resolve_default_branch_from_origin(repo)
.or_else(|| resolve_default_branch_from_local(repo))
.unwrap_or_else(|| "main".to_string())
}
fn resolve_default_branch_from_origin(repo: &git2::Repository) -> Option<String> {
let origin_head = repo.find_reference("refs/remotes/origin/HEAD").ok()?;
let target = origin_head.symbolic_target()?;
target
.strip_prefix("refs/remotes/origin/")
.map(String::from)
}
fn resolve_default_branch_from_local(repo: &git2::Repository) -> Option<String> {
if repo.find_branch("main", git2::BranchType::Local).is_ok() {
return Some("main".to_string());
}
if repo.find_branch("master", git2::BranchType::Local).is_ok() {
return Some("master".to_string());
}
None
}
fn get_default_branch_impl(repo: &git2::Repository) -> String {
determine_default_branch(repo)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_main_or_master_branch_returns_result() {
let result = is_main_or_master_branch();
let _ = result;
}
#[test]
fn test_get_default_branch_returns_result() {
let result = get_default_branch();
let _ = result;
}
}