uv_git/
credentials.rs

1use std::collections::HashMap;
2use std::sync::{Arc, LazyLock, RwLock};
3use tracing::trace;
4use uv_auth::Credentials;
5use uv_cache_key::RepositoryUrl;
6use uv_redacted::DisplaySafeUrl;
7
8/// Global authentication cache for a uv invocation.
9///
10/// This is used to share Git credentials within a single process.
11pub static GIT_STORE: LazyLock<GitStore> = LazyLock::new(GitStore::default);
12
13/// A store for Git credentials.
14#[derive(Debug, Default)]
15pub struct GitStore(RwLock<HashMap<RepositoryUrl, Arc<Credentials>>>);
16
17impl GitStore {
18    /// Insert [`Credentials`] for the given URL into the store.
19    pub fn insert(&self, url: RepositoryUrl, credentials: Credentials) -> Option<Arc<Credentials>> {
20        self.0.write().unwrap().insert(url, Arc::new(credentials))
21    }
22
23    /// Get the [`Credentials`] for the given URL, if they exist.
24    pub fn get(&self, url: &RepositoryUrl) -> Option<Arc<Credentials>> {
25        self.0.read().unwrap().get(url).cloned()
26    }
27}
28
29/// Populate the global authentication store with credentials on a Git URL, if there are any.
30///
31/// Returns `true` if the store was updated.
32pub fn store_credentials_from_url(url: &DisplaySafeUrl) -> bool {
33    if let Some(credentials) = Credentials::from_url(url) {
34        trace!("Caching credentials for {url}");
35        GIT_STORE.insert(RepositoryUrl::new(url), credentials);
36        true
37    } else {
38        false
39    }
40}