Skip to main content

lux_lib/rockspec/lua/
mod.rs

1pub mod partial;
2
3pub use partial::Partial;
4
5use crate::package;
6use std::{collections::HashMap, io, path::PathBuf};
7
8use ottavino::{Closure, Executor, Fuel};
9use ottavino_util::serde::from_value;
10use serde::{de::DeserializeOwned, Deserialize};
11
12use miette::{Diagnostic, NamedSource, SourceSpan};
13use ssri::Integrity;
14use thiserror::Error;
15
16use super::{
17    build, deploy, description,
18    display::{self, AsLuaKV, AsLuaValue},
19    external_dependency, platform, source, test, Format, PerPlatform,
20};
21use crate::{
22    hash::HasIntegrity,
23    rockspec::{lua_dependency, Rockspec},
24    ROCKSPEC_FUEL_LIMIT,
25};
26
27#[derive(Error, Debug, Diagnostic)]
28#[non_exhaustive]
29pub enum Error {
30    #[error("manifest exceeds computational limit of {ROCKSPEC_FUEL_LIMIT} steps")]
31    #[diagnostic(
32        code(lux_lib::rockspec::lua::fuel_limit_exceeded),
33        help(
34            r#"the rockspec may be too complex or contain too many dependencies.
35try reducing the number of dependencies or simplifying build instructions.
36"#
37        )
38    )]
39    FuelLimitExceeded,
40    #[error("could not parse rockspec")]
41    #[diagnostic(code(lux_lib::rockspec::lua::execution),
42        help("check the rockspec or lux.toml for valid syntax and make sure it matches the specification."),
43        url("https://lux.lumen-labs.org/reference/lux-toml")
44    )]
45    ExecutionError {
46        cause: Box<String>,
47        #[source_code]
48        content: NamedSource<String>,
49        #[label("this package")]
50        pkg_span: SourceSpan,
51        #[label("{cause}")]
52        err_span: Option<SourceSpan>,
53    },
54    #[error("{}copy_directories cannot contain the rockspec name", ._0.as_ref().map(|p| format!("{p}: ")).unwrap_or_default())]
55    CopyDirectoriesContainRockspecName(Option<String>),
56    #[error("cannot create Lua rockspec with off-spec dependency")]
57    #[diagnostic(
58        code(lux_lib::rockspec::lua::off_spec_dependency),
59        url("https://lux.lumen-labs.org/reference/lux-toml#dependencies")
60    )]
61    OffSpecSpec(package::Name),
62    #[error("cannot create Lua rockspec with off-spec build dependency")]
63    #[diagnostic(
64        code(lux_lib::rockspec::lua::off_spec_build_dependency),
65        url("https://lux.lumen-labs.org/reference/lux-toml#dependencies")
66    )]
67    OffSpecBuildSpec(package::Name),
68    #[error("cannot create Lua rockspec with off-spec test dependency")]
69    #[diagnostic(
70        code(lux_lib::rockspec::lua::off_spec_test_dependency),
71        url("https://lux.lumen-labs.org/reference/lux-toml#dependencies")
72    )]
73    OffSpecTestSpec(package::Name),
74}
75
76impl Error {
77    fn from_ottavino(cause: ottavino::ExternError, rockspec_content: &str) -> Self {
78        let msg = match &cause {
79            ottavino::ExternError::Runtime(rt) => rt.to_string(),
80            _ => cause.to_string(),
81        };
82        let field = msg
83            .strip_prefix("invalid rockspec field '")
84            .and_then(|rest| rest.split('\'').next())
85            .map(|f| f.to_owned());
86        let err_span = field.as_deref().and_then(|field| {
87            let span = find_key_span(rockspec_content, field);
88            if span.is_empty() {
89                None
90            } else {
91                Some(span)
92            }
93        });
94        Error::ExecutionError {
95            cause: Box::new(msg),
96            content: NamedSource::new("rockspec", rockspec_content.to_string()),
97            pkg_span: find_value_span(rockspec_content, "package"),
98            err_span,
99        }
100    }
101}
102
103/// This error can be returned within `ottavino::Lua::try_enter`.
104/// ottavino wraps it in an [`ottavino::ExternError`], which Lux wraps inn
105/// a [`Error::ExecutionError`]
106#[derive(Error, Debug, Diagnostic)]
107#[non_exhaustive]
108enum ParseLuaRockspecFieldError {
109    #[error("invalid rockspec field '{field}': {source}")]
110    Deserialize {
111        field: String,
112        source: Box<ottavino_util::serde::de::Error>,
113    },
114    #[error(
115        r#"invalid rockspec field '{field}'.
116Failed to parse a table field: {source}"#
117    )]
118    DeserializeTable {
119        field: String,
120        source: Box<ottavino_util::serde::de::Error>,
121    },
122    #[error("invalid rockspec field '{field}'. expected a table, but got: {invalid_type}")]
123    NotATable { field: String, invalid_type: String },
124}
125
126/// RockSpec for a local rock installation, deserialized from a `.rockspec` file
127#[derive(Clone, Debug)]
128#[cfg_attr(test, derive(PartialEq))]
129pub struct Local {
130    /// The file format version. Example: "1.0"
131    format: Option<Format>,
132    /// The name of the package. Example: "luasocket"
133    package: package::Name,
134    /// The version of the package, plus a suffix indicating the revision of the rockspec. Example: "2.0.1-1"
135    version: package::Version,
136    description: description::Spec,
137    supported_platforms: platform::Support,
138    /// The Lua version requirement for this rock
139    lua: package::VersionReq,
140    dependencies: PerPlatform<Vec<lua_dependency::Spec>>,
141    build_dependencies: PerPlatform<Vec<lua_dependency::Spec>>,
142    external_dependencies: PerPlatform<HashMap<String, external_dependency::Spec>>,
143    test_dependencies: PerPlatform<Vec<lua_dependency::Spec>>,
144    build: PerPlatform<build::Spec>,
145    source: PerPlatform<source::Remote>,
146    test: PerPlatform<test::Spec>,
147    deploy: PerPlatform<deploy::Spec>,
148    /// The original content of this rockspec, needed by luarocks
149    raw_content: String,
150}
151
152trait HasRockspecKey<'gc> {
153    fn get_rockspec_key<V: Deserialize<'gc>>(
154        &self,
155        ctx: ottavino::Context<'gc>,
156        key: &str,
157    ) -> Result<V, ParseLuaRockspecFieldError>;
158}
159
160impl<'gc> HasRockspecKey<'gc> for ottavino::Table<'gc> {
161    fn get_rockspec_key<V: Deserialize<'gc>>(
162        &self,
163        ctx: ottavino::Context<'gc>,
164        key: &str,
165    ) -> Result<V, ParseLuaRockspecFieldError> {
166        let value = self.get_value(ctx, key.to_string());
167        let is_table = matches!(&value, ottavino::Value::Table(_));
168        from_value(value).map_err(|source| {
169            if is_table {
170                ParseLuaRockspecFieldError::DeserializeTable {
171                    field: key.into(),
172                    source: Box::new(source),
173                }
174            } else {
175                ParseLuaRockspecFieldError::Deserialize {
176                    field: key.into(),
177                    source: Box::new(source),
178                }
179            }
180        })
181    }
182}
183
184impl Local {
185    /// Builds a [`Local`] from an already-parsed project.
186    pub(crate) fn from_project_toml(project: &super::toml::Local, raw_content: String) -> Self {
187        use crate::rockspec::Rockspec;
188
189        Self {
190            format: Some(project.generated_rockspec_format()),
191            package: project.package().clone(),
192            version: project.version().clone(),
193            description: project.description().clone(),
194            supported_platforms: project.supported_platforms().clone(),
195            lua: project.lua().clone(),
196            dependencies: project.dependencies().clone(),
197            build_dependencies: project.build_dependencies().clone(),
198            external_dependencies: project.external_dependencies().clone(),
199            test_dependencies: project.test_dependencies().clone(),
200            build: project.build().clone(),
201            source: project.source().clone(),
202            test: project.test().clone(),
203            deploy: project.deploy().clone(),
204            raw_content,
205        }
206    }
207
208    /// Wraps this rockspec into a [`Remote`], overriding its source
209    /// with the given `source`.
210    pub fn into_remote_with_source(self, source: PerPlatform<source::Remote>) -> Remote {
211        Remote {
212            local: self,
213            source,
214        }
215    }
216
217    pub fn new(rockspec_content: &str, project_root: PathBuf) -> Result<Self, Error> {
218        let mut lua = ottavino::Lua::core();
219
220        let rockspec = lua
221            .try_enter(|ctx| {
222                let closure = Closure::load(ctx, None, rockspec_content.as_bytes())?;
223
224                let executor = Executor::start(ctx, closure.into(), ());
225
226                let output = executor.step(ctx, &mut Fuel::with(ROCKSPEC_FUEL_LIMIT))?;
227
228                if !output {
229                    return Ok(Err(Error::FuelLimitExceeded));
230                }
231
232                let globals = ctx.globals();
233
234                let dependencies: PerPlatform<Vec<lua_dependency::Spec>> =
235                    globals.get_rockspec_key(ctx, "dependencies")?;
236
237                let lua_version_req = dependencies
238                    .current_platform()
239                    .iter()
240                    .find(|dep| dep.name().to_string() == "lua")
241                    .cloned()
242                    .map(|dep| dep.version_req().clone())
243                    .unwrap_or(package::VersionReq::Any);
244
245                fn strip_lua(
246                    dependencies: PerPlatform<Vec<lua_dependency::Spec>>,
247                ) -> PerPlatform<Vec<lua_dependency::Spec>> {
248                    dependencies.map(|deps| {
249                        deps.iter()
250                            .filter(|dep| dep.name().to_string() != "lua")
251                            .cloned()
252                            .collect()
253                    })
254                }
255
256                let build_dependencies: PerPlatform<Vec<lua_dependency::Spec>> =
257                    globals.get_rockspec_key(ctx, "build_dependencies")?;
258
259                let test_dependencies: PerPlatform<Vec<lua_dependency::Spec>> =
260                    globals.get_rockspec_key(ctx, "test_dependencies")?;
261
262                let source: PerPlatform<source::Remote> = match globals.get_value(ctx, "source") {
263                    ottavino::Value::Nil => {
264                        PerPlatform::new(source::Spec::File(project_root).into())
265                    }
266                    value => from_value(value).map_err(|source| {
267                        ParseLuaRockspecFieldError::Deserialize {
268                            field: "source".into(),
269                            source: Box::new(source),
270                        }
271                    })?,
272                };
273
274                let rockspec = Local {
275                    format: globals.get_rockspec_key(ctx, "rockspec_format")?,
276                    package: globals.get_rockspec_key(ctx, "package")?,
277                    version: globals.get_rockspec_key(ctx, "version")?,
278                    description: parse_lua_tbl_or_default(ctx, "description")?,
279                    supported_platforms: parse_lua_tbl_or_default(ctx, "supported_platforms")?,
280                    lua: lua_version_req,
281                    dependencies: strip_lua(dependencies),
282                    build_dependencies: strip_lua(build_dependencies),
283                    test_dependencies: strip_lua(test_dependencies),
284                    external_dependencies: globals
285                        .get_rockspec_key(ctx, "external_dependencies")?,
286                    build: globals.get_rockspec_key(ctx, "build")?,
287                    test: globals.get_rockspec_key(ctx, "test")?,
288                    deploy: globals.get_rockspec_key(ctx, "deploy")?,
289                    raw_content: rockspec_content.into(),
290
291                    source,
292                };
293
294                Ok(Ok(rockspec))
295            })
296            .map_err(|cause| Error::from_ottavino(cause, rockspec_content))??;
297
298        let rockspec_file_name = format!("{}-{}.rockspec", rockspec.package(), rockspec.version());
299
300        if rockspec
301            .build()
302            .default
303            .copy_directories
304            .contains(&PathBuf::from(&rockspec_file_name))
305        {
306            return Err(Error::CopyDirectoriesContainRockspecName(None));
307        }
308
309        for (platform, build_override) in &rockspec.build().per_platform {
310            if build_override
311                .copy_directories
312                .contains(&PathBuf::from(&rockspec_file_name))
313            {
314                return Err(Error::CopyDirectoriesContainRockspecName(Some(
315                    platform.to_string(),
316                )));
317            }
318        }
319        Ok(rockspec)
320    }
321}
322
323impl Rockspec for Local {
324    fn package(&self) -> &package::Name {
325        &self.package
326    }
327
328    fn version(&self) -> &package::Version {
329        &self.version
330    }
331
332    fn description(&self) -> &description::Spec {
333        &self.description
334    }
335
336    fn supported_platforms(&self) -> &platform::Support {
337        &self.supported_platforms
338    }
339
340    fn lua(&self) -> &package::VersionReq {
341        &self.lua
342    }
343
344    fn dependencies(&self) -> &PerPlatform<Vec<lua_dependency::Spec>> {
345        &self.dependencies
346    }
347
348    fn build_dependencies(&self) -> &PerPlatform<Vec<lua_dependency::Spec>> {
349        &self.build_dependencies
350    }
351
352    fn external_dependencies(&self) -> &PerPlatform<HashMap<String, external_dependency::Spec>> {
353        &self.external_dependencies
354    }
355
356    fn test_dependencies(&self) -> &PerPlatform<Vec<lua_dependency::Spec>> {
357        &self.test_dependencies
358    }
359
360    fn build(&self) -> &PerPlatform<build::Spec> {
361        &self.build
362    }
363
364    fn test(&self) -> &PerPlatform<test::Spec> {
365        &self.test
366    }
367
368    fn source(&self) -> &PerPlatform<source::Remote> {
369        &self.source
370    }
371
372    fn deploy(&self) -> &PerPlatform<deploy::Spec> {
373        &self.deploy
374    }
375
376    fn build_mut(&mut self) -> &mut PerPlatform<build::Spec> {
377        &mut self.build
378    }
379
380    fn test_mut(&mut self) -> &mut PerPlatform<test::Spec> {
381        &mut self.test
382    }
383
384    fn source_mut(&mut self) -> &mut PerPlatform<source::Remote> {
385        &mut self.source
386    }
387
388    fn deploy_mut(&mut self) -> &mut PerPlatform<deploy::Spec> {
389        &mut self.deploy
390    }
391
392    fn format(&self) -> &Option<Format> {
393        &self.format
394    }
395
396    fn to_lua_remote_rockspec_string(&self) -> Result<String, super::Error> {
397        Ok(self.raw_content.clone())
398    }
399}
400
401impl HasIntegrity for Local {
402    async fn hash(&self) -> io::Result<Integrity> {
403        Ok(Integrity::from(&self.raw_content))
404    }
405}
406
407/// RockSpec for a remote rock, deserialized from a `.rockspec` file
408#[derive(Clone, Debug)]
409#[cfg_attr(test, derive(PartialEq))]
410pub struct Remote {
411    local: Local,
412    source: PerPlatform<source::Remote>,
413}
414
415impl Remote {
416    pub fn new(rockspec_content: &str) -> Result<Self, Error> {
417        let mut lua = ottavino::Lua::core();
418
419        let source = lua
420            .try_enter(|ctx| {
421                let closure = Closure::load(ctx, None, rockspec_content.as_bytes())?;
422
423                let executor = Executor::start(ctx, closure.into(), ());
424
425                let output = executor.step(ctx, &mut Fuel::with(ROCKSPEC_FUEL_LIMIT))?;
426
427                if !output {
428                    return Ok(Err(Error::FuelLimitExceeded));
429                }
430
431                let globals = ctx.globals();
432
433                let source: PerPlatform<source::Remote> =
434                    globals.get_rockspec_key(ctx, "source")?;
435
436                Ok(Ok(source))
437            })
438            .map_err(|cause| Error::from_ottavino(cause, rockspec_content))??;
439
440        Ok(Remote {
441            // NOTE: Calling this outside of `lua.try_enter` reduces error message repetition
442            local: Local::new(rockspec_content, PathBuf::new())?,
443            source,
444        })
445    }
446
447    /// Builds a rockspec from a source spec and dependencies.
448    ///
449    /// With no modules, the rockspec uses the `source` build backend.
450    /// Otherwise, it uses the `builtin` build backend with the given modules.
451    pub(crate) fn from_source_spec(
452        package_spec: package::Spec,
453        source_spec: source::Spec,
454        dependencies: Vec<lua_dependency::Spec>,
455        modules: HashMap<build::backend::Module, build::backend::ModuleSpec>,
456    ) -> Self {
457        let version = package_spec.version().clone();
458        let rockspec_format = Format::default();
459        let (backend, build_lua) = if modules.is_empty() {
460            (
461                build::backend::Spec::Source,
462                r#"type = "source""#.to_string(),
463            )
464        } else {
465            let modules_lua = modules_lua(&modules);
466            (
467                build::backend::Spec::Builtin(build::backend::Builtin { modules }),
468                format!("type = \"builtin\",\n  modules = {{\n{modules_lua}\n  }}"),
469            )
470        };
471        let build_spec = build::Spec {
472            backend: Some(backend),
473            ..Default::default()
474        };
475        let raw_content = rockspec_content(&package_spec, &source_spec, &build_lua);
476        let source: source::Remote = source_spec.into();
477
478        let local = Local {
479            format: Some(rockspec_format),
480            package: package_spec.name().clone(),
481            version,
482            description: description::Spec::default(),
483            supported_platforms: platform::Support::default(),
484            lua: package::VersionReq::Any,
485            dependencies: PerPlatform::new(dependencies),
486            build_dependencies: PerPlatform::default(),
487            external_dependencies: PerPlatform::default(),
488            test_dependencies: PerPlatform::default(),
489            build: PerPlatform::new(build_spec),
490            source: PerPlatform::new(source.clone()),
491            test: PerPlatform::default(),
492            deploy: PerPlatform::default(),
493            raw_content,
494        };
495        Self {
496            local,
497            source: PerPlatform::new(source),
498        }
499    }
500}
501
502fn rockspec_content(
503    package_spec: &package::Spec,
504    source_spec: &source::Spec,
505    build_lua: &str,
506) -> String {
507    format!(
508        r#"
509rockspec_format = "{}"
510package = "{}"
511version = "{}"
512{}
513build = {{
514{}
515}}"#,
516        Format::default(),
517        package_spec.name(),
518        package_spec.version(),
519        source_spec.display_lua(),
520        build_lua,
521    )
522}
523
524fn modules_lua(modules: &HashMap<build::backend::Module, build::backend::ModuleSpec>) -> String {
525    let mut entries: Vec<_> = modules.iter().collect();
526    entries.sort_by_key(|(module, _)| module.as_str());
527    display::LuaValue::Table(
528        entries
529            .into_iter()
530            .map(|(module, spec)| display::LuaKV {
531                key: module.to_string(),
532                value: spec.display_lua_value(),
533            })
534            .collect(),
535    )
536    .to_string()
537}
538
539impl Rockspec for Remote {
540    fn package(&self) -> &package::Name {
541        self.local.package()
542    }
543
544    fn version(&self) -> &package::Version {
545        self.local.version()
546    }
547
548    fn description(&self) -> &description::Spec {
549        self.local.description()
550    }
551
552    fn supported_platforms(&self) -> &platform::Support {
553        self.local.supported_platforms()
554    }
555
556    fn lua(&self) -> &package::VersionReq {
557        self.local.lua()
558    }
559
560    fn dependencies(&self) -> &PerPlatform<Vec<lua_dependency::Spec>> {
561        self.local.dependencies()
562    }
563
564    fn build_dependencies(&self) -> &PerPlatform<Vec<lua_dependency::Spec>> {
565        match self.format() {
566            // Rockspec formats < 3.0 don't support `build_dependencies`,
567            // so we have to return regular dependencies if the build backend might need to use them.
568            Some(Format::_1_0 | Format::_2_0)
569                if self
570                    .build()
571                    .current_platform()
572                    .backend
573                    .as_ref()
574                    .is_some_and(|build_backend| build_backend.can_use_build_dependencies()) =>
575            {
576                self.local.dependencies()
577            }
578            _ => self.local.build_dependencies(),
579        }
580    }
581
582    fn external_dependencies(&self) -> &PerPlatform<HashMap<String, external_dependency::Spec>> {
583        self.local.external_dependencies()
584    }
585
586    fn test_dependencies(&self) -> &PerPlatform<Vec<lua_dependency::Spec>> {
587        self.local.test_dependencies()
588    }
589
590    fn build(&self) -> &PerPlatform<build::Spec> {
591        self.local.build()
592    }
593
594    fn test(&self) -> &PerPlatform<test::Spec> {
595        self.local.test()
596    }
597
598    fn source(&self) -> &PerPlatform<source::Remote> {
599        &self.source
600    }
601
602    fn deploy(&self) -> &PerPlatform<deploy::Spec> {
603        self.local.deploy()
604    }
605
606    fn build_mut(&mut self) -> &mut PerPlatform<build::Spec> {
607        self.local.build_mut()
608    }
609
610    fn test_mut(&mut self) -> &mut PerPlatform<test::Spec> {
611        self.local.test_mut()
612    }
613
614    fn source_mut(&mut self) -> &mut PerPlatform<source::Remote> {
615        &mut self.source
616    }
617
618    fn deploy_mut(&mut self) -> &mut PerPlatform<deploy::Spec> {
619        self.local.deploy_mut()
620    }
621
622    fn format(&self) -> &Option<Format> {
623        self.local.format()
624    }
625
626    fn to_lua_remote_rockspec_string(&self) -> Result<String, super::Error> {
627        Ok(self.local.raw_content.clone())
628    }
629}
630
631impl HasIntegrity for Remote {
632    async fn hash(&self) -> io::Result<Integrity> {
633        Ok(Integrity::from(&self.local.raw_content))
634    }
635}
636
637fn find_key_span(rockspec_content: &str, key: &str) -> SourceSpan {
638    rockspec_content
639        .match_indices(key)
640        .find(|&(start, _)| {
641            let end = start + key.len();
642            let prefix_ok =
643                start == 0 || !rockspec_content.as_bytes()[start - 1].is_ascii_alphanumeric();
644            let suffix_ok = rockspec_content
645                .get(end..)
646                .is_some_and(|s| s.starts_with('=') || s.trim_start().starts_with('='));
647            prefix_ok && suffix_ok
648        })
649        .map(|(start, _)| (start..start + key.len()).into())
650        .unwrap_or((0..0).into())
651}
652
653fn find_value_span(rockspec_content: &str, key: &str) -> SourceSpan {
654    let key = find_key_span(rockspec_content, key);
655    if key.is_empty() {
656        return key;
657    }
658    let key_offset = key.offset();
659    let key_end = key_offset + key.len();
660    let eq_start = key_end + rockspec_content[key_end..].find('=').unwrap_or(0);
661    let value_offset = eq_start + 1;
662    let line_end = rockspec_content[value_offset..]
663        .find('\n')
664        .map(|i| value_offset + i)
665        .unwrap_or(rockspec_content.len());
666    let trimmed = &rockspec_content[value_offset..line_end];
667    let start = value_offset + (trimmed.len() - trimmed.trim_start().len());
668    let end = line_end - (trimmed.len() - trimmed.trim_end().len());
669    (start..end).into()
670}
671
672fn parse_lua_tbl_or_default<T>(
673    ctx: ottavino::Context<'_>,
674    field: &str,
675) -> Result<T, ParseLuaRockspecFieldError>
676where
677    T: Default,
678    T: DeserializeOwned,
679{
680    let ret = match ctx.globals().get_value(ctx, field.to_string()) {
681        ottavino::Value::Nil => T::default(),
682        value @ ottavino::Value::Table(_) => {
683            from_value(value).map_err(|source| ParseLuaRockspecFieldError::DeserializeTable {
684                field: field.to_string(),
685                source: Box::new(source),
686            })?
687        }
688        value => Err(ParseLuaRockspecFieldError::NotATable {
689            field: field.to_string(),
690            invalid_type: value.type_name().to_string(),
691        })?,
692    };
693    Ok(ret)
694}
695
696#[cfg(test)]
697mod tests {
698    use std::path::PathBuf;
699    use std::str::FromStr;
700
701    use crate::git;
702    use url::Url;
703
704    use super::*;
705
706    #[test]
707    pub fn parse_rockspec() {
708        let rockspec_content = "
709        rockspec_format = '1.0'\n
710        package = 'foo'\n
711        version = '1.0.0-1'\n
712        source = {\n
713            url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
714        }\n
715        "
716        .to_string();
717        let rockspec = Remote::new(&rockspec_content).unwrap();
718        assert_eq!(rockspec.local.format, Some(Format::_1_0));
719        assert_eq!(rockspec.local.package, "foo".into());
720        assert_eq!(rockspec.local.version, "1.0.0-1".parse().unwrap());
721        assert_eq!(rockspec.local.description, description::Spec::default());
722
723        let rockspec_content = "
724        package = 'bar'\n
725        version = '2.0.0-1'\n
726        description = {}\n
727        source = {\n
728            url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
729        }\n
730        "
731        .to_string();
732        let rockspec = Remote::new(&rockspec_content).unwrap();
733        assert_eq!(rockspec.local.format, None);
734        assert_eq!(rockspec.local.package, "bar".into());
735        assert_eq!(rockspec.local.version, "2.0.0-1".parse().unwrap());
736        assert_eq!(rockspec.local.description, description::Spec::default());
737
738        let rockspec_content = "
739        package = 'rocks.nvim'\n
740        version = '3.0.0-1'\n
741        description = {\n
742            summary = 'some summary',
743            detailed = 'some detailed description',
744            license = 'MIT',
745            homepage = 'https://github.com/lumen-oss/rocks.nvim',
746            issues_url = 'https://github.com/lumen-oss/rocks.nvim/issues',
747            maintainer = 'Lumen Labs',
748        }\n
749        source = {\n
750            url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
751        }\n
752        "
753        .to_string();
754        let rockspec = Remote::new(&rockspec_content).unwrap();
755        assert_eq!(rockspec.local.format, None);
756        assert_eq!(rockspec.local.package, "rocks.nvim".into());
757        assert_eq!(rockspec.local.version, "3.0.0-1".parse().unwrap());
758        let expected_description = description::Spec {
759            summary: Some("some summary".into()),
760            detailed: Some("some detailed description".into()),
761            license: Some("MIT".into()),
762            homepage: Some(Url::parse("https://github.com/lumen-oss/rocks.nvim").unwrap()),
763            issues_url: Some(Url::parse("https://github.com/lumen-oss/rocks.nvim/issues").unwrap()),
764            maintainer: Some("Lumen Labs".into()),
765            labels: Vec::new(),
766        };
767        assert_eq!(rockspec.local.description, expected_description);
768
769        let rockspec_content = "
770        package = 'rocks.nvim'\n
771        version = '3.0.0-1'\n
772        description = {\n
773            summary = 'some summary',
774            detailed = 'some detailed description',
775            license = 'MIT',
776            homepage = 'https://github.com/lumen-oss/rocks.nvim',
777            issues_url = 'https://github.com/lumen-oss/rocks.nvim/issues',
778            maintainer = 'Lumen Labs',
779            labels = {},
780        }\n
781        external_dependencies = { FOO = { library = 'foo' } }\n
782        source = {\n
783            url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
784        }\n
785        "
786        .to_string();
787        let rockspec = Remote::new(&rockspec_content).unwrap();
788        assert_eq!(rockspec.local.format, None);
789        assert_eq!(rockspec.local.package, "rocks.nvim".into());
790        assert_eq!(rockspec.local.version, "3.0.0-1".parse().unwrap());
791        let expected_description = description::Spec {
792            summary: Some("some summary".into()),
793            detailed: Some("some detailed description".into()),
794            license: Some("MIT".into()),
795            homepage: Some(Url::parse("https://github.com/lumen-oss/rocks.nvim").unwrap()),
796            issues_url: Some(Url::parse("https://github.com/lumen-oss/rocks.nvim/issues").unwrap()),
797            maintainer: Some("Lumen Labs".into()),
798            labels: Vec::new(),
799        };
800        assert_eq!(rockspec.local.description, expected_description);
801        assert_eq!(
802            *rockspec
803                .local
804                .external_dependencies
805                .default
806                .get("FOO")
807                .unwrap(),
808            external_dependency::Spec {
809                library: Some("foo".into()),
810                header: None
811            }
812        );
813
814        let rockspec_content = "
815        package = 'rocks.nvim'\n
816        version = '3.0.0-1'\n
817        description = {\n
818            summary = 'some summary',
819            detailed = 'some detailed description',
820            license = 'MIT',
821            homepage = 'https://github.com/lumen-oss/rocks.nvim',
822            issues_url = 'https://github.com/lumen-oss/rocks.nvim/issues',
823            maintainer = 'Lumen Labs',
824            labels = { 'package management', },
825        }\n
826        supported_platforms = { 'unix', '!windows' }\n
827        dependencies = { 'neorg ~> 6' }\n
828        build_dependencies = { 'foo' }\n
829        external_dependencies = { FOO = { header = 'foo.h' } }\n
830        test_dependencies = { 'busted >= 2.0.0' }\n
831        source = {\n
832            url = 'git+https://github.com/lumen-oss/rocks.nvim',\n
833            hash = 'sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=',\n
834        }\n
835        "
836        .to_string();
837        let rockspec = Remote::new(&rockspec_content).unwrap();
838        assert_eq!(rockspec.local.format, None);
839        assert_eq!(rockspec.local.package, "rocks.nvim".into());
840        assert_eq!(rockspec.local.version, "3.0.0-1".parse().unwrap());
841        let expected_description = description::Spec {
842            summary: Some("some summary".into()),
843            detailed: Some("some detailed description".into()),
844            license: Some("MIT".into()),
845            homepage: Some(Url::parse("https://github.com/lumen-oss/rocks.nvim").unwrap()),
846            issues_url: Some(Url::parse("https://github.com/lumen-oss/rocks.nvim/issues").unwrap()),
847            maintainer: Some("Lumen Labs".into()),
848            labels: vec!["package management".into()],
849        };
850        assert_eq!(rockspec.local.description, expected_description);
851        assert!(rockspec
852            .local
853            .supported_platforms
854            .is_supported(&platform::Identifier::Unix));
855        assert!(!rockspec
856            .local
857            .supported_platforms
858            .is_supported(&platform::Identifier::Windows));
859        let neorg = package::Spec::parse("neorg".into(), "6.0.0".into()).unwrap();
860        assert!(rockspec
861            .local
862            .dependencies
863            .default
864            .into_iter()
865            .any(|dep| dep.matches(&neorg)));
866        let foo = package::Spec::parse("foo".into(), "1.0.0".into()).unwrap();
867        assert!(rockspec
868            .local
869            .build_dependencies
870            .default
871            .into_iter()
872            .any(|dep| dep.matches(&foo)));
873        let busted = package::Spec::parse("busted".into(), "2.2.0".into()).unwrap();
874        assert_eq!(
875            *rockspec
876                .local
877                .external_dependencies
878                .default
879                .get("FOO")
880                .unwrap(),
881            external_dependency::Spec {
882                header: Some("foo.h".into()),
883                library: None
884            }
885        );
886        assert!(rockspec
887            .local
888            .test_dependencies
889            .default
890            .into_iter()
891            .any(|dep| dep.matches(&busted)));
892
893        let rockspec_content = "
894        rockspec_format = '1.0'\n
895        package = 'foo'\n
896        version = '1.0.0-1'\n
897        source = {\n
898            url = 'git+https://hub.com/owner/example-project/',\n
899            branch = 'bar',\n
900        }\n
901        "
902        .to_string();
903        let rockspec = Remote::new(&rockspec_content).unwrap();
904        assert_eq!(
905            rockspec.local.source.default.source_spec,
906            source::Spec::Git(git::Source {
907                url: "https://hub.com/owner/example-project/".parse().unwrap(),
908                git_ref: Some(git::Ref::Branch("bar".into()))
909            })
910        );
911        assert_eq!(rockspec.local.test, PerPlatform::default());
912        let rockspec_content = "
913        rockspec_format = '1.0'\n
914        package = 'foo'\n
915        version = '1.0.0-1'\n
916        source = {\n
917            url = 'git+https://hub.com/owner/example-project/',\n
918            tag = 'bar',\n
919        }\n
920        "
921        .to_string();
922        let rockspec = Remote::new(&rockspec_content).unwrap();
923        assert_eq!(
924            rockspec.local.source.default.source_spec,
925            source::Spec::Git(git::Source {
926                url: "https://hub.com/owner/example-project/".parse().unwrap(),
927                git_ref: Some(git::Ref::Tag("bar".into()))
928            })
929        );
930        let rockspec_content = "
931        rockspec_format = '1.0'\n
932        package = 'foo'\n
933        version = '1.0.0-1'\n
934        source = {\n
935            url = 'git+https://hub.com/owner/example-project/',\n
936            branch = 'bar',\n
937            tag = 'baz',\n
938        }\n
939        "
940        .to_string();
941        let _rockspec = Remote::new(&rockspec_content).unwrap_err();
942        let rockspec_content = "
943        rockspec_format = '1.0'\n
944        package = 'foo'\n
945        version = '1.0.0-1'\n
946        source = {\n
947            url = 'git+https://hub.com/owner/example-project/',\n
948            tag = 'bar',\n
949            file = 'foo.tar.gz',\n
950        }\n
951        build = {\n
952            install = {\n
953                conf = {['foo.bar'] = 'config/bar.toml'},\n
954            },\n
955        }\n
956        "
957        .to_string();
958        let rockspec = Remote::new(&rockspec_content).unwrap();
959        assert_eq!(
960            rockspec.local.source.default.archive_name,
961            Some("foo.tar.gz".into())
962        );
963        let foo_bar_path = rockspec
964            .local
965            .build
966            .default
967            .install
968            .conf
969            .get("foo.bar")
970            .unwrap();
971        assert_eq!(*foo_bar_path, PathBuf::from("config/bar.toml"));
972        let rockspec_content = "
973        rockspec_format = '1.0'\n
974        package = 'foo'\n
975        version = '1.0.0-1'\n
976        source = {\n
977            url = 'git+https://hub.com/example-project/foo.zip',\n
978        }\n
979        build = {\n
980            install = {\n
981                lua = {\n
982                    'foo.lua',\n
983                    ['foo.bar'] = 'src/bar.lua',\n
984                },\n
985                bin = {['foo.bar'] = 'bin/bar'},\n
986            },\n
987        }\n
988        "
989        .to_string();
990        let rockspec = Remote::new(&rockspec_content).unwrap();
991        assert!(matches!(
992            rockspec.local.build.default.backend,
993            Some(build::backend::Spec::Builtin { .. })
994        ));
995        let install_lua_spec = rockspec.local.build.default.install.lua;
996        let foo_bar_path = install_lua_spec
997            .get(&build::backend::Module::from_str("foo.bar").unwrap())
998            .unwrap();
999        assert_eq!(*foo_bar_path, PathBuf::from("src/bar.lua"));
1000        let foo_path = install_lua_spec
1001            .get(&build::backend::Module::from_str("foo").unwrap())
1002            .unwrap();
1003        assert_eq!(*foo_path, PathBuf::from("foo.lua"));
1004        let foo_bar_path = rockspec
1005            .local
1006            .build
1007            .default
1008            .install
1009            .bin
1010            .get("foo.bar")
1011            .unwrap();
1012        assert_eq!(*foo_bar_path, PathBuf::from("bin/bar"));
1013        let rockspec_content = "
1014        rockspec_format = '1.0'\n
1015        package = 'foo'\n
1016        version = '1.0.0-1'\n
1017        source = {\n
1018            url = 'git+https://hub.com/example-project/',\n
1019        }\n
1020        build = {\n
1021            copy_directories = { 'lua' },\n
1022        }\n
1023        "
1024        .to_string();
1025        let _rockspec = Remote::new(&rockspec_content).unwrap_err();
1026        let rockspec_content = "
1027        rockspec_format = '1.0'\n
1028        package = 'foo'\n
1029        version = '1.0.0-1'\n
1030        source = {\n
1031            url = 'git+https://hub.com/example-project/',\n
1032        }\n
1033        build = {\n
1034            copy_directories = { 'lib' },\n
1035        }\n
1036        "
1037        .to_string();
1038        let _rockspec = Remote::new(&rockspec_content).unwrap_err();
1039        let rockspec_content = "
1040        rockspec_format = '1.0'\n
1041        package = 'foo'\n
1042        version = '1.0.0-1'\n
1043        source = {\n
1044            url = 'git+https://hub.com/example-project/',\n
1045        }\n
1046        build = {\n
1047            copy_directories = { 'rock_manifest' },\n
1048        }\n
1049        "
1050        .to_string();
1051        let _rockspec = Remote::new(&rockspec_content).unwrap_err();
1052        let rockspec_content = "
1053        rockspec_format = '1.0'\n
1054        package = 'foo'\n
1055        version = '1.0.0-1'\n
1056        source = {\n
1057            url = 'git+https://hub.com/example-project/foo.zip',\n
1058            dir = 'baz',\n
1059        }\n
1060        build = {\n
1061            type = 'make',\n
1062            install = {\n
1063                lib = {['foo.so'] = 'lib/bar.so'},\n
1064            },\n
1065            copy_directories = {\n
1066                'plugin',\n
1067                'ftplugin',\n
1068            },\n
1069            patches = {\n
1070                ['lua51-support.diff'] = [[\n
1071                    --- before.c\n
1072                    +++ path/to/after.c\n
1073                ]],\n
1074            },\n
1075        }\n
1076        "
1077        .to_string();
1078        let rockspec = Remote::new(&rockspec_content).unwrap();
1079        assert_eq!(rockspec.local.source.default.unpack_dir, Some("baz".into()));
1080        assert_eq!(
1081            rockspec.local.build.default.backend,
1082            Some(build::backend::Spec::Make(build::backend::Make::default()))
1083        );
1084        let foo_bar_path = rockspec
1085            .local
1086            .build
1087            .default
1088            .install
1089            .lib
1090            .get("foo.so")
1091            .unwrap();
1092        assert_eq!(*foo_bar_path, PathBuf::from("lib/bar.so"));
1093        let copy_directories = rockspec.local.build.default.copy_directories;
1094        assert_eq!(
1095            copy_directories,
1096            vec![PathBuf::from("plugin"), PathBuf::from("ftplugin")]
1097        );
1098        let patches = rockspec.local.build.default.patches;
1099        let _patch = patches.get(&PathBuf::from("lua51-support.diff")).unwrap();
1100        let rockspec_content = "
1101        rockspec_format = '1.0'\n
1102        package = 'foo'\n
1103        version = '1.0.0-1'\n
1104        source = {\n
1105            url = 'git+https://hub.com/example-project/foo.zip',\n
1106        }\n
1107        build = {\n
1108            type = 'cmake',\n
1109        }\n
1110        "
1111        .to_string();
1112        let rockspec = Remote::new(&rockspec_content).unwrap();
1113        assert_eq!(
1114            rockspec.local.build.default.backend,
1115            Some(build::backend::Spec::CMake(build::backend::CMake::default()))
1116        );
1117        let rockspec_content = "
1118        rockspec_format = '1.0'\n
1119        package = 'foo'\n
1120        version = '1.0.0-1'\n
1121        source = {\n
1122            url = 'git+https://hub.com/example-project/foo.zip',\n
1123        }\n
1124        build = {\n
1125            type = 'command',\n
1126            build_command = 'foo',\n
1127            install_command = 'bar',\n
1128        }\n
1129        "
1130        .to_string();
1131        let rockspec = Remote::new(&rockspec_content).unwrap();
1132        assert!(matches!(
1133            rockspec.local.build.default.backend,
1134            Some(build::backend::Spec::Command(
1135                build::backend::Command { .. }
1136            ))
1137        ));
1138        let rockspec_content = "
1139        rockspec_format = '1.0'\n
1140        package = 'foo'\n
1141        version = '1.0.0-1'\n
1142        source = {\n
1143            url = 'git+https://hub.com/example-project/foo.zip',\n
1144        }\n
1145        build = {\n
1146            type = 'command',\n
1147            install_command = 'foo',\n
1148        }\n
1149        "
1150        .to_string();
1151        Remote::new(&rockspec_content).unwrap();
1152        let rockspec_content = "
1153        rockspec_format = '1.0'\n
1154        package = 'foo'\n
1155        version = '1.0.0-1'\n
1156        source = {\n
1157            url = 'git+https://hub.com/example-project/foo.zip',\n
1158        }\n
1159        build = {\n
1160            type = 'command',\n
1161            build_command = 'foo',\n
1162        }\n
1163        "
1164        .to_string();
1165        Remote::new(&rockspec_content).unwrap();
1166        // platform overrides
1167        let rockspec_content = "
1168        package = 'rocks'\n
1169        version = '3.0.0-1'\n
1170        dependencies = {\n
1171          'neorg ~> 6',\n
1172          'toml-edit ~> 1',\n
1173          platforms = {\n
1174            windows = {\n
1175              'neorg = 5.0.0',\n
1176              'toml = 1.0.0',\n
1177            },\n
1178            unix = {\n
1179              'neorg = 5.0.0',\n
1180            },\n
1181            linux = {\n
1182              'toml = 1.0.0',\n
1183            },\n
1184          },\n
1185        }\n
1186        source = {\n
1187            url = 'git+https://github.com/lumen-oss/rocks.nvim',\n
1188            hash = 'sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=',\n
1189        }\n
1190        "
1191        .to_string();
1192        let rockspec = Remote::new(&rockspec_content).unwrap();
1193        let neorg_override = package::Spec::parse("neorg".into(), "5.0.0".into()).unwrap();
1194        let toml_edit = package::Spec::parse("toml-edit".into(), "1.0.0".into()).unwrap();
1195        let toml = package::Spec::parse("toml".into(), "1.0.0".into()).unwrap();
1196        assert_eq!(rockspec.local.dependencies.default.len(), 2);
1197        let per_platform = &rockspec.local.dependencies.per_platform;
1198        assert_eq!(
1199            per_platform
1200                .get(&platform::Identifier::Windows)
1201                .unwrap()
1202                .iter()
1203                .filter(|dep| dep.matches(&neorg_override)
1204                    || dep.matches(&toml_edit)
1205                    || dep.matches(&toml))
1206                .count(),
1207            3
1208        );
1209        assert_eq!(
1210            per_platform
1211                .get(&platform::Identifier::Unix)
1212                .unwrap()
1213                .iter()
1214                .filter(|dep| dep.matches(&neorg_override)
1215                    || dep.matches(&toml_edit)
1216                    || dep.matches(&toml))
1217                .count(),
1218            2
1219        );
1220        assert_eq!(
1221            per_platform
1222                .get(&platform::Identifier::Linux)
1223                .unwrap()
1224                .iter()
1225                .filter(|dep| dep.matches(&neorg_override)
1226                    || dep.matches(&toml_edit)
1227                    || dep.matches(&toml))
1228                .count(),
1229            3
1230        );
1231        let rockspec_content = "
1232        package = 'rocks'\n
1233        version = '3.0.0-1'\n
1234        external_dependencies = {\n
1235            FOO = { library = 'foo' },\n
1236            platforms = {\n
1237              windows = {\n
1238                FOO = { library = 'foo.dll' },\n
1239              },\n
1240              unix = {\n
1241                BAR = { header = 'bar.h' },\n
1242              },\n
1243              linux = {\n
1244                FOO = { library = 'foo.so' },\n
1245              },\n
1246            },\n
1247        }\n
1248        source = {\n
1249            url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
1250        }\n
1251        "
1252        .to_string();
1253        let rockspec = Remote::new(&rockspec_content).unwrap();
1254        assert_eq!(
1255            *rockspec
1256                .local
1257                .external_dependencies
1258                .default
1259                .get("FOO")
1260                .unwrap(),
1261            external_dependency::Spec {
1262                library: Some("foo".into()),
1263                header: None
1264            }
1265        );
1266        let per_platform = rockspec.local.external_dependencies.per_platform;
1267        assert_eq!(
1268            *per_platform
1269                .get(&platform::Identifier::Windows)
1270                .and_then(|it| it.get("FOO"))
1271                .unwrap(),
1272            external_dependency::Spec {
1273                library: Some("foo.dll".into()),
1274                header: None
1275            }
1276        );
1277        assert_eq!(
1278            *per_platform
1279                .get(&platform::Identifier::Unix)
1280                .and_then(|it| it.get("FOO"))
1281                .unwrap(),
1282            external_dependency::Spec {
1283                library: Some("foo".into()),
1284                header: None
1285            }
1286        );
1287        assert_eq!(
1288            *per_platform
1289                .get(&platform::Identifier::Unix)
1290                .and_then(|it| it.get("BAR"))
1291                .unwrap(),
1292            external_dependency::Spec {
1293                header: Some("bar.h".into()),
1294                library: None
1295            }
1296        );
1297        assert_eq!(
1298            *per_platform
1299                .get(&platform::Identifier::Linux)
1300                .and_then(|it| it.get("BAR"))
1301                .unwrap(),
1302            external_dependency::Spec {
1303                header: Some("bar.h".into()),
1304                library: None
1305            }
1306        );
1307        assert_eq!(
1308            *per_platform
1309                .get(&platform::Identifier::Linux)
1310                .and_then(|it| it.get("FOO"))
1311                .unwrap(),
1312            external_dependency::Spec {
1313                library: Some("foo.so".into()),
1314                header: None
1315            }
1316        );
1317        let rockspec_content = "
1318        rockspec_format = '1.0'\n
1319        package = 'foo'\n
1320        version = '1.0.0-1'\n
1321        source = {\n
1322            url = 'git+https://hub.com/example-project/.git',\n
1323            branch = 'bar',\n
1324            platforms = {\n
1325                macosx = {\n
1326                    branch = 'mac',\n
1327                },\n
1328                windows = {\n
1329                    url = 'git+https://winhub.com/example-project/.git',\n
1330                    branch = 'win',\n
1331                },\n
1332            },\n
1333        }\n
1334        "
1335        .to_string();
1336        let rockspec = Remote::new(&rockspec_content).unwrap();
1337        assert_eq!(
1338            rockspec.local.source.default.source_spec,
1339            source::Spec::Git(git::Source {
1340                url: "https://hub.com/example-project/.git".parse().unwrap(),
1341                git_ref: Some(git::Ref::Branch("bar".into()))
1342            })
1343        );
1344        assert_eq!(
1345            rockspec
1346                .source
1347                .per_platform
1348                .get(&platform::Identifier::MacOSX)
1349                .map(|it| it.source_spec.clone())
1350                .unwrap(),
1351            source::Spec::Git(git::Source {
1352                url: "https://hub.com/example-project/.git".parse().unwrap(),
1353                git_ref: Some(git::Ref::Branch("mac".into()))
1354            })
1355        );
1356        assert_eq!(
1357            rockspec
1358                .source
1359                .per_platform
1360                .get(&platform::Identifier::Windows)
1361                .map(|it| it.source_spec.clone())
1362                .unwrap(),
1363            source::Spec::Git(git::Source {
1364                url: "https://winhub.com/example-project/.git".parse().unwrap(),
1365                git_ref: Some(git::Ref::Branch("win".into()))
1366            })
1367        );
1368        let rockspec_content = "
1369        rockspec_format = '1.0'\n
1370        package = 'foo'\n
1371        version = '1.0.0-1'\n
1372        source = { url = 'git+https://hub.com/example-project/foo.zip' }\n
1373        build = {\n
1374            type = 'make',\n
1375            install = {\n
1376                lib = {['foo.bar'] = 'lib/bar.so'},\n
1377            },\n
1378            copy_directories = { 'plugin' },\n
1379            platforms = {\n
1380                unix = {\n
1381                    copy_directories = { 'ftplugin' },\n
1382                },\n
1383                linux = {\n
1384                    copy_directories = { 'foo' },\n
1385                },\n
1386            },\n
1387        }\n
1388        "
1389        .to_string();
1390        let rockspec = Remote::new(&rockspec_content).unwrap();
1391        let per_platform = rockspec.local.build.per_platform;
1392        let unix = per_platform.get(&platform::Identifier::Unix).unwrap();
1393        assert_eq!(
1394            unix.copy_directories,
1395            vec![PathBuf::from("plugin"), PathBuf::from("ftplugin")]
1396        );
1397        let linux = per_platform.get(&platform::Identifier::Linux).unwrap();
1398        assert_eq!(
1399            linux.copy_directories,
1400            vec![
1401                PathBuf::from("plugin"),
1402                PathBuf::from("foo"),
1403                PathBuf::from("ftplugin")
1404            ]
1405        );
1406        let rockspec_content = "
1407        package = 'foo'\n
1408        version = '1.0.0-1'\n
1409        source = { url = 'git+https://hub.com/example-project/foo.zip' }\n
1410        build = {\n
1411            type = 'builtin',\n
1412            modules = {\n
1413                cjson = {\n
1414                    sources = { 'lua_cjson.c', 'strbuf.c', 'fpconv.c' },\n
1415                }\n
1416            },\n
1417            platforms = {\n
1418                win32 = { modules = { cjson = { defines = {\n
1419                    'DISABLE_INVALID_NUMBERS', 'USE_INTERNAL_ISINF'\n
1420                } } } }\n
1421            },\n
1422        }\n
1423        "
1424        .to_string();
1425        let rockspec = Remote::new(&rockspec_content).unwrap();
1426        let win32 = rockspec.local.build.get(&platform::Identifier::Windows);
1427        assert_eq!(
1428            win32.backend,
1429            Some(build::backend::Spec::Builtin(build::backend::Builtin {
1430                modules: vec![(
1431                    build::backend::Module::from_str("cjson").unwrap(),
1432                    build::backend::ModuleSpec::ModulePaths(build::backend::ModulePaths {
1433                        sources: vec!["lua_cjson.c".into(), "strbuf.c".into(), "fpconv.c".into()],
1434                        libraries: Vec::default(),
1435                        defines: vec![
1436                            ("DISABLE_INVALID_NUMBERS".into(), None),
1437                            ("USE_INTERNAL_ISINF".into(), None)
1438                        ],
1439                        incdirs: Vec::default(),
1440                        libdirs: Vec::default(),
1441                    })
1442                )]
1443                .into_iter()
1444                .collect()
1445            }))
1446        );
1447        let rockspec_content = "
1448        rockspec_format = '1.0'\n
1449        package = 'foo'\n
1450        version = '1.0.0-1'\n
1451        deploy = {\n
1452            wrap_bin_scripts = false,\n
1453        }\n
1454        source = { url = 'git+https://hub.com/example-project/foo.zip' }\n
1455        ";
1456        let rockspec = Remote::new(rockspec_content).unwrap();
1457        let deploy_spec = &rockspec.deploy().current_platform();
1458        assert!(!deploy_spec.wrap_bin_scripts);
1459    }
1460
1461    #[test]
1462    pub fn parse_scm_rockspec() {
1463        let rockspec_content = "
1464        package = 'foo'\n
1465        version = 'scm-1'\n
1466        source = {\n
1467            url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
1468        }\n
1469        "
1470        .to_string();
1471        let rockspec = Remote::new(&rockspec_content).unwrap();
1472        assert_eq!(rockspec.local.package, "foo".into());
1473        assert_eq!(rockspec.local.version, "scm-1".parse().unwrap());
1474    }
1475
1476    #[test]
1477    pub fn regression_luasystem() {
1478        let rockspec_content = String::from_utf8(
1479            std::fs::read(
1480                PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1481                    .join("resources/test/luasystem-0.4.4-1.rockspec"),
1482            )
1483            .unwrap(),
1484        )
1485        .unwrap();
1486        let rockspec = Remote::new(&rockspec_content).unwrap();
1487        let build_spec = rockspec.local.build.current_platform();
1488        assert!(matches!(
1489            build_spec.backend,
1490            Some(build::backend::Spec::Builtin { .. })
1491        ));
1492        if let Some(build::backend::Spec::Builtin(build::backend::Builtin { modules })) =
1493            &build_spec.backend
1494        {
1495            assert_eq!(
1496                modules.get(&build::backend::Module::from_str("system.init").unwrap()),
1497                Some(&build::backend::ModuleSpec::SourcePath(
1498                    "system/init.lua".into()
1499                ))
1500            );
1501            assert_eq!(
1502                modules.get(&build::backend::Module::from_str("system.core").unwrap()),
1503                Some(&build::backend::ModuleSpec::ModulePaths(
1504                    build::backend::ModulePaths {
1505                        sources: vec![
1506                            "src/core.c".into(),
1507                            "src/compat.c".into(),
1508                            "src/time.c".into(),
1509                            "src/environment.c".into(),
1510                            "src/random.c".into(),
1511                            "src/term.c".into(),
1512                            "src/bitflags.c".into(),
1513                            "src/wcwidth.c".into(),
1514                        ],
1515                        defines: luasystem_expected_defines(),
1516                        libraries: luasystem_expected_libraries(),
1517                        incdirs: luasystem_expected_incdirs(),
1518                        libdirs: luasystem_expected_libdirs(),
1519                    }
1520                ))
1521            );
1522        }
1523        if let Some(build::backend::Spec::Builtin(build::backend::Builtin { modules })) = &rockspec
1524            .local
1525            .build
1526            .get(&platform::Identifier::Windows)
1527            .backend
1528        {
1529            if let build::backend::ModuleSpec::ModulePaths(paths) = modules
1530                .get(&build::backend::Module::from_str("system.core").unwrap())
1531                .unwrap()
1532            {
1533                assert_eq!(paths.libraries, luasystem_expected_windows_libraries());
1534            };
1535        }
1536        if let Some(build::backend::Spec::Builtin(build::backend::Builtin { modules })) = &rockspec
1537            .local
1538            .build
1539            .get(&platform::Identifier::Win32)
1540            .backend
1541        {
1542            if let build::backend::ModuleSpec::ModulePaths(paths) = modules
1543                .get(&build::backend::Module::from_str("system.core").unwrap())
1544                .unwrap()
1545            {
1546                assert_eq!(paths.libraries, luasystem_expected_windows_libraries());
1547            };
1548        }
1549    }
1550
1551    fn luasystem_expected_defines() -> Vec<(String, Option<String>)> {
1552        if cfg!(target_os = "windows") {
1553            vec![
1554                ("WINVER".into(), Some("0x0600".into())),
1555                ("_WIN32_WINNT".into(), Some("0x0600".into())),
1556            ]
1557        } else {
1558            Vec::default()
1559        }
1560    }
1561
1562    fn luasystem_expected_windows_libraries() -> Vec<PathBuf> {
1563        vec!["advapi32".into(), "winmm".into()]
1564    }
1565    fn luasystem_expected_libraries() -> Vec<PathBuf> {
1566        if cfg!(any(target_os = "linux", target_os = "android")) {
1567            vec!["rt".into()]
1568        } else if cfg!(target_os = "windows") {
1569            luasystem_expected_windows_libraries()
1570        } else {
1571            Vec::default()
1572        }
1573    }
1574
1575    fn luasystem_expected_incdirs() -> Vec<PathBuf> {
1576        Vec::default()
1577    }
1578
1579    fn luasystem_expected_libdirs() -> Vec<PathBuf> {
1580        Vec::default()
1581    }
1582
1583    #[test]
1584    pub fn rust_mlua_rockspec() {
1585        let rockspec_content = "
1586    package = 'foo'\n
1587    version = 'scm-1'\n
1588    source = {\n
1589        url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
1590    }\n
1591    build = {
1592        type = 'rust-mlua',
1593        modules = {
1594            'foo',
1595            bar = 'baz',
1596        },
1597        target_path = 'path/to/cargo/target/directory',
1598        default_features = false,
1599        include = {
1600            'file.lua',
1601            ['path/to/another/file.lua'] = 'another-file.lua',
1602        },
1603        features = {'extra', 'features'},
1604    }
1605            ";
1606        let rockspec = Remote::new(rockspec_content).unwrap();
1607        let build_spec = rockspec.local.build.current_platform();
1608        if let Some(build::backend::Spec::RustMlua(build_spec)) = build_spec.backend.to_owned() {
1609            assert_eq!(
1610                build_spec.modules.get("foo").unwrap(),
1611                &PathBuf::from(format!("libfoo.{}", std::env::consts::DLL_EXTENSION))
1612            );
1613            assert_eq!(
1614                build_spec.modules.get("bar").unwrap(),
1615                &PathBuf::from(format!("libbaz.{}", std::env::consts::DLL_EXTENSION))
1616            );
1617            assert_eq!(
1618                build_spec.include.get(&PathBuf::from("file.lua")).unwrap(),
1619                &PathBuf::from("file.lua")
1620            );
1621            assert_eq!(
1622                build_spec
1623                    .include
1624                    .get(&PathBuf::from("path/to/another/file.lua"))
1625                    .unwrap(),
1626                &PathBuf::from("another-file.lua")
1627            );
1628        } else {
1629            panic!("Expected RustMlua build backend");
1630        }
1631    }
1632
1633    #[test]
1634    pub fn rust_binary_rockspec() {
1635        let rockspec_content = "
1636    package = 'foo'\n
1637    version = 'scm-1'\n
1638    source = {\n
1639        url = 'https://github.com/lumen-oss/rocks.nvim/archive/1.0.0/rocks.nvim.zip',\n
1640    }\n
1641    build = {\n
1642        type = 'rust-binary',\n
1643        package = 'foo',\n
1644        features = {'extra', 'features'},\n
1645    }\n
1646            ";
1647        let rockspec = Remote::new(rockspec_content).unwrap();
1648        let build_spec = rockspec.local.build.current_platform();
1649        if let Some(build::backend::Spec::RustBinary(build_spec)) = build_spec.backend.to_owned() {
1650            assert_eq!(build_spec.package, Some("foo".to_string()));
1651            assert_eq!(build_spec.features, vec!["extra", "features"]);
1652        } else {
1653            panic!("Expected RustBinary build backend");
1654        }
1655    }
1656
1657    #[tokio::test]
1658    pub async fn regression_ltui() {
1659        let content = String::from_utf8(
1660            std::fs::read(
1661                PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1662                    .join("resources/test/ltui-2.8-2.rockspec"),
1663            )
1664            .unwrap(),
1665        )
1666        .unwrap();
1667        Remote::new(&content).unwrap();
1668    }
1669
1670    // Luarocks allows the `install.bin` field to be a list, even though it
1671    // should only allow a table.
1672    #[test]
1673    pub fn regression_off_spec_install_binaries() {
1674        let rockspec_content = r#"
1675            package = "WSAPI"
1676            version = "1.7-1"
1677
1678            source = {
1679              url = "git://github.com/keplerproject/wsapi",
1680              tag = "v1.7",
1681            }
1682
1683            build = {
1684              type = "builtin",
1685              modules = {
1686                ["wsapi"] = "src/wsapi.lua",
1687              },
1688              -- Offending Line
1689              install = { bin = { "src/launcher/wsapi.cgi" } }
1690            }
1691        "#;
1692
1693        let rockspec = Remote::new(rockspec_content).unwrap();
1694
1695        assert_eq!(
1696            rockspec.build().current_platform().install.bin,
1697            HashMap::from([("wsapi.cgi".into(), PathBuf::from("src/launcher/wsapi.cgi"))])
1698        );
1699    }
1700
1701    #[test]
1702    pub fn regression_external_dependencies() {
1703        let content = String::from_utf8(
1704            std::fs::read(
1705                PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1706                    .join("resources/test/luaossl-20220711-0.rockspec"),
1707            )
1708            .unwrap(),
1709        )
1710        .unwrap();
1711        let rockspec = Remote::new(&content).unwrap();
1712        if cfg!(target_family = "unix") {
1713            assert_eq!(
1714                rockspec
1715                    .local
1716                    .external_dependencies
1717                    .current_platform()
1718                    .get("OPENSSL")
1719                    .unwrap(),
1720                &external_dependency::Spec {
1721                    library: Some("ssl".into()),
1722                    header: Some("openssl/ssl.h".into()),
1723                }
1724            );
1725        }
1726        let per_platform = rockspec.local.external_dependencies.per_platform;
1727        assert_eq!(
1728            *per_platform
1729                .get(&platform::Identifier::Windows)
1730                .and_then(|it| it.get("OPENSSL"))
1731                .unwrap(),
1732            external_dependency::Spec {
1733                library: Some("libeay32".into()),
1734                header: Some("openssl/ssl.h".into()),
1735            }
1736        );
1737    }
1738
1739    #[test]
1740    pub fn remote_lua_rockspec_from_package_and_source_spec() {
1741        let package_req = "foo@1.0.5".parse().unwrap();
1742        let source = git::Source {
1743            url: "https://hub.com/owner/example-project.git".parse().unwrap(),
1744            git_ref: Some(git::Ref::Tag("1.0.5".into())),
1745        };
1746        let source_spec = source::Spec::Git(source);
1747        let rockspec =
1748            Remote::from_source_spec(package_req, source_spec.clone(), Vec::new(), HashMap::new());
1749        let generated_rockspec_str = rockspec.local.raw_content;
1750        let rockspec2 = Remote::new(&generated_rockspec_str).unwrap();
1751        assert_eq!(rockspec2.local.package, "foo".into());
1752        assert_eq!(rockspec2.local.version, "1.0.5".parse().unwrap());
1753        assert_eq!(rockspec2.local.source, PerPlatform::new(source_spec.into()));
1754    }
1755
1756    #[test]
1757    pub fn regression_complex_source_field() {
1758        let rockspec_content = r#"
1759            package = "say"
1760            local rock_version = "1.4.1"
1761            local rock_release = "3"
1762            local namespace = "lunarmodules"
1763            local repository = package
1764
1765            version = ("%s-%s"):format(rock_version, rock_release)
1766
1767            source = {
1768              url = ("git+https://github.com/%s/%s.git"):format(namespace, repository),
1769              branch = rock_version == "scm" and "master" or nil,
1770              tag = rock_version ~= "scm" and "v"..rock_version or nil,
1771            }
1772
1773            description = {
1774              summary = "Lua string hashing/indexing library",
1775            }
1776
1777            dependencies = {
1778              "lua >= 5.1",
1779            }
1780
1781            build = {
1782              type = "builtin",
1783            }
1784        "#
1785        .to_string();
1786        Remote::new(&rockspec_content).unwrap();
1787    }
1788
1789    fn eval_lua_global<T: serde::de::DeserializeOwned>(code: &str, key: &'static str) -> T {
1790        use ottavino::{Closure, Executor, Fuel, Lua};
1791        use ottavino_util::serde::from_value;
1792        Lua::core()
1793            .try_enter(|ctx| {
1794                let closure = Closure::load(ctx, None, code.as_bytes())?;
1795                let executor = Executor::start(ctx, closure.into(), ());
1796                executor.step(ctx, &mut Fuel::with(i32::MAX))?;
1797                from_value(ctx.globals().get_value(ctx, key)).map_err(ottavino::Error::from)
1798            })
1799            .unwrap()
1800    }
1801
1802    #[test]
1803    pub fn rock_description_roundtrip() {
1804        let desc = description::Spec {
1805            summary: Some("A great package".into()),
1806            detailed: Some("Detailed description here".into()),
1807            license: Some("MIT".into()),
1808            homepage: Some("https://example.com".parse().unwrap()),
1809            issues_url: Some("https://example.com/issues".parse().unwrap()),
1810            maintainer: Some("Some Maintainer <maintainer@example.com>".into()),
1811            labels: vec!["neovim".into(), "lua".into()],
1812        };
1813        let lua = desc.display_lua().to_string();
1814        let restored: description::Spec = eval_lua_global(&lua, "description");
1815        assert_eq!(desc, restored);
1816    }
1817
1818    #[test]
1819    pub fn rock_description_empty_roundtrip() {
1820        let desc = description::Spec::default();
1821        let lua = desc.display_lua().to_string();
1822        // An empty description produces an empty assignment; restore from empty table.
1823        let lua = if lua.trim().is_empty() {
1824            "description = {}".to_string()
1825        } else {
1826            lua
1827        };
1828        let restored: description::Spec = eval_lua_global(&lua, "description");
1829        assert_eq!(desc, restored);
1830    }
1831
1832    #[test]
1833    pub fn regression_luasec() {
1834        let rockspec_content = r#"
1835package = "LuaSec"
1836version = "1.3.2-1"
1837source = {
1838  url = "git+https://github.com/brunoos/luasec",
1839  tag = "v1.3.2",
1840}
1841external_dependencies = {
1842   platforms = {
1843      unix = {
1844         OPENSSL = {
1845            header = "openssl/ssl.h",
1846            library = "ssl"
1847         }
1848      },
1849      windows = {
1850         OPENSSL = {
1851            header = "openssl/ssl.h",
1852         }
1853      },
1854   }
1855}
1856"#;
1857        let rockspec = Remote::new(rockspec_content).unwrap();
1858        let linux_external_deps = rockspec
1859            .external_dependencies()
1860            .get(&platform::Identifier::Linux);
1861        assert!(linux_external_deps.get("OPENSSL").is_some());
1862        let windows_external_deps = rockspec
1863            .external_dependencies()
1864            .get(&platform::Identifier::Windows);
1865        assert!(windows_external_deps.get("OPENSSL").is_some());
1866    }
1867
1868    #[test]
1869    pub fn find_value_span_spaces() {
1870        let source = "package = 'foo'\nversion = '1.0'";
1871        let span = find_value_span(source, "package");
1872        assert_eq!(&source[span.offset()..span.offset() + span.len()], "'foo'");
1873    }
1874
1875    #[test]
1876    pub fn find_value_span_no_spaces() {
1877        let source = "package='foo'";
1878        let span = find_value_span(source, "package");
1879        assert_eq!(&source[span.offset()..span.offset() + span.len()], "'foo'");
1880    }
1881
1882    #[test]
1883    pub fn find_value_span_returns_empty_when_not_found() {
1884        let source = "version = '1.0'";
1885        let span = find_value_span(source, "package");
1886        assert_eq!(span.len(), 0);
1887    }
1888
1889    #[test]
1890    pub fn find_value_span_skips_url_containing_field() {
1891        let source = "homepage = 'https://luapackager.com'\npackage = 'foo'";
1892        let span = find_value_span(source, "package");
1893        assert_eq!(&source[span.offset()..span.offset() + span.len()], "'foo'");
1894    }
1895
1896    #[test]
1897    pub fn find_value_span_double_quoted() {
1898        let source = r#"package = "foo""#;
1899        let span = find_value_span(source, "package");
1900        assert_eq!(
1901            &source[span.offset()..span.offset() + span.len()],
1902            r#""foo""#
1903        );
1904    }
1905
1906    #[test]
1907    pub fn find_value_span_table() {
1908        let source = "description = {\n    summary = 'bar'\n}";
1909        let span = find_value_span(source, "description");
1910        assert_eq!(&source[span.offset()..span.offset() + span.len()], "{");
1911    }
1912
1913    #[test]
1914    pub fn parse_lua_rockspec_field_error() {
1915        let rockspec_content = "package = 'my-lua-lib'\nfoo = 123";
1916        let extern_err = ottavino::Lua::core()
1917            .try_enter(|_ctx| {
1918                Err(ParseLuaRockspecFieldError::Deserialize {
1919                    field: "foo".into(),
1920                    source: Box::new(ottavino_util::serde::de::Error::Message(
1921                        "expected bar".into(),
1922                    )),
1923                })?;
1924                Ok(())
1925            })
1926            .unwrap_err();
1927        let err = Error::from_ottavino(extern_err, rockspec_content);
1928        match err {
1929            Error::ExecutionError {
1930                cause,
1931                err_span: Some(span),
1932                ..
1933            } => {
1934                assert!(cause.contains("invalid rockspec field 'foo'"));
1935                assert_eq!(
1936                    &rockspec_content[span.offset()..span.offset() + span.len()],
1937                    "foo"
1938                );
1939            }
1940            other => panic!("expected ExecutionError with err_span, got: {other:?}"),
1941        }
1942        let extern_err = ottavino::Lua::core()
1943            .try_enter(|_ctx| {
1944                Err(ParseLuaRockspecFieldError::DeserializeTable {
1945                    field: "foo".into(),
1946                    source: Box::new(ottavino_util::serde::de::Error::Message(
1947                        "expected bar".into(),
1948                    )),
1949                })?;
1950                Ok(())
1951            })
1952            .unwrap_err();
1953        let err = Error::from_ottavino(extern_err, rockspec_content);
1954        match err {
1955            Error::ExecutionError {
1956                cause,
1957                err_span: Some(span),
1958                ..
1959            } => {
1960                assert!(cause.contains("invalid rockspec field 'foo'"));
1961                assert_eq!(
1962                    &rockspec_content[span.offset()..span.offset() + span.len()],
1963                    "foo"
1964                );
1965            }
1966            other => panic!("expected ExecutionError with err_span, got: {other:?}"),
1967        }
1968        let extern_err = ottavino::Lua::core()
1969            .try_enter(|_ctx| {
1970                Err(ParseLuaRockspecFieldError::NotATable {
1971                    field: "foo".into(),
1972                    invalid_type: "integer".into(),
1973                })?;
1974                Ok(())
1975            })
1976            .unwrap_err();
1977        let err = Error::from_ottavino(extern_err, rockspec_content);
1978        match err {
1979            Error::ExecutionError {
1980                cause,
1981                err_span: Some(span),
1982                ..
1983            } => {
1984                assert!(cause.contains("invalid rockspec field 'foo'"));
1985                assert_eq!(
1986                    &rockspec_content[span.offset()..span.offset() + span.len()],
1987                    "foo"
1988                );
1989            }
1990            other => panic!("expected ExecutionError with err_span, got: {other:?}"),
1991        }
1992    }
1993}