Skip to main content

uv_git/
source.rs

1//! Git support is derived from Cargo's implementation.
2//! Cargo is dual-licensed under either Apache 2.0 or MIT, at the user's choice.
3//! Source: <https://github.com/rust-lang/cargo/blob/23eb492cf920ce051abfc56bbaf838514dc8365c/src/cargo/sources/git/source.rs>
4
5use std::borrow::Cow;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use anyhow::Result;
10use tracing::{debug, instrument};
11
12use uv_cache_key::cache_digest;
13use uv_git_types::{GitOid, GitUrl};
14use uv_redacted::SafeUrl;
15
16use crate::credentials::GIT_STORE;
17use crate::git::{GitDatabase, GitRemote};
18
19/// A remote Git source that can be checked out locally.
20pub(crate) struct GitSource {
21    /// The Git reference from the manifest file.
22    git: GitUrl,
23    /// Whether to disable SSL verification.
24    disable_ssl: bool,
25    /// Whether to operate without network connectivity.
26    offline: bool,
27    /// The path to the Git source database.
28    cache: PathBuf,
29    /// The reporter to use for this source.
30    reporter: Option<Arc<dyn Reporter>>,
31}
32
33impl GitSource {
34    /// Initialize a [`GitSource`] with the given Git URL, HTTP client, and cache path.
35    pub(crate) fn new(git: GitUrl, cache: impl Into<PathBuf>, offline: bool) -> Self {
36        Self {
37            git,
38            disable_ssl: false,
39            offline,
40            cache: cache.into(),
41            reporter: None,
42        }
43    }
44
45    /// Disable SSL verification for this [`GitSource`].
46    #[must_use]
47    pub(crate) fn dangerous(self) -> Self {
48        Self {
49            disable_ssl: true,
50            ..self
51        }
52    }
53
54    /// Set the [`Reporter`] to use for the [`GitSource`].
55    #[must_use]
56    pub(crate) fn with_reporter(self, reporter: Arc<dyn Reporter>) -> Self {
57        Self {
58            reporter: Some(reporter),
59            ..self
60        }
61    }
62
63    /// Fetch the underlying Git repository at the given revision.
64    #[instrument(skip(self), fields(repository = %self.git.url(), rev = ?self.git.precise()))]
65    pub(crate) fn fetch(self) -> Result<Fetch> {
66        let lfs_requested = self.git.lfs().enabled();
67
68        // The path to the repo, within the Git database.
69        let ident = cache_digest(self.git.repository());
70        let db_path = self.cache.join("db").join(&ident);
71
72        // Authenticate the URL, if necessary.
73        let remote = if let Some(credentials) = GIT_STORE.get(self.git.repository()) {
74            Cow::Owned(credentials.apply(self.git.url().clone()))
75        } else {
76            Cow::Borrowed(self.git.url())
77        };
78
79        // Fetch the commit, if we don't already have it. Wrapping this section in a closure makes
80        // it easier to short-circuit this in the cases where we do have the commit.
81        let (db, actual_rev, maybe_task) = || -> Result<(GitDatabase, GitOid, Option<usize>)> {
82            let git_remote = GitRemote::new(remote.clone().into_owned());
83            let maybe_db = git_remote.db_at(&db_path).ok();
84
85            // If we have a locked revision, and we have a pre-existing database which has that
86            // revision, then no update needs to happen.
87            // When requested, we also check if LFS artifacts have been fetched and validated.
88            if let (Some(rev), Some(db)) = (self.git.precise(), &maybe_db) {
89                if db.contains(rev) && (!lfs_requested || db.contains_lfs_artifacts(rev)) {
90                    debug!("Using existing Git source `{}`", self.git.url());
91                    return Ok((
92                        maybe_db
93                            .unwrap()
94                            .with_lfs_ready(lfs_requested.then_some(true)),
95                        rev,
96                        None,
97                    ));
98                }
99            }
100
101            // ... otherwise, we use this state to update the Git database. Note that we still check
102            // for being offline here, for example in the situation that we have a locked revision
103            // but the database doesn't have it.
104            debug!("Updating Git source `{}`", self.git.url());
105
106            // Report the checkout operation to the reporter.
107            let task = self.reporter.as_ref().map(|reporter| {
108                reporter.on_checkout_start(git_remote.url(), self.git.reference().as_rev())
109            });
110
111            let (db, actual_rev) = git_remote.checkout(
112                &db_path,
113                maybe_db,
114                self.git.reference(),
115                self.git.precise(),
116                self.disable_ssl,
117                self.offline,
118                lfs_requested,
119            )?;
120
121            Ok((db, actual_rev, task))
122        }()?;
123
124        // Validate the resolved commit before checking out its contents.
125        let git = self.git.clone().with_precise(actual_rev)?;
126
127        // Don’t use the full hash, in order to contribute less to reaching the
128        // path length limit on Windows.
129        let short_id = db.to_short_id(actual_rev)?;
130
131        // Compute the canonical URL for the repository checkout.
132        let canonical = git.repository().clone().with_lfs(Some(lfs_requested));
133        // Recompute the checkout hash when Git LFS is enabled as we want
134        // to distinctly differentiate between LFS vs non-LFS source trees.
135        let ident = if lfs_requested {
136            cache_digest(&canonical)
137        } else {
138            ident
139        };
140        let checkout_path = self
141            .cache
142            .join("checkouts")
143            .join(&ident)
144            .join(short_id.as_str());
145
146        // Check out `actual_rev` from the database to a scoped location on the
147        // filesystem. This will use hard links and such to ideally make the
148        // checkout operation here pretty fast.
149        let checkout = db.copy_to(actual_rev, &checkout_path)?;
150
151        // Report the checkout operation to the reporter.
152        if let Some(task) = maybe_task {
153            if let Some(reporter) = self.reporter.as_ref() {
154                reporter.on_checkout_complete(remote.as_ref(), actual_rev.as_str(), task);
155            }
156        }
157
158        Ok(Fetch {
159            git,
160            path: checkout_path,
161            lfs_ready: checkout.lfs_ready().unwrap_or(false),
162        })
163    }
164}
165
166pub struct Fetch {
167    /// The [`GitUrl`] reference that was fetched.
168    git: GitUrl,
169    /// The path to the checked out repository.
170    path: PathBuf,
171    /// Git LFS artifacts have been initialized (if requested).
172    lfs_ready: bool,
173}
174
175impl Fetch {
176    pub fn git(&self) -> &GitUrl {
177        &self.git
178    }
179
180    pub fn path(&self) -> &Path {
181        &self.path
182    }
183
184    pub fn lfs_ready(&self) -> &bool {
185        &self.lfs_ready
186    }
187}
188
189pub trait Reporter: Send + Sync {
190    /// Callback to invoke when a repository checkout begins.
191    fn on_checkout_start(&self, url: &SafeUrl, rev: &str) -> usize;
192
193    /// Callback to invoke when a repository checkout completes.
194    fn on_checkout_complete(&self, url: &SafeUrl, rev: &str, index: usize);
195}