Skip to main content

lux_lib/rockspec/source/
mod.rs

1use super::platform;
2use crate::{
3    git::{self, url::RemoteGitUrl},
4    rockspec::platform::per_platform_from_intermediate,
5    wally,
6};
7
8use miette::Diagnostic;
9use reqwest::Url;
10use serde::{de, Deserialize, Deserializer};
11use std::{
12    convert::Infallible,
13    fmt::Display,
14    fs, io,
15    ops::Deref,
16    path::{Path, PathBuf},
17    str::FromStr,
18};
19use thiserror::Error;
20
21use super::{display, PerPlatform};
22
23/// Specifies the source of a rock that has been fetched
24#[derive(Default, Deserialize, Clone, Debug, PartialEq)]
25pub struct Local {
26    pub archive_name: Option<PathBuf>,
27    pub unpack_dir: Option<PathBuf>,
28}
29
30/// Specifies the source of a remote rock to be fetched
31#[derive(Deserialize, Clone, Debug, PartialEq)]
32pub struct Remote {
33    pub(crate) local: Local,
34    pub source_spec: Spec,
35}
36
37impl Remote {
38    /// Builds a remote rock source, normalising a Git rock's `source.dir` to its
39    /// effective source root.
40    ///
41    /// The repository name is the final path component of the Git URL, with any
42    /// `.git` suffix removed.
43    ///
44    /// Luarocks clones Git sources into a `<repository>` directory and resolves
45    /// `source.dir` relative to its parent.
46    /// Lux clones directly into the fetch root, which results in the same
47    /// NAR hash as is used by `fetchgit` (Nix).
48    ///
49    /// For a repository named `foo`:
50    ///
51    /// | input `source.dir` | resulting directory |
52    /// |--------------------|---------------------|
53    /// | `nil`              | `.`                 |
54    /// | `foo`              | `.`                 |
55    /// | `foo/src`          | `src`               |
56    /// | `src`              | `src`               |
57    pub(crate) fn new(mut local: Local, source_spec: Spec) -> Self {
58        if let Spec::Git(git) = &source_spec {
59            let repo = git.url.repo();
60            let normalised = match local.unpack_dir.take() {
61                Some(dir) if dir == Path::new(repo) => ".".into(),
62                Some(dir) => match dir.strip_prefix(repo) {
63                    Ok(stripped) => stripped.to_path_buf(),
64                    Err(_) => dir,
65                },
66                None => PathBuf::from("."),
67            };
68            local.unpack_dir = Some(normalised);
69        }
70        Self { local, source_spec }
71    }
72}
73
74impl From<Spec> for Remote {
75    fn from(source_spec: Spec) -> Self {
76        Self::new(Local::default(), source_spec)
77    }
78}
79
80impl Deref for Remote {
81    type Target = Local;
82
83    fn deref(&self) -> &Self::Target {
84        &self.local
85    }
86}
87
88#[derive(Error, Debug, Diagnostic)]
89#[non_exhaustive]
90pub enum Error {
91    #[error("invalid rockspec source field combination")]
92    InvalidCombination,
93    #[error(transparent)]
94    #[diagnostic(transparent)]
95    SourceUrl(#[from] UrlError),
96    #[error("source URL missing")]
97    SourceUrlMissing,
98}
99
100impl From<internal::Spec> for Local {
101    fn from(internal: internal::Spec) -> Self {
102        Local {
103            archive_name: internal.file,
104            unpack_dir: internal.dir,
105        }
106    }
107}
108
109impl TryFrom<internal::Spec> for Remote {
110    type Error = Error;
111
112    fn try_from(internal: internal::Spec) -> Result<Self, Self::Error> {
113        let local = Local::from(internal.clone());
114
115        // The rockspec.source table allows invalid combinations
116        // This ensures that invalid combinations are caught while parsing.
117        let url = internal::SourceUrl::from_str(&internal.url.ok_or(Error::SourceUrlMissing)?)?;
118
119        let source_spec = match (url, internal.tag, internal.branch) {
120            (source, None, None) => Ok(Spec::default_from_source_url(source)),
121            (internal::SourceUrl::Git(url), Some(tag), None) => Ok(Spec::Git(git::Source {
122                url,
123                git_ref: Some(git::Ref::Tag(tag)),
124            })),
125            (internal::SourceUrl::Git(url), None, Some(branch)) => Ok(Spec::Git(git::Source {
126                url,
127                git_ref: Some(git::Ref::Branch(branch)),
128            })),
129            _ => Err(Error::InvalidCombination),
130        }?;
131
132        Ok(Remote::new(local, source_spec))
133    }
134}
135
136impl<'de> Deserialize<'de> for PerPlatform<Remote> {
137    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
138    where
139        D: Deserializer<'de>,
140    {
141        per_platform_from_intermediate::<_, internal::Spec, _>(deserializer)
142    }
143}
144
145/// Specifies a rock's source
146#[derive(Debug, PartialEq, Eq, Hash, Clone)]
147pub enum Spec {
148    Git(git::Source),
149    File(PathBuf),
150    Url(Url),
151    Wally(wally::package::Req),
152}
153
154impl Spec {
155    fn default_from_source_url(url: internal::SourceUrl) -> Self {
156        match url {
157            internal::SourceUrl::File(path) => Self::File(path),
158            internal::SourceUrl::Url(url) => Self::Url(url),
159            internal::SourceUrl::Git(url) => Self::Git(git::Source { url, git_ref: None }),
160        }
161    }
162}
163
164impl Display for Spec {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        match self {
167            Spec::Git(git_source) => git_source.fmt(f),
168            Spec::File(path_buf) => path_buf.display().fmt(f),
169            Spec::Url(url) => url.fmt(f),
170            Spec::Wally(req) => req.fmt(f),
171        }
172    }
173}
174
175impl<'de> Deserialize<'de> for Spec {
176    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
177    where
178        D: Deserializer<'de>,
179    {
180        let url = String::deserialize(deserializer)?;
181        Ok(Spec::default_from_source_url(
182            url.parse().map_err(de::Error::custom)?,
183        ))
184    }
185}
186
187impl display::AsLuaKV for Spec {
188    fn display_lua(&self) -> display::LuaKV {
189        match self {
190            Spec::Git(git_source) => git_source.display_lua(),
191            Spec::File(path) => {
192                let mut source_tbl = Vec::new();
193                source_tbl.push(display::LuaKV {
194                    key: "url".to_string(),
195                    value: display::LuaValue::String(format!("file://{}", path.display())),
196                });
197                display::LuaKV {
198                    key: "source".to_string(),
199                    value: display::LuaValue::Table(source_tbl),
200                }
201            }
202            Spec::Url(url) => {
203                let mut source_tbl = Vec::new();
204                source_tbl.push(display::LuaKV {
205                    key: "url".to_string(),
206                    value: display::LuaValue::String(format!("{url}")),
207                });
208                display::LuaKV {
209                    key: "source".to_string(),
210                    value: display::LuaValue::Table(source_tbl),
211                }
212            }
213            Spec::Wally(req) => req.display_lua(),
214        }
215    }
216}
217
218#[derive(Error, Debug, Diagnostic)]
219#[non_exhaustive]
220#[error("missing source")]
221pub struct MissingSource;
222
223const SUPPORTED_URL_FORMATS_HELP: &str = r#"supported formats are:
224- 'git://...'
225- 'git+file://...'
226- 'git+https://...'
227- 'git+http://...'
228- 'git+ssh://...'
229- 'https://...'
230- 'http://...'
231- 'ftp://...'
232- 'file://...'
233"#;
234
235const LUX_ISSUES_URL: &str = "https://github.com/lumen-oss/lux/issues";
236const LUAROCKS_BUILD_RULES_URL: &str =
237    "https://github.com/luarocks/luarocks/blob/v3.13.0/docs/rockspec_format.md#build-rules";
238
239#[derive(Error, Debug, Diagnostic)]
240#[non_exhaustive]
241#[error("failed to parse source url")]
242pub enum UrlError {
243    Io(#[from] io::Error),
244    Git(#[from] git::url::Error),
245    Url(#[source] <Url as FromStr>::Err),
246    #[error("lux does not support rockspecs with CVS sources.")]
247    #[diagnostic(
248        help("if you need support for CVS sources, open an issue"),
249        url("{LUX_ISSUES_URL}")
250    )]
251    CVS,
252    #[error("lux does not support rockspecs with mercurial sources.")]
253    #[diagnostic(
254        help("if you need support for Mercurial sources, open an issue"),
255        url("{LUX_ISSUES_URL}")
256    )]
257    Mercurial,
258    #[error("lux does not support rockspecs with SSCM sources.")]
259    #[diagnostic(
260        help("if you need support for SSCM sources, open an issue"),
261        url("{LUX_ISSUES_URL}")
262    )]
263    SSCM,
264    #[error("lux does not support rockspecs with SVN sources.")]
265    #[diagnostic(
266        help("if you need support for SVN sources, open an issue"),
267        url("{LUX_ISSUES_URL}")
268    )]
269    SVN,
270    #[error("unsupported source URL prefix: '{0}+' in URL '{1}'")]
271    #[diagnostic(
272        help("{SUPPORTED_URL_FORMATS_HELP}"),
273        url("{LUAROCKS_BUILD_RULES_URL}")
274    )]
275    UnsupportedPrefix(String, String),
276    #[error("unsupported source URL: '{0}'")]
277    #[diagnostic(
278        help("{SUPPORTED_URL_FORMATS_HELP}"),
279        url("{LUAROCKS_BUILD_RULES_URL}")
280    )]
281    Unsupported(String),
282}
283
284pub(crate) mod internal {
285    use super::*;
286
287    /// Used as a helper for Deserialize,
288    /// because the Rockspec schema allows invalid rockspecs (╯°□°)╯︵ ┻━┻
289    #[derive(Debug, PartialEq, Deserialize, Clone, Default, lux_macros::AsLuaKV)]
290    #[display_lua(key = "source")]
291    pub(crate) struct Spec {
292        #[serde(default)]
293        pub(crate) url: Option<String>,
294        pub(crate) file: Option<PathBuf>,
295        pub(crate) dir: Option<PathBuf>,
296        pub(crate) tag: Option<String>,
297        pub(crate) branch: Option<String>,
298    }
299
300    impl platform::PartialOverride for Spec {
301        type Err = Infallible;
302
303        fn apply_overrides(&self, override_spec: &Self) -> Result<Self, Self::Err> {
304            let (tag, branch) = match (&override_spec.tag, &override_spec.branch) {
305                (Some(tag), _) => (Some(tag.clone()), None),
306                (_, Some(branch)) => (None, Some(branch.clone())),
307                (None, None) => (self.tag.clone(), self.branch.clone()),
308            };
309
310            Ok(Self {
311                url: override_opt(override_spec.url.as_ref(), self.url.as_ref()),
312                file: override_opt(override_spec.file.as_ref(), self.file.as_ref()),
313                dir: override_opt(override_spec.dir.as_ref(), self.dir.as_ref()),
314                tag,
315                branch,
316            })
317        }
318    }
319
320    impl platform::Overridable for Spec {
321        type Err = MissingSource;
322
323        fn on_nil<T>() -> Result<PerPlatform<T>, <Self as platform::Overridable>::Err>
324        where
325            T: platform::Overridable,
326        {
327            Err(MissingSource)
328        }
329    }
330
331    fn override_opt<T: Clone>(override_opt: Option<&T>, base: Option<&T>) -> Option<T> {
332        override_opt.or(base).cloned()
333    }
334
335    /// Internal helper for parsing
336    #[derive(Debug, PartialEq, Clone)]
337
338    pub(crate) enum SourceUrl {
339        /// For URLs in the local filesystem
340        File(PathBuf),
341        /// Web URLs
342        Url(Url),
343        /// For the Git source control manager
344        Git(RemoteGitUrl),
345    }
346
347    impl FromStr for SourceUrl {
348        type Err = UrlError;
349
350        fn from_str(str: &str) -> Result<Self, Self::Err> {
351            match str.split_once("+") {
352                Some(("git" | "gitrec", url)) => Ok(Self::Git(url.parse()?)),
353                Some((prefix, _)) => Err(UrlError::UnsupportedPrefix(
354                    prefix.to_string(),
355                    str.to_string(),
356                )),
357                None => match str {
358                    s if s.starts_with("file://") => {
359                        let path_buf: PathBuf = s.trim_start_matches("file://").into();
360                        let path = fs::canonicalize(&path_buf)?;
361                        Ok(Self::File(path))
362                    }
363                    s if s.starts_with("git://") => {
364                        Ok(Self::Git(s.replacen("git", "https", 1).parse()?))
365                    }
366                    s if s.ends_with(".git") => Ok(Self::Git(s.parse()?)),
367                    s if starts_with_any(s, ["https://", "http://", "ftp://"].into()) => {
368                        Ok(Self::Url(s.parse().map_err(UrlError::Url)?))
369                    }
370                    s if s.starts_with("cvs://") => Err(UrlError::CVS),
371                    s if starts_with_any(
372                        s,
373                        ["hg://", "hg+http://", "hg+https://", "hg+ssh://"].into(),
374                    ) =>
375                    {
376                        Err(UrlError::Mercurial)
377                    }
378                    s if s.starts_with("sscm://") => Err(UrlError::SSCM),
379                    s if s.starts_with("svn://") => Err(UrlError::SVN),
380                    s => Err(UrlError::Unsupported(s.to_string())),
381                },
382            }
383        }
384    }
385
386    impl<'de> Deserialize<'de> for SourceUrl {
387        fn deserialize<D>(deserializer: D) -> Result<SourceUrl, D::Error>
388        where
389            D: Deserializer<'de>,
390        {
391            SourceUrl::from_str(&String::deserialize(deserializer)?).map_err(de::Error::custom)
392        }
393    }
394
395    fn starts_with_any(str: &str, prefixes: Vec<&str>) -> bool {
396        prefixes.iter().any(|&prefix| str.starts_with(prefix))
397    }
398}
399
400#[cfg(test)]
401mod tests {
402    use super::display::AsLuaKV;
403
404    use assert_fs::TempDir;
405
406    use super::*;
407
408    fn eval_lua_global<T: serde::de::DeserializeOwned>(code: &str, key: &'static str) -> T {
409        use ottavino::{Closure, Executor, Fuel, Lua};
410        use ottavino_util::serde::from_value;
411        Lua::core()
412            .try_enter(|ctx| {
413                let closure = Closure::load(ctx, None, code.as_bytes())?;
414                let executor = Executor::start(ctx, closure.into(), ());
415                executor.step(ctx, &mut Fuel::with(i32::MAX))?;
416                from_value(ctx.globals().get_value(ctx, key)).map_err(ottavino::Error::from)
417            })
418            .unwrap()
419    }
420
421    #[test]
422    pub fn rock_source_internal_roundtrip() {
423        let source = internal::Spec {
424            url: Some("https://github.com/example/repo/archive/v1.0.tar.gz".into()),
425            file: Some("repo-1.0.tar.gz".into()),
426            dir: Some("repo-1.0".into()),
427            tag: Some("v1.0".into()),
428            branch: None,
429        };
430        let lua = source.display_lua().to_string();
431        let restored: internal::Spec = eval_lua_global(&lua, "source");
432        assert_eq!(source, restored);
433    }
434
435    #[test]
436    pub fn rock_source_internal_branch_roundtrip() {
437        let source = internal::Spec {
438            url: Some("git+https://github.com/example/repo.git".into()),
439            file: None,
440            dir: None,
441            tag: None,
442            branch: Some("main".into()),
443        };
444        let lua = source.display_lua().to_string();
445        let restored: internal::Spec = eval_lua_global(&lua, "source");
446        assert_eq!(source, restored);
447    }
448
449    #[test]
450    pub fn normalises_git_source_dir() {
451        let parse = |url: &str, dir: Option<&str>| {
452            Remote::try_from(internal::Spec {
453                url: Some(url.into()),
454                file: None,
455                dir: dir.map(Into::into),
456                tag: None,
457                branch: None,
458            })
459            .unwrap()
460            .local
461            .unpack_dir
462        };
463        let git = "git+https://github.com/lumen-oss/foo";
464        assert_eq!(parse(git, None), Some(".".into()));
465        assert_eq!(parse(git, Some("foo")), Some(".".into()));
466        assert_eq!(parse(git, Some("foo/src")), Some("src".into()));
467        assert_eq!(parse(git, Some("src")), Some("src".into()));
468        assert_eq!(
469            parse("https://example.com/repo-1.0.tar.gz", Some("repo-1.0")),
470            Some("repo-1.0".into())
471        );
472    }
473
474    #[tokio::test]
475    async fn parse_source_url() {
476        let dir = TempDir::new().unwrap();
477        let url: internal::SourceUrl = format!("file://{}", dir.to_string_lossy()).parse().unwrap();
478        assert_eq!(url, internal::SourceUrl::File(dir.path().to_path_buf()));
479        let url: internal::SourceUrl = "ftp://example.com/foo/bar".parse().unwrap();
480        assert!(matches!(url, internal::SourceUrl::Url { .. }));
481        let url: internal::SourceUrl = "git://example.com/foo/bar".parse().unwrap();
482        assert!(matches!(url, internal::SourceUrl::Git { .. }));
483        // We don't support file-like URLs, as they are not remote.
484        internal::SourceUrl::from_str("git+file:///path/to/repo.git").unwrap_err();
485        let url: internal::SourceUrl = "git+http://example.com/foo/bar".parse().unwrap();
486        assert!(matches!(url, internal::SourceUrl::Git { .. }));
487        let url: internal::SourceUrl = "git+https://example.com/foo/bar".parse().unwrap();
488        assert!(matches!(url, internal::SourceUrl::Git { .. }));
489        let url: internal::SourceUrl = "git+ssh://example.com/foo/bar".parse().unwrap();
490        assert!(matches!(url, internal::SourceUrl::Git { .. }));
491        let url: internal::SourceUrl = "gitrec+https://example.com/foo/bar".parse().unwrap();
492        assert!(matches!(url, internal::SourceUrl::Git { .. }));
493        let url: internal::SourceUrl = "https://example.com/foo/bar".parse().unwrap();
494        assert!(matches!(url, internal::SourceUrl::Url { .. }));
495        let url: internal::SourceUrl = "http://example.com/foo/bar".parse().unwrap();
496        assert!(matches!(url, internal::SourceUrl::Url { .. }));
497    }
498}