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