1use git2::{Direction, Remote, RemoteCallbacks, Repository};
2use log::debug;
3
4use crate::error::{DefaultBranchError, Result};
5use crate::get_remote_callbacks;
6
7pub struct DefaultBranch<'repo, 'cb> {
9 repo: &'repo Repository,
10 remote: Option<Remote<'repo>>,
11 callbacks: Option<RemoteCallbacks<'cb>>,
12}
13
14impl<'repo, 'cb> DefaultBranch<'repo, 'cb> {
15 pub fn new(repo: &'repo Repository) -> Self {
17 Self {
18 repo,
19 remote: None,
20 callbacks: None,
21 }
22 }
23
24 pub fn remote(&mut self, remote: Remote<'repo>) -> &mut Self {
26 self.remote = Some(remote);
27 self
28 }
29
30 pub fn remote_callbacks(&mut self, cbs: RemoteCallbacks<'cb>) -> &mut Self {
32 self.callbacks = Some(cbs);
33 self
34 }
35
36 pub fn get_name(self) -> Result<String> {
41 match self.remote {
42 Some(mut remote) => {
43 let mut cxn = remote.connect_auth(Direction::Fetch, self.callbacks, None)?;
44
45 if !cxn.connected() {
46 return Err(DefaultBranchError::NotConnected.into());
47 }
48
49 match cxn.default_branch()?.as_str() {
50 Some(default_branch) => Ok(default_branch
51 .strip_prefix("refs/heads/")
52 .unwrap_or(default_branch)
53 .to_string()),
54 None => Err(DefaultBranchError::NoRemoteDefault {
55 remote: cxn.remote().name().map(|s| s.to_string()),
56 }
57 .into()),
58 }
59 }
60 None => {
61 let config = self.repo.config()?;
62 let defaultbranch = config.get_str("init.defaultbranch").unwrap_or("main");
63 Ok(defaultbranch.to_string())
64 }
65 }
66 }
67}
68
69pub fn get_default_branch_name(repo: &Repository, remote: Option<Remote>) -> Result<String> {
74 let mut default_branch = DefaultBranch::new(repo);
75 if let Some(remote) = remote {
76 let url = remote.url().map(str::to_string);
77 default_branch.remote(remote);
78 default_branch.remote_callbacks(get_remote_callbacks(url.as_deref()).unwrap());
79 }
80 default_branch.get_name().or_else(|_| {
81 debug!("Failed to read default branch from remote, trying git config");
82 let branch = repo
83 .config()
84 .ok()
85 .and_then(|config| config.get_string("init.defaultbranch").ok())
86 .unwrap_or_else(|| {
87 debug!("No init.defaultbranch config, falling back to 'main'");
88 "main".to_string()
89 });
90 Ok(branch)
91 })
92}
93
94pub fn get_default_branch(repo: &Repository) -> Result<String> {
102 if let Ok(config) = repo.config() {
104 if let Ok(default_branch) = config.get_string("init.defaultBranch") {
105 if repo
107 .find_branch(&default_branch, git2::BranchType::Local)
108 .is_ok()
109 {
110 return Ok(default_branch);
111 }
112 }
113 }
114
115 if repo.find_branch("main", git2::BranchType::Local).is_ok() {
117 return Ok("main".to_string());
118 }
119
120 if repo.find_branch("master", git2::BranchType::Local).is_ok() {
122 return Ok("master".to_string());
123 }
124
125 Err(DefaultBranchError::NoDefaultBranch.into())
126}