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    /// Renders the rockspec for local builds, using the rockspec's own version
749    /// and its source pointing at the project root.
750    pub fn to_local_rockspec(&self) -> Result<rockspec::lua::Remote, rockspec::Error> {
751        let content = self.to_lua_local_rockspec_string()?;
752        Ok(rockspec::lua::Local::from_project_toml(self, content)
753            .into_remote_with_source(self.source.clone()))
754    }
755
756    /// Like [`Rockspec::to_lua_remote_rockspec_string`], but pointing at the project root,
757    /// so projects without a release URL can still render a rockspec.
758    fn to_lua_local_rockspec_string(&self) -> Result<String, Error> {
759        self.render_rockspec(
760            &self.version,
761            Some(self.source.current_platform().source_spec.display_lua()),
762        )
763    }
764
765    fn render_rockspec(
766        &self,
767        version: &package::Version,
768        source: Option<rockspec::display::LuaKV>,
769    ) -> Result<String, Error> {
770        let starter = format!(
771            r#"
772rockspec_format = "{}"
773package = "{}"
774version = "{}""#,
775            self.rockspec_format
776                .as_ref()
777                .unwrap_or(&rockspec::Format::default()),
778            self.package,
779            version
780        );
781
782        let mut template = Vec::new();
783
784        if self.description != rockspec::description::Spec::default() {
785            template.push(self.description.display_lua());
786        }
787
788        if self.supported_platforms != rockspec::platform::Support::default() {
789            template.push(self.supported_platforms.display_lua());
790        }
791
792        {
793            let mut dependencies = self.internal.dependencies.clone().unwrap_or_default();
794            if !self.lua.is_luau() {
795                dependencies.insert(
796                    0,
797                    package::Req {
798                        name: "lua".into(),
799                        version_req: self.lua.clone(),
800                    }
801                    .into(),
802                );
803            }
804            template.push(Dependencies(&dependencies).display_lua());
805        }
806
807        let mut build_dependencies = self
808            .internal
809            .build_dependencies
810            .as_ref()
811            .cloned()
812            .unwrap_or_default();
813
814        let build_backend_dependency = self
815            .internal
816            .build
817            .build_type
818            .as_ref()
819            .and_then(|build_type| build_type.luarocks_build_backend());
820
821        if let Some(build_backend_dependency) = build_backend_dependency {
822            build_dependencies.push(build_backend_dependency);
823        }
824
825        if !build_dependencies.is_empty() {
826            template.push(BuildDependencies(&build_dependencies).display_lua());
827        }
828
829        match self.internal.external_dependencies {
830            Some(ref external_dependencies) if !external_dependencies.is_empty() => {
831                template.push(
832                    rockspec::external_dependency::Dependencies(external_dependencies)
833                        .display_lua(),
834                );
835            }
836            _ => {}
837        }
838
839        if let Some(source) = source {
840            template.push(source);
841        }
842
843        template.push(
844            build_spec_with_autodetected_modules(&self.internal.build, &self.internal.lux_toml_dir)
845                .display_lua(),
846        );
847
848        let unformatted_code = std::iter::once(starter)
849            .chain(template.into_iter().map(|kv| kv.to_string()))
850            .join("\n\n");
851        let result = match stylua_lib::format_code(
852            &unformatted_code,
853            stylua_lib::Config::default(),
854            None,
855            stylua_lib::OutputVerification::Full,
856        ) {
857            Ok(formatted_code) => formatted_code,
858            Err(_) => unformatted_code,
859        };
860        validate_generated_lua(&result)?;
861        Ok(result)
862    }
863}
864
865impl Rockspec for Local {
866    fn package(&self) -> &package::Name {
867        &self.package
868    }
869
870    fn version(&self) -> &package::Version {
871        &self.version
872    }
873
874    fn description(&self) -> &rockspec::description::Spec {
875        &self.description
876    }
877
878    fn supported_platforms(&self) -> &rockspec::platform::Support {
879        &self.supported_platforms
880    }
881
882    fn lua(&self) -> &package::VersionReq {
883        &self.lua
884    }
885
886    fn dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
887        &self.dependencies
888    }
889
890    fn build_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
891        &self.build_dependencies
892    }
893
894    fn external_dependencies(
895        &self,
896    ) -> &rockspec::PerPlatform<HashMap<String, rockspec::external_dependency::Spec>> {
897        &self.external_dependencies
898    }
899
900    fn test_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
901        &self.test_dependencies
902    }
903
904    fn build(&self) -> &rockspec::PerPlatform<rockspec::build::Spec> {
905        &self.build
906    }
907
908    fn test(&self) -> &rockspec::PerPlatform<rockspec::test::Spec> {
909        &self.test
910    }
911
912    fn build_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::build::Spec> {
913        &mut self.build
914    }
915
916    fn test_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::test::Spec> {
917        &mut self.test
918    }
919
920    fn format(&self) -> &Option<rockspec::Format> {
921        &self.rockspec_format
922    }
923
924    fn source(&self) -> &rockspec::PerPlatform<rockspec::source::Remote> {
925        &self.source
926    }
927
928    fn source_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::source::Remote> {
929        &mut self.source
930    }
931
932    fn deploy(&self) -> &rockspec::PerPlatform<rockspec::deploy::Spec> {
933        &self.deploy
934    }
935
936    fn deploy_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::deploy::Spec> {
937        &mut self.deploy
938    }
939
940    fn to_lua_remote_rockspec_string(&self) -> Result<String, rockspec::Error> {
941        let lux_toml_dir = &self.internal.lux_toml_dir;
942        let version = self
943            .internal
944            .version_template
945            .try_generate(lux_toml_dir, None)
946            .map_err(Error::from)?;
947        let source = self
948            .internal
949            .source_template
950            .try_generate(lux_toml_dir, &self.package, &version)
951            .map_err(Error::from)?;
952        Ok(self.render_rockspec(&version, Some(source.display_lua()))?)
953    }
954}
955
956/// Creates a [`build::internal::Spec`] with auto-detected modules (e.g. *.luau sources)
957/// that LuaRocks does not auto-detect, so that LuaRocks can install them.
958fn build_spec_with_autodetected_modules(
959    spec: &rockspec::build::internal::Spec,
960    project_root: &Path,
961) -> rockspec::build::internal::Spec {
962    let builtin_capable = spec.build_type.as_ref().is_none_or(|build_type| {
963        matches!(
964            build_type,
965            rockspec::build::internal::Type::Builtin | rockspec::build::internal::Type::None
966        )
967    });
968    if !builtin_capable {
969        return spec.clone();
970    }
971    let detected = match autodetect_modules(project_root, Default::default()) {
972        Ok(modules) => modules
973            .into_iter()
974            .filter_map(|(module, spec)| match spec {
975                rockspec::build::backend::ModuleSpec::SourcePath(path)
976                    if path.extension().is_some_and(|ext| ext == "luau") =>
977                {
978                    Some((module, path))
979                }
980                _ => None,
981            })
982            .collect_vec(),
983        Err(_) => return spec.clone(),
984    };
985    if detected.is_empty() {
986        spec.clone()
987    } else {
988        let mut new_spec = spec.clone();
989        let modules = new_spec.builtin_spec.get_or_insert_with(Default::default);
990        for (module, path) in detected {
991            modules
992                .entry(rockspec::serde_util::LuaTableKey::StringKey(
993                    module.to_string(),
994                ))
995                .or_insert(
996                    rockspec::build::backend::builtin::internal::ModuleSpec::SourcePath(path),
997                );
998        }
999        new_spec
1000    }
1001}
1002
1003fn validate_generated_lua(lua_str: &str) -> Result<(), Error> {
1004    let mut lua = ottavino::Lua::core();
1005    lua.try_enter(|ctx| {
1006        let closure = ottavino::Closure::load(ctx, None, lua_str.as_bytes())?;
1007        let executor = ottavino::Executor::start(ctx, closure.into(), ());
1008        if !executor.step(ctx, &mut ottavino::Fuel::with(ROCKSPEC_FUEL_LIMIT))? {
1009            return Ok(Err(Error::FuelLimitExceeded));
1010        }
1011        Ok(Ok(()))
1012    })
1013    .map_err(|err| Error::GeneratedInvalidLua(err.to_string()))?
1014}
1015
1016impl HasIntegrity for Local {
1017    async fn hash(&self) -> io::Result<Integrity> {
1018        match self.to_lua_rockspec() {
1019            Ok(lua_rockspec) => lua_rockspec.hash().await,
1020            Err(_) => self.internal.hash().await,
1021        }
1022    }
1023}
1024
1025/// The `lux.toml`, after being validated and prepared for upload
1026#[derive(Debug)]
1027pub struct Remote {
1028    local: Local,
1029    source: rockspec::PerPlatform<rockspec::source::Remote>,
1030}
1031
1032impl Remote {
1033    pub fn to_lua_rockspec(&self) -> Result<rockspec::lua::Remote, rockspec::Error> {
1034        Ok(rockspec::lua::Remote::new(
1035            &self.to_lua_remote_rockspec_string()?,
1036        )?)
1037    }
1038}
1039
1040impl Rockspec for Remote {
1041    fn package(&self) -> &package::Name {
1042        self.local.package()
1043    }
1044
1045    fn version(&self) -> &package::Version {
1046        self.local.version()
1047    }
1048
1049    fn description(&self) -> &rockspec::description::Spec {
1050        self.local.description()
1051    }
1052
1053    fn supported_platforms(&self) -> &rockspec::platform::Support {
1054        self.local.supported_platforms()
1055    }
1056
1057    fn lua(&self) -> &package::VersionReq {
1058        self.local.lua()
1059    }
1060
1061    fn dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
1062        self.local.dependencies()
1063    }
1064
1065    fn build_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
1066        self.local.build_dependencies()
1067    }
1068
1069    fn external_dependencies(
1070        &self,
1071    ) -> &rockspec::PerPlatform<HashMap<String, rockspec::external_dependency::Spec>> {
1072        self.local.external_dependencies()
1073    }
1074
1075    fn test_dependencies(&self) -> &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>> {
1076        self.local.test_dependencies()
1077    }
1078
1079    fn build(&self) -> &rockspec::PerPlatform<rockspec::build::Spec> {
1080        self.local.build()
1081    }
1082
1083    fn test(&self) -> &rockspec::PerPlatform<rockspec::test::Spec> {
1084        self.local.test()
1085    }
1086
1087    fn build_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::build::Spec> {
1088        self.local.build_mut()
1089    }
1090
1091    fn test_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::test::Spec> {
1092        self.local.test_mut()
1093    }
1094
1095    fn format(&self) -> &Option<rockspec::Format> {
1096        self.local.format()
1097    }
1098
1099    fn source(&self) -> &rockspec::PerPlatform<rockspec::source::Remote> {
1100        &self.source
1101    }
1102
1103    fn source_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::source::Remote> {
1104        &mut self.source
1105    }
1106
1107    fn deploy(&self) -> &rockspec::PerPlatform<rockspec::deploy::Spec> {
1108        self.local.deploy()
1109    }
1110
1111    fn deploy_mut(&mut self) -> &mut rockspec::PerPlatform<rockspec::deploy::Spec> {
1112        self.local.deploy_mut()
1113    }
1114
1115    fn to_lua_remote_rockspec_string(&self) -> Result<String, rockspec::Error> {
1116        let lux_toml_dir = &self.local.internal.lux_toml_dir;
1117        let starter = format!(
1118            r#"
1119rockspec_format = "{}"
1120package = "{}"
1121version = "{}""#,
1122            self.local
1123                .rockspec_format
1124                .as_ref()
1125                .unwrap_or(&rockspec::Format::default()),
1126            self.local.package,
1127            self.version()
1128        );
1129
1130        let mut template = Vec::new();
1131
1132        if self.local.description != rockspec::description::Spec::default() {
1133            template.push(self.local.description.display_lua());
1134        }
1135
1136        if self.local.supported_platforms != rockspec::platform::Support::default() {
1137            template.push(self.local.supported_platforms.display_lua());
1138        }
1139
1140        {
1141            let mut dependencies = self.local.internal.dependencies.clone().unwrap_or_default();
1142            if !self.local.lua.is_luau() {
1143                dependencies.insert(
1144                    0,
1145                    package::Req {
1146                        name: "lua".into(),
1147                        version_req: self.local.lua.clone(),
1148                    }
1149                    .into(),
1150                );
1151            }
1152            template.push(Dependencies(&dependencies).display_lua());
1153        }
1154
1155        let mut build_dependencies = self
1156            .local
1157            .internal
1158            .build_dependencies
1159            .as_ref()
1160            .cloned()
1161            .unwrap_or_default();
1162
1163        let build_backend_dependency = self
1164            .local
1165            .internal
1166            .build
1167            .build_type
1168            .as_ref()
1169            .and_then(|build_type| build_type.luarocks_build_backend());
1170
1171        if let Some(build_backend_dependency) = build_backend_dependency {
1172            build_dependencies.push(build_backend_dependency);
1173        }
1174
1175        if !build_dependencies.is_empty() {
1176            template.push(BuildDependencies(&build_dependencies).display_lua());
1177        }
1178
1179        match self.local.internal.external_dependencies {
1180            Some(ref external_dependencies) if !external_dependencies.is_empty() => {
1181                template.push(
1182                    rockspec::external_dependency::Dependencies(external_dependencies)
1183                        .display_lua(),
1184                );
1185            }
1186            _ => {}
1187        }
1188
1189        let source = self
1190            .local
1191            .internal
1192            .source_template
1193            .try_generate(lux_toml_dir, &self.local.internal.package, self.version())
1194            .map_err(Error::from)?;
1195        template.push(source.display_lua());
1196
1197        if let Some(ref deploy) = self.local.internal.deploy {
1198            template.push(deploy.display_lua());
1199        }
1200
1201        template.push(
1202            build_spec_with_autodetected_modules(&self.local.internal.build, lux_toml_dir)
1203                .display_lua(),
1204        );
1205
1206        let unformatted_code = std::iter::once(starter)
1207            .chain(template.into_iter().map(|kv| kv.to_string()))
1208            .join("\n\n");
1209        let result = match stylua_lib::format_code(
1210            &unformatted_code,
1211            stylua_lib::Config::default(),
1212            None,
1213            stylua_lib::OutputVerification::Full,
1214        ) {
1215            Ok(formatted_code) => formatted_code,
1216            Err(_) => unformatted_code,
1217        };
1218        validate_generated_lua(&result)?;
1219        Ok(result)
1220    }
1221}
1222
1223impl HasIntegrity for Remote {
1224    async fn hash(&self) -> io::Result<Integrity> {
1225        self.to_lua_rockspec()
1226            .map_err(|err| {
1227                io::Error::other(format!(
1228                    "unable to convert remote project to Lua rockspec:\n{}",
1229                    err
1230                ))
1231            })?
1232            .hash()
1233            .await
1234    }
1235}
1236
1237#[cfg(test)]
1238mod tests {
1239    use std::path::PathBuf;
1240
1241    use crate::rockspec;
1242
1243    use assert_fs::prelude::{PathChild, PathCopy, PathCreateDir};
1244    use git2::Repository;
1245    use url::Url;
1246
1247    use crate::{
1248        git::{self, url::RemoteGitUrl},
1249        project::{Project, TOML_FILE_NAME},
1250        rockspec::Rockspec,
1251    };
1252
1253    use super::Partial;
1254
1255    #[test]
1256    fn project_toml_parsing() {
1257        let project_toml = r#"
1258        package = "my-package"
1259        version = "1.0.0"
1260        lua = "5.3"
1261
1262        rockspec_format = "1.0"
1263
1264        [source]
1265        url = "https://example.com"
1266
1267        [dependencies]
1268        foo = "1.0"
1269        bar = ">=2.0"
1270
1271        [run]
1272        args = ["--foo", "--bar"]
1273
1274        [build]
1275        type = "builtin"
1276        "#;
1277
1278        let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1279        let _ = project.into_remote(None).unwrap();
1280
1281        let project_toml = r#"
1282        package = "my-package"
1283        version = "1.0.0"
1284        lua = "5.1"
1285
1286        [description]
1287        summary = "A summary"
1288        detailed = "A detailed description"
1289        license = "MIT"
1290        homepage = "https://example.com"
1291        issues_url = "https://example.com/issues"
1292        maintainer = "John Doe"
1293        labels = ["label1", "label2"]
1294
1295        [supported_platforms]
1296        linux = true
1297        windows = false
1298
1299        [dependencies]
1300        foo = "1.0"
1301        bar = ">=2.0"
1302
1303        [build_dependencies]
1304        baz = "1.0"
1305
1306        [external_dependencies.foo]
1307        header = "foo.h"
1308
1309        [external_dependencies.bar]
1310        library = "libbar.so"
1311
1312        [test_dependencies]
1313        busted = "69.420"
1314
1315        [source]
1316        url = "https://example.com"
1317        hash = "sha256-di00mD8txN7rjaVpvxzNbnQsAh6H16zUtJZapH7U4HU="
1318        file = "my-package-1.0.0.tar.gz"
1319        dir = "my-package-1.0.0"
1320
1321        [test]
1322        type = "command"
1323        script = "test.lua"
1324        flags = [ "foo", "bar" ]
1325
1326        [run]
1327        command = "my-command"
1328        args = ["--foo", "--bar"]
1329
1330        [build]
1331        type = "builtin"
1332        "#;
1333
1334        let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1335        let _ = project.into_remote(None).unwrap();
1336    }
1337
1338    #[test]
1339    fn compare_project_toml_with_rockspec() {
1340        let project_toml = r#"
1341        package = "my-package"
1342        version = "1.0.0"
1343        lua = "5.1"
1344
1345        # For testing, specify a custom rockspec format
1346        # (defaults to 3.0)
1347        rockspec_format = "1.0"
1348
1349        [description]
1350        summary = "A summary"
1351        detailed = "A detailed description"
1352        license = "MIT"
1353        homepage = "https://example.com"
1354        issues_url = "https://example.com/issues"
1355        maintainer = "John Doe"
1356        labels = ["label1", "label2"]
1357
1358        [supported_platforms]
1359        linux = true
1360        windows = false
1361
1362        [dependencies]
1363        foo = "1.0"
1364        bar = ">=2.0"
1365
1366        [build_dependencies]
1367        baz = "1.0"
1368
1369        [external_dependencies.foo]
1370        header = "foo.h"
1371
1372        [external_dependencies.bar]
1373        library = "libbar.so"
1374
1375        [test_dependencies]
1376        busted = "1.0"
1377
1378        [source]
1379        url = "https://example.com"
1380        file = "my-package-1.0.0.tar.gz"
1381        dir = "my-package-1.0.0"
1382
1383        [test]
1384        type = "command"
1385        script = "test.lua"
1386        flags = [ "foo", "bar" ]
1387
1388        [run]
1389        command = "my-command"
1390        args = ["--foo", "--bar"]
1391
1392        [deploy]
1393        wrap_bin_scripts = false
1394
1395        [build]
1396        type = "builtin"
1397
1398        [build.install.lua]
1399        "foo.bar" = "src/bar.lua"
1400
1401        [build.install.lib]
1402        "foo.baz" = "src/baz.c"
1403
1404        [build.install.bin]
1405        "bla" = "src/bla"
1406
1407        [build.install.conf]
1408        "cfg.conf" = "resources/config.conf"
1409        "#;
1410
1411        let expected_rockspec = r#"
1412            rockspec_format = "1.0"
1413            package = "my-package"
1414            version = "1.0.0"
1415
1416            source = {
1417                url = "https://example.com",
1418                file = "my-package-1.0.0.tar.gz",
1419                dir = "my-package-1.0.0",
1420            }
1421
1422            description = {
1423                summary = "A summary",
1424                detailed = "A detailed description",
1425                license = "MIT",
1426                homepage = "https://example.com",
1427                issues_url = "https://example.com/issues",
1428                maintainer = "John Doe",
1429                labels = {"label1", "label2"},
1430            }
1431
1432            supported_platforms = {"linux", "!windows"}
1433
1434            dependencies = {
1435                "lua ==5.1",
1436                "foo ==1.0",
1437                "bar >=2.0",
1438            }
1439
1440            build_dependencies = {
1441                "baz ==1.0",
1442            }
1443
1444            external_dependencies = {
1445                foo = { header = "foo.h" },
1446                bar = { library = "libbar.so" },
1447            }
1448
1449            source = {
1450                url = "https://example.com",
1451                hash = "sha256-di00mD8txN7rjaVpvxzNbnQsAh6H16zUtJZapH7U4HU=",
1452                file = "my-package-1.0.0.tar.gz",
1453                dir = "my-package-1.0.0",
1454            }
1455
1456            test = {
1457                type = "command",
1458                script = "test.lua",
1459                flags = {"foo", "bar"},
1460            }
1461
1462            deploy = {
1463                wrap_bin_scripts = false,
1464            }
1465
1466            build = {
1467                type = "builtin",
1468                install = {
1469                    lua = {
1470                        ["foo.bar"] = "src/bar.lua",
1471                    },
1472                    lib = {
1473                        ["foo.baz"] = "src/baz.c",
1474                    },
1475                    bin = {
1476                        bla = "src/bla",
1477                    },
1478                    conf = {
1479                        ["cfg.conf"] = "resources/config.conf",
1480                    },
1481                },
1482            }
1483        "#;
1484
1485        let expected_rockspec = rockspec::lua::Remote::new(expected_rockspec).unwrap();
1486
1487        let project_toml = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1488        let rockspec = project_toml
1489            .into_remote(None)
1490            .unwrap()
1491            .to_lua_rockspec()
1492            .unwrap();
1493
1494        let sorted_package_reqs =
1495            |v: &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>| {
1496                let mut v = v.current_platform().clone();
1497                v.sort_by(|a, b| a.name().cmp(b.name()));
1498                v
1499            };
1500
1501        assert_eq!(rockspec.package(), expected_rockspec.package());
1502        assert_eq!(rockspec.version(), expected_rockspec.version());
1503        assert_eq!(rockspec.description(), expected_rockspec.description());
1504        assert_eq!(
1505            rockspec.supported_platforms(),
1506            expected_rockspec.supported_platforms()
1507        );
1508        assert_eq!(
1509            sorted_package_reqs(rockspec.dependencies()),
1510            sorted_package_reqs(expected_rockspec.dependencies())
1511        );
1512        assert_eq!(
1513            sorted_package_reqs(rockspec.build_dependencies()),
1514            sorted_package_reqs(expected_rockspec.build_dependencies())
1515        );
1516        assert_eq!(
1517            rockspec.external_dependencies(),
1518            expected_rockspec.external_dependencies()
1519        );
1520        assert_eq!(rockspec.source(), expected_rockspec.source());
1521        assert_eq!(rockspec.build(), expected_rockspec.build());
1522        assert_eq!(rockspec.format(), expected_rockspec.format());
1523    }
1524
1525    #[test]
1526    fn merge_project_toml_with_partial_rockspec() {
1527        let project_toml = r#"
1528        package = "my-package"
1529        version = "1.0.0"
1530        lua = "5.1"
1531
1532        # For testing, specify a custom rockspec format
1533        # (defaults to 3.0)
1534        rockspec_format = "1.0"
1535
1536        [description]
1537        summary = "A summary"
1538        detailed = "A detailed description"
1539        license = "MIT"
1540        homepage = "https://example.com"
1541        issues_url = "https://example.com/issues"
1542        maintainer = "John Doe"
1543        labels = ["label1", "label2"]
1544
1545        [supported_platforms]
1546        linux = true
1547        windows = false
1548
1549        [dependencies]
1550        foo = "1.0"
1551        bar = ">=2.0"
1552
1553        [build_dependencies]
1554        baz = "1.0"
1555
1556        [external_dependencies.foo]
1557        header = "foo.h"
1558
1559        [external_dependencies.bar]
1560        library = "libbar.so"
1561
1562        [test_dependencies]
1563        busted = "1.0"
1564
1565        [source]
1566        url = "https://example.com"
1567        file = "my-package-1.0.0.tar.gz"
1568        dir = "my-package-1.0.0"
1569
1570        [test]
1571        type = "command"
1572        script = "test.lua"
1573        flags = [ "foo", "bar" ]
1574
1575        [run]
1576        command = "my-command"
1577        args = [ "--foo", "--bar" ]
1578
1579        [build]
1580        type = "builtin"
1581        "#;
1582
1583        let mergable_rockspec_content = r#"
1584            rockspec_format = "1.0"
1585            package = "my-package-overwritten"
1586
1587            description = {
1588                summary = "A summary overwritten",
1589                detailed = "A detailed description overwritten",
1590                license = "GPL-2.0",
1591                homepage = "https://example.com/overwritten",
1592                issues_url = "https://example.com/issues/overwritten",
1593                maintainer = "John Doe Overwritten",
1594                labels = {"over", "written"},
1595            }
1596
1597            -- Inverted supported platforms
1598            supported_platforms = {"!linux", "windows"}
1599
1600            dependencies = {
1601                "lua 5.1",
1602                "foo >1.0",
1603                "bar <=2.0",
1604            }
1605
1606            build_dependencies = {
1607                "baz >1.0",
1608            }
1609
1610            external_dependencies = {
1611                foo = { header = "overwritten.h" },
1612                bar = { library = "overwritten.so" },
1613            }
1614
1615            test = {
1616                type = "command",
1617                script = "overwritten.lua",
1618                flags = {"over", "written"},
1619            }
1620
1621            build = {
1622                type = "builtin",
1623            }
1624        "#;
1625
1626        let remote_rockspec_content = format!(
1627            r#"{}
1628            version = "1.0.0"
1629            source = {{
1630                url = "https://example.com",
1631                file = "my-package-1.0.0.tar.gz",
1632                dir = "my-package-1.0.0",
1633            }}
1634        "#,
1635            mergable_rockspec_content
1636        );
1637
1638        let project_toml = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1639        let partial_rockspec = rockspec::lua::Partial::new(mergable_rockspec_content).unwrap();
1640        let expected_rockspec = rockspec::lua::Remote::new(&remote_rockspec_content).unwrap();
1641
1642        let merged = project_toml
1643            .merge(partial_rockspec)
1644            .into_remote(None)
1645            .unwrap();
1646
1647        let sorted_package_reqs =
1648            |v: &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>| {
1649                let mut v = v.current_platform().clone();
1650                v.sort_by(|a, b| a.name().cmp(b.name()));
1651                v
1652            };
1653
1654        assert_eq!(merged.package(), expected_rockspec.package());
1655        assert_eq!(merged.version(), expected_rockspec.version());
1656        assert_eq!(merged.description(), expected_rockspec.description());
1657        assert_eq!(
1658            merged.supported_platforms(),
1659            expected_rockspec.supported_platforms()
1660        );
1661        assert_eq!(
1662            sorted_package_reqs(merged.dependencies()),
1663            sorted_package_reqs(expected_rockspec.dependencies())
1664        );
1665        assert_eq!(
1666            sorted_package_reqs(merged.build_dependencies()),
1667            sorted_package_reqs(expected_rockspec.build_dependencies())
1668        );
1669        assert_eq!(
1670            merged.external_dependencies(),
1671            expected_rockspec.external_dependencies()
1672        );
1673        assert_eq!(merged.source(), expected_rockspec.source());
1674        assert_eq!(merged.build(), expected_rockspec.build());
1675        assert_eq!(merged.format(), expected_rockspec.format());
1676        // Ensure that the run command is retained after merge.
1677        assert!(merged.local.run().is_some());
1678    }
1679
1680    #[test]
1681    fn wally_dependency_parsing() {
1682        let project_toml = r#"
1683        package = "my-package"
1684        version = "1.0.0"
1685        lua = "5.1"
1686
1687        [dependencies.roact]
1688        wally = "jsdotperf/roact@^1.4.0"
1689
1690        [build]
1691        type = "builtin"
1692        "#;
1693
1694        let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
1695        let deps = project.dependencies.unwrap();
1696        assert_eq!(deps.len(), 1);
1697        assert_eq!(deps[0].name().to_string(), "roact");
1698        assert!(matches!(
1699            deps[0].source(),
1700            Some(rockspec::source::Spec::Wally(req)) if req.name().to_string() == "jsdotperf/roact"
1701        ));
1702    }
1703
1704    #[test]
1705    fn wally_dependency_conflicts_with_version() {
1706        let project_toml = r#"
1707        package = "my-package"
1708        version = "1.0.0"
1709        lua = "5.1"
1710
1711        [dependencies.roact]
1712        wally = "jsdotperf/roact@^1.4.0"
1713        version = "1.4.0"
1714
1715        [build]
1716        type = "builtin"
1717        "#;
1718
1719        Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap_err();
1720    }
1721
1722    #[test]
1723    fn project_toml_with_lua_in_dependencies() {
1724        let project_toml = r#"
1725        package = "my-package"
1726        version = "1.0.0"
1727        # lua = ">5.1"
1728
1729        [dependencies]
1730        lua = "5.1" # disallowed
1731
1732        [build]
1733        type = "builtin"
1734        "#;
1735
1736        Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default())
1737            .unwrap()
1738            .into_local()
1739            .unwrap_err();
1740    }
1741
1742    #[test]
1743    fn project_toml_with_invalid_run_command() {
1744        for command in ["lua", "lua5.1", "lua5.2", "lua5.3", "lua5.4", "luajit"] {
1745            let project_toml = format!(
1746                r#"
1747                package = "my-package"
1748                version = "1.0.0"
1749                lua = "5.1"
1750
1751                [build]
1752                type = "builtin"
1753
1754                [run]
1755                command = "{command}"
1756                "#,
1757            );
1758
1759            Partial::new(TOML_FILE_NAME, &project_toml, PathBuf::default()).unwrap_err();
1760        }
1761    }
1762
1763    #[test]
1764    fn project_root_dir_override_and_rockspec_generation() {
1765        let project_toml = r#"
1766        package = "my-package"
1767        version = "1.0.0"
1768        lua = "5.1"
1769
1770        [project]
1771        root_dir = ".."
1772
1773        [source]
1774        url = "https://example.com"
1775
1776        [build]
1777        type = "builtin"
1778        "#;
1779
1780        let workspace_root = assert_fs::TempDir::new().unwrap();
1781        let lux_toml_dir = workspace_root.child("proj");
1782        lux_toml_dir.create_dir_all().unwrap();
1783        std::fs::write(lux_toml_dir.join(TOML_FILE_NAME), project_toml).unwrap();
1784
1785        let project =
1786            Partial::new(TOML_FILE_NAME, project_toml, lux_toml_dir.to_path_buf()).unwrap();
1787        let local = project.into_local().unwrap();
1788        let rockspec::source::Spec::File(root_dir) = &local.source().current_platform().source_spec
1789        else {
1790            panic!("expected a file source");
1791        };
1792        assert_eq!(
1793            root_dir,
1794            &std::fs::canonicalize(workspace_root.path()).unwrap()
1795        );
1796
1797        // The `[project]` table must be ignored when generating a rockspec.
1798        let rockspec = local.to_lua_rockspec().unwrap();
1799        assert!(!rockspec
1800            .to_lua_remote_rockspec_string()
1801            .unwrap()
1802            .contains("root_dir"));
1803    }
1804
1805    #[test]
1806    fn generate_non_deterministic_git_source() {
1807        let rockspec_content = r#"
1808            package = "test-package"
1809            version = "1.0.0"
1810            lua = ">=5.1"
1811
1812            [source]
1813            url = "git+https://exaple.com/repo.git"
1814
1815            [build]
1816            type = "builtin"
1817        "#;
1818
1819        Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
1820            .unwrap()
1821            .into_remote(None)
1822            .unwrap_err();
1823    }
1824
1825    #[test]
1826    fn generate_deterministic_git_source() {
1827        let rockspec_content = r#"
1828            package = "test-package"
1829            version = "1.0.0"
1830            lua = ">=5.1"
1831
1832            [source]
1833            url = "git+https://exaple.com/owner/repo.git"
1834            tag = "v0.1.0"
1835
1836            [build]
1837            type = "builtin"
1838        "#;
1839
1840        Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
1841            .unwrap()
1842            .into_remote(None)
1843            .unwrap();
1844    }
1845
1846    #[test]
1847    fn generate_git_source_with_branch() {
1848        let rockspec_content = r#"
1849            package = "test-package"
1850            version = "1.0.0"
1851            lua = ">=5.1"
1852
1853            [source]
1854            url = "git+https://example.com/owner/repo.git"
1855            branch = "main"
1856
1857            [build]
1858            type = "builtin"
1859        "#;
1860
1861        let toml = Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
1862            .unwrap()
1863            .into_remote(None)
1864            .unwrap();
1865
1866        let lua = toml.to_lua_remote_rockspec_string().unwrap();
1867        assert!(lua.contains("branch = \"main\""));
1868        assert!(!lua.contains("tag = "));
1869    }
1870
1871    fn init_git_repo(path: &std::path::Path) -> Repository {
1872        let repo = Repository::init(path).unwrap();
1873        {
1874            let tree_id = repo.index().unwrap().write_tree().unwrap();
1875            let tree = repo.find_tree(tree_id).unwrap();
1876            let sig = git2::Signature::now("name", "email").unwrap();
1877            repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
1878                .unwrap();
1879        }
1880        repo
1881    }
1882
1883    fn init_sample_project_repo(temp_dir: &assert_fs::TempDir) -> Repository {
1884        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1885            .join("resources/test/sample-projects/source-template/");
1886        temp_dir.copy_from(&sample_project, &["**"]).unwrap();
1887        init_git_repo(temp_dir.path())
1888    }
1889
1890    fn create_tag(repo: &Repository, name: &str) {
1891        let sig = git2::Signature::now("name", "email").unwrap();
1892        let id = repo.head().unwrap().target().unwrap();
1893        let obj = repo.find_object(id, None).unwrap();
1894        repo.tag(name, &obj, &sig, "msg", true).unwrap();
1895    }
1896
1897    #[test]
1898    fn test_git_project_generate_dev_source() {
1899        let project_root = assert_fs::TempDir::new().unwrap();
1900        init_sample_project_repo(&project_root);
1901        let project = Project::from_exact(&project_root).unwrap().unwrap();
1902        let remote_project_toml = project.toml().into_remote(None).unwrap();
1903        let source = remote_project_toml.source.current_platform();
1904        let source_spec = &source.source_spec;
1905        assert!(matches!(source_spec, &rockspec::source::Spec::Git { .. }));
1906        if let rockspec::source::Spec::Git(git::Source { url, git_ref }) = source_spec {
1907            let expected_url: RemoteGitUrl =
1908                "https://github.com/lumen-oss/lux.git".parse().unwrap();
1909            assert_eq!(url, &expected_url);
1910            assert!(git_ref.is_some());
1911        }
1912        assert_eq!(source.unpack_dir, Some("lux-dev".into()));
1913    }
1914
1915    #[test]
1916    fn test_git_project_generate_non_semver_tag_source() {
1917        let project_root = assert_fs::TempDir::new().unwrap();
1918        let repo = init_sample_project_repo(&project_root);
1919        let tag_name = "bla";
1920        create_tag(&repo, tag_name);
1921        let project = Project::from_exact(&project_root).unwrap().unwrap();
1922        let remote_project_toml = project.toml().into_remote(None).unwrap();
1923        let source = remote_project_toml.source.current_platform();
1924        let source_spec = &source.source_spec;
1925        assert!(matches!(source_spec, &rockspec::source::Spec::Git { .. }));
1926        if let rockspec::source::Spec::Git(git::Source { url, git_ref }) = source_spec {
1927            let expected_url: RemoteGitUrl =
1928                "https://github.com/lumen-oss/lux.git".parse().unwrap();
1929            assert_eq!(url, &expected_url);
1930            assert_eq!(git_ref, &Some(git::Ref::Tag(tag_name.to_string())));
1931        }
1932        assert_eq!(source.unpack_dir, Some("lux-dev".into()));
1933    }
1934
1935    #[test]
1936    fn test_git_project_generate_release_source_tag_with_v_prefix() {
1937        let project_root = assert_fs::TempDir::new().unwrap();
1938        let repo = init_sample_project_repo(&project_root);
1939        let tag_name = "v1.0.0";
1940        create_tag(&repo, "bla");
1941        create_tag(&repo, tag_name);
1942        let project = Project::from_exact(&project_root).unwrap().unwrap();
1943        let remote_project_toml = project.toml().into_remote(None).unwrap();
1944        let source = remote_project_toml.source.current_platform();
1945        let source_spec = &source.source_spec;
1946        assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1947        if let rockspec::source::Spec::Url(url) = source_spec {
1948            let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/v1.0.0.zip"
1949                .parse()
1950                .unwrap();
1951            assert_eq!(url, &expected_url);
1952        }
1953        assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1954    }
1955
1956    #[test]
1957    fn test_git_project_generate_release_source_tag_without_v_prefix() {
1958        let project_root = assert_fs::TempDir::new().unwrap();
1959        let repo = init_sample_project_repo(&project_root);
1960        create_tag(&repo, "bla");
1961        let tag_name = "1.0.0";
1962        create_tag(&repo, tag_name);
1963        let project = Project::from_exact(&project_root).unwrap().unwrap();
1964        let remote_project_toml = project.toml().into_remote(None).unwrap();
1965        let source = remote_project_toml.source.current_platform();
1966        let source_spec = &source.source_spec;
1967        assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1968        if let rockspec::source::Spec::Url(url) = source_spec {
1969            let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/1.0.0.zip"
1970                .parse()
1971                .unwrap();
1972            assert_eq!(url, &expected_url);
1973        }
1974        assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1975    }
1976
1977    #[test]
1978    fn test_git_project_in_subdirectory() {
1979        let temp_dir = assert_fs::TempDir::new().unwrap();
1980        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1981            .join("resources/test/sample-projects/source-template/");
1982        let project_dir = temp_dir.child("lux");
1983        project_dir.create_dir_all().unwrap();
1984        project_dir.copy_from(&sample_project, &["**"]).unwrap();
1985        let repo = init_git_repo(temp_dir.path());
1986        create_tag(&repo, "bla");
1987        let tag_name = "1.0.0";
1988        create_tag(&repo, tag_name);
1989        let project = Project::from_exact(&project_dir).unwrap().unwrap();
1990        let remote_project_toml = project.toml().into_remote(None).unwrap();
1991        let source = remote_project_toml.source.current_platform();
1992        let source_spec = &source.source_spec;
1993        assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1994        if let rockspec::source::Spec::Url(url) = source_spec {
1995            let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/1.0.0.zip"
1996                .parse()
1997                .unwrap();
1998            assert_eq!(url, &expected_url);
1999        }
2000        assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
2001    }
2002
2003    #[test]
2004    fn test_git_project_in_subdirectory_generate_dev_source() {
2005        let temp_dir = assert_fs::TempDir::new().unwrap();
2006        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2007            .join("resources/test/sample-projects/source-template/");
2008        let project_dir = temp_dir.child("lux");
2009        project_dir.create_dir_all().unwrap();
2010        project_dir.copy_from(&sample_project, &["**"]).unwrap();
2011        init_git_repo(temp_dir.path());
2012
2013        let project = Project::from_exact(&project_dir).unwrap().unwrap();
2014        let remote_project_toml = project.toml().into_remote(None).unwrap();
2015        let rockspec::source::Spec::Git(git::Source { git_ref, .. }) =
2016            &remote_project_toml.source.current_platform().source_spec
2017        else {
2018            panic!("expected a git source");
2019        };
2020        assert!(git_ref.is_some());
2021    }
2022}