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#[derive(Clone, Debug, Deserialize)]
26#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
27pub struct Partial {
28 #[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 #[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 #[serde(default)]
51 pub(crate) build: rockspec::build::internal::Spec,
52 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 pub fn version(&self) -> Result<package::Version, GenerateVersionError> {
316 self.version_template.try_generate(&self.lux_toml_dir, None)
317 }
318
319 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#[derive(Debug, Clone, Deserialize)]
459#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
460pub(crate) struct ProjectSpec {
461 root_dir: Option<PathBuf>,
465 #[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 pub(crate) command: Option<run::Command>,
484 #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
486 pub(crate) args: Option<NonEmpty<String>>,
487}