Skip to main content

uv_git/
resolver.rs

1use std::borrow::Cow;
2use std::path::PathBuf;
3use std::str::FromStr;
4use std::sync::Arc;
5
6use fs_err::tokio as fs;
7use papaya::{HashMap, ResizeMode};
8use reqwest_middleware::ClientWithMiddleware;
9use tracing::debug;
10
11use uv_cache_key::{GitUpstreamUrl, cache_digest};
12use uv_fs::{LockedFile, LockedFileError, LockedFileMode};
13use uv_git_types::{GitHubRepository, GitOid, GitReference, GitUrl};
14use uv_static::EnvVars;
15use uv_version::version;
16
17use crate::{
18    Fetch, GitSource, Reporter,
19    rate_limit::{GITHUB_RATE_LIMIT_STATUS, is_github_rate_limited},
20};
21
22#[derive(Debug, thiserror::Error)]
23pub enum GitResolverError {
24    #[error(transparent)]
25    Io(#[from] std::io::Error),
26    #[error(transparent)]
27    LockedFile(#[from] LockedFileError),
28    #[error(transparent)]
29    Join(#[from] tokio::task::JoinError),
30    #[error("Git operation failed")]
31    Git(#[source] anyhow::Error),
32    #[error(transparent)]
33    Reqwest(#[from] reqwest::Error),
34    #[error(transparent)]
35    ReqwestMiddleware(#[from] reqwest_middleware::Error),
36}
37
38impl GitResolverError {
39    /// Return whether this is an expected user-facing failure.
40    pub fn is_user_failure(&self) -> bool {
41        match self {
42            Self::Git(error) => {
43                for cause in error.chain() {
44                    if let Some(error) = cause.downcast_ref::<reqwest::Error>() {
45                        return error.status() == Some(reqwest::StatusCode::NOT_FOUND);
46                    }
47                    if cause.is::<std::io::Error>() {
48                        return false;
49                    }
50                }
51                true
52            }
53            Self::Reqwest(error) => error.status() == Some(reqwest::StatusCode::NOT_FOUND),
54            Self::ReqwestMiddleware(error) => {
55                error.status() == Some(reqwest::StatusCode::NOT_FOUND)
56            }
57            Self::Io(_) | Self::LockedFile(_) | Self::Join(_) => false,
58        }
59    }
60}
61
62/// HTTP settings for fetching a Git repository.
63#[derive(Debug, Clone, Copy, Default)]
64pub struct GitHttpSettings {
65    disable_ssl: bool,
66    offline: bool,
67}
68
69impl GitHttpSettings {
70    /// Configure whether certificate verification should be disabled.
71    #[must_use]
72    pub fn with_disabled_ssl(mut self, disable_ssl: bool) -> Self {
73        self.disable_ssl = disable_ssl;
74        self
75    }
76
77    /// Configure whether network access should be disabled.
78    #[must_use]
79    pub fn with_offline(mut self, offline: bool) -> Self {
80        self.offline = offline;
81        self
82    }
83}
84
85/// A resolver for Git repositories.
86#[derive(Clone)]
87pub struct GitResolver(Arc<HashMap<RepositoryReference, GitOid>>);
88
89impl Default for GitResolver {
90    fn default() -> Self {
91        Self(Arc::new(
92            HashMap::builder().resize_mode(ResizeMode::Blocking).build(),
93        ))
94    }
95}
96
97impl GitResolver {
98    /// Inserts a new [`GitOid`] for the given [`RepositoryReference`].
99    pub fn insert(&self, reference: RepositoryReference, sha: GitOid) {
100        self.0.pin().insert(reference, sha);
101    }
102
103    /// Returns the [`GitOid`] for the given [`RepositoryReference`], if it exists.
104    fn get(&self, reference: &RepositoryReference) -> Option<GitOid> {
105        self.0.pin().get(reference).copied()
106    }
107
108    /// Return the [`GitOid`] for the given [`GitUrl`], if it is already known.
109    pub fn get_precise(&self, url: &GitUrl) -> Option<GitOid> {
110        // If the URL is already precise, return it.
111        if let Some(precise) = url.precise() {
112            return Some(precise);
113        }
114
115        // If we know the precise commit already, return it.
116        let reference = RepositoryReference::from(url);
117        if let Some(precise) = self.get(&reference) {
118            return Some(precise);
119        }
120
121        None
122    }
123
124    /// Resolve a Git URL to a specific commit without performing any Git operations.
125    ///
126    /// Returns a [`GitOid`] if the URL has already been resolved (i.e., is available in the cache),
127    /// or if it can be fetched via the GitHub API. Otherwise, returns `None`.
128    pub async fn github_fast_path(
129        &self,
130        url: &GitUrl,
131        client: &ClientWithMiddleware,
132    ) -> Result<Option<GitOid>, GitResolverError> {
133        if std::env::var_os(EnvVars::UV_NO_GITHUB_FAST_PATH).is_some() {
134            return Ok(None);
135        }
136
137        // If the URL is already precise or we know the precise commit, return it.
138        if let Some(precise) = self.get_precise(url) {
139            return Ok(Some(precise));
140        }
141
142        // If the URL is a GitHub URL, attempt to resolve it via the GitHub API.
143        let Some(GitHubRepository { owner, repo }) =
144            GitHubRepository::parse(url.repository().as_url())
145        else {
146            return Ok(None);
147        };
148
149        // Check if we're rate-limited by GitHub, before determining the Git reference
150        if GITHUB_RATE_LIMIT_STATUS.is_active() {
151            debug!("Rate-limited by GitHub. Skipping GitHub fast path attempt for: {url}");
152            return Ok(None);
153        }
154
155        // Determine the Git reference.
156        let reference = url
157            .reference()
158            .as_url_rev()
159            .unwrap_or_else(|| "HEAD".into());
160
161        let github_api_base_url = std::env::var(EnvVars::UV_GITHUB_FAST_PATH_URL)
162            .unwrap_or("https://api.github.com/repos".to_owned());
163        let github_api_url = format!("{github_api_base_url}/{owner}/{repo}/commits/{reference}");
164
165        debug!("Querying GitHub for commit at: {github_api_url}");
166        let mut request = client.get(&github_api_url);
167        request = request.header("Accept", "application/vnd.github.3.sha");
168        request = request.header(
169            "User-Agent",
170            format!("uv/{} (+https://github.com/astral-sh/uv)", version()),
171        );
172
173        let response = request.send().await?;
174        let status = response.status();
175        if !status.is_success() {
176            // Returns a 404 if the repository does not exist, and a 422 if GitHub is unable to
177            // resolve the requested rev.
178            debug!(
179                "GitHub API request failed for: {github_api_url} ({})",
180                response.status()
181            );
182
183            if is_github_rate_limited(&response) {
184                // Mark that we are being rate-limited by GitHub
185                GITHUB_RATE_LIMIT_STATUS.activate();
186            }
187
188            return Ok(None);
189        }
190
191        // Parse the response as a Git SHA.
192        let precise = response.text().await?;
193        let precise =
194            GitOid::from_str(&precise).map_err(|err| GitResolverError::Git(err.into()))?;
195        let url = url
196            .clone()
197            .with_precise(precise)
198            .map_err(|error| GitResolverError::Git(error.into()))?;
199
200        // Insert the resolved URL into the in-memory cache. This ensures that subsequent fetches
201        // resolve to the same precise commit.
202        self.insert(RepositoryReference::from(&url), precise);
203
204        Ok(Some(precise))
205    }
206
207    /// Fetch a remote Git repository.
208    pub async fn fetch(
209        &self,
210        url: &GitUrl,
211        http_settings: GitHttpSettings,
212        cache: PathBuf,
213        reporter: Option<Arc<dyn Reporter>>,
214    ) -> Result<Fetch, GitResolverError> {
215        debug!("Fetching source distribution from Git: {url}");
216
217        let reference = RepositoryReference::from(url);
218
219        // If we know the precise commit already, reuse it, to ensure that all fetches within a
220        // single process are consistent.
221        let url = {
222            if let Some(precise) = self.get(&reference) {
223                Cow::Owned(
224                    url.clone()
225                        .with_precise(precise)
226                        .map_err(|error| GitResolverError::Git(error.into()))?,
227                )
228            } else {
229                Cow::Borrowed(url)
230            }
231        };
232
233        // Avoid races between different processes, too.
234        let lock_dir = cache.join("locks");
235        fs::create_dir_all(&lock_dir).await?;
236        let repository_url = url.repository().clone();
237        let _lock = LockedFile::acquire(
238            lock_dir.join(cache_digest(&repository_url)),
239            LockedFileMode::Exclusive,
240            &repository_url,
241        )
242        .await?;
243
244        // Fetch the Git repository.
245        let source = if let Some(reporter) = reporter {
246            GitSource::new(url.as_ref().clone(), cache, http_settings.offline)
247                .with_reporter(reporter)
248        } else {
249            GitSource::new(url.as_ref().clone(), cache, http_settings.offline)
250        };
251
252        // If necessary, disable SSL.
253        let source = if http_settings.disable_ssl {
254            source.dangerous()
255        } else {
256            source
257        };
258
259        let fetch = tokio::task::spawn_blocking(move || source.fetch())
260            .await?
261            .map_err(GitResolverError::Git)?;
262
263        // Insert the resolved URL into the in-memory cache. This ensures that subsequent fetches
264        // resolve to the same precise commit.
265        if let Some(precise) = fetch.git().precise() {
266            self.insert(reference, precise);
267        }
268
269        Ok(fetch)
270    }
271
272    /// Given a remote source distribution, return a precise variant, if possible.
273    ///
274    /// For example, given a Git dependency with a reference to a branch or tag, return a URL
275    /// with a precise reference to the current commit of that branch or tag.
276    ///
277    /// This method takes into account various normalizations that are independent of the Git
278    /// layer. For example: removing `#subdirectory=pkg_dir`-like fragments, and removing `git+`
279    /// prefix kinds.
280    ///
281    /// Returns a URL if its commit is already known or has been resolved by this resolver.
282    /// Returns `None` for unresolved named or ambiguous references.
283    pub fn precise(&self, url: GitUrl) -> Option<GitUrl> {
284        let precise = self.get_precise(&url)?;
285        url.with_precise(precise).ok()
286    }
287
288    /// Returns `true` if the two Git URLs refer to the same precise commit.
289    pub fn same_ref(&self, a: &GitUrl, b: &GitUrl) -> bool {
290        // Convert `a` to a repository URL.
291        let a_ref = RepositoryReference::from(a);
292
293        // Convert `b` to a repository URL.
294        let b_ref = RepositoryReference::from(b);
295
296        // The URLs must refer to the same repository.
297        if a_ref.url != b_ref.url {
298            return false;
299        }
300
301        // If the URLs have the same tag, they refer to the same commit.
302        if a_ref.reference == b_ref.reference {
303            return true;
304        }
305
306        // Otherwise, the URLs must resolve to the same precise commit.
307        let Some(a_precise) = a.precise().or_else(|| self.get(&a_ref)) else {
308            return false;
309        };
310
311        let Some(b_precise) = b.precise().or_else(|| self.get(&b_ref)) else {
312            return false;
313        };
314
315        a_precise == b_precise
316    }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq, Hash)]
320pub struct ResolvedRepositoryReference {
321    /// An abstract reference to a Git repository, including the URL and the commit (e.g., a branch,
322    /// tag, or revision).
323    pub reference: RepositoryReference,
324    /// The precise commit SHA of the reference.
325    pub sha: GitOid,
326}
327
328#[derive(Debug, Clone, PartialEq, Eq, Hash)]
329pub struct RepositoryReference {
330    /// The normalized Git repository URL used as the repository's identity.
331    pub url: GitUpstreamUrl,
332    /// The reference to the commit to use, which could be a branch, tag, or revision.
333    pub reference: GitReference,
334}
335
336impl From<&GitUrl> for RepositoryReference {
337    fn from(git: &GitUrl) -> Self {
338        Self {
339            url: git.repository().clone(),
340            reference: git.reference().clone(),
341        }
342    }
343}