Skip to main content

lux_lib/operations/fetch/
mod.rs

1use crate::config::Config;
2use crate::fs;
3use crate::git;
4use crate::hash::HasIntegrity;
5use crate::lockfile::RemotePackageSourceUrl;
6use crate::package;
7use crate::project;
8use crate::reqwest::RequestBuilderExt;
9use crate::rockspec;
10use crate::rockspec::Rockspec;
11use crate::wally;
12use auth_git2::{GitAuthenticator, Prompter};
13use bon::Builder;
14use git2::build::RepoBuilder;
15use git2::{FetchOptions, RemoteCallbacks};
16use miette::Diagnostic;
17use remove_dir_all::remove_dir_all;
18use ssri::Integrity;
19use std::io;
20use std::io::Cursor;
21use std::io::Read;
22use std::path::{Path, PathBuf};
23use thiserror::Error;
24
25mod src_rock;
26
27use crate::operations::unpack;
28
29/// A rocks package source fetcher, providing fine-grained control
30/// over how a package should be fetched.
31#[derive(Builder)]
32#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
33pub(super) struct SrcRock<'a> {
34    #[builder(start_fn)]
35    package: &'a package::Spec,
36    #[builder(start_fn)]
37    dest_dir: &'a Path,
38    #[builder(start_fn)]
39    config: &'a Config,
40}
41
42impl<State> SrcRockBuilder<'_, State>
43where
44    State: src_rock_builder::State + src_rock_builder::IsComplete,
45{
46    pub async fn fetch(self) -> Result<RemotePackageSourceMetadata, src_rock::Error> {
47        src_rock::do_fetch_src_rock(self._build()).await
48    }
49}
50
51/// A rocks package source fetcher, providing fine-grained control
52/// over how a package should be fetched.
53#[derive(Builder)]
54#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
55pub struct FetchSrc<'a, R: Rockspec> {
56    #[builder(start_fn)]
57    dest_dir: &'a Path,
58    #[builder(start_fn)]
59    rockspec: &'a R,
60    #[builder(start_fn)]
61    config: &'a Config,
62    #[builder(setters(vis = "pub(crate)"))]
63    source_url: Option<RemotePackageSourceUrl>,
64}
65
66#[derive(Debug)]
67pub(crate) struct RemotePackageSourceMetadata {
68    pub hash: Integrity,
69    pub source_url: RemotePackageSourceUrl,
70}
71
72impl<R: Rockspec, State> FetchSrcBuilder<'_, R, State>
73where
74    State: fetch_src_builder::State + fetch_src_builder::IsComplete,
75{
76    /// Fetch and unpack the source into the `dest_dir`.
77    pub async fn fetch(self) -> Result<(), Error> {
78        self.fetch_internal().await?;
79        Ok(())
80    }
81
82    /// Fetch and unpack the source into the `dest_dir`,
83    /// returning the source `Integrity`.
84    pub(crate) async fn fetch_internal(self) -> Result<RemotePackageSourceMetadata, Error> {
85        let fetch = self._build();
86        let rockspec = fetch.rockspec;
87        let rock_source = rockspec.source().current_platform();
88        let dest_dir = fetch.dest_dir;
89        let config = fetch.config;
90        // prioritise lockfile source, if present
91        let source_spec = match &fetch.source_url {
92            Some(source_url) => match source_url {
93                RemotePackageSourceUrl::Git {
94                    url, checkout_ref, ..
95                } => rockspec::source::Spec::Git(git::Source {
96                    url: url.parse()?,
97                    git_ref: Some(git::Ref::Tag(checkout_ref.clone())),
98                }),
99                RemotePackageSourceUrl::Url { url } => rockspec::source::Spec::Url(url.clone()),
100                RemotePackageSourceUrl::File { path } => rockspec::source::Spec::File(path.clone()),
101            },
102            None => rock_source.source_spec.clone(),
103        };
104        match fetch_src_impl(source_spec, rockspec, rock_source, dest_dir, config).await {
105            Err(err)
106                if fetch
107                    .source_url
108                    .is_some_and(|url| matches!(url, RemotePackageSourceUrl::File { .. })) =>
109            {
110                // Don't fall back to downloading .src.rock archives if a local source was specified.
111                Err(err)
112            }
113            Err(err) => match &fetch.rockspec.source().current_platform().source_spec {
114                rockspec::source::Spec::Git(_) | rockspec::source::Spec::Url(_) => {
115                    let package = package::Spec::new(
116                        fetch.rockspec.package().clone(),
117                        fetch.rockspec.version().clone(),
118                    );
119                    match SrcRock::new(&package, fetch.dest_dir, fetch.config)
120                        .fetch()
121                        .await
122                    {
123                        Ok(metadata) => Ok(metadata),
124                        Err(fallback_err) => {
125                            tracing::error!("fallback .src.rock download failed: {fallback_err:?}");
126                            Err(err)
127                        }
128                    }
129                }
130                rockspec::source::Spec::File(_) | rockspec::source::Spec::Wally(_) => Err(err),
131            },
132            Ok(metadata) => Ok(metadata),
133        }
134    }
135}
136
137#[derive(Error, Debug, Diagnostic)]
138#[non_exhaustive]
139pub enum Error {
140    #[error("failed to clone rock source")]
141    #[diagnostic(help("check your network connection and verify the git URL is correct."))]
142    GitClone(#[from] git2::Error),
143    #[error("git operation failed")]
144    #[diagnostic(help("this is a bug, please report it."))]
145    GitJoin(#[from] tokio::task::JoinError),
146    #[error("failed to parse git URL")]
147    #[diagnostic(forward(0))]
148    GitUrlParse(#[from] git::url::Error),
149    #[error(transparent)]
150    #[diagnostic(transparent)]
151    Request(#[from] crate::reqwest::Error),
152    #[error(transparent)]
153    #[diagnostic(transparent)]
154    Unpack(#[from] unpack::Error),
155    #[error(transparent)]
156    #[diagnostic(transparent)]
157    SrcRock(#[from] src_rock::Error),
158    #[error("unable to remove the '.git' directory")]
159    #[diagnostic(help(
160        "check that no process is using the directory and you have write permissions."
161    ))]
162    CleanGitDir(#[source] io::Error),
163    #[error("failed to resolve wally package '{0}'")]
164    #[diagnostic(
165        code(lux_lib::wally::unresolved_source),
166        help("this is a bug, please report it.")
167    )]
168    WallySource(String),
169    #[error("unable to compute hash")]
170    Hash(#[source] io::Error),
171    #[error(transparent)]
172    #[diagnostic(transparent)]
173    Fs(#[from] fs::Error),
174}
175
176/// A no-prompt implementer for auth_git2's prompter
177#[derive(Copy, Clone, Debug)]
178struct NullPrompter;
179
180impl Prompter for NullPrompter {
181    fn prompt_username_password(&mut self, _: &str, _: &git2::Config) -> Option<(String, String)> {
182        None
183    }
184
185    fn prompt_password(&mut self, _: &str, _: &str, _: &git2::Config) -> Option<String> {
186        None
187    }
188
189    fn prompt_ssh_key_passphrase(&mut self, _: &Path, _: &git2::Config) -> Option<String> {
190        None
191    }
192}
193
194/// Initialises and checks out git submodules,
195/// returning the relative paths of any submodules that were checked out.
196fn init_submodules(
197    repo: &git2::Repository,
198    auth: &GitAuthenticator,
199    git_config: &git2::Config,
200) -> Result<Vec<PathBuf>, Error> {
201    let workdir = repo
202        .workdir()
203        .ok_or_else(|| git2::Error::from_str("cloned repository has no working directory"))?;
204    let mut submodule_paths = Vec::new();
205    for mut submodule in repo.submodules()? {
206        let mut callbacks = RemoteCallbacks::new();
207        callbacks.credentials(auth.credentials(git_config));
208        let mut fetch_options = FetchOptions::new();
209        fetch_options.remote_callbacks(callbacks);
210        let mut options = git2::SubmoduleUpdateOptions::new();
211        options.fetch(fetch_options);
212        submodule.update(true, Some(&mut options))?;
213        // The .git file/directory is not deterministic
214        let git_file = workdir.join(submodule.path()).join(".git");
215        if git_file.is_dir() {
216            fs::sync::remove_dir_all(&git_file)?;
217        } else {
218            fs::sync::remove_file(&git_file)?;
219        }
220        submodule_paths.push(submodule.path().to_path_buf());
221    }
222    Ok(submodule_paths)
223}
224
225#[tracing::instrument(
226    name = "Fetching source",
227    level = "info",
228    skip_all,
229    fields(location = source_spec.to_string()),
230)]
231async fn fetch_src_impl<R: Rockspec>(
232    mut source_spec: rockspec::source::Spec,
233    rockspec: &R,
234    rock_source: &rockspec::source::Remote,
235    dest_dir: &Path,
236    config: &Config,
237) -> Result<RemotePackageSourceMetadata, Error> {
238    if let Some(vendor_dir) = config.vendor_dir() {
239        source_spec = match source_spec {
240            // could be a project directory (not vendored) or a local source
241            // or a vendored dependency that we have already resolved
242            rockspec::source::Spec::File(_) => source_spec,
243            _ => {
244                let pkg_vendor_dir =
245                    vendor_dir.join(format!("{}@{}", rockspec.package(), rockspec.version()));
246                rockspec::source::Spec::File(pkg_vendor_dir)
247            }
248        }
249    }
250    let metadata = match &source_spec {
251        rockspec::source::Spec::Git(git) => {
252            let url = git.url.to_string();
253            tracing::debug!(message = format!("Cloning {url}").as_str());
254
255            let clone_url = url.clone();
256            let clone_dir = dest_dir.to_path_buf();
257            let host = git.url.host().to_string();
258            let no_prompt = config.no_prompt();
259            let access_token = config.access_token(&host);
260            let git_ref = git.git_ref.clone();
261
262            let (checkout_ref, has_submodules) = tokio::task::spawn_blocking(move || {
263                let mut auth = if no_prompt {
264                    GitAuthenticator::default()
265                        .try_password_prompt(0)
266                        .prompt_ssh_key_password(false)
267                        .set_prompter(NullPrompter)
268                } else {
269                    GitAuthenticator::default()
270                };
271                if let Some(access_token) = access_token {
272                    auth = auth.add_plaintext_credentials(&host, access_token.username(), unsafe {
273                        access_token.password()
274                    });
275                }
276                let git_config = git2::Config::open_default()?;
277                let mut callbacks = RemoteCallbacks::new();
278                callbacks.credentials(auth.credentials(&git_config));
279                let mut fetch_options = FetchOptions::new();
280                fetch_options.update_fetchhead(false);
281                fetch_options.remote_callbacks(callbacks);
282                let checkout_ref = match &git_ref {
283                    Some(git::Ref::Tag(tag)) => Some(tag.as_str()),
284                    Some(git::Ref::Branch(branch)) => Some(branch.as_str()),
285                    None => None,
286                };
287                if checkout_ref.is_none() {
288                    fetch_options.depth(1);
289                };
290                let mut repo_builder = RepoBuilder::new();
291                repo_builder.fetch_options(fetch_options);
292                let repo = repo_builder.clone(&clone_url, &clone_dir)?;
293
294                let checkout_ref = match checkout_ref {
295                    Some(checkout_ref) => {
296                        let ref_name = if let Some(git::Ref::Branch(branch)) = &git_ref {
297                            format!("origin/{branch}")
298                        } else {
299                            checkout_ref.to_string()
300                        };
301                        let (object, _) = repo.revparse_ext(&ref_name)?;
302                        repo.checkout_tree(&object, None)?;
303                        checkout_ref.to_string()
304                    }
305                    None => {
306                        let head = repo.head()?;
307                        let commit = head.peel_to_commit()?;
308                        commit.id().to_string()
309                    }
310                };
311
312                let submodule_paths = init_submodules(&repo, &auth, &git_config)?;
313
314                Ok::<_, Error>((checkout_ref, !submodule_paths.is_empty()))
315            })
316            .await??;
317
318            // The .git directory is not deterministic
319            remove_dir_all(dest_dir.join(".git")).map_err(Error::CleanGitDir)?;
320            let hash = dest_dir.hash().await.map_err(Error::Hash)?;
321            RemotePackageSourceMetadata {
322                hash,
323                source_url: RemotePackageSourceUrl::Git {
324                    url,
325                    checkout_ref,
326                    submodules: has_submodules,
327                },
328            }
329        }
330        rockspec::source::Spec::Url(url) => {
331            tracing::debug!(message = format!("Downloading {url}").as_str());
332
333            // NOTE: We don't enforce HTTPS when fetching sources because some rockspecs
334            // have HTTP URLs in `source.url`.
335            let request = crate::reqwest::http_client(config)?
336                .get(url.clone())
337                .apply_access_token(config, url);
338            let request = wally::apply_content_headers(request, url);
339            let response = request.send().await?.error_for_status()?.bytes().await?;
340            let hash = response.hash().await.map_err(Error::Hash)?;
341            let file_name = url
342                .path_segments()
343                .and_then(|mut segments| segments.next_back())
344                .and_then(|name| {
345                    if name.is_empty() {
346                        None
347                    } else {
348                        Some(name.to_string())
349                    }
350                })
351                .unwrap_or(url.to_string());
352            let cursor = Cursor::new(response);
353            let mime_type = infer::get(cursor.get_ref()).map(|file_type| file_type.mime_type());
354            unpack::extract(
355                mime_type,
356                cursor,
357                rock_source.unpack_dir.is_none(),
358                file_name,
359                dest_dir,
360            )
361            .await?;
362            RemotePackageSourceMetadata {
363                hash,
364                source_url: RemotePackageSourceUrl::Url { url: url.clone() },
365            }
366        }
367        rockspec::source::Spec::Wally(_) => {
368            return Err(Error::WallySource(rockspec.package().to_string()))
369        }
370        rockspec::source::Spec::File(path) => {
371            tracing::debug!(message = format!("Copying {}", path.display()).as_str());
372
373            let hash = if path.is_dir() {
374                let hash = path.hash().await.map_err(Error::Hash)?;
375                project::copy_dir(path, dest_dir).await?;
376                hash
377            } else {
378                let mut file = fs::sync::open(path)?;
379                let mut buffer = Vec::new();
380                file.read_to_end(&mut buffer)
381                    .map_err(|source| fs::Error::Read {
382                        path: path.to_path_buf(),
383                        source,
384                    })?;
385                let mime_type = infer::get(&buffer).map(|file_type| file_type.mime_type());
386                let file_name = path
387                    .file_name()
388                    .map(|os_str| os_str.to_string_lossy())
389                    .unwrap_or(path.to_string_lossy())
390                    .to_string();
391                unpack::extract(
392                    mime_type,
393                    file,
394                    rock_source.unpack_dir.is_none(),
395                    file_name,
396                    dest_dir,
397                )
398                .await?;
399                path.hash().await.map_err(Error::Hash)?
400            };
401            RemotePackageSourceMetadata {
402                hash,
403                source_url: RemotePackageSourceUrl::File { path: path.clone() },
404            }
405        }
406    };
407    Ok(metadata)
408}
409
410impl From<reqwest::Error> for Error {
411    fn from(err: reqwest::Error) -> Self {
412        Self::Request(err.into())
413    }
414}