Skip to main content

lux_lib/rockspec/toml/
mod.rs

1//! Structs and utilities for `lux.toml`
2
3use crate::fs;
4use crate::git;
5use crate::git::shorthand::RemoteGitUrlShorthand;
6use crate::hash::HasIntegrity;
7use crate::lockfile::OptState;
8use crate::lockfile::PinnedState;
9use crate::lua;
10use crate::operations::run;
11use crate::package;
12use crate::project::TomlDeError;
13use crate::rockspec;
14use crate::rockspec::display::AsLuaKV;
15use crate::rockspec::lua_dependency;
16use crate::ROCKSPEC_FUEL_LIMIT;
17use std::io;
18use std::path::Path;
19use std::{collections::HashMap, path::PathBuf};
20
21use crate::{
22    build::autodetect_modules,
23    config::Config,
24    package::{BuildDependencies, Dependencies},
25    rockspec::{LuaVersionCompatibility, Rockspec},
26};
27use itertools::Itertools;
28use miette::Diagnostic;
29use nonempty::NonEmpty;
30
31use crate::wally;
32use serde::de;
33use serde::{Deserialize, Deserializer};
34use ssri::Integrity;
35use thiserror::Error;
36
37mod gen;
38mod validate;
39
40use self::gen::PackageVersionTemplate;
41use self::gen::RockSourceTemplate;
42pub use self::gen::{GenerateSourceError, GenerateVersionError};
43use crate::project::TOML_FILE_NAME;
44
45#[derive(Deserialize)]
46#[serde(untagged)]
47#[allow(clippy::large_enum_variant)] // This is ok because it's just a Deserialize helper
48enum DependencyEntry {
49    Simple(package::VersionReq),
50    Detailed(DependencyTableEntry),
51}
52
53#[derive(Debug, Deserialize)]
54struct DependencyTableEntry {
55    #[serde(default)]
56    version: Option<package::VersionReq>,
57    #[serde(default)]
58    opt: Option<bool>,
59    #[serde(default)]
60    pin: Option<bool>,
61    #[serde(default)]
62    git: Option<RemoteGitUrlShorthand>,
63    #[serde(default)]
64    path: Option<PathBuf>,
65    #[serde(default)]
66    rev: Option<String>,
67    #[serde(default)]
68    wally: Option<wally::package::Req>,
69}
70
71fn parse_map_to_dependency_vec_opt<'de, D>(
72    deserializer: D,
73) -> Result<Option<Vec<lua_dependency::Spec>>, D::Error>
74where
75    D: Deserializer<'de>,
76{
77    let packages: Option<HashMap<package::Name, DependencyEntry>> =
78        Option::deserialize(deserializer)?;
79
80    match packages {
81        None => Ok(None),
82        Some(packages) => Ok(Some(
83            packages
84                .into_iter()
85                .map(|(name, spec)| match spec {
86                    DependencyEntry::Simple(version_req) => {
87                        Ok(package::Req { name, version_req }.into())
88                    }
89                    DependencyEntry::Detailed(entry) => {
90                        let DependencyTableEntry {
91                            version,
92                            opt,
93                            pin,
94                            git,
95                            path,
96                            rev,
97                            wally,
98                        } = entry;
99
100                        let (version_req, source) = if let Some(wally) = wally {
101                            if version.is_some() || git.is_some() || rev.is_some() || path.is_some() {
102                                return Err(de::Error::custom(format!(
103                                    "dependency '{}' specifies 'wally', which cannot be combined with 'version', 'git', 'rev', or 'path'",
104                                    name
105                                )));
106                            }
107                            (
108                                package::VersionReq::SemVer(wally.version_req().clone()),
109                                Some(rockspec::source::Spec::Wally(wally)),
110                            )
111                        } else {
112                            let version = version.ok_or_else(|| {
113                                de::Error::custom(format!(
114                                    "dependency '{name}' is missing a 'version' or 'wally' field"
115                                ))
116                            })?;
117                            let source = match (git, rev, path) {
118                                (None, None, None) => Ok(None),
119                                (None, Some(_), None) => Err(de::Error::custom(format!(
120                                    "dependency {} specifies a 'rev', but missing a 'git' field",
121                                    name
122                                ))),
123                                (Some(git), Some(rev), None) => {
124                                    Ok(Some(rockspec::source::Spec::Git(git::Source {
125                                        url: git.into(),
126                                        git_ref: Some(git::Ref::Tag(rev)),
127                                    })))
128                                }
129                                (Some(git), None, None) => Ok(Some(rockspec::source::Spec::Git(git::Source {
130                                    url: git.into(),
131                                    git_ref: Some(git::Ref::Tag(
132                                        version
133                                            .clone()
134                                            .to_string()
135                                            .trim_start_matches("=")
136                                            .to_string(),
137                                    )),
138                                }))),
139                                (None, None, Some(path)) => Ok(Some(rockspec::source::Spec::File(path))),
140                                (_, _, Some(_)) => Err(de::Error::custom(format!(
141                                    "dependency '{}' specifies a 'path', which cannot be combined with 'git' or 'rev'",
142                                    name
143                                ))),
144                            }?;
145                            (version, source)
146                        };
147
148                        Ok(lua_dependency::Spec {
149                            package_req: package::Req { name, version_req },
150                            opt: OptState::from(opt.unwrap_or(false)),
151                            pin: PinnedState::from(pin.unwrap_or(false)),
152                            source,
153                        })
154                    }
155                })
156                .try_collect()?,
157        )),
158    }
159}
160
161#[derive(Debug, Error, Diagnostic)]
162pub enum Error {
163    #[error("error generating rockspec source")]
164    #[diagnostic(forward(0))]
165    GenerateSource(#[from] GenerateSourceError),
166    #[error("error generating rockspec version")]
167    #[diagnostic(forward(0))]
168    GenerateVersion(#[from] GenerateVersionError),
169    #[error("generated rockspec exceeds computational limit of {ROCKSPEC_FUEL_LIMIT} steps")]
170    #[diagnostic(help(
171        r#"the rockspec may be too complex or contain too many dependencies.
172        Try reducing the number of dependencies or simplifying build instructions."#
173    ))]
174    FuelLimitExceeded,
175    #[error(
176        r#"generated invalid Lua from TOML:
177{0}
178"#
179    )]
180    #[diagnostic(help("this is a bug in Lux. please report it."))]
181    GeneratedInvalidLua(String),
182    #[error("no lua version provided")]
183    #[diagnostic(help(
184        r#"add a `lua` field to your lux.toml, for example:
185
186  lua = ">=5.1""#
187    ))]
188    NoLuaVersion,
189    #[error("could not decode the test spec")]
190    #[diagnostic(forward(0))]
191    Decode(#[from] rockspec::test::DecodeError),
192    #[error("could not decode the build spec")]
193    #[diagnostic(forward(0))]
194    Build(#[from] rockspec::build::internal::Error),
195    #[error(transparent)]
196    #[diagnostic(transparent)]
197    PlatformValidation(#[from] rockspec::platform::Error),
198    #[error("{}copy_directories cannot contain a rockspec name", ._0.as_ref().map(|p| format!("{p}: ")).unwrap_or_default())]
199    CopyDirectoriesContainRockspecName(Option<String>),
200    #[error("could not decode the source spec")]
201    #[diagnostic(forward(0))]
202    RockSource(#[from] rockspec::source::Error),
203    #[error("duplicate dependencies: {0}")]
204    #[diagnostic(help("remove the duplicate entries from the [dependencies] table."))]
205    DuplicateDependencies(package::List),
206    #[error("duplicate test dependencies: {0}")]
207    #[diagnostic(help("remove the duplicate entries from the [test_dependencies] table."))]
208    DuplicateTestDependencies(package::List),
209    #[error("duplicate build dependencies: {0}")]
210    #[diagnostic(help("remove the duplicate entries from the [build_dependencies] table."))]
211    DuplicateBuildDependencies(package::List),
212    #[error(
213        r#"dependencies field cannot contain 'lua'.
214        Please provide the version in the top-level 'lua' field
215
216        Example:
217
218        ```toml
219        package = "my-package"
220        lua = ">=5.1"
221
222        [dependencies]
223        # do not add Lua here!
224        ```
225        "#
226    )]
227    DependenciesContainLua,
228}
229
230/// The `lux.toml` file for a project.
231/// The only required fields are `package` and `build`, which are required to build a project using `lux build`.
232/// The rest of the fields are optional, but are required to build a rockspec.
233#[derive(Clone, Debug, Deserialize)]
234#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
235pub struct Partial {
236    /// The name of the rock. Lux converts it to lower case when publishing.
237    #[cfg_attr(
238        feature = "schema",
239        schemars(extend("x-lux-toml-example" = r#"package = "my-lua-project""#))
240    )]
241    pub(crate) package: package::Name,
242    /// The package version. If unset, Lux derives it from the current SemVer
243    /// git tag (optional `v` prefix), falling back to "dev".
244    ///
245    /// Versions like `1.0` are corrected to `1.0.0`.
246    /// Non-SemVer versions (e.g. `1.0-rc1` instead of `1.0.0-rc1`) are treated
247    /// as Dev versions and cannot be compared with SemVer versions.
248    #[serde(default, rename = "version")]
249    #[cfg_attr(feature = "schema", schemars(with = "String"))]
250    #[cfg_attr(
251        feature = "schema",
252        schemars(extend("x-lux-toml-example" = r#"version = "1.0.0""#))
253    )]
254    pub(crate) version_template: PackageVersionTemplate,
255    /// How to build the project. See the build backend fields below.
256    ///
257    /// Rocks with C sources require a C compiler. Lux does not bundle one.
258    #[serde(default)]
259    pub(crate) build: rockspec::build::internal::Spec,
260    /// The LuaRocks rockspec format version to write to the generated rockspec ("1.0", "2.0", or "3.0").
261    /// Default: "3.0".
262    #[cfg_attr(
263        feature = "schema",
264        schemars(extend("x-lux-toml-example" = r#"rockspec_format = "3.0""#))
265    )]
266    pub(crate) rockspec_format: Option<rockspec::Format>,
267    /// How to run the project with `lx run`.
268    #[serde(default)]
269    #[cfg_attr(
270        feature = "schema",
271        schemars(extend("x-lux-toml-example" = r#"
272[run]
273args = ["src/main.lua"]
274"#))
275    )]
276    pub(crate) run: Option<RunSpec>,
277    /// The Lua version requirement, e.g. ">= 5.1". Required to build a rockspec.
278    /// Set to "luau" to build and run the project with Luau.
279    #[serde(default)]
280    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
281    #[cfg_attr(
282        feature = "schema",
283        schemars(extend("x-lux-toml-example" = r#"lua = ">=5.1""#))
284    )]
285    pub(crate) lua: Option<package::VersionReq>,
286    /// Metadata published to LuaRocks.
287    #[serde(default)]
288    #[cfg_attr(
289        feature = "schema",
290        schemars(extend("x-lux-toml-example" = r#"
291[description]
292summary = "A one-line description of the package"
293detailed = """
294A longer description of the package
295that often spans multiple lines.
296"""
297license = "GPLv2"
298homepage = "https://lumen-oss.github.io"
299issues_url = "https://github.com/lumen-oss/lux/issues"
300maintainer = "neorocks org"
301labels = ["neovim", "tls", "https"]
302"#))
303    )]
304    pub(crate) description: Option<rockspec::description::Spec>,
305    /// Platforms this rock supports, mapping platform identifiers to `true` or
306    /// `false` (e.g. `linux = true`).
307    #[serde(default)]
308    #[cfg_attr(
309        feature = "schema",
310        schemars(with = "Option<std::collections::BTreeMap<String, bool>>")
311    )]
312    #[cfg_attr(
313        feature = "schema",
314        schemars(extend("x-lux-toml-example" = r#"
315[supported_platforms]
316linux = true
317windows = false
318"#))
319    )]
320    pub(crate) supported_platforms: Option<HashMap<rockspec::platform::Identifier, bool>>,
321    /// Runtime Lua dependencies, mapping package names to a version requirement
322    /// (e.g. `foo = "1.0"`) or to a detailed table with `version`, `opt`, `pin`,
323    /// `git`, `rev`, and `path` keys.
324    ///
325    /// Version requirements support the operators `==`, `~=`, `<`, `>`, `<=`,
326    /// `>=`, and `~>`. `~> 2` means `>= 2, < 3`. An operator is optional;
327    /// without one, the requirement is treated as `==`. Version requirements
328    /// are mandatory.
329    ///
330    /// Dependencies are declared under `lua`, `[dependencies]`,
331    /// `[build_dependencies]`, `[test_dependencies]`, and
332    /// `[external_dependencies]`.
333    ///
334    /// Git dependencies support the `github:` (default), `gitlab:`,
335    /// `codeberg:`, and `sourcehut:` shorthands, as well as full HTTPS and SSH
336    /// URLs. If `rev` is unset, `version` is used as the commit SHA or tag.
337    /// Lux searches the repository root for a `lux.toml` or `.rockspec` to
338    /// determine the build specification, defaulting to `builtin` if none is
339    /// found. Rocks with git dependencies cannot be published to LuaRocks. Git
340    /// dependencies that require a custom LuaRocks build backend are not
341    /// supported.
342    #[serde(default, deserialize_with = "parse_map_to_dependency_vec_opt")]
343    #[cfg_attr(
344        feature = "schema",
345        schemars(
346            with = "Option<std::collections::BTreeMap<String, crate::schema::DependencyEntry>>"
347        )
348    )]
349    #[cfg_attr(
350        feature = "schema",
351        schemars(extend("x-lux-toml-example" = r#"
352[dependencies]
353luafilesystem = "1.0.0"
354
355[dependencies.argparse]
356version = "0.7"
357opt = true
358
359[dependencies.foo]
360version = "09511782201302ade916d4b250d01a6c61b56844"
361git = "github:lunarmodules/foo"
362
363[dependencies.bar]
364path = "../bar"
365version = "1.0.0"
366"#))
367    )]
368    pub(crate) dependencies: Option<Vec<lua_dependency::Spec>>,
369    /// Dependencies needed at build time. Same syntax as `dependencies`.
370    #[serde(default, deserialize_with = "parse_map_to_dependency_vec_opt")]
371    #[cfg_attr(
372        feature = "schema",
373        schemars(
374            with = "Option<std::collections::BTreeMap<String, crate::schema::DependencyEntry>>"
375        )
376    )]
377    pub(crate) build_dependencies: Option<Vec<lua_dependency::Spec>>,
378    /// System (C/FFI) dependencies, discovered via pkg-config. Each entry may
379    /// set `header` and/or `library`.
380    #[serde(default)]
381    #[cfg_attr(
382        feature = "schema",
383        schemars(extend("x-lux-toml-example" = r#"
384[external_dependencies.OPENSSL]
385header = "openssl/ssl.h"
386library = "ssl"
387"#))
388    )]
389    pub(crate) external_dependencies: Option<HashMap<String, rockspec::external_dependency::Spec>>,
390    /// Dependencies needed when running `lx test`. Same syntax as `dependencies`.
391    #[serde(default, deserialize_with = "parse_map_to_dependency_vec_opt")]
392    #[cfg_attr(
393        feature = "schema",
394        schemars(
395            with = "Option<std::collections::BTreeMap<String, crate::schema::DependencyEntry>>"
396        )
397    )]
398    #[cfg_attr(
399        feature = "schema",
400        schemars(extend("x-lux-toml-example" = r#"
401[test_dependencies]
402busted = ">=2.0.0"
403nlua = "~>0.3"
404"#))
405    )]
406    pub(crate) test_dependencies: Option<Vec<lua_dependency::Spec>>,
407    /// Templates for generating the source URL of a release.
408    ///
409    /// Variable substitutions:
410    /// - `$(PACKAGE)`: package name
411    /// - `$(VERSION)`: package version (from the git tag if not declared)
412    /// - `$(REF)`: git tag or revision (priority: SemVer tag, tag, commit SHA)
413    /// - `$(<VAR_NAME>)`: any environment variable
414    #[serde(default, rename = "source")]
415    #[cfg_attr(
416        feature = "schema",
417        schemars(extend("x-lux-toml-example" = r#"
418[source]
419url = "https://host.com/owner/$(PACKAGE)/archive/refs/tags/$(REF).zip"
420dev = "git+https://host.com/owner/$(PACKAGE).git"
421"#))
422    )]
423    pub(crate) source_template: RockSourceTemplate,
424    /// How to run the test suite with `lx test`.
425    ///
426    /// The `busted` backend is used when a `.busted` file exists and no backend
427    /// is specified. `busted-nlua` is used when a `.busted` file exists or
428    /// `busted` and `nlua` are `test_dependencies`. The `busted-nlua` backend is
429    /// currently broken on macOS and Windows. Luau projects default to `tiniest`.
430    #[serde(default)]
431    #[cfg_attr(
432        feature = "schema",
433        schemars(extend("x-lux-toml-example" = r#"
434[test]
435type = "busted"
436flags = []
437"#))
438    )]
439    pub(crate) test: Option<rockspec::test::internal::Spec>,
440    /// Additional install and deployment options.
441    #[serde(default)]
442    #[cfg_attr(
443        feature = "schema",
444        schemars(extend("x-lux-toml-example" = r#"
445[deploy]
446wrap_bin_scripts = false
447"#))
448    )]
449    pub(crate) deploy: Option<rockspec::deploy::Spec>,
450    /// Lux-specific project settings, ignored when generating a rockspec.
451    #[serde(default)]
452    #[cfg_attr(
453        feature = "schema",
454        schemars(extend("x-lux-toml-example" = r#"
455[project]
456root_dir = ".."
457"#))
458    )]
459    pub(crate) project: ProjectSpec,
460
461    /// Used to bind the TOML to the directory containing the `lux.toml`.
462    #[serde(skip, default = "PathBuf::new")]
463    lux_toml_dir: PathBuf,
464}
465
466impl HasIntegrity for Partial {
467    async fn hash(&self) -> io::Result<Integrity> {
468        let toml_file = self.lux_toml_dir.join(TOML_FILE_NAME);
469        let content = fs::sync::read_to_string(&toml_file).map_err(io::Error::other)?;
470        Ok(Integrity::from(&content))
471    }
472}
473
474impl Partial {
475    pub(crate) fn new(name: &str, str: &str, lux_toml_dir: PathBuf) -> Result<Self, TomlDeError> {
476        let mut this: Self = crate::project::parse_toml(name, str)?;
477        this.lux_toml_dir = lux_toml_dir.to_path_buf();
478        this.project.root = match this.project.root_dir {
479            Some(ref root_dir) => {
480                let relative_project_root = lux_toml_dir.join(root_dir);
481                std::fs::canonicalize(&relative_project_root).unwrap_or(relative_project_root)
482            }
483            None => lux_toml_dir,
484        };
485        Ok(this)
486    }
487
488    /// This project's Lua version requirement, if any
489    pub fn lua(&self) -> Option<&package::VersionReq> {
490        self.lua.as_ref()
491    }
492
493    // In the not-yet-validated struct, we create getters only
494    // for the non-optional fields.
495    pub fn package(&self) -> &package::Name {
496        &self.package
497    }
498
499    /// Returns the current package version, which may be generated from a template
500    pub fn version(&self) -> Result<package::Version, GenerateVersionError> {
501        self.version_template.try_generate(&self.lux_toml_dir, None)
502    }
503
504    /// Merge the `ProjectToml` struct with an unvalidated `LuaRockspec`.
505    /// The final merged struct can then be validated.
506    pub fn merge(self, other: rockspec::lua::Partial) -> Self {
507        Partial {
508            package: other.package.unwrap_or(self.package),
509            version_template: self.version_template,
510            lua: other
511                .dependencies
512                .as_ref()
513                .and_then(|deps| {
514                    deps.iter()
515                        .find(|dep| dep.name() == &"lua".into())
516                        .and_then(|dep| {
517                            if dep.version_req().is_any() {
518                                None
519                            } else {
520                                Some(dep.version_req().clone())
521                            }
522                        })
523                })
524                .or(self.lua),
525            build: other.build.unwrap_or(self.build),
526            run: self.run,
527            description: other.description.or(self.description),
528            supported_platforms: other
529                .supported_platforms
530                .map(|platform_support| platform_support.platforms().clone())
531                .or(self.supported_platforms),
532            dependencies: other
533                .dependencies
534                .map(|deps| {
535                    deps.into_iter()
536                        .filter(|dep| dep.name() != &"lua".into())
537                        .collect()
538                })
539                .or(self.dependencies),
540            build_dependencies: other.build_dependencies.or(self.build_dependencies),
541            test_dependencies: other.test_dependencies.or(self.test_dependencies),
542            external_dependencies: other.external_dependencies.or(self.external_dependencies),
543            source_template: self.source_template,
544            test: other.test.or(self.test),
545            deploy: other.deploy.or(self.deploy),
546            rockspec_format: other.format.or(self.rockspec_format),
547
548            // Keep the project root the same, as it is not part of the lua rockspec
549            project: self.project,
550            lux_toml_dir: self.lux_toml_dir.clone(),
551        }
552    }
553
554    fn resolve_lua_dependency_spec(&self, dep: lua_dependency::Spec) -> lua_dependency::Spec {
555        match &dep.source {
556            Some(rockspec::source::Spec::File(path)) if path.is_dir() => dep,
557            Some(rockspec::source::Spec::File(path)) => lua_dependency::Spec {
558                source: Some(rockspec::source::Spec::File(self.lux_toml_dir.join(path))),
559                ..dep
560            },
561            _ => dep,
562        }
563    }
564}
565
566// This is automatically implemented for `Remote`,
567// but we also add a special implementation for `ProjectToml` (as providing a lua version
568// is required even by the non-validated struct).
569impl LuaVersionCompatibility for Partial {
570    fn validate_lua_version(&self, version: &lua::Version) -> Result<(), rockspec::Error> {
571        if self.supports_lua_version(version) {
572            Ok(())
573        } else {
574            Err(rockspec::Error::UnsupportedLuaVersion(
575                version.clone(),
576                self.package().to_owned(),
577                Box::new(
578                    self.version_template
579                        .try_generate(&self.lux_toml_dir, None)
580                        .unwrap_or(package::Version::default_dev_version()),
581                ),
582            ))
583        }
584    }
585
586    fn validate_lua_version_from_config(&self, config: &Config) -> Result<(), rockspec::Error> {
587        let _ = self.lua_version_matches(config)?;
588        Ok(())
589    }
590
591    fn lua_version_matches(&self, config: &Config) -> Result<lua::Version, rockspec::Error> {
592        let version = lua::Version::from(config)?.clone();
593        if self.supports_lua_version(&version) {
594            Ok(version)
595        } else {
596            Err(rockspec::Error::UnsupportedLuaVersion(
597                version,
598                self.package.clone(),
599                Box::new(
600                    self.version_template
601                        .try_generate(&self.lux_toml_dir, None)
602                        .unwrap_or(package::Version::default_dev_version()),
603                ),
604            ))
605        }
606    }
607
608    fn supports_lua_version(&self, lua_version: &lua::Version) -> bool {
609        self.lua.as_ref().is_none_or(|lua| {
610            if lua.is_luau() {
611                return matches!(lua_version, lua::Version::Luau);
612            }
613            lua.matches(&lua_version.as_version())
614        })
615    }
616
617    fn lua_version(&self) -> Option<lua::Version> {
618        if self.lua.as_ref().is_some_and(|lua| lua.is_luau()) {
619            return Some(lua::Version::Luau);
620        }
621        for (possibility, version) in [
622            ("5.5.0", lua::Version::Lua55),
623            ("5.4.0", lua::Version::Lua54),
624            ("5.3.0", lua::Version::Lua53),
625            ("5.2.0", lua::Version::Lua52),
626            ("5.1.0", lua::Version::Lua51),
627        ] {
628            let possibility = unsafe { possibility.parse().unwrap_unchecked() };
629            if self
630                .lua
631                .as_ref()
632                .is_none_or(|lua| lua.matches(&possibility))
633            {
634                return Some(version);
635            }
636        }
637        None
638    }
639}
640
641/// Lux-specific project configuration.
642///
643/// This is not part of the rockspec format and is ignored when generating a rockspec.
644#[derive(Debug, Clone, Deserialize)]
645#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
646pub(crate) struct ProjectSpec {
647    /// The project root directory, relative to the directory containing the `lux.toml`.
648    /// Useful for multi-project workspaces, where the build files
649    /// (e.g. the cargo workspace `Cargo.toml`) do not live next to the `lux.toml`.
650    root_dir: Option<PathBuf>,
651    /// The project root directory, resolved from `root_dir` when deserializing.
652    #[serde(skip, default)]
653    pub(crate) root: PathBuf,
654}
655
656impl Default for ProjectSpec {
657    fn default() -> Self {
658        Self {
659            root_dir: None,
660            root: PathBuf::new(),
661        }
662    }
663}
664
665// TODO(vhyrro): Move this struct into a different directory.
666#[derive(Debug, Clone, Deserialize)]
667#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
668pub struct RunSpec {
669    /// The command to execute when running the project
670    pub(crate) command: Option<run::Command>,
671    /// Arguments to pass to the command
672    #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
673    pub(crate) args: Option<NonEmpty<String>>,
674}
675
676/// The `lux.toml` file, after being properly deserialized.
677/// This struct may be used to build a local version of a project.
678/// To build a rockspec, use `Remote`.
679#[derive(Debug)]
680pub struct Local {
681    package: package::Name,
682    version: package::Version,
683    lua: package::VersionReq,
684    rockspec_format: Option<rockspec::Format>,
685    run: Option<rockspec::PerPlatform<RunSpec>>,
686    description: rockspec::description::Spec,
687    supported_platforms: rockspec::platform::Support,
688    dependencies: rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>,
689    build_dependencies: rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>,
690    external_dependencies:
691        rockspec::PerPlatform<HashMap<String, rockspec::external_dependency::Spec>>,
692    test_dependencies: rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>,
693    test: rockspec::PerPlatform<rockspec::test::Spec>,
694    build: rockspec::PerPlatform<rockspec::build::Spec>,
695    deploy: rockspec::PerPlatform<rockspec::deploy::Spec>,
696
697    // Used for simpler serialization
698    internal: Partial,
699
700    /// A source pointing to the current project's root.
701    source: rockspec::PerPlatform<rockspec::source::Remote>,
702}
703
704impl Local {
705    pub fn run(&self) -> Option<&rockspec::PerPlatform<RunSpec>> {
706        self.run.as_ref()
707    }
708
709    /// Convert this project TOML to a Lua rockspec.
710    /// Fails if there is no valid project root or if there are off-spec dependencies.
711    pub fn to_lua_rockspec(&self) -> Result<rockspec::lua::Local, rockspec::Error> {
712        if let Some(dep) = self
713            .dependencies()
714            .per_platform
715            .values()
716            .filter_map(|deps| deps.iter().find(|dep| dep.source().is_some()))
717            .collect_vec()
718            .first()
719        {
720            return Err(rockspec::lua::Error::OffSpecSpec(dep.name().clone()).into());
721        }
722        if let Some(dep) = self
723            .build_dependencies()
724            .per_platform
725            .values()
726            .filter_map(|deps| deps.iter().find(|dep| dep.source().is_some()))
727            .collect_vec()
728            .first()
729        {
730            return Err(rockspec::lua::Error::OffSpecBuildSpec(dep.name().clone()).into());
731        }
732        if let Some(dep) = self
733            .test_dependencies()
734            .per_platform
735            .values()
736            .filter_map(|deps| deps.iter().find(|dep| dep.source().is_some()))
737            .collect_vec()
738            .first()
739        {
740            return Err(rockspec::lua::Error::OffSpecTestSpec(dep.name().clone()).into());
741        }
742        Ok(rockspec::lua::Local::new(
743            &self.to_lua_remote_rockspec_string()?,
744            self.internal.lux_toml_dir.clone(),
745        )?)
746    }
747
748    /// Generates this project's rockspec for building it in place.
749    ///
750    /// Uses the remote source when one can be generated,
751    /// so that the rockspec stored in the install tree points at the published source.
752    /// The returned rockspec's effective source points at the project root.
753    pub fn to_build_rockspec(&self) -> Result<rockspec::lua::Remote, rockspec::Error> {
754        let content = match self.to_lua_remote_rockspec_string() {
755            Ok(content) => content,
756            Err(_) => self.to_lua_local_rockspec_string()?,
757        };
758        Ok(rockspec::lua::Local::from_project_toml(self, content)
759            .into_remote_with_source(self.source.clone()))
760    }
761
762    /// Like [`Rockspec::to_lua_remote_rockspec_string`], but pointing at the project root,
763    /// so projects without a release URL can still render a rockspec.
764    fn to_lua_local_rockspec_string(&self) -> Result<String, Error> {
765        self.render_rockspec(
766            &self.version,
767            Some(self.source.current_platform().source_spec.display_lua()),
768        )
769    }
770
771    fn render_rockspec(
772        &self,
773        version: &package::Version,
774        source: Option<rockspec::display::LuaKV>,
775    ) -> Result<String, Error> {
776        let starter = format!(
777            r#"
778rockspec_format = "{}"
779package = "{}"
780version = "{}""#,
781            self.rockspec_format
782                .as_ref()
783                .unwrap_or(&rockspec::Format::default()),
784            self.package,
785            version
786        );
787
788        let mut template = Vec::new();
789
790        if self.description != rockspec::description::Spec::default() {
791            template.push(self.description.display_lua());
792        }
793
794        if self.supported_platforms != rockspec::platform::Support::default() {
795            template.push(self.supported_platforms.display_lua());
796        }
797
798        {
799            let mut dependencies = self.internal.dependencies.clone().unwrap_or_default();
800            if !self.lua.is_luau() {
801                dependencies.insert(
802                    0,
803                    package::Req {
804                        name: "lua".into(),
805                        version_req: self.lua.clone(),
806                    }
807                    .into(),
808                );
809            }
810            template.push(Dependencies(&dependencies).display_lua());
811        }
812
813        let mut build_dependencies = self
814            .internal
815            .build_dependencies
816            .as_ref()
817            .cloned()
818            .unwrap_or_default();
819
820        let build_backend_dependency = self
821            .internal
822            .build
823            .build_type
824            .as_ref()
825            .and_then(|build_type| build_type.luarocks_build_backend());
826
827        if let Some(build_backend_dependency) = build_backend_dependency {
828            build_dependencies.push(build_backend_dependency);
829        }
830
831        if !build_dependencies.is_empty() {
832            template.push(BuildDependencies(&build_dependencies).display_lua());
833        }
834
835        match self.internal.external_dependencies {
836            Some(ref external_dependencies) if !external_dependencies.is_empty() => {
837                template.push(
838                    rockspec::external_dependency::Dependencies(external_dependencies)
839                        .display_lua(),
840                );
841            }
842            _ => {}
843        }
844
845        if let Some(source) = source {
846            template.push(source);
847        }
848
849        template.push(
850            build_spec_with_autodetected_modules(&self.internal.build, &self.internal.lux_toml_dir)
851                .display_lua(),
852        );
853
854        let unformatted_code = std::iter::once(starter)
855            .chain(template.into_iter().map(|kv| kv.to_string()))
856            .join("\n\n");
857        let result = match stylua_lib::format_code(
858            &unformatted_code,
859            stylua_lib::Config::default(),
860            None,
861            stylua_lib::OutputVerification::Full,
862        ) {
863            Ok(formatted_code) => formatted_code,
864            Err(_) => unformatted_code,
865        };
866        validate_generated_lua(&result)?;
867        Ok(result)
868    }
869}
870
871impl Rockspec for Local {
872    fn package(&self) -> &package::Name {
873        &self.package
874    }
875
876    fn version(&self) -> &package::Version {
877        &self.version
878    }
879
880    fn description(&self) -> &rockspec::description::Spec {
881        &self.description
882    }
883
884    fn supported_platforms(&self) -> &rockspec::platform::Support {
885        &self.supported_platforms
886    }
887
888    fn lua(&self) -> &package::VersionReq {
889        &self.lua
890    }
891
892    fn dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
893        &self.dependencies
894    }
895
896    fn build_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
897        &self.build_dependencies
898    }
899
900    fn external_dependencies(
901        &self,
902    ) -> &rockspec::PerPlatform<HashMap<String, rockspec::external_dependency::Spec>> {
903        &self.external_dependencies
904    }
905
906    fn test_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
907        &self.test_dependencies
908    }
909
910    fn build(&self) -> &rockspec::PerPlatform<rockspec::build::Spec> {
911        &self.build
912    }
913
914    fn test(&self) -> &rockspec::PerPlatform<rockspec::test::Spec> {
915        &self.test
916    }
917
918    fn build_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::build::Spec> {
919        &mut self.build
920    }
921
922    fn test_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::test::Spec> {
923        &mut self.test
924    }
925
926    fn format(&self) -> &Option<rockspec::Format> {
927        &self.rockspec_format
928    }
929
930    fn source(&self) -> &rockspec::PerPlatform<rockspec::source::Remote> {
931        &self.source
932    }
933
934    fn source_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::source::Remote> {
935        &mut self.source
936    }
937
938    fn deploy(&self) -> &rockspec::PerPlatform<rockspec::deploy::Spec> {
939        &self.deploy
940    }
941
942    fn deploy_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::deploy::Spec> {
943        &mut self.deploy
944    }
945
946    fn to_lua_remote_rockspec_string(&self) -> Result<String, rockspec::Error> {
947        let lux_toml_dir = &self.internal.lux_toml_dir;
948        let version = self
949            .internal
950            .version_template
951            .try_generate(lux_toml_dir, None)
952            .map_err(Error::from)?;
953        let source = self
954            .internal
955            .source_template
956            .try_generate(lux_toml_dir, &self.package, &version)
957            .map_err(Error::from)?;
958        Ok(self.render_rockspec(&version, Some(source.display_lua()))?)
959    }
960}
961
962/// Creates a [`build::internal::Spec`] with auto-detected modules (e.g. *.luau sources)
963/// that LuaRocks does not auto-detect, so that LuaRocks can install them.
964fn build_spec_with_autodetected_modules(
965    spec: &rockspec::build::internal::Spec,
966    project_root: &Path,
967) -> rockspec::build::internal::Spec {
968    let builtin_capable = spec.build_type.as_ref().is_none_or(|build_type| {
969        matches!(
970            build_type,
971            rockspec::build::internal::Type::Builtin | rockspec::build::internal::Type::None
972        )
973    });
974    if !builtin_capable {
975        return spec.clone();
976    }
977    let detected = match autodetect_modules(project_root, Default::default()) {
978        Ok(modules) => modules
979            .into_iter()
980            .filter_map(|(module, spec)| match spec {
981                rockspec::build::backend::ModuleSpec::SourcePath(path)
982                    if path.extension().is_some_and(|ext| ext == "luau") =>
983                {
984                    Some((module, path))
985                }
986                _ => None,
987            })
988            .collect_vec(),
989        Err(_) => return spec.clone(),
990    };
991    if detected.is_empty() {
992        spec.clone()
993    } else {
994        let mut new_spec = spec.clone();
995        let modules = new_spec.builtin_spec.get_or_insert_with(Default::default);
996        for (module, path) in detected {
997            modules
998                .entry(rockspec::serde_util::LuaTableKey::StringKey(
999                    module.to_string(),
1000                ))
1001                .or_insert(
1002                    rockspec::build::backend::builtin::internal::ModuleSpec::SourcePath(path),
1003                );
1004        }
1005        new_spec
1006    }
1007}
1008
1009fn validate_generated_lua(lua_str: &str) -> Result<(), Error> {
1010    let mut lua = ottavino::Lua::core();
1011    lua.try_enter(|ctx| {
1012        let closure = ottavino::Closure::load(ctx, None, lua_str.as_bytes())?;
1013        let executor = ottavino::Executor::start(ctx, closure.into(), ());
1014        if !executor.step(ctx, &mut ottavino::Fuel::with(ROCKSPEC_FUEL_LIMIT))? {
1015            return Ok(Err(Error::FuelLimitExceeded));
1016        }
1017        Ok(Ok(()))
1018    })
1019    .map_err(|err| Error::GeneratedInvalidLua(err.to_string()))?
1020}
1021
1022impl HasIntegrity for Local {
1023    async fn hash(&self) -> io::Result<Integrity> {
1024        match self.to_lua_rockspec() {
1025            Ok(lua_rockspec) => lua_rockspec.hash().await,
1026            Err(_) => self.internal.hash().await,
1027        }
1028    }
1029}
1030
1031/// The `lux.toml`, after being validated and prepared for upload
1032#[derive(Debug)]
1033pub struct Remote {
1034    local: Local,
1035    source: rockspec::PerPlatform<rockspec::source::Remote>,
1036}
1037
1038impl Remote {
1039    pub fn to_lua_rockspec(&self) -> Result<rockspec::lua::Remote, rockspec::Error> {
1040        Ok(rockspec::lua::Remote::new(
1041            &self.to_lua_remote_rockspec_string()?,
1042        )?)
1043    }
1044}
1045
1046impl Rockspec for Remote {
1047    fn package(&self) -> &package::Name {
1048        self.local.package()
1049    }
1050
1051    fn version(&self) -> &package::Version {
1052        self.local.version()
1053    }
1054
1055    fn description(&self) -> &rockspec::description::Spec {
1056        self.local.description()
1057    }
1058
1059    fn supported_platforms(&self) -> &rockspec::platform::Support {
1060        self.local.supported_platforms()
1061    }
1062
1063    fn lua(&self) -> &package::VersionReq {
1064        self.local.lua()
1065    }
1066
1067    fn dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
1068        self.local.dependencies()
1069    }
1070
1071    fn build_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
1072        self.local.build_dependencies()
1073    }
1074
1075    fn external_dependencies(
1076        &self,
1077    ) -> &rockspec::PerPlatform<HashMap<String, rockspec::external_dependency::Spec>> {
1078        self.local.external_dependencies()
1079    }
1080
1081    fn test_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
1082        self.local.test_dependencies()
1083    }
1084
1085    fn build(&self) -> &rockspec::PerPlatform<rockspec::build::Spec> {
1086        self.local.build()
1087    }
1088
1089    fn test(&self) -> &rockspec::PerPlatform<rockspec::test::Spec> {
1090        self.local.test()
1091    }
1092
1093    fn build_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::build::Spec> {
1094        self.local.build_mut()
1095    }
1096
1097    fn test_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::test::Spec> {
1098        self.local.test_mut()
1099    }
1100
1101    fn format(&self) -> &Option<rockspec::Format> {
1102        self.local.format()
1103    }
1104
1105    fn source(&self) -> &rockspec::PerPlatform<rockspec::source::Remote> {
1106        &self.source
1107    }
1108
1109    fn source_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::source::Remote> {
1110        &mut self.source
1111    }
1112
1113    fn deploy(&self) -> &rockspec::PerPlatform<rockspec::deploy::Spec> {
1114        self.local.deploy()
1115    }
1116
1117    fn deploy_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::deploy::Spec> {
1118        self.local.deploy_mut()
1119    }
1120
1121    fn to_lua_remote_rockspec_string(&self) -> Result<String, rockspec::Error> {
1122        let lux_toml_dir = &self.local.internal.lux_toml_dir;
1123        let starter = format!(
1124            r#"
1125rockspec_format = "{}"
1126package = "{}"
1127version = "{}""#,
1128            self.local
1129                .rockspec_format
1130                .as_ref()
1131                .unwrap_or(&rockspec::Format::default()),
1132            self.local.package,
1133            self.version()
1134        );
1135
1136        let mut template = Vec::new();
1137
1138        if self.local.description != rockspec::description::Spec::default() {
1139            template.push(self.local.description.display_lua());
1140        }
1141
1142        if self.local.supported_platforms != rockspec::platform::Support::default() {
1143            template.push(self.local.supported_platforms.display_lua());
1144        }
1145
1146        {
1147            let mut dependencies = self.local.internal.dependencies.clone().unwrap_or_default();
1148            if !self.local.lua.is_luau() {
1149                dependencies.insert(
1150                    0,
1151                    package::Req {
1152                        name: "lua".into(),
1153                        version_req: self.local.lua.clone(),
1154                    }
1155                    .into(),
1156                );
1157            }
1158            template.push(Dependencies(&dependencies).display_lua());
1159        }
1160
1161        let mut build_dependencies = self
1162            .local
1163            .internal
1164            .build_dependencies
1165            .as_ref()
1166            .cloned()
1167            .unwrap_or_default();
1168
1169        let build_backend_dependency = self
1170            .local
1171            .internal
1172            .build
1173            .build_type
1174            .as_ref()
1175            .and_then(|build_type| build_type.luarocks_build_backend());
1176
1177        if let Some(build_backend_dependency) = build_backend_dependency {
1178            build_dependencies.push(build_backend_dependency);
1179        }
1180
1181        if !build_dependencies.is_empty() {
1182            template.push(BuildDependencies(&build_dependencies).display_lua());
1183        }
1184
1185        match self.local.internal.external_dependencies {
1186            Some(ref external_dependencies) if !external_dependencies.is_empty() => {
1187                template.push(
1188                    rockspec::external_dependency::Dependencies(external_dependencies)
1189                        .display_lua(),
1190                );
1191            }
1192            _ => {}
1193        }
1194
1195        let source = self
1196            .local
1197            .internal
1198            .source_template
1199            .try_generate(lux_toml_dir, &self.local.internal.package, self.version())
1200            .map_err(Error::from)?;
1201        template.push(source.display_lua());
1202
1203        if let Some(ref deploy) = self.local.internal.deploy {
1204            template.push(deploy.display_lua());
1205        }
1206
1207        template.push(
1208            build_spec_with_autodetected_modules(&self.local.internal.build, lux_toml_dir)
1209                .display_lua(),
1210        );
1211
1212        let unformatted_code = std::iter::once(starter)
1213            .chain(template.into_iter().map(|kv| kv.to_string()))
1214            .join("\n\n");
1215        let result = match stylua_lib::format_code(
1216            &unformatted_code,
1217            stylua_lib::Config::default(),
1218            None,
1219            stylua_lib::OutputVerification::Full,
1220        ) {
1221            Ok(formatted_code) => formatted_code,
1222            Err(_) => unformatted_code,
1223        };
1224        validate_generated_lua(&result)?;
1225        Ok(result)
1226    }
1227}
1228
1229impl HasIntegrity for Remote {
1230    async fn hash(&self) -> io::Result<Integrity> {
1231        self.to_lua_rockspec()
1232            .map_err(|err| {
1233                io::Error::other(format!(
1234                    "unable to convert remote project to Lua rockspec:\n{}",
1235                    err
1236                ))
1237            })?
1238            .hash()
1239            .await
1240    }
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245    use std::path::PathBuf;
1246
1247    use crate::rockspec;
1248
1249    use assert_fs::prelude::{PathChild, PathCopy, PathCreateDir};
1250    use git2::Repository;
1251    use url::Url;
1252
1253    use crate::{
1254        git::{self, url::RemoteGitUrl},
1255        project::{Project, TOML_FILE_NAME},
1256        rockspec::Rockspec,
1257    };
1258
1259    use super::Partial;
1260
1261    #[test]
1262    fn project_toml_parsing() {
1263        let project_toml = r#"
1264        package = "my-package"
1265        version = "1.0.0"
1266        lua = "5.3"
1267
1268        rockspec_format = "1.0"
1269
1270        [source]
1271        url = "https://example.com"
1272
1273        [dependencies]
1274        foo = "1.0"
1275        bar = ">=2.0"
1276
1277        [run]
1278        args = ["--foo", "--bar"]
1279
1280        [build]
1281        type = "builtin"
1282        "#;
1283
1284        let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1285        let _ = project.into_remote(None).unwrap();
1286
1287        let project_toml = r#"
1288        package = "my-package"
1289        version = "1.0.0"
1290        lua = "5.1"
1291
1292        [description]
1293        summary = "A summary"
1294        detailed = "A detailed description"
1295        license = "MIT"
1296        homepage = "https://example.com"
1297        issues_url = "https://example.com/issues"
1298        maintainer = "John Doe"
1299        labels = ["label1", "label2"]
1300
1301        [supported_platforms]
1302        linux = true
1303        windows = false
1304
1305        [dependencies]
1306        foo = "1.0"
1307        bar = ">=2.0"
1308
1309        [build_dependencies]
1310        baz = "1.0"
1311
1312        [external_dependencies.foo]
1313        header = "foo.h"
1314
1315        [external_dependencies.bar]
1316        library = "libbar.so"
1317
1318        [test_dependencies]
1319        busted = "69.420"
1320
1321        [source]
1322        url = "https://example.com"
1323        hash = "sha256-di00mD8txN7rjaVpvxzNbnQsAh6H16zUtJZapH7U4HU="
1324        file = "my-package-1.0.0.tar.gz"
1325        dir = "my-package-1.0.0"
1326
1327        [test]
1328        type = "command"
1329        script = "test.lua"
1330        flags = [ "foo", "bar" ]
1331
1332        [run]
1333        command = "my-command"
1334        args = ["--foo", "--bar"]
1335
1336        [build]
1337        type = "builtin"
1338        "#;
1339
1340        let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1341        let _ = project.into_remote(None).unwrap();
1342    }
1343
1344    #[test]
1345    fn compare_project_toml_with_rockspec() {
1346        let project_toml = r#"
1347        package = "my-package"
1348        version = "1.0.0"
1349        lua = "5.1"
1350
1351        # For testing, specify a custom rockspec format
1352        # (defaults to 3.0)
1353        rockspec_format = "1.0"
1354
1355        [description]
1356        summary = "A summary"
1357        detailed = "A detailed description"
1358        license = "MIT"
1359        homepage = "https://example.com"
1360        issues_url = "https://example.com/issues"
1361        maintainer = "John Doe"
1362        labels = ["label1", "label2"]
1363
1364        [supported_platforms]
1365        linux = true
1366        windows = false
1367
1368        [dependencies]
1369        foo = "1.0"
1370        bar = ">=2.0"
1371
1372        [build_dependencies]
1373        baz = "1.0"
1374
1375        [external_dependencies.foo]
1376        header = "foo.h"
1377
1378        [external_dependencies.bar]
1379        library = "libbar.so"
1380
1381        [test_dependencies]
1382        busted = "1.0"
1383
1384        [source]
1385        url = "https://example.com"
1386        file = "my-package-1.0.0.tar.gz"
1387        dir = "my-package-1.0.0"
1388
1389        [test]
1390        type = "command"
1391        script = "test.lua"
1392        flags = [ "foo", "bar" ]
1393
1394        [run]
1395        command = "my-command"
1396        args = ["--foo", "--bar"]
1397
1398        [deploy]
1399        wrap_bin_scripts = false
1400
1401        [build]
1402        type = "builtin"
1403
1404        [build.install.lua]
1405        "foo.bar" = "src/bar.lua"
1406
1407        [build.install.lib]
1408        "foo.baz" = "src/baz.c"
1409
1410        [build.install.bin]
1411        "bla" = "src/bla"
1412
1413        [build.install.conf]
1414        "cfg.conf" = "resources/config.conf"
1415        "#;
1416
1417        let expected_rockspec = r#"
1418            rockspec_format = "1.0"
1419            package = "my-package"
1420            version = "1.0.0"
1421
1422            source = {
1423                url = "https://example.com",
1424                file = "my-package-1.0.0.tar.gz",
1425                dir = "my-package-1.0.0",
1426            }
1427
1428            description = {
1429                summary = "A summary",
1430                detailed = "A detailed description",
1431                license = "MIT",
1432                homepage = "https://example.com",
1433                issues_url = "https://example.com/issues",
1434                maintainer = "John Doe",
1435                labels = {"label1", "label2"},
1436            }
1437
1438            supported_platforms = {"linux", "!windows"}
1439
1440            dependencies = {
1441                "lua ==5.1",
1442                "foo ==1.0",
1443                "bar >=2.0",
1444            }
1445
1446            build_dependencies = {
1447                "baz ==1.0",
1448            }
1449
1450            external_dependencies = {
1451                foo = { header = "foo.h" },
1452                bar = { library = "libbar.so" },
1453            }
1454
1455            source = {
1456                url = "https://example.com",
1457                hash = "sha256-di00mD8txN7rjaVpvxzNbnQsAh6H16zUtJZapH7U4HU=",
1458                file = "my-package-1.0.0.tar.gz",
1459                dir = "my-package-1.0.0",
1460            }
1461
1462            test = {
1463                type = "command",
1464                script = "test.lua",
1465                flags = {"foo", "bar"},
1466            }
1467
1468            deploy = {
1469                wrap_bin_scripts = false,
1470            }
1471
1472            build = {
1473                type = "builtin",
1474                install = {
1475                    lua = {
1476                        ["foo.bar"] = "src/bar.lua",
1477                    },
1478                    lib = {
1479                        ["foo.baz"] = "src/baz.c",
1480                    },
1481                    bin = {
1482                        bla = "src/bla",
1483                    },
1484                    conf = {
1485                        ["cfg.conf"] = "resources/config.conf",
1486                    },
1487                },
1488            }
1489        "#;
1490
1491        let expected_rockspec = rockspec::lua::Remote::new(expected_rockspec).unwrap();
1492
1493        let project_toml = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1494        let rockspec = project_toml
1495            .into_remote(None)
1496            .unwrap()
1497            .to_lua_rockspec()
1498            .unwrap();
1499
1500        let sorted_package_reqs =
1501            |v: &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>| {
1502                let mut v = v.current_platform().clone();
1503                v.sort_by(|a, b| a.name().cmp(b.name()));
1504                v
1505            };
1506
1507        assert_eq!(rockspec.package(), expected_rockspec.package());
1508        assert_eq!(rockspec.version(), expected_rockspec.version());
1509        assert_eq!(rockspec.description(), expected_rockspec.description());
1510        assert_eq!(
1511            rockspec.supported_platforms(),
1512            expected_rockspec.supported_platforms()
1513        );
1514        assert_eq!(
1515            sorted_package_reqs(rockspec.dependencies()),
1516            sorted_package_reqs(expected_rockspec.dependencies())
1517        );
1518        assert_eq!(
1519            sorted_package_reqs(rockspec.build_dependencies()),
1520            sorted_package_reqs(expected_rockspec.build_dependencies())
1521        );
1522        assert_eq!(
1523            rockspec.external_dependencies(),
1524            expected_rockspec.external_dependencies()
1525        );
1526        assert_eq!(rockspec.source(), expected_rockspec.source());
1527        assert_eq!(rockspec.build(), expected_rockspec.build());
1528        assert_eq!(rockspec.format(), expected_rockspec.format());
1529    }
1530
1531    #[test]
1532    fn merge_project_toml_with_partial_rockspec() {
1533        let project_toml = r#"
1534        package = "my-package"
1535        version = "1.0.0"
1536        lua = "5.1"
1537
1538        # For testing, specify a custom rockspec format
1539        # (defaults to 3.0)
1540        rockspec_format = "1.0"
1541
1542        [description]
1543        summary = "A summary"
1544        detailed = "A detailed description"
1545        license = "MIT"
1546        homepage = "https://example.com"
1547        issues_url = "https://example.com/issues"
1548        maintainer = "John Doe"
1549        labels = ["label1", "label2"]
1550
1551        [supported_platforms]
1552        linux = true
1553        windows = false
1554
1555        [dependencies]
1556        foo = "1.0"
1557        bar = ">=2.0"
1558
1559        [build_dependencies]
1560        baz = "1.0"
1561
1562        [external_dependencies.foo]
1563        header = "foo.h"
1564
1565        [external_dependencies.bar]
1566        library = "libbar.so"
1567
1568        [test_dependencies]
1569        busted = "1.0"
1570
1571        [source]
1572        url = "https://example.com"
1573        file = "my-package-1.0.0.tar.gz"
1574        dir = "my-package-1.0.0"
1575
1576        [test]
1577        type = "command"
1578        script = "test.lua"
1579        flags = [ "foo", "bar" ]
1580
1581        [run]
1582        command = "my-command"
1583        args = [ "--foo", "--bar" ]
1584
1585        [build]
1586        type = "builtin"
1587        "#;
1588
1589        let mergable_rockspec_content = r#"
1590            rockspec_format = "1.0"
1591            package = "my-package-overwritten"
1592
1593            description = {
1594                summary = "A summary overwritten",
1595                detailed = "A detailed description overwritten",
1596                license = "GPL-2.0",
1597                homepage = "https://example.com/overwritten",
1598                issues_url = "https://example.com/issues/overwritten",
1599                maintainer = "John Doe Overwritten",
1600                labels = {"over", "written"},
1601            }
1602
1603            -- Inverted supported platforms
1604            supported_platforms = {"!linux", "windows"}
1605
1606            dependencies = {
1607                "lua 5.1",
1608                "foo >1.0",
1609                "bar <=2.0",
1610            }
1611
1612            build_dependencies = {
1613                "baz >1.0",
1614            }
1615
1616            external_dependencies = {
1617                foo = { header = "overwritten.h" },
1618                bar = { library = "overwritten.so" },
1619            }
1620
1621            test = {
1622                type = "command",
1623                script = "overwritten.lua",
1624                flags = {"over", "written"},
1625            }
1626
1627            build = {
1628                type = "builtin",
1629            }
1630        "#;
1631
1632        let remote_rockspec_content = format!(
1633            r#"{}
1634            version = "1.0.0"
1635            source = {{
1636                url = "https://example.com",
1637                file = "my-package-1.0.0.tar.gz",
1638                dir = "my-package-1.0.0",
1639            }}
1640        "#,
1641            mergable_rockspec_content
1642        );
1643
1644        let project_toml = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1645        let partial_rockspec = rockspec::lua::Partial::new(mergable_rockspec_content).unwrap();
1646        let expected_rockspec = rockspec::lua::Remote::new(&remote_rockspec_content).unwrap();
1647
1648        let merged = project_toml
1649            .merge(partial_rockspec)
1650            .into_remote(None)
1651            .unwrap();
1652
1653        let sorted_package_reqs =
1654            |v: &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>| {
1655                let mut v = v.current_platform().clone();
1656                v.sort_by(|a, b| a.name().cmp(b.name()));
1657                v
1658            };
1659
1660        assert_eq!(merged.package(), expected_rockspec.package());
1661        assert_eq!(merged.version(), expected_rockspec.version());
1662        assert_eq!(merged.description(), expected_rockspec.description());
1663        assert_eq!(
1664            merged.supported_platforms(),
1665            expected_rockspec.supported_platforms()
1666        );
1667        assert_eq!(
1668            sorted_package_reqs(merged.dependencies()),
1669            sorted_package_reqs(expected_rockspec.dependencies())
1670        );
1671        assert_eq!(
1672            sorted_package_reqs(merged.build_dependencies()),
1673            sorted_package_reqs(expected_rockspec.build_dependencies())
1674        );
1675        assert_eq!(
1676            merged.external_dependencies(),
1677            expected_rockspec.external_dependencies()
1678        );
1679        assert_eq!(merged.source(), expected_rockspec.source());
1680        assert_eq!(merged.build(), expected_rockspec.build());
1681        assert_eq!(merged.format(), expected_rockspec.format());
1682        // Ensure that the run command is retained after merge.
1683        assert!(merged.local.run().is_some());
1684    }
1685
1686    #[test]
1687    fn wally_dependency_parsing() {
1688        let project_toml = r#"
1689        package = "my-package"
1690        version = "1.0.0"
1691        lua = "5.1"
1692
1693        [dependencies.roact]
1694        wally = "jsdotperf/roact@^1.4.0"
1695
1696        [build]
1697        type = "builtin"
1698        "#;
1699
1700        let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1701        let deps = project.dependencies.unwrap();
1702        assert_eq!(deps.len(), 1);
1703        assert_eq!(deps[0].name().to_string(), "roact");
1704        assert!(matches!(
1705            deps[0].source(),
1706            Some(rockspec::source::Spec::Wally(req)) if req.name().to_string() == "jsdotperf/roact"
1707        ));
1708    }
1709
1710    #[test]
1711    fn wally_dependency_conflicts_with_version() {
1712        let project_toml = r#"
1713        package = "my-package"
1714        version = "1.0.0"
1715        lua = "5.1"
1716
1717        [dependencies.roact]
1718        wally = "jsdotperf/roact@^1.4.0"
1719        version = "1.4.0"
1720
1721        [build]
1722        type = "builtin"
1723        "#;
1724
1725        Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap_err();
1726    }
1727
1728    #[test]
1729    fn project_toml_with_lua_in_dependencies() {
1730        let project_toml = r#"
1731        package = "my-package"
1732        version = "1.0.0"
1733        # lua = ">5.1"
1734
1735        [dependencies]
1736        lua = "5.1" # disallowed
1737
1738        [build]
1739        type = "builtin"
1740        "#;
1741
1742        Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default())
1743            .unwrap()
1744            .into_local()
1745            .unwrap_err();
1746    }
1747
1748    #[test]
1749    fn project_toml_with_invalid_run_command() {
1750        for command in ["lua", "lua5.1", "lua5.2", "lua5.3", "lua5.4", "luajit"] {
1751            let project_toml = format!(
1752                r#"
1753                package = "my-package"
1754                version = "1.0.0"
1755                lua = "5.1"
1756
1757                [build]
1758                type = "builtin"
1759
1760                [run]
1761                command = "{command}"
1762                "#,
1763            );
1764
1765            Partial::new(TOML_FILE_NAME, &project_toml, PathBuf::default()).unwrap_err();
1766        }
1767    }
1768
1769    #[test]
1770    fn project_root_dir_override_and_rockspec_generation() {
1771        let project_toml = r#"
1772        package = "my-package"
1773        version = "1.0.0"
1774        lua = "5.1"
1775
1776        [project]
1777        root_dir = ".."
1778
1779        [source]
1780        url = "https://example.com"
1781
1782        [build]
1783        type = "builtin"
1784        "#;
1785
1786        let workspace_root = assert_fs::TempDir::new().unwrap();
1787        let lux_toml_dir = workspace_root.child("proj");
1788        lux_toml_dir.create_dir_all().unwrap();
1789        std::fs::write(lux_toml_dir.join(TOML_FILE_NAME), project_toml).unwrap();
1790
1791        let project =
1792            Partial::new(TOML_FILE_NAME, project_toml, lux_toml_dir.to_path_buf()).unwrap();
1793        let local = project.into_local().unwrap();
1794        let rockspec::source::Spec::File(root_dir) = &local.source().current_platform().source_spec
1795        else {
1796            panic!("expected a file source");
1797        };
1798        assert_eq!(
1799            root_dir,
1800            &std::fs::canonicalize(workspace_root.path()).unwrap()
1801        );
1802
1803        // The `[project]` table must be ignored when generating a rockspec.
1804        let rockspec = local.to_lua_rockspec().unwrap();
1805        assert!(!rockspec
1806            .to_lua_remote_rockspec_string()
1807            .unwrap()
1808            .contains("root_dir"));
1809    }
1810
1811    #[test]
1812    fn generate_non_deterministic_git_source() {
1813        let rockspec_content = r#"
1814            package = "test-package"
1815            version = "1.0.0"
1816            lua = ">=5.1"
1817
1818            [source]
1819            url = "git+https://exaple.com/repo.git"
1820
1821            [build]
1822            type = "builtin"
1823        "#;
1824
1825        Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
1826            .unwrap()
1827            .into_remote(None)
1828            .unwrap_err();
1829    }
1830
1831    #[test]
1832    fn generate_deterministic_git_source() {
1833        let rockspec_content = r#"
1834            package = "test-package"
1835            version = "1.0.0"
1836            lua = ">=5.1"
1837
1838            [source]
1839            url = "git+https://exaple.com/owner/repo.git"
1840            tag = "v0.1.0"
1841
1842            [build]
1843            type = "builtin"
1844        "#;
1845
1846        Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
1847            .unwrap()
1848            .into_remote(None)
1849            .unwrap();
1850    }
1851
1852    #[test]
1853    fn generate_git_source_with_branch() {
1854        let rockspec_content = r#"
1855            package = "test-package"
1856            version = "1.0.0"
1857            lua = ">=5.1"
1858
1859            [source]
1860            url = "git+https://example.com/owner/repo.git"
1861            branch = "main"
1862
1863            [build]
1864            type = "builtin"
1865        "#;
1866
1867        let toml = Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
1868            .unwrap()
1869            .into_remote(None)
1870            .unwrap();
1871
1872        let lua = toml.to_lua_remote_rockspec_string().unwrap();
1873        assert!(lua.contains("branch = \"main\""));
1874        assert!(!lua.contains("tag = "));
1875    }
1876
1877    fn init_git_repo(path: &std::path::Path) -> Repository {
1878        let repo = Repository::init(path).unwrap();
1879        {
1880            let tree_id = repo.index().unwrap().write_tree().unwrap();
1881            let tree = repo.find_tree(tree_id).unwrap();
1882            let sig = git2::Signature::now("name", "email").unwrap();
1883            repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
1884                .unwrap();
1885        }
1886        repo
1887    }
1888
1889    fn init_sample_project_repo(temp_dir: &assert_fs::TempDir) -> Repository {
1890        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1891            .join("resources/test/sample-projects/source-template/");
1892        temp_dir.copy_from(&sample_project, &["**"]).unwrap();
1893        init_git_repo(temp_dir.path())
1894    }
1895
1896    fn create_tag(repo: &Repository, name: &str) {
1897        let sig = git2::Signature::now("name", "email").unwrap();
1898        let id = repo.head().unwrap().target().unwrap();
1899        let obj = repo.find_object(id, None).unwrap();
1900        repo.tag(name, &obj, &sig, "msg", true).unwrap();
1901    }
1902
1903    #[test]
1904    fn test_git_project_generate_dev_source() {
1905        let project_root = assert_fs::TempDir::new().unwrap();
1906        init_sample_project_repo(&project_root);
1907        let project = Project::from_exact(&project_root).unwrap().unwrap();
1908        let remote_project_toml = project.toml().into_remote(None).unwrap();
1909        let source = remote_project_toml.source.current_platform();
1910        let source_spec = &source.source_spec;
1911        assert!(matches!(source_spec, &rockspec::source::Spec::Git { .. }));
1912        if let rockspec::source::Spec::Git(git::Source { url, git_ref }) = source_spec {
1913            let expected_url: RemoteGitUrl =
1914                "https://github.com/lumen-oss/lux.git".parse().unwrap();
1915            assert_eq!(url, &expected_url);
1916            assert!(git_ref.is_some());
1917        }
1918        assert_eq!(source.unpack_dir, Some("lux-dev".into()));
1919    }
1920
1921    #[test]
1922    fn test_git_project_generate_non_semver_tag_source() {
1923        let project_root = assert_fs::TempDir::new().unwrap();
1924        let repo = init_sample_project_repo(&project_root);
1925        let tag_name = "bla";
1926        create_tag(&repo, tag_name);
1927        let project = Project::from_exact(&project_root).unwrap().unwrap();
1928        let remote_project_toml = project.toml().into_remote(None).unwrap();
1929        let source = remote_project_toml.source.current_platform();
1930        let source_spec = &source.source_spec;
1931        assert!(matches!(source_spec, &rockspec::source::Spec::Git { .. }));
1932        if let rockspec::source::Spec::Git(git::Source { url, git_ref }) = source_spec {
1933            let expected_url: RemoteGitUrl =
1934                "https://github.com/lumen-oss/lux.git".parse().unwrap();
1935            assert_eq!(url, &expected_url);
1936            assert_eq!(git_ref, &Some(git::Ref::Tag(tag_name.to_string())));
1937        }
1938        assert_eq!(source.unpack_dir, Some("lux-dev".into()));
1939    }
1940
1941    #[test]
1942    fn test_git_project_generate_release_source_tag_with_v_prefix() {
1943        let project_root = assert_fs::TempDir::new().unwrap();
1944        let repo = init_sample_project_repo(&project_root);
1945        let tag_name = "v1.0.0";
1946        create_tag(&repo, "bla");
1947        create_tag(&repo, tag_name);
1948        let project = Project::from_exact(&project_root).unwrap().unwrap();
1949        let remote_project_toml = project.toml().into_remote(None).unwrap();
1950        let source = remote_project_toml.source.current_platform();
1951        let source_spec = &source.source_spec;
1952        assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1953        if let rockspec::source::Spec::Url(url) = source_spec {
1954            let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/v1.0.0.zip"
1955                .parse()
1956                .unwrap();
1957            assert_eq!(url, &expected_url);
1958        }
1959        assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1960    }
1961
1962    #[test]
1963    fn test_git_project_generate_release_source_tag_without_v_prefix() {
1964        let project_root = assert_fs::TempDir::new().unwrap();
1965        let repo = init_sample_project_repo(&project_root);
1966        create_tag(&repo, "bla");
1967        let tag_name = "1.0.0";
1968        create_tag(&repo, tag_name);
1969        let project = Project::from_exact(&project_root).unwrap().unwrap();
1970        let remote_project_toml = project.toml().into_remote(None).unwrap();
1971        let source = remote_project_toml.source.current_platform();
1972        let source_spec = &source.source_spec;
1973        assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1974        if let rockspec::source::Spec::Url(url) = source_spec {
1975            let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/1.0.0.zip"
1976                .parse()
1977                .unwrap();
1978            assert_eq!(url, &expected_url);
1979        }
1980        assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1981    }
1982
1983    #[test]
1984    fn test_git_project_in_subdirectory() {
1985        let temp_dir = assert_fs::TempDir::new().unwrap();
1986        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1987            .join("resources/test/sample-projects/source-template/");
1988        let project_dir = temp_dir.child("lux");
1989        project_dir.create_dir_all().unwrap();
1990        project_dir.copy_from(&sample_project, &["**"]).unwrap();
1991        let repo = init_git_repo(temp_dir.path());
1992        create_tag(&repo, "bla");
1993        let tag_name = "1.0.0";
1994        create_tag(&repo, tag_name);
1995        let project = Project::from_exact(&project_dir).unwrap().unwrap();
1996        let remote_project_toml = project.toml().into_remote(None).unwrap();
1997        let source = remote_project_toml.source.current_platform();
1998        let source_spec = &source.source_spec;
1999        assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
2000        if let rockspec::source::Spec::Url(url) = source_spec {
2001            let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/1.0.0.zip"
2002                .parse()
2003                .unwrap();
2004            assert_eq!(url, &expected_url);
2005        }
2006        assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
2007    }
2008
2009    #[test]
2010    fn test_git_project_in_subdirectory_generate_dev_source() {
2011        let temp_dir = assert_fs::TempDir::new().unwrap();
2012        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2013            .join("resources/test/sample-projects/source-template/");
2014        let project_dir = temp_dir.child("lux");
2015        project_dir.create_dir_all().unwrap();
2016        project_dir.copy_from(&sample_project, &["**"]).unwrap();
2017        init_git_repo(temp_dir.path());
2018
2019        let project = Project::from_exact(&project_dir).unwrap().unwrap();
2020        let remote_project_toml = project.toml().into_remote(None).unwrap();
2021        let rockspec::source::Spec::Git(git::Source { git_ref, .. }) =
2022            &remote_project_toml.source.current_platform().source_spec
2023        else {
2024            panic!("expected a git source");
2025        };
2026        assert!(git_ref.is_some());
2027    }
2028}