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::{Direction, FetchOptions, ObjectType, 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                    // A failed fetch may leave a partial source tree behind, which confuses source
116                    // root detection after unpacking the fallback archive.
117                    if fetch.dest_dir.exists() {
118                        fs::sync::remove_dir_all(fetch.dest_dir)?;
119                    }
120                    let package = package::Spec::new(
121                        fetch.rockspec.package().clone(),
122                        fetch.rockspec.version().clone(),
123                    );
124                    match SrcRock::new(&package, fetch.dest_dir, fetch.config)
125                        .fetch()
126                        .await
127                    {
128                        Ok(metadata) => Ok(metadata),
129                        Err(fallback_err) => {
130                            tracing::error!("fallback .src.rock download failed: {fallback_err:?}");
131                            Err(err)
132                        }
133                    }
134                }
135                rockspec::source::Spec::File(_) | rockspec::source::Spec::Wally(_) => Err(err),
136            },
137            Ok(metadata) => Ok(metadata),
138        }
139    }
140}
141
142#[derive(Error, Debug, Diagnostic)]
143#[non_exhaustive]
144pub enum Error {
145    #[error("failed to clone rock source")]
146    #[diagnostic(help("check your network connection and verify the git URL is correct."))]
147    GitClone(#[from] git2::Error),
148    #[error("git operation failed")]
149    #[diagnostic(help("this is a bug, please report it."))]
150    GitJoin(#[from] tokio::task::JoinError),
151    #[error("failed to parse git URL")]
152    #[diagnostic(forward(0))]
153    GitUrlParse(#[from] git::url::Error),
154    #[error(transparent)]
155    #[diagnostic(transparent)]
156    Request(#[from] crate::reqwest::Error),
157    #[error(transparent)]
158    #[diagnostic(transparent)]
159    Unpack(#[from] unpack::Error),
160    #[error(transparent)]
161    #[diagnostic(transparent)]
162    SrcRock(#[from] src_rock::Error),
163    #[error("unable to remove the '.git' directory")]
164    #[diagnostic(help(
165        "check that no process is using the directory and you have write permissions."
166    ))]
167    CleanGitDir(#[source] io::Error),
168    #[error("failed to resolve wally package '{0}'")]
169    #[diagnostic(
170        code(lux_lib::wally::unresolved_source),
171        help("this is a bug, please report it.")
172    )]
173    WallySource(String),
174    #[error("unable to compute hash")]
175    Hash(#[source] io::Error),
176    #[error(transparent)]
177    #[diagnostic(transparent)]
178    Fs(#[from] fs::Error),
179}
180
181/// A no-prompt implementer for auth_git2's prompter
182#[derive(Copy, Clone, Debug)]
183struct NullPrompter;
184
185impl Prompter for NullPrompter {
186    fn prompt_username_password(&mut self, _: &str, _: &git2::Config) -> Option<(String, String)> {
187        None
188    }
189
190    fn prompt_password(&mut self, _: &str, _: &str, _: &git2::Config) -> Option<String> {
191        None
192    }
193
194    fn prompt_ssh_key_passphrase(&mut self, _: &Path, _: &git2::Config) -> Option<String> {
195        None
196    }
197}
198
199/// Returns the refspecs to try for a pinned git ref.
200fn ref_candidates(git_ref: &git::Ref) -> Vec<(String, String)> {
201    // Some rockspecs reference a tag in the `branch` field (penlight), so a branch should also try
202    // falling back to a tag.
203    let tag_candidate = |name: &str| {
204        let ref_name = format!("refs/tags/{name}");
205        (ref_name.clone(), format!("+{ref_name}:{ref_name}"))
206    };
207    // Some rockspecs pin a commit hash in the `branch` or `tag` field (e.g. tiniest).
208    let sha_candidate = |name: &str| {
209        git2::Oid::from_str(name)
210            .ok()
211            .map(|_| (name.to_string(), name.to_string()))
212    };
213
214    match git_ref {
215        git::Ref::Branch(branch) => {
216            let mut candidates = vec![
217                (
218                    format!("refs/heads/{branch}"),
219                    format!("+refs/heads/{branch}:refs/remotes/origin/{branch}"),
220                ),
221                tag_candidate(branch),
222            ];
223            candidates.extend(sha_candidate(branch));
224            candidates
225        }
226        git::Ref::Tag(tag) => {
227            let mut candidates = vec![tag_candidate(tag)];
228            candidates.extend(sha_candidate(tag));
229            candidates
230        }
231    }
232}
233
234/// Initialises an empty repository and shallow-fetches only the necessary ref.
235fn fetch_pinned_ref(
236    path: &Path,
237    url: &str,
238    auth: &GitAuthenticator,
239    git_config: &git2::Config,
240    candidates: &[(String, String)],
241) -> Result<git2::Repository, git2::Error> {
242    let repo = git2::Repository::init(path)?;
243
244    // Scopes used to prevent the Borrow Checkerâ„¢ from complaining.
245    {
246        let mut remote = repo.remote("origin", url)?;
247        let mut callbacks = RemoteCallbacks::new();
248        callbacks.credentials(auth.credentials(git_config));
249        let mut connection = remote.connect_auth(Direction::Fetch, Some(callbacks), None)?;
250
251        let available = connection.list()?;
252        let (refspec, oid) = candidates
253            .iter()
254            .find_map(|(ref_name, refspec)| {
255                available
256                    .iter()
257                    .find(|head| head.name() == ref_name)
258                    .map(|head| (refspec.as_str(), head.oid()))
259            })
260            .or_else(|| {
261                // A pinned commit hash isn't advertised as a ref, but the server can fetch it.
262                candidates.iter().find_map(|(ref_name, refspec)| {
263                    git2::Oid::from_str(ref_name)
264                        .ok()
265                        .map(|oid| (refspec.as_str(), oid))
266                })
267            })
268            .ok_or_else(|| git2::Error::from_str("no matching branch or tag found"))?;
269
270        let mut fetch_options = FetchOptions::new();
271        fetch_options.depth(1);
272        fetch_options.update_fetchhead(false);
273        connection
274            .remote()
275            .download(&[refspec], Some(&mut fetch_options))?;
276
277        let commit = repo.find_object(oid, None)?.peel(ObjectType::Commit)?;
278        repo.checkout_tree(&commit, None)?;
279    };
280
281    Ok(repo)
282}
283
284/// Shallow-clones the remote's default branch.
285fn clone_default_branch(
286    path: &Path,
287    url: &str,
288    auth: &GitAuthenticator,
289    git_config: &git2::Config,
290) -> Result<git2::Repository, git2::Error> {
291    let mut callbacks = RemoteCallbacks::new();
292    callbacks.credentials(auth.credentials(git_config));
293    let mut fetch_options = FetchOptions::new();
294    fetch_options.update_fetchhead(false);
295    fetch_options.remote_callbacks(callbacks);
296    fetch_options.depth(1);
297
298    RepoBuilder::new()
299        .fetch_options(fetch_options)
300        .clone(url, path)
301}
302
303/// Initialises and checks out git submodules,
304/// returning the relative paths of any submodules that were checked out.
305fn init_submodules(
306    repo: &git2::Repository,
307    auth: &GitAuthenticator,
308    git_config: &git2::Config,
309) -> Result<Vec<PathBuf>, Error> {
310    let workdir = repo
311        .workdir()
312        .ok_or_else(|| git2::Error::from_str("cloned repository has no working directory"))?;
313    let index = repo.index()?;
314    let mut submodule_paths = Vec::new();
315    for mut submodule in repo.submodules()? {
316        // `.gitmodules` may list paths that are not gitlinks in the checked-out tree.
317        // Updating those does nothing and leaves no `.git` to clean up below.
318        if index.get_path(submodule.path(), 0).is_none() {
319            continue;
320        }
321        let mut callbacks = RemoteCallbacks::new();
322        callbacks.credentials(auth.credentials(git_config));
323        let mut fetch_options = FetchOptions::new();
324        fetch_options.remote_callbacks(callbacks);
325        let mut options = git2::SubmoduleUpdateOptions::new();
326        options.fetch(fetch_options);
327        submodule.update(true, Some(&mut options))?;
328        // The .git file/directory is not deterministic
329        let git_file = workdir.join(submodule.path()).join(".git");
330        if git_file.is_dir() {
331            fs::sync::remove_dir_all(&git_file)?;
332        } else {
333            fs::sync::remove_file(&git_file)?;
334        }
335        submodule_paths.push(submodule.path().to_path_buf());
336    }
337    Ok(submodule_paths)
338}
339
340#[tracing::instrument(
341    name = "Fetching source",
342    level = "info",
343    skip_all,
344    fields(location = source_spec.to_string()),
345)]
346async fn fetch_src_impl<R: Rockspec>(
347    mut source_spec: rockspec::source::Spec,
348    rockspec: &R,
349    rock_source: &rockspec::source::Remote,
350    dest_dir: &Path,
351    config: &Config,
352) -> Result<RemotePackageSourceMetadata, Error> {
353    if let Some(vendor_dir) = config.vendor_dir() {
354        source_spec = match source_spec {
355            // could be a project directory (not vendored) or a local source
356            // or a vendored dependency that we have already resolved
357            rockspec::source::Spec::File(_) => source_spec,
358            _ => {
359                let pkg_vendor_dir =
360                    vendor_dir.join(format!("{}@{}", rockspec.package(), rockspec.version()));
361                rockspec::source::Spec::File(pkg_vendor_dir)
362            }
363        }
364    }
365    let metadata = match &source_spec {
366        rockspec::source::Spec::Git(git) => {
367            let url = git.url.to_string();
368            tracing::debug!(message = format!("Cloning {url}").as_str());
369
370            let clone_url = url.clone();
371            let clone_dir = dest_dir.to_path_buf();
372            let host = git.url.host().to_string();
373            let no_prompt = config.no_prompt();
374            let access_token = config.access_token(&host);
375            let git_ref = git.git_ref.clone();
376
377            let (checkout_ref, has_submodules) = tokio::task::spawn_blocking(move || {
378                let mut auth = if no_prompt {
379                    GitAuthenticator::default()
380                        .try_password_prompt(0)
381                        .prompt_ssh_key_password(false)
382                        .set_prompter(NullPrompter)
383                } else {
384                    GitAuthenticator::default()
385                };
386                if let Some(access_token) = access_token {
387                    auth = auth.add_plaintext_credentials(&host, access_token.username(), unsafe {
388                        access_token.password()
389                    });
390                }
391                let git_config = git2::Config::open_default()?;
392                let repo = match &git_ref {
393                    Some(git_ref) => fetch_pinned_ref(
394                        &clone_dir,
395                        &clone_url,
396                        &auth,
397                        &git_config,
398                        &ref_candidates(git_ref),
399                    )?,
400                    None => clone_default_branch(&clone_dir, &clone_url, &auth, &git_config)?,
401                };
402
403                let checkout_ref = match &git_ref {
404                    Some(git_ref) => match git_ref {
405                        git::Ref::Tag(name) | git::Ref::Branch(name) => name.clone(),
406                    },
407                    None => repo.head()?.peel_to_commit()?.id().to_string(),
408                };
409
410                let submodule_paths = init_submodules(&repo, &auth, &git_config)?;
411
412                Ok::<_, Error>((checkout_ref, !submodule_paths.is_empty()))
413            })
414            .await??;
415
416            // The .git directory is not deterministic
417            remove_dir_all(dest_dir.join(".git")).map_err(Error::CleanGitDir)?;
418            let hash = dest_dir.hash().await.map_err(Error::Hash)?;
419            RemotePackageSourceMetadata {
420                hash,
421                source_url: RemotePackageSourceUrl::Git {
422                    url,
423                    checkout_ref,
424                    submodules: has_submodules,
425                },
426            }
427        }
428        rockspec::source::Spec::Url(url) => {
429            tracing::debug!(message = format!("Downloading {url}").as_str());
430
431            // NOTE: We don't enforce HTTPS when fetching sources because some rockspecs
432            // have HTTP URLs in `source.url`.
433            let request = crate::reqwest::http_client(config)?
434                .get(url.clone())
435                .apply_access_token(config, url);
436            let request = wally::apply_content_headers(request, url);
437            let response = request.send().await?.error_for_status()?.bytes().await?;
438            let hash = response.hash().await.map_err(Error::Hash)?;
439            let file_name = url
440                .path_segments()
441                .and_then(|mut segments| segments.next_back())
442                .and_then(|name| {
443                    if name.is_empty() {
444                        None
445                    } else {
446                        Some(name.to_string())
447                    }
448                })
449                .unwrap_or(url.to_string());
450            let cursor = Cursor::new(response);
451            let mime_type = infer::get(cursor.get_ref()).map(|file_type| file_type.mime_type());
452            unpack::extract(
453                mime_type,
454                cursor,
455                rock_source.unpack_dir.is_none(),
456                file_name,
457                dest_dir,
458            )
459            .await?;
460            RemotePackageSourceMetadata {
461                hash,
462                source_url: RemotePackageSourceUrl::Url { url: url.clone() },
463            }
464        }
465        rockspec::source::Spec::Wally(_) => {
466            return Err(Error::WallySource(rockspec.package().to_string()))
467        }
468        rockspec::source::Spec::File(path) => {
469            tracing::debug!(message = format!("Copying {}", path.display()).as_str());
470
471            let hash = if path.is_dir() {
472                let hash = path.hash().await.map_err(Error::Hash)?;
473                project::copy_dir(path, dest_dir).await?;
474                hash
475            } else {
476                let mut file = fs::sync::open(path)?;
477                let mut buffer = Vec::new();
478                file.read_to_end(&mut buffer)
479                    .map_err(|source| fs::Error::Read {
480                        path: path.to_path_buf(),
481                        source,
482                    })?;
483                let mime_type = infer::get(&buffer).map(|file_type| file_type.mime_type());
484                let file_name = path
485                    .file_name()
486                    .map(|os_str| os_str.to_string_lossy())
487                    .unwrap_or(path.to_string_lossy())
488                    .to_string();
489                unpack::extract(
490                    mime_type,
491                    file,
492                    rock_source.unpack_dir.is_none(),
493                    file_name,
494                    dest_dir,
495                )
496                .await?;
497                path.hash().await.map_err(Error::Hash)?
498            };
499            RemotePackageSourceMetadata {
500                hash,
501                source_url: RemotePackageSourceUrl::File { path: path.clone() },
502            }
503        }
504    };
505    Ok(metadata)
506}
507
508impl From<reqwest::Error> for Error {
509    fn from(err: reqwest::Error) -> Self {
510        Self::Request(err.into())
511    }
512}