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