Skip to main content

lux_lib/rockspec/toml/
partial.rs

1use std::collections::HashMap;
2use std::io;
3use std::path::PathBuf;
4
5use nonempty::NonEmpty;
6use serde::Deserialize;
7use ssri::Integrity;
8
9use crate::config::Config;
10use crate::fs;
11use crate::hash::HasIntegrity;
12use crate::lua;
13use crate::operations::run;
14use crate::package;
15use crate::project::{TomlDeError, TOML_FILE_NAME};
16use crate::rockspec::{self, lua_dependency, LuaVersionCompatibility};
17
18use super::gen::{PackageVersionTemplate, RockSourceTemplate};
19use super::parse_map_to_dependency_vec_opt;
20use super::GenerateVersionError;
21
22/// The `lux.toml` file for a project.
23/// The only required fields are `package` and `build`, which are required to build a project using `lux build`.
24/// The rest of the fields are optional, but are required to build a rockspec.
25#[derive(Clone, Debug, Deserialize)]
26#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
27pub struct Partial {
28    /// The name of the rock. Lux converts it to lower case when publishing.
29    #[cfg_attr(
30        feature = "schema",
31        schemars(extend("x-lux-toml-example" = r#"package = "my-lua-project""#))
32    )]
33    pub(crate) package: package::Name,
34    /// The package version. If unset, Lux derives it from the current SemVer
35    /// git tag (optional `v` prefix), falling back to "dev".
36    ///
37    /// Versions like `1.0` are corrected to `1.0.0`.
38    /// Non-SemVer versions (e.g. `1.0-rc1` instead of `1.0.0-rc1`) are treated
39    /// as Dev versions and cannot be compared with SemVer versions.
40    #[serde(default, rename = "version")]
41    #[cfg_attr(feature = "schema", schemars(with = "String"))]
42    #[cfg_attr(
43        feature = "schema",
44        schemars(extend("x-lux-toml-example" = r#"version = "1.0.0""#))
45    )]
46    pub(crate) version_template: PackageVersionTemplate,
47    /// How to build the project. See the build backend fields below.
48    ///
49    /// Rocks with C sources require a C compiler. Lux does not bundle one.
50    #[serde(default)]
51    pub(crate) build: rockspec::build::internal::Spec,
52    /// The LuaRocks rockspec format version to write to the generated rockspec
53    /// ("1.0", "2.0", "3.0", "3.1", or "3.2").
54    /// Defaults to "3.2" when `tl` is a build dependency, otherwise "3.1".
55    ///
56    /// Format 3.1 and newer expose `$(LUA_VERSION)` and
57    /// `$(<BUILD_DEPENDENCY>_ROCKDIR)` to build commands and variables.
58    #[cfg_attr(
59        feature = "schema",
60        schemars(extend("x-lux-toml-example" = r#"rockspec_format = "3.1""#))
61    )]
62    pub(crate) rockspec_format: Option<rockspec::Format>,
63    /// How to run the project with `lx run`.
64    #[serde(default)]
65    #[cfg_attr(
66        feature = "schema",
67        schemars(extend("x-lux-toml-example" = r#"
68[run]
69args = ["src/main.lua"]
70"#))
71    )]
72    pub(crate) run: Option<RunSpec>,
73    /// The Lua version requirement, e.g. ">= 5.1". Required to build a rockspec.
74    /// Set to "luau" to build and run the project with Luau.
75    #[serde(default)]
76    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
77    #[cfg_attr(
78        feature = "schema",
79        schemars(extend("x-lux-toml-example" = r#"lua = ">=5.1""#))
80    )]
81    pub(crate) lua: Option<package::VersionReq>,
82    /// Metadata published to LuaRocks.
83    #[serde(default)]
84    #[cfg_attr(
85        feature = "schema",
86        schemars(extend("x-lux-toml-example" = r#"
87[description]
88summary = "A one-line description of the package"
89detailed = """
90A longer description of the package
91that often spans multiple lines.
92"""
93license = "GPLv2"
94homepage = "https://lumen-oss.github.io"
95issues_url = "https://github.com/lumen-oss/lux/issues"
96maintainer = "neorocks org"
97labels = ["neovim", "tls", "https"]
98"#))
99    )]
100    pub(crate) description: Option<rockspec::description::Spec>,
101    /// Platforms this rock supports, mapping platform identifiers to `true` or
102    /// `false` (e.g. `linux = true`).
103    #[serde(default)]
104    #[cfg_attr(
105        feature = "schema",
106        schemars(with = "Option<std::collections::BTreeMap<String, bool>>")
107    )]
108    #[cfg_attr(
109        feature = "schema",
110        schemars(extend("x-lux-toml-example" = r#"
111[supported_platforms]
112linux = true
113windows = false
114"#))
115    )]
116    pub(crate) supported_platforms: Option<HashMap<rockspec::platform::Identifier, bool>>,
117    /// Runtime Lua dependencies, mapping package names to a version requirement
118    /// (e.g. `foo = "1.0"`) or to a detailed table with `version`, `opt`, `pin`,
119    /// `git`, `rev`, and `path` keys.
120    ///
121    /// Version requirements support the operators `==`, `~=`, `<`, `>`, `<=`,
122    /// `>=`, and `~>`. `~> 2` means `>= 2, < 3`. An operator is optional;
123    /// without one, the requirement is treated as `==`. Version requirements
124    /// are mandatory.
125    ///
126    /// Dependencies are declared under `lua`, `[dependencies]`,
127    /// `[build_dependencies]`, `[test_dependencies]`, and
128    /// `[external_dependencies]`.
129    ///
130    /// Git dependencies support the `github:` (default), `gitlab:`,
131    /// `codeberg:`, and `sourcehut:` shorthands, as well as full HTTPS and SSH
132    /// URLs. If `rev` is unset, `version` is used as the commit SHA or tag.
133    /// Lux searches the repository root for a `lux.toml` or `.rockspec` to
134    /// determine the build specification, defaulting to `builtin` if none is
135    /// found. Rocks with git dependencies cannot be published to LuaRocks. Git
136    /// dependencies that require a custom LuaRocks build backend are not
137    /// supported.
138    #[serde(default, deserialize_with = "parse_map_to_dependency_vec_opt")]
139    #[cfg_attr(
140        feature = "schema",
141        schemars(
142            with = "Option<std::collections::BTreeMap<String, crate::schema::DependencyEntry>>"
143        )
144    )]
145    #[cfg_attr(
146        feature = "schema",
147        schemars(extend("x-lux-toml-example" = r#"
148[dependencies]
149luafilesystem = "1.0.0"
150
151[dependencies.argparse]
152version = "0.7"
153opt = true
154
155[dependencies.foo]
156version = "09511782201302ade916d4b250d01a6c61b56844"
157git = "github:lunarmodules/foo"
158
159[dependencies.bar]
160path = "../bar"
161version = "1.0.0"
162"#))
163    )]
164    pub(crate) dependencies: Option<Vec<lua_dependency::Spec>>,
165    /// Dependencies needed at build time. Same syntax as `dependencies`.
166    ///
167    /// Build dependencies are installed in a separate build tree. With rockspec
168    /// format 3.1 or newer, build commands and variables can access their
169    /// installation directory through `$(<NAME>_ROCKDIR)`, where `<NAME>` is the
170    /// dependency name in uppercase.
171    ///
172    /// Only build dependencies expose this variable.
173    /// Unlike Luarocks, Lux does not make regular dependencies available at build time.
174    #[serde(default, deserialize_with = "parse_map_to_dependency_vec_opt")]
175    #[cfg_attr(
176        feature = "schema",
177        schemars(
178            with = "Option<std::collections::BTreeMap<String, crate::schema::DependencyEntry>>"
179        )
180    )]
181    #[cfg_attr(
182        feature = "schema",
183        schemars(extend("x-lux-toml-example" = r#"
184[build_dependencies]
185foo = "1.0.0"
186
187[build]
188type = "cmake"
189
190[build.variables]
191FOO_INCLUDE_DIR = "$(FOO_ROCKDIR)/include"
192"#))
193    )]
194    pub(crate) build_dependencies: Option<Vec<lua_dependency::Spec>>,
195    /// System (C/FFI) dependencies, discovered via pkg-config. Each entry may
196    /// set `header` and/or `library`.
197    #[serde(default)]
198    #[cfg_attr(
199        feature = "schema",
200        schemars(extend("x-lux-toml-example" = r#"
201[external_dependencies.OPENSSL]
202header = "openssl/ssl.h"
203library = "ssl"
204"#))
205    )]
206    pub(crate) external_dependencies: Option<HashMap<String, rockspec::external_dependency::Spec>>,
207    /// Dependencies needed when running `lx test`. Same syntax as `dependencies`.
208    #[serde(default, deserialize_with = "parse_map_to_dependency_vec_opt")]
209    #[cfg_attr(
210        feature = "schema",
211        schemars(
212            with = "Option<std::collections::BTreeMap<String, crate::schema::DependencyEntry>>"
213        )
214    )]
215    #[cfg_attr(
216        feature = "schema",
217        schemars(extend("x-lux-toml-example" = r#"
218[test_dependencies]
219busted = ">=2.0.0"
220nlua = "~>0.3"
221"#))
222    )]
223    pub(crate) test_dependencies: Option<Vec<lua_dependency::Spec>>,
224    /// Templates for generating the source URL of a release.
225    ///
226    /// Variable substitutions:
227    /// - `$(PACKAGE)`: package name
228    /// - `$(VERSION)`: package version (from the git tag if not declared)
229    /// - `$(REF)`: git tag or revision (priority: SemVer tag, tag, commit SHA)
230    /// - `$(<VAR_NAME>)`: any environment variable
231    #[serde(default, rename = "source")]
232    #[cfg_attr(
233        feature = "schema",
234        schemars(extend("x-lux-toml-example" = r#"
235[source]
236url = "https://host.com/owner/$(PACKAGE)/archive/refs/tags/$(REF).zip"
237dev = "git+https://host.com/owner/$(PACKAGE).git"
238"#))
239    )]
240    pub(crate) source_template: RockSourceTemplate,
241    /// How to run the test suite with `lx test`.
242    ///
243    /// The `busted` backend is used when a `.busted` file exists and no backend
244    /// is specified. `busted-nlua` is used when a `.busted` file exists or
245    /// `busted` and `nlua` are `test_dependencies`. The `busted-nlua` backend is
246    /// currently broken on macOS and Windows. Luau projects default to `tiniest`.
247    #[serde(default)]
248    #[cfg_attr(
249        feature = "schema",
250        schemars(extend("x-lux-toml-example" = r#"
251[test]
252type = "busted"
253flags = []
254"#))
255    )]
256    pub(crate) test: Option<rockspec::test::internal::Spec>,
257    /// Additional install and deployment options.
258    #[serde(default)]
259    #[cfg_attr(
260        feature = "schema",
261        schemars(extend("x-lux-toml-example" = r#"
262[deploy]
263wrap_bin_scripts = false
264"#))
265    )]
266    pub(crate) deploy: Option<rockspec::deploy::Spec>,
267    /// Lux-specific project settings, ignored when generating a rockspec.
268    #[serde(default)]
269    #[cfg_attr(
270        feature = "schema",
271        schemars(extend("x-lux-toml-example" = r#"
272[project]
273root_dir = ".."
274"#))
275    )]
276    pub(crate) project: ProjectSpec,
277
278    /// Used to bind the TOML to the directory containing the `lux.toml`.
279    #[serde(skip, default = "PathBuf::new")]
280    pub(super) lux_toml_dir: PathBuf,
281}
282
283impl HasIntegrity for Partial {
284    async fn hash(&self) -> io::Result<Integrity> {
285        let toml_file = self.lux_toml_dir.join(TOML_FILE_NAME);
286        let content = fs::sync::read_to_string(&toml_file).map_err(io::Error::other)?;
287        Ok(Integrity::from(&content))
288    }
289}
290
291impl Partial {
292    pub(crate) fn new(name: &str, str: &str, lux_toml_dir: PathBuf) -> Result<Self, TomlDeError> {
293        let mut this: Self = crate::project::parse_toml(name, str)?;
294        this.lux_toml_dir = lux_toml_dir.to_path_buf();
295        this.project.root = match this.project.root_dir {
296            Some(ref root_dir) => {
297                let relative_project_root = lux_toml_dir.join(root_dir);
298                std::fs::canonicalize(&relative_project_root).unwrap_or(relative_project_root)
299            }
300            None => lux_toml_dir,
301        };
302        Ok(this)
303    }
304
305    /// This project's Lua version requirement, if any
306    pub fn lua(&self) -> Option<&package::VersionReq> {
307        self.lua.as_ref()
308    }
309
310    pub fn package(&self) -> &package::Name {
311        &self.package
312    }
313
314    /// Returns the current package version, which may be generated from a template
315    pub fn version(&self) -> Result<package::Version, GenerateVersionError> {
316        self.version_template.try_generate(&self.lux_toml_dir, None)
317    }
318
319    /// Merge the `ProjectToml` struct with an unvalidated `LuaRockspec`.
320    /// The final merged struct can then be validated.
321    pub fn merge(self, other: rockspec::lua::Partial) -> Self {
322        Partial {
323            package: other.package.unwrap_or(self.package),
324            version_template: self.version_template,
325            lua: other
326                .dependencies
327                .as_ref()
328                .and_then(|deps| {
329                    deps.iter()
330                        .find(|dep| dep.name() == &"lua".into())
331                        .and_then(|dep| {
332                            if dep.version_req().is_any() {
333                                None
334                            } else {
335                                Some(dep.version_req().clone())
336                            }
337                        })
338                })
339                .or(self.lua),
340            build: other.build.unwrap_or(self.build),
341            run: self.run,
342            description: other.description.or(self.description),
343            supported_platforms: other
344                .supported_platforms
345                .map(|platform_support| platform_support.platforms().clone())
346                .or(self.supported_platforms),
347            dependencies: other
348                .dependencies
349                .map(|deps| {
350                    deps.into_iter()
351                        .filter(|dep| dep.name() != &"lua".into())
352                        .collect()
353                })
354                .or(self.dependencies),
355            build_dependencies: other.build_dependencies.or(self.build_dependencies),
356            test_dependencies: other.test_dependencies.or(self.test_dependencies),
357            external_dependencies: other.external_dependencies.or(self.external_dependencies),
358            source_template: self.source_template,
359            test: other.test.or(self.test),
360            deploy: other.deploy.or(self.deploy),
361            rockspec_format: other.format.or(self.rockspec_format),
362
363            project: self.project,
364            lux_toml_dir: self.lux_toml_dir.clone(),
365        }
366    }
367
368    pub(super) fn resolve_lua_dependency_spec(
369        &self,
370        dep: lua_dependency::Spec,
371    ) -> lua_dependency::Spec {
372        match &dep.source {
373            Some(rockspec::source::Spec::File(path)) if path.is_dir() => dep,
374            Some(rockspec::source::Spec::File(path)) => lua_dependency::Spec {
375                source: Some(rockspec::source::Spec::File(self.lux_toml_dir.join(path))),
376                ..dep
377            },
378            _ => dep,
379        }
380    }
381}
382
383impl LuaVersionCompatibility for Partial {
384    fn validate_lua_version(&self, version: &lua::Version) -> Result<(), rockspec::Error> {
385        if self.supports_lua_version(version) {
386            Ok(())
387        } else {
388            Err(rockspec::Error::UnsupportedLuaVersion(
389                version.clone(),
390                self.package().to_owned(),
391                Box::new(
392                    self.version_template
393                        .try_generate(&self.lux_toml_dir, None)
394                        .unwrap_or(package::Version::default_dev_version()),
395                ),
396            ))
397        }
398    }
399
400    fn validate_lua_version_from_config(&self, config: &Config) -> Result<(), rockspec::Error> {
401        let _ = self.lua_version_matches(config)?;
402        Ok(())
403    }
404
405    fn lua_version_matches(&self, config: &Config) -> Result<lua::Version, rockspec::Error> {
406        let version = lua::Version::from(config)?.clone();
407        if self.supports_lua_version(&version) {
408            Ok(version)
409        } else {
410            Err(rockspec::Error::UnsupportedLuaVersion(
411                version,
412                self.package.clone(),
413                Box::new(
414                    self.version_template
415                        .try_generate(&self.lux_toml_dir, None)
416                        .unwrap_or(package::Version::default_dev_version()),
417                ),
418            ))
419        }
420    }
421
422    fn supports_lua_version(&self, lua_version: &lua::Version) -> bool {
423        self.lua.as_ref().is_none_or(|lua| {
424            if lua.is_luau() {
425                return matches!(lua_version, lua::Version::Luau);
426            }
427            lua.matches(&lua_version.as_version())
428        })
429    }
430
431    fn lua_version(&self) -> Option<lua::Version> {
432        if self.lua.as_ref().is_some_and(|lua| lua.is_luau()) {
433            return Some(lua::Version::Luau);
434        }
435        for (possibility, version) in [
436            ("5.5.0", lua::Version::Lua55),
437            ("5.4.0", lua::Version::Lua54),
438            ("5.3.0", lua::Version::Lua53),
439            ("5.2.0", lua::Version::Lua52),
440            ("5.1.0", lua::Version::Lua51),
441        ] {
442            let possibility = unsafe { possibility.parse().unwrap_unchecked() };
443            if self
444                .lua
445                .as_ref()
446                .is_none_or(|lua| lua.matches(&possibility))
447            {
448                return Some(version);
449            }
450        }
451        None
452    }
453}
454
455/// Lux-specific project configuration.
456///
457/// This is not part of the rockspec format and is ignored when generating a rockspec.
458#[derive(Debug, Clone, Deserialize)]
459#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
460pub(crate) struct ProjectSpec {
461    /// The project root directory, relative to the directory containing the `lux.toml`.
462    /// Useful for multi-project workspaces, where the build files
463    /// (e.g. the cargo workspace `Cargo.toml`) do not live next to the `lux.toml`.
464    root_dir: Option<PathBuf>,
465    /// The project root directory, resolved from `root_dir` when deserializing.
466    #[serde(skip, default)]
467    pub(crate) root: PathBuf,
468}
469
470impl Default for ProjectSpec {
471    fn default() -> Self {
472        Self {
473            root_dir: None,
474            root: PathBuf::new(),
475        }
476    }
477}
478
479#[derive(Debug, Clone, Deserialize)]
480#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
481pub struct RunSpec {
482    /// The command to execute when running the project
483    pub(crate) command: Option<run::Command>,
484    /// Arguments to pass to the command
485    #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
486    pub(crate) args: Option<NonEmpty<String>>,
487}