Skip to main content

lux_lib/git/
utils.rs

1use crate::{config::Config, fs, git};
2use git2::{AutotagOption, Cred, FetchOptions, RemoteCallbacks, Repository};
3use itertools::Itertools;
4
5pub(crate) enum SemVerTagOrSha {
6    SemVerTag(String),
7    CommitSha(String),
8}
9
10#[tracing::instrument(level = "trace")]
11pub(crate) fn latest_semver_tag_or_commit_sha(
12    url: &git::remote::Url,
13    config: &Config,
14) -> Result<SemVerTagOrSha, super::Error> {
15    match latest_semver_tag(url, config)? {
16        Some(tag) => Ok(SemVerTagOrSha::SemVerTag(tag)),
17        None => {
18            let sha = latest_commit_sha(url, config)?
19                .ok_or(super::Error::NoTagOrCommitSha(url.to_string()))?;
20            Ok(SemVerTagOrSha::CommitSha(sha))
21        }
22    }
23}
24
25#[tracing::instrument(level = "trace")]
26fn latest_semver_tag(
27    url: &git::remote::Url,
28    config: &Config,
29) -> Result<Option<String>, super::Error> {
30    let temp_dir = fs::tempfile::tempdir()?;
31
32    let url_str = url.to_string();
33    let repo = Repository::init_bare(&temp_dir).map_err(super::Error::BareRepoInit)?;
34    let mut remote = repo
35        .remote_anonymous(&url_str)
36        .map_err(|err| super::Error::RemoteInit(url_str.clone(), err))?;
37    let mut callbacks = RemoteCallbacks::new();
38    callbacks.credentials(mk_credentials_callback(url, config));
39    let mut fetch_opts = FetchOptions::new();
40    fetch_opts.download_tags(AutotagOption::All);
41    fetch_opts.remote_callbacks(callbacks);
42    remote
43        .fetch(&[] as &[&str], Some(&mut fetch_opts), None)
44        .map_err(|err| super::Error::RemoteFetch(url_str.clone(), err))?;
45    let refs = remote
46        .list()
47        .map_err(|err| super::Error::RemoteList(url_str.clone(), err))?;
48    Ok(refs
49        .iter()
50        .filter_map(|head| {
51            let tag_name = head.name().strip_prefix("refs/tags/")?;
52            let version_str = tag_name.strip_prefix('v').unwrap_or(tag_name);
53            if let Ok(version) = semver::Version::parse(version_str) {
54                Some((tag_name.to_string(), version))
55            } else {
56                None
57            }
58        })
59        .sorted_by(|(_, a), (_, b)| b.cmp(a))
60        .map(|(version_str, _)| version_str)
61        .collect_vec()
62        .first()
63        .cloned())
64}
65
66fn mk_credentials_callback(
67    url: &git::remote::Url,
68    config: &Config,
69) -> impl FnMut(&str, Option<&str>, git2::CredentialType) -> Result<Cred, git2::Error> {
70    let access_token = config.access_token(url.host()).map(|token| {
71        (
72            token.username().to_string(),
73            unsafe { token.password() }.to_string(),
74        )
75    });
76    move |_url, username_from_url, _allowed_types| {
77        if let Some((username, password)) = &access_token {
78            Cred::userpass_plaintext(username, password)
79        } else {
80            Cred::ssh_key_from_agent(username_from_url.unwrap_or("git"))
81        }
82    }
83}
84
85fn latest_commit_sha(
86    url: &git::remote::Url,
87    config: &Config,
88) -> Result<Option<String>, super::Error> {
89    let temp_dir = fs::tempfile::tempdir()?;
90    let url_str = url.to_string();
91    let repo = Repository::init_bare(&temp_dir).map_err(super::Error::BareRepoInit)?;
92    let mut remote = repo
93        .remote_anonymous(&url_str)
94        .map_err(|err| super::Error::RemoteInit(url_str.clone(), err))?;
95    let mut callbacks = RemoteCallbacks::new();
96    callbacks.credentials(mk_credentials_callback(url, config));
97    let mut fetch_opts = FetchOptions::new();
98    fetch_opts.remote_callbacks(callbacks);
99    remote
100        .fetch(&[] as &[&str], Some(&mut fetch_opts), None)
101        .map_err(|err| super::Error::RemoteFetch(url_str.clone(), err))?;
102    let refs = remote
103        .list()
104        .map_err(|err| super::Error::RemoteList(url_str.clone(), err))?;
105    Ok(refs.iter().find_map(|head| match head.name() {
106        "refs/heads/HEAD" => Some(head.oid().to_string()),
107        "refs/heads/main" => Some(head.oid().to_string()),
108        "refs/heads/master" => Some(head.oid().to_string()),
109        _ => None,
110    }))
111}
112
113#[cfg(all(test, any(feature = "impure_tests", feature = "ssh-tests")))]
114mod tests {
115
116    use super::*;
117    use crate::config;
118    #[cfg(feature = "impure_tests")]
119    use flaky_test::flaky_test;
120
121    fn test_config() -> Config {
122        config::Builder::new().unwrap().build().unwrap()
123    }
124
125    #[cfg(feature = "impure_tests")]
126    #[flaky_test(tokio, times = 5)]
127    async fn test_latest_semver_tag_http() {
128        let url = "https://github.com/lumen-oss/lux.git".parse().unwrap();
129        assert!(latest_semver_tag(&url, &test_config()).unwrap().is_some());
130    }
131
132    #[tokio::test]
133    #[cfg(feature = "ssh-tests")]
134    async fn test_latest_semver_tag_ssh_user() {
135        let url = "git@github.com:lumen-oss/lux.git".parse().unwrap();
136        assert!(latest_semver_tag(&url, &test_config()).unwrap().is_some());
137    }
138
139    #[tokio::test]
140    #[cfg(feature = "ssh-tests")]
141    async fn test_latest_semver_tag_ssh_schema() {
142        let url = "ssh://github.com/lumen-oss/lux.git".parse().unwrap();
143        assert!(latest_semver_tag(&url, &test_config()).unwrap().is_some());
144    }
145
146    #[cfg(feature = "impure_tests")]
147    #[flaky_test(tokio, times = 5)]
148    async fn test_latest_commit_sha_http() {
149        let url = "https://github.com/lumen-oss/lux.git".parse().unwrap();
150        assert!(latest_commit_sha(&url, &test_config()).unwrap().is_some());
151    }
152
153    #[tokio::test]
154    #[cfg(feature = "ssh-tests")]
155    async fn test_latest_commit_sha_ssh_user() {
156        let url = "git@github.com:lumen-oss/lux.git".parse().unwrap();
157        assert!(latest_commit_sha(&url, &test_config()).unwrap().is_some());
158    }
159
160    #[tokio::test]
161    #[cfg(feature = "ssh-tests")]
162    async fn test_latest_commit_sha_ssh_schema() {
163        let url = "ssh://github.com/lumen-oss/lux.git".parse().unwrap();
164        assert!(latest_commit_sha(&url, &test_config()).unwrap().is_some());
165    }
166}