Skip to main content

workon/
default_branch.rs

1use git2::{Direction, Remote, RemoteCallbacks, Repository};
2use log::debug;
3
4use crate::error::{DefaultBranchError, Result};
5use crate::get_remote_callbacks;
6
7/// Builder for resolving the default branch name of a repository or remote.
8pub 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    /// Create a new builder for the given repository.
16    pub fn new(repo: &'repo Repository) -> Self {
17        Self {
18            repo,
19            remote: None,
20            callbacks: None,
21        }
22    }
23
24    /// Set the remote to query for its default branch.
25    pub fn remote(&mut self, remote: Remote<'repo>) -> &mut Self {
26        self.remote = Some(remote);
27        self
28    }
29
30    /// Set credential callbacks for the remote connection.
31    pub fn remote_callbacks(&mut self, cbs: RemoteCallbacks<'cb>) -> &mut Self {
32        self.callbacks = Some(cbs);
33        self
34    }
35
36    /// Resolve the default branch name.
37    ///
38    /// If a remote was set, queries the remote for its HEAD ref.
39    /// Otherwise reads `init.defaultbranch` from git config (defaulting to `"main"`).
40    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
69/// Convenience wrapper around [`DefaultBranch`].
70///
71/// Queries the remote for its default branch if one is provided, otherwise
72/// falls back to `init.defaultbranch` config (defaulting to `"main"`).
73pub 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
94/// Get the default branch name for a repository, validated to exist.
95///
96/// This function:
97/// 1. Checks the `init.defaultBranch` config
98/// 2. Falls back to "main" if it exists
99/// 3. Falls back to "master" if it exists
100/// 4. Returns an error if none exist
101pub fn get_default_branch(repo: &Repository) -> Result<String> {
102    // Check init.defaultBranch config
103    if let Ok(config) = repo.config() {
104        if let Ok(default_branch) = config.get_string("init.defaultBranch") {
105            // Verify the configured branch exists
106            if repo
107                .find_branch(&default_branch, git2::BranchType::Local)
108                .is_ok()
109            {
110                return Ok(default_branch);
111            }
112        }
113    }
114
115    // Fall back to "main" if it exists
116    if repo.find_branch("main", git2::BranchType::Local).is_ok() {
117        return Ok("main".to_string());
118    }
119
120    // Fall back to "master" if it exists
121    if repo.find_branch("master", git2::BranchType::Local).is_ok() {
122        return Ok("master".to_string());
123    }
124
125    Err(DefaultBranchError::NoDefaultBranch.into())
126}