1use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5
6use itertools::Itertools;
7use miette::Diagnostic;
8
9use crate::build::autodetect_modules;
10use crate::git;
11use crate::lockfile::OptState;
12use crate::lockfile::PinnedState;
13use crate::package;
14use crate::rockspec::{self, lua_dependency};
15use crate::wally;
16use crate::ROCKSPEC_FUEL_LIMIT;
17use serde::de;
18use serde::{Deserialize, Deserializer};
19use thiserror::Error;
20
21mod gen;
22mod local;
23mod partial;
24mod remote;
25mod validate;
26
27pub use self::gen::{GenerateSourceError, GenerateVersionError};
28pub use local::Local;
29pub use partial::{Partial, RunSpec};
30pub use remote::Remote;
31
32#[derive(Deserialize)]
33#[serde(untagged)]
34#[allow(clippy::large_enum_variant)] enum DependencyEntry {
36 Simple(package::VersionReq),
37 Detailed(DependencyTableEntry),
38}
39
40#[derive(Debug, Deserialize)]
41struct DependencyTableEntry {
42 #[serde(default)]
43 version: Option<package::VersionReq>,
44 #[serde(default)]
45 opt: Option<bool>,
46 #[serde(default)]
47 pin: Option<bool>,
48 #[serde(default)]
49 git: Option<git::remote::Shorthand>,
50 #[serde(default)]
51 path: Option<PathBuf>,
52 #[serde(default)]
53 rev: Option<String>,
54 #[serde(default)]
55 wally: Option<wally::package::Req>,
56}
57
58fn parse_map_to_dependency_vec_opt<'de, D>(
59 deserializer: D,
60) -> Result<Option<Vec<lua_dependency::Spec>>, D::Error>
61where
62 D: Deserializer<'de>,
63{
64 let packages: Option<HashMap<package::Name, DependencyEntry>> =
65 Option::deserialize(deserializer)?;
66
67 match packages {
68 None => Ok(None),
69 Some(packages) => Ok(Some(
70 packages
71 .into_iter()
72 .map(|(name, spec)| match spec {
73 DependencyEntry::Simple(version_req) => {
74 Ok(package::Req { name, version_req }.into())
75 }
76 DependencyEntry::Detailed(entry) => {
77 let DependencyTableEntry {
78 version,
79 opt,
80 pin,
81 git,
82 path,
83 rev,
84 wally,
85 } = entry;
86
87 let (version_req, source) = if let Some(wally) = wally {
88 if version.is_some() || git.is_some() || rev.is_some() || path.is_some() {
89 return Err(de::Error::custom(format!(
90 "dependency '{}' specifies 'wally', which cannot be combined with 'version', 'git', 'rev', or 'path'",
91 name
92 )));
93 }
94 (
95 package::VersionReq::SemVer(wally.version_req().clone()),
96 Some(rockspec::source::Spec::Wally(wally)),
97 )
98 } else {
99 let version = version.ok_or_else(|| {
100 de::Error::custom(format!(
101 "dependency '{name}' is missing a 'version' or 'wally' field"
102 ))
103 })?;
104 let source = match (git, rev, path) {
105 (None, None, None) => Ok(None),
106 (None, Some(_), None) => Err(de::Error::custom(format!(
107 "dependency {} specifies a 'rev', but missing a 'git' field",
108 name
109 ))),
110 (Some(git), Some(rev), None) => {
111 Ok(Some(rockspec::source::Spec::Git(git::Source {
112 url: git.into(),
113 git_ref: Some(git::Ref::Tag(rev)),
114 })))
115 }
116 (Some(git), None, None) => Ok(Some(rockspec::source::Spec::Git(git::Source {
117 url: git.into(),
118 git_ref: Some(git::Ref::Tag(
119 version
120 .clone()
121 .to_string()
122 .trim_start_matches("=")
123 .to_string(),
124 )),
125 }))),
126 (None, None, Some(path)) => Ok(Some(rockspec::source::Spec::File(path))),
127 (_, _, Some(_)) => Err(de::Error::custom(format!(
128 "dependency '{}' specifies a 'path', which cannot be combined with 'git' or 'rev'",
129 name
130 ))),
131 }?;
132 (version, source)
133 };
134
135 Ok(lua_dependency::Spec {
136 package_req: package::Req { name, version_req },
137 opt: OptState::from(opt.unwrap_or(false)),
138 pin: PinnedState::from(pin.unwrap_or(false)),
139 source,
140 })
141 }
142 })
143 .try_collect()?,
144 )),
145 }
146}
147
148#[derive(Debug, Error, Diagnostic)]
149pub enum Error {
150 #[error("error generating rockspec source")]
151 #[diagnostic(forward(0))]
152 GenerateSource(#[from] GenerateSourceError),
153 #[error("error generating rockspec version")]
154 #[diagnostic(forward(0))]
155 GenerateVersion(#[from] GenerateVersionError),
156 #[error("generated rockspec exceeds computational limit of {ROCKSPEC_FUEL_LIMIT} steps")]
157 #[diagnostic(help(
158 r#"the rockspec may be too complex or contain too many dependencies.
159 Try reducing the number of dependencies or simplifying build instructions."#
160 ))]
161 FuelLimitExceeded,
162 #[error(
163 r#"generated invalid Lua from TOML:
164{0}
165"#
166 )]
167 #[diagnostic(help("this is a bug in Lux. please report it."))]
168 GeneratedInvalidLua(String),
169 #[error("no lua version provided")]
170 #[diagnostic(help(
171 r#"add a `lua` field to your lux.toml, for example:
172
173 lua = ">=5.1""#
174 ))]
175 NoLuaVersion,
176 #[error("could not decode the test spec")]
177 #[diagnostic(forward(0))]
178 Decode(#[from] rockspec::test::DecodeError),
179 #[error("could not decode the build spec")]
180 #[diagnostic(forward(0))]
181 Build(#[from] rockspec::build::internal::Error),
182 #[error(transparent)]
183 #[diagnostic(transparent)]
184 PlatformValidation(#[from] rockspec::platform::Error),
185 #[error("{}copy_directories cannot contain a rockspec name", ._0.as_ref().map(|p| format!("{p}: ")).unwrap_or_default())]
186 CopyDirectoriesContainRockspecName(Option<String>),
187 #[error("could not decode the source spec")]
188 #[diagnostic(forward(0))]
189 RockSource(#[from] rockspec::source::Error),
190 #[error("duplicate dependencies: {0}")]
191 #[diagnostic(help("remove the duplicate entries from the [dependencies] table."))]
192 DuplicateDependencies(package::List),
193 #[error("duplicate test dependencies: {0}")]
194 #[diagnostic(help("remove the duplicate entries from the [test_dependencies] table."))]
195 DuplicateTestDependencies(package::List),
196 #[error("duplicate build dependencies: {0}")]
197 #[diagnostic(help("remove the duplicate entries from the [build_dependencies] table."))]
198 DuplicateBuildDependencies(package::List),
199 #[error(
200 r#"dependencies field cannot contain 'lua'.
201 Please provide the version in the top-level 'lua' field
202
203 Example:
204
205 ```toml
206 package = "my-package"
207 lua = ">=5.1"
208
209 [dependencies]
210 # do not add Lua here!
211 ```
212 "#
213 )]
214 DependenciesContainLua,
215}
216
217fn build_spec_with_autodetected_modules(
220 spec: &rockspec::build::internal::Spec,
221 project_root: &Path,
222) -> rockspec::build::internal::Spec {
223 let builtin_capable = spec.build_type.as_ref().is_none_or(|build_type| {
224 matches!(
225 build_type,
226 rockspec::build::internal::Type::Builtin | rockspec::build::internal::Type::None
227 )
228 });
229 if !builtin_capable {
230 return spec.clone();
231 }
232 let detected = match autodetect_modules(project_root, Default::default()) {
233 Ok((modules, _)) => modules
234 .into_iter()
235 .filter_map(|(module, spec)| match spec {
236 rockspec::build::backend::ModuleSpec::SourcePath(path)
237 if path.extension().is_some_and(|ext| ext == "luau") =>
238 {
239 Some((module, path))
240 }
241 _ => None,
242 })
243 .collect_vec(),
244 Err(_) => return spec.clone(),
245 };
246 if detected.is_empty() {
247 spec.clone()
248 } else {
249 let mut new_spec = spec.clone();
250 let modules = new_spec.builtin_spec.get_or_insert_with(Default::default);
251 for (module, path) in detected {
252 modules
253 .entry(rockspec::serde_util::LuaTableKey::StringKey(
254 module.to_string(),
255 ))
256 .or_insert(
257 rockspec::build::backend::builtin::internal::ModuleSpec::SourcePath(path),
258 );
259 }
260 new_spec
261 }
262}
263
264fn validate_generated_lua(lua_str: &str) -> Result<(), Error> {
265 let mut lua = ottavino::Lua::core();
266 lua.try_enter(|ctx| {
267 let closure = ottavino::Closure::load(ctx, None, lua_str.as_bytes())?;
268 let executor = ottavino::Executor::start(ctx, closure.into(), ());
269 if !executor.step(ctx, &mut ottavino::Fuel::with(ROCKSPEC_FUEL_LIMIT))? {
270 return Ok(Err(Error::FuelLimitExceeded));
271 }
272 Ok(Ok(()))
273 })
274 .map_err(|err| Error::GeneratedInvalidLua(err.to_string()))?
275}
276
277#[cfg(test)]
278mod tests {
279 use std::path::PathBuf;
280
281 use crate::rockspec;
282
283 use assert_fs::prelude::{PathChild, PathCopy, PathCreateDir};
284 use git2::Repository;
285 use url::Url;
286
287 use crate::{
288 git::{self},
289 project::{Project, TOML_FILE_NAME},
290 rockspec::Rockspec,
291 };
292
293 use super::Partial;
294
295 #[test]
296 fn project_toml_parsing() {
297 let project_toml = r#"
298 package = "my-package"
299 version = "1.0.0"
300 lua = "5.3"
301
302 rockspec_format = "1.0"
303
304 [source]
305 url = "https://example.com"
306
307 [dependencies]
308 foo = "1.0"
309 bar = ">=2.0"
310
311 [run]
312 args = ["--foo", "--bar"]
313
314 [build]
315 type = "builtin"
316 "#;
317
318 let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
319 let _ = project.into_remote(None).unwrap();
320
321 let project_toml = r#"
322 package = "my-package"
323 version = "1.0.0"
324 lua = "5.1"
325
326 [description]
327 summary = "A summary"
328 detailed = "A detailed description"
329 license = "MIT"
330 homepage = "https://example.com"
331 issues_url = "https://example.com/issues"
332 maintainer = "John Doe"
333 labels = ["label1", "label2"]
334
335 [supported_platforms]
336 linux = true
337 windows = false
338
339 [dependencies]
340 foo = "1.0"
341 bar = ">=2.0"
342
343 [build_dependencies]
344 baz = "1.0"
345
346 [external_dependencies.foo]
347 header = "foo.h"
348
349 [external_dependencies.bar]
350 library = "libbar.so"
351
352 [test_dependencies]
353 busted = "69.420"
354
355 [source]
356 url = "https://example.com"
357 hash = "sha256-di00mD8txN7rjaVpvxzNbnQsAh6H16zUtJZapH7U4HU="
358 file = "my-package-1.0.0.tar.gz"
359 dir = "my-package-1.0.0"
360
361 [test]
362 type = "command"
363 script = "test.lua"
364 flags = [ "foo", "bar" ]
365
366 [run]
367 command = "my-command"
368 args = ["--foo", "--bar"]
369
370 [build]
371 type = "builtin"
372 "#;
373
374 let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
375 let _ = project.into_remote(None).unwrap();
376 }
377
378 #[test]
379 fn compare_project_toml_with_rockspec() {
380 let project_toml = r#"
381 package = "my-package"
382 version = "1.0.0"
383 lua = "5.1"
384
385 # For testing, specify a custom rockspec format
386 # (defaults to 3.0)
387 rockspec_format = "1.0"
388
389 [description]
390 summary = "A summary"
391 detailed = "A detailed description"
392 license = "MIT"
393 homepage = "https://example.com"
394 issues_url = "https://example.com/issues"
395 maintainer = "John Doe"
396 labels = ["label1", "label2"]
397
398 [supported_platforms]
399 linux = true
400 windows = false
401
402 [dependencies]
403 foo = "1.0"
404 bar = ">=2.0"
405
406 [build_dependencies]
407 baz = "1.0"
408
409 [external_dependencies.foo]
410 header = "foo.h"
411
412 [external_dependencies.bar]
413 library = "libbar.so"
414
415 [test_dependencies]
416 busted = "1.0"
417
418 [source]
419 url = "https://example.com"
420 file = "my-package-1.0.0.tar.gz"
421 dir = "my-package-1.0.0"
422
423 [test]
424 type = "command"
425 script = "test.lua"
426 flags = [ "foo", "bar" ]
427
428 [run]
429 command = "my-command"
430 args = ["--foo", "--bar"]
431
432 [deploy]
433 wrap_bin_scripts = false
434
435 [build]
436 type = "builtin"
437
438 [build.install.lua]
439 "foo.bar" = "src/bar.lua"
440
441 [build.install.lib]
442 "foo.baz" = "src/baz.c"
443
444 [build.install.bin]
445 "bla" = "src/bla"
446
447 [build.install.conf]
448 "cfg.conf" = "resources/config.conf"
449 "#;
450
451 let expected_rockspec = r#"
452 rockspec_format = "1.0"
453 package = "my-package"
454 version = "1.0.0"
455
456 source = {
457 url = "https://example.com",
458 file = "my-package-1.0.0.tar.gz",
459 dir = "my-package-1.0.0",
460 }
461
462 description = {
463 summary = "A summary",
464 detailed = "A detailed description",
465 license = "MIT",
466 homepage = "https://example.com",
467 issues_url = "https://example.com/issues",
468 maintainer = "John Doe",
469 labels = {"label1", "label2"},
470 }
471
472 supported_platforms = {"linux", "!windows"}
473
474 dependencies = {
475 "lua ==5.1",
476 "foo ==1.0",
477 "bar >=2.0",
478 }
479
480 build_dependencies = {
481 "baz ==1.0",
482 }
483
484 external_dependencies = {
485 foo = { header = "foo.h" },
486 bar = { library = "libbar.so" },
487 }
488
489 source = {
490 url = "https://example.com",
491 hash = "sha256-di00mD8txN7rjaVpvxzNbnQsAh6H16zUtJZapH7U4HU=",
492 file = "my-package-1.0.0.tar.gz",
493 dir = "my-package-1.0.0",
494 }
495
496 test = {
497 type = "command",
498 script = "test.lua",
499 flags = {"foo", "bar"},
500 }
501
502 deploy = {
503 wrap_bin_scripts = false,
504 }
505
506 build = {
507 type = "builtin",
508 install = {
509 lua = {
510 ["foo.bar"] = "src/bar.lua",
511 },
512 lib = {
513 ["foo.baz"] = "src/baz.c",
514 },
515 bin = {
516 bla = "src/bla",
517 },
518 conf = {
519 ["cfg.conf"] = "resources/config.conf",
520 },
521 },
522 }
523 "#;
524
525 let expected_rockspec = rockspec::lua::Remote::new(expected_rockspec).unwrap();
526
527 let project_toml = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
528 let rockspec = project_toml
529 .into_remote(None)
530 .unwrap()
531 .to_lua_rockspec()
532 .unwrap();
533
534 let sorted_package_reqs =
535 |v: &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>| {
536 let mut v = v.current_platform().clone();
537 v.sort_by(|a, b| a.name().cmp(b.name()));
538 v
539 };
540
541 assert_eq!(rockspec.package(), expected_rockspec.package());
542 assert_eq!(rockspec.version(), expected_rockspec.version());
543 assert_eq!(rockspec.description(), expected_rockspec.description());
544 assert_eq!(
545 rockspec.supported_platforms(),
546 expected_rockspec.supported_platforms()
547 );
548 assert_eq!(
549 sorted_package_reqs(rockspec.dependencies()),
550 sorted_package_reqs(expected_rockspec.dependencies())
551 );
552 assert_eq!(
553 sorted_package_reqs(rockspec.build_dependencies()),
554 sorted_package_reqs(expected_rockspec.build_dependencies())
555 );
556 assert_eq!(
557 rockspec.external_dependencies(),
558 expected_rockspec.external_dependencies()
559 );
560 assert_eq!(rockspec.source(), expected_rockspec.source());
561 assert_eq!(rockspec.build(), expected_rockspec.build());
562 assert_eq!(rockspec.format(), expected_rockspec.format());
563 }
564
565 #[test]
566 fn merge_project_toml_with_partial_rockspec() {
567 let project_toml = r#"
568 package = "my-package"
569 version = "1.0.0"
570 lua = "5.1"
571
572 # For testing, specify a custom rockspec format
573 # (defaults to 3.0)
574 rockspec_format = "1.0"
575
576 [description]
577 summary = "A summary"
578 detailed = "A detailed description"
579 license = "MIT"
580 homepage = "https://example.com"
581 issues_url = "https://example.com/issues"
582 maintainer = "John Doe"
583 labels = ["label1", "label2"]
584
585 [supported_platforms]
586 linux = true
587 windows = false
588
589 [dependencies]
590 foo = "1.0"
591 bar = ">=2.0"
592
593 [build_dependencies]
594 baz = "1.0"
595
596 [external_dependencies.foo]
597 header = "foo.h"
598
599 [external_dependencies.bar]
600 library = "libbar.so"
601
602 [test_dependencies]
603 busted = "1.0"
604
605 [source]
606 url = "https://example.com"
607 file = "my-package-1.0.0.tar.gz"
608 dir = "my-package-1.0.0"
609
610 [test]
611 type = "command"
612 script = "test.lua"
613 flags = [ "foo", "bar" ]
614
615 [run]
616 command = "my-command"
617 args = [ "--foo", "--bar" ]
618
619 [build]
620 type = "builtin"
621 "#;
622
623 let mergable_rockspec_content = r#"
624 rockspec_format = "1.0"
625 package = "my-package-overwritten"
626
627 description = {
628 summary = "A summary overwritten",
629 detailed = "A detailed description overwritten",
630 license = "GPL-2.0",
631 homepage = "https://example.com/overwritten",
632 issues_url = "https://example.com/issues/overwritten",
633 maintainer = "John Doe Overwritten",
634 labels = {"over", "written"},
635 }
636
637 -- Inverted supported platforms
638 supported_platforms = {"!linux", "windows"}
639
640 dependencies = {
641 "lua 5.1",
642 "foo >1.0",
643 "bar <=2.0",
644 }
645
646 build_dependencies = {
647 "baz >1.0",
648 }
649
650 external_dependencies = {
651 foo = { header = "overwritten.h" },
652 bar = { library = "overwritten.so" },
653 }
654
655 test = {
656 type = "command",
657 script = "overwritten.lua",
658 flags = {"over", "written"},
659 }
660
661 build = {
662 type = "builtin",
663 }
664 "#;
665
666 let remote_rockspec_content = format!(
667 r#"{}
668 version = "1.0.0"
669 source = {{
670 url = "https://example.com",
671 file = "my-package-1.0.0.tar.gz",
672 dir = "my-package-1.0.0",
673 }}
674 "#,
675 mergable_rockspec_content
676 );
677
678 let project_toml = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
679 let partial_rockspec = rockspec::lua::Partial::new(mergable_rockspec_content).unwrap();
680 let expected_rockspec = rockspec::lua::Remote::new(&remote_rockspec_content).unwrap();
681
682 let merged = project_toml
683 .merge(partial_rockspec)
684 .into_remote(None)
685 .unwrap();
686
687 let sorted_package_reqs =
688 |v: &rockspec::PerPlatform<Vec<rockspec::lua_dependency::Spec>>| {
689 let mut v = v.current_platform().clone();
690 v.sort_by(|a, b| a.name().cmp(b.name()));
691 v
692 };
693
694 assert_eq!(merged.package(), expected_rockspec.package());
695 assert_eq!(merged.version(), expected_rockspec.version());
696 assert_eq!(merged.description(), expected_rockspec.description());
697 assert_eq!(
698 merged.supported_platforms(),
699 expected_rockspec.supported_platforms()
700 );
701 assert_eq!(
702 sorted_package_reqs(merged.dependencies()),
703 sorted_package_reqs(expected_rockspec.dependencies())
704 );
705 assert_eq!(
706 sorted_package_reqs(merged.build_dependencies()),
707 sorted_package_reqs(expected_rockspec.build_dependencies())
708 );
709 assert_eq!(
710 merged.external_dependencies(),
711 expected_rockspec.external_dependencies()
712 );
713 assert_eq!(merged.source(), expected_rockspec.source());
714 assert_eq!(merged.build(), expected_rockspec.build());
715 assert_eq!(merged.format(), expected_rockspec.format());
716 assert!(merged.local.run().is_some());
718 }
719
720 #[test]
721 fn wally_dependency_parsing() {
722 let project_toml = r#"
723 package = "my-package"
724 version = "1.0.0"
725 lua = "5.1"
726
727 [dependencies.roact]
728 wally = "jsdotperf/roact@^1.4.0"
729
730 [build]
731 type = "builtin"
732 "#;
733
734 let project = Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap();
735 let deps = project.dependencies.unwrap();
736 assert_eq!(deps.len(), 1);
737 assert_eq!(deps[0].name().to_string(), "roact");
738 assert!(matches!(
739 deps[0].source(),
740 Some(rockspec::source::Spec::Wally(req)) if req.name().to_string() == "jsdotperf/roact"
741 ));
742 }
743
744 #[test]
745 fn wally_dependency_conflicts_with_version() {
746 let project_toml = r#"
747 package = "my-package"
748 version = "1.0.0"
749 lua = "5.1"
750
751 [dependencies.roact]
752 wally = "jsdotperf/roact@^1.4.0"
753 version = "1.4.0"
754
755 [build]
756 type = "builtin"
757 "#;
758
759 Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default()).unwrap_err();
760 }
761
762 #[test]
763 fn project_toml_with_lua_in_dependencies() {
764 let project_toml = r#"
765 package = "my-package"
766 version = "1.0.0"
767 # lua = ">5.1"
768
769 [dependencies]
770 lua = "5.1" # disallowed
771
772 [build]
773 type = "builtin"
774 "#;
775
776 Partial::new(TOML_FILE_NAME, project_toml, PathBuf::default())
777 .unwrap()
778 .into_local()
779 .unwrap_err();
780 }
781
782 #[test]
783 fn project_toml_with_invalid_run_command() {
784 for command in ["lua", "lua5.1", "lua5.2", "lua5.3", "lua5.4", "luajit"] {
785 let project_toml = format!(
786 r#"
787 package = "my-package"
788 version = "1.0.0"
789 lua = "5.1"
790
791 [build]
792 type = "builtin"
793
794 [run]
795 command = "{command}"
796 "#,
797 );
798
799 Partial::new(TOML_FILE_NAME, &project_toml, PathBuf::default()).unwrap_err();
800 }
801 }
802
803 #[test]
804 fn project_root_dir_override_and_rockspec_generation() {
805 let project_toml = r#"
806 package = "my-package"
807 version = "1.0.0"
808 lua = "5.1"
809
810 [project]
811 root_dir = ".."
812
813 [source]
814 url = "https://example.com"
815
816 [build]
817 type = "builtin"
818 "#;
819
820 let workspace_root = assert_fs::TempDir::new().unwrap();
821 let lux_toml_dir = workspace_root.child("proj");
822 lux_toml_dir.create_dir_all().unwrap();
823 std::fs::write(lux_toml_dir.join(TOML_FILE_NAME), project_toml).unwrap();
824
825 let project =
826 Partial::new(TOML_FILE_NAME, project_toml, lux_toml_dir.to_path_buf()).unwrap();
827 let local = project.into_local().unwrap();
828 let rockspec::source::Spec::File(root_dir) = &local.source().current_platform().source_spec
829 else {
830 panic!("expected a file source");
831 };
832 assert_eq!(
833 root_dir,
834 &std::fs::canonicalize(workspace_root.path()).unwrap()
835 );
836
837 let rockspec = local.to_lua_rockspec().unwrap();
839 assert!(!rockspec
840 .to_lua_remote_rockspec_string()
841 .unwrap()
842 .contains("root_dir"));
843 }
844
845 #[test]
846 fn generate_non_deterministic_git_source() {
847 let rockspec_content = r#"
848 package = "test-package"
849 version = "1.0.0"
850 lua = ">=5.1"
851
852 [source]
853 url = "git+https://exaple.com/repo.git"
854
855 [build]
856 type = "builtin"
857 "#;
858
859 Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
860 .unwrap()
861 .into_remote(None)
862 .unwrap_err();
863 }
864
865 #[test]
866 fn generate_deterministic_git_source() {
867 let rockspec_content = r#"
868 package = "test-package"
869 version = "1.0.0"
870 lua = ">=5.1"
871
872 [source]
873 url = "git+https://exaple.com/owner/repo.git"
874 tag = "v0.1.0"
875
876 [build]
877 type = "builtin"
878 "#;
879
880 Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
881 .unwrap()
882 .into_remote(None)
883 .unwrap();
884 }
885
886 #[test]
887 fn generated_rockspec_format_follows_teal_build_dependency() {
888 let rockspec = |build_dependencies: &str| {
889 let content = format!(
890 r#"
891package = "test-package"
892version = "1.0.0"
893lua = ">=5.1"
894
895[source]
896url = "git+https://example.com/owner/repo.git"
897tag = "v0.1.0"
898
899[build]
900type = "builtin"
901{build_dependencies}
902"#
903 );
904 Partial::new(TOML_FILE_NAME, &content, PathBuf::default())
905 .unwrap()
906 .into_remote(None)
907 .unwrap()
908 .to_lua_remote_rockspec_string()
909 .unwrap()
910 };
911 assert!(rockspec("").contains("rockspec_format = \"3.1\""));
912 assert!(
913 rockspec("[build_dependencies]\ntl = \">=0.24\"").contains("rockspec_format = \"3.2\"")
914 );
915 }
916
917 #[test]
918 fn generate_git_source_with_branch() {
919 let rockspec_content = r#"
920 package = "test-package"
921 version = "1.0.0"
922 lua = ">=5.1"
923
924 [source]
925 url = "git+https://example.com/owner/repo.git"
926 branch = "main"
927
928 [build]
929 type = "builtin"
930 "#;
931
932 let toml = Partial::new(TOML_FILE_NAME, rockspec_content, PathBuf::default())
933 .unwrap()
934 .into_remote(None)
935 .unwrap();
936
937 let lua = toml.to_lua_remote_rockspec_string().unwrap();
938 assert!(lua.contains("branch = \"main\""));
939 assert!(!lua.contains("tag = "));
940 }
941
942 fn init_git_repo(path: &std::path::Path) -> Repository {
943 let repo = Repository::init(path).unwrap();
944 {
945 let tree_id = repo.index().unwrap().write_tree().unwrap();
946 let tree = repo.find_tree(tree_id).unwrap();
947 let sig = git2::Signature::now("name", "email").unwrap();
948 repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
949 .unwrap();
950 }
951 repo
952 }
953
954 fn init_sample_project_repo(temp_dir: &assert_fs::TempDir) -> Repository {
955 let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
956 .join("resources/test/sample-projects/source-template/");
957 temp_dir.copy_from(&sample_project, &["**"]).unwrap();
958 init_git_repo(temp_dir.path())
959 }
960
961 fn create_tag(repo: &Repository, name: &str) {
962 let sig = git2::Signature::now("name", "email").unwrap();
963 let id = repo.head().unwrap().target().unwrap();
964 let obj = repo.find_object(id, None).unwrap();
965 repo.tag(name, &obj, &sig, "msg", true).unwrap();
966 }
967
968 #[test]
969 fn test_git_project_generate_dev_source() {
970 let project_root = assert_fs::TempDir::new().unwrap();
971 init_sample_project_repo(&project_root);
972 let project = Project::from_exact(&project_root).unwrap().unwrap();
973 let remote_project_toml = project.toml().into_remote(None).unwrap();
974 let source = remote_project_toml.source.current_platform();
975 let source_spec = &source.source_spec;
976 assert!(matches!(source_spec, &rockspec::source::Spec::Git { .. }));
977 if let rockspec::source::Spec::Git(git::Source { url, git_ref }) = source_spec {
978 let expected_url: git::remote::Url =
979 "https://github.com/lumen-oss/lux.git".parse().unwrap();
980 assert_eq!(url, &expected_url);
981 assert!(git_ref.is_some());
982 }
983 assert_eq!(source.unpack_dir, Some("lux-dev".into()));
984 }
985
986 #[test]
987 fn test_git_project_generate_non_semver_tag_source() {
988 let project_root = assert_fs::TempDir::new().unwrap();
989 let repo = init_sample_project_repo(&project_root);
990 let tag_name = "bla";
991 create_tag(&repo, tag_name);
992 let project = Project::from_exact(&project_root).unwrap().unwrap();
993 let remote_project_toml = project.toml().into_remote(None).unwrap();
994 let source = remote_project_toml.source.current_platform();
995 let source_spec = &source.source_spec;
996 assert!(matches!(source_spec, &rockspec::source::Spec::Git { .. }));
997 if let rockspec::source::Spec::Git(git::Source { url, git_ref }) = source_spec {
998 let expected_url: git::remote::Url =
999 "https://github.com/lumen-oss/lux.git".parse().unwrap();
1000 assert_eq!(url, &expected_url);
1001 assert_eq!(git_ref, &Some(git::Ref::Tag(tag_name.to_string())));
1002 }
1003 assert_eq!(source.unpack_dir, Some("lux-dev".into()));
1004 }
1005
1006 #[test]
1007 fn test_git_project_generate_release_source_tag_with_v_prefix() {
1008 let project_root = assert_fs::TempDir::new().unwrap();
1009 let repo = init_sample_project_repo(&project_root);
1010 let tag_name = "v1.0.0";
1011 create_tag(&repo, "bla");
1012 create_tag(&repo, tag_name);
1013 let project = Project::from_exact(&project_root).unwrap().unwrap();
1014 let remote_project_toml = project.toml().into_remote(None).unwrap();
1015 let source = remote_project_toml.source.current_platform();
1016 let source_spec = &source.source_spec;
1017 assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1018 if let rockspec::source::Spec::Url(url) = source_spec {
1019 let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/v1.0.0.zip"
1020 .parse()
1021 .unwrap();
1022 assert_eq!(url, &expected_url);
1023 }
1024 assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1025 }
1026
1027 #[test]
1028 fn test_git_project_generate_release_source_tag_without_v_prefix() {
1029 let project_root = assert_fs::TempDir::new().unwrap();
1030 let repo = init_sample_project_repo(&project_root);
1031 create_tag(&repo, "bla");
1032 let tag_name = "1.0.0";
1033 create_tag(&repo, tag_name);
1034 let project = Project::from_exact(&project_root).unwrap().unwrap();
1035 let remote_project_toml = project.toml().into_remote(None).unwrap();
1036 let source = remote_project_toml.source.current_platform();
1037 let source_spec = &source.source_spec;
1038 assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1039 if let rockspec::source::Spec::Url(url) = source_spec {
1040 let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/1.0.0.zip"
1041 .parse()
1042 .unwrap();
1043 assert_eq!(url, &expected_url);
1044 }
1045 assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1046 }
1047
1048 #[test]
1049 fn test_git_project_in_subdirectory() {
1050 let temp_dir = assert_fs::TempDir::new().unwrap();
1051 let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1052 .join("resources/test/sample-projects/source-template/");
1053 let project_dir = temp_dir.child("lux");
1054 project_dir.create_dir_all().unwrap();
1055 project_dir.copy_from(&sample_project, &["**"]).unwrap();
1056 let repo = init_git_repo(temp_dir.path());
1057 create_tag(&repo, "bla");
1058 let tag_name = "1.0.0";
1059 create_tag(&repo, tag_name);
1060 let project = Project::from_exact(&project_dir).unwrap().unwrap();
1061 let remote_project_toml = project.toml().into_remote(None).unwrap();
1062 let source = remote_project_toml.source.current_platform();
1063 let source_spec = &source.source_spec;
1064 assert!(matches!(source_spec, &rockspec::source::Spec::Url { .. }));
1065 if let rockspec::source::Spec::Url(url) = source_spec {
1066 let expected_url: Url = "https://github.com/lumen-oss/lux/archive/refs/tags/1.0.0.zip"
1067 .parse()
1068 .unwrap();
1069 assert_eq!(url, &expected_url);
1070 }
1071 assert_eq!(source.unpack_dir, Some("lux-1.0.0".into()));
1072 }
1073
1074 #[test]
1075 fn test_git_project_in_subdirectory_generate_dev_source() {
1076 let temp_dir = assert_fs::TempDir::new().unwrap();
1077 let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1078 .join("resources/test/sample-projects/source-template/");
1079 let project_dir = temp_dir.child("lux");
1080 project_dir.create_dir_all().unwrap();
1081 project_dir.copy_from(&sample_project, &["**"]).unwrap();
1082 init_git_repo(temp_dir.path());
1083
1084 let project = Project::from_exact(&project_dir).unwrap().unwrap();
1085 let remote_project_toml = project.toml().into_remote(None).unwrap();
1086 let rockspec::source::Spec::Git(git::Source { git_ref, .. }) =
1087 &remote_project_toml.source.current_platform().source_spec
1088 else {
1089 panic!("expected a git source");
1090 };
1091 assert!(git_ref.is_some());
1092 }
1093}