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