Skip to main content

lux_lib/operations/
fetch.rs

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