1use crate::package;
2use std::collections::{BTreeMap, HashSet};
3use std::fmt::Display;
4use std::io::{self, Write};
5use std::marker::PhantomData;
6use std::{
7 collections::HashMap,
8 fs::File,
9 io::ErrorKind,
10 path::{Path, PathBuf},
11};
12
13use itertools::Itertools;
14
15use miette::Diagnostic;
16use serde::{de, Deserialize, Serialize, Serializer};
17use sha2::{Digest, Sha256};
18use ssri::Integrity;
19use strum_macros::EnumIter;
20use thiserror::Error;
21use url::Url;
22
23use crate::fs;
24use crate::remote;
25use crate::rockspec::lua_dependency;
26use crate::rockspec::RockBinaries;
27use crate::tree::{EntryType, InstallTree, Tree};
28
29pub mod constraint;
30mod guard;
31
32pub use constraint::Constraint;
33pub use guard::Guard;
34
35const LOCKFILE_VERSION: u64 = 2;
38pub(crate) const LOCKFILE_VERSION_STR: &str = "2.0.0";
39
40#[derive(Copy, Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord, Default)]
41pub enum PinnedState {
42 #[default]
44 Unpinned,
45 Pinned,
47}
48
49impl Display for PinnedState {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 match &self {
52 PinnedState::Unpinned => "unpinned".fmt(f),
53 PinnedState::Pinned => "pinned".fmt(f),
54 }
55 }
56}
57
58impl From<bool> for PinnedState {
59 fn from(value: bool) -> Self {
60 if value {
61 Self::Pinned
62 } else {
63 Self::Unpinned
64 }
65 }
66}
67
68impl PinnedState {
69 pub fn as_bool(&self) -> bool {
70 match self {
71 Self::Unpinned => false,
72 Self::Pinned => true,
73 }
74 }
75
76 fn is_default(&self) -> bool {
77 &Self::default() == self
78 }
79}
80
81impl Serialize for PinnedState {
82 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
83 where
84 S: serde::Serializer,
85 {
86 serializer.serialize_bool(self.as_bool())
87 }
88}
89
90impl<'de> Deserialize<'de> for PinnedState {
91 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
92 where
93 D: serde::Deserializer<'de>,
94 {
95 Ok(match bool::deserialize(deserializer)? {
96 false => Self::Unpinned,
97 true => Self::Pinned,
98 })
99 }
100}
101
102#[derive(Copy, Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord, Default)]
103pub enum OptState {
104 #[default]
106 Required,
107 Optional,
109}
110
111impl OptState {
112 pub(crate) fn as_bool(&self) -> bool {
113 match self {
114 Self::Required => false,
115 Self::Optional => true,
116 }
117 }
118
119 fn is_default(&self) -> bool {
120 &Self::default() == self
121 }
122}
123
124impl From<bool> for OptState {
125 fn from(value: bool) -> Self {
126 if value {
127 Self::Optional
128 } else {
129 Self::Required
130 }
131 }
132}
133
134impl Display for OptState {
135 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136 match &self {
137 OptState::Required => "required".fmt(f),
138 OptState::Optional => "optional".fmt(f),
139 }
140 }
141}
142
143impl Serialize for OptState {
144 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
145 where
146 S: serde::Serializer,
147 {
148 serializer.serialize_bool(self.as_bool())
149 }
150}
151
152impl<'de> Deserialize<'de> for OptState {
153 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
154 where
155 D: serde::Deserializer<'de>,
156 {
157 Ok(match bool::deserialize(deserializer)? {
158 false => Self::Required,
159 true => Self::Optional,
160 })
161 }
162}
163
164#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
165pub struct LockedPackageSpec {
166 name: package::Name,
167 version: package::Version,
168 pinned: PinnedState,
169 opt: OptState,
170 dependencies: Vec<LockedPackageId>,
171 build_dependencies: Vec<LockedPackageId>,
172 constraint: Option<String>,
174}
175
176#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Clone)]
183pub struct LockedPackageId(String);
184
185impl LockedPackageId {
186 pub fn new(
187 name: &package::Name,
188 version: &package::Version,
189 pinned: PinnedState,
190 opt: OptState,
191 constraint: Constraint,
192 ) -> Self {
193 let mut hasher = Sha256::new();
194
195 hasher.update(format!(
196 "{}{}{}{}{}",
197 name,
198 version,
199 pinned.as_bool(),
200 opt.as_bool(),
201 match constraint {
202 Constraint::Unconstrained => String::default(),
203 Constraint::Constrained(version_req) => version_req.to_string(),
204 },
205 ));
206
207 Self(hex::encode(hasher.finalize()))
208 }
209
210 pub unsafe fn from_unchecked(str: String) -> Self {
218 Self(str)
219 }
220
221 pub fn into_string(self) -> String {
222 self.0
223 }
224}
225
226impl Display for LockedPackageId {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 self.0.fmt(f)
229 }
230}
231
232impl LockedPackageSpec {
233 #[allow(clippy::too_many_arguments)]
234 pub(crate) fn new(
235 name: &package::Name,
236 version: &package::Version,
237 constraint: Constraint,
238 dependencies: Vec<LockedPackageId>,
239 build_dependencies: Vec<LockedPackageId>,
240 pinned: &PinnedState,
241 opt: &OptState,
242 ) -> Self {
243 Self {
244 name: name.clone(),
245 version: version.clone(),
246 pinned: *pinned,
247 opt: *opt,
248 dependencies,
249 build_dependencies,
250 constraint: match constraint {
251 Constraint::Unconstrained => None,
252 Constraint::Constrained(version_req) => Some(version_req.to_string()),
253 },
254 }
255 }
256
257 pub fn id(&self) -> LockedPackageId {
258 LockedPackageId::new(
259 self.name(),
260 self.version(),
261 self.pinned,
262 self.opt,
263 match &self.constraint {
264 None => Constraint::Unconstrained,
265 Some(_) => self.constraint(),
266 },
267 )
268 }
269
270 pub fn constraint(&self) -> Constraint {
271 unsafe { Constraint::try_from(&self.constraint).unwrap_unchecked() }
273 }
274
275 pub fn name(&self) -> &package::Name {
276 &self.name
277 }
278
279 pub fn version(&self) -> &package::Version {
280 &self.version
281 }
282
283 pub fn pinned(&self) -> PinnedState {
284 self.pinned
285 }
286
287 pub fn opt(&self) -> OptState {
288 self.opt
289 }
290
291 pub fn dependencies(&self) -> Vec<&LockedPackageId> {
292 self.dependencies.iter().collect()
293 }
294
295 pub fn build_dependencies(&self) -> Vec<&LockedPackageId> {
296 self.build_dependencies.iter().collect()
297 }
298
299 pub fn to_package(&self) -> package::Spec {
300 package::Spec::new(self.name.clone(), self.version.clone())
301 }
302
303 pub fn into_package_req(self) -> package::Req {
304 match self.constraint() {
305 Constraint::Unconstrained => self.name.into(),
306 Constraint::Constrained(version_req) => package::Req {
307 name: self.name,
308 version_req,
309 },
310 }
311 }
312
313 pub(crate) fn as_package_req(&self) -> package::Req {
314 match self.constraint() {
315 Constraint::Unconstrained => self.name.clone().into(),
316 Constraint::Constrained(version_req) => package::Req {
317 name: self.name.clone(),
318 version_req: version_req.clone(),
319 },
320 }
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
325#[serde(rename_all = "lowercase", tag = "type")]
326pub(crate) enum RemotePackageSourceUrl {
327 Git {
328 url: String,
329 #[serde(rename = "ref")]
330 checkout_ref: String,
331 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
334 submodules: bool,
335 }, Url {
337 #[serde(deserialize_with = "deserialize_url", serialize_with = "serialize_url")]
338 url: Url,
339 },
340 File {
341 path: PathBuf,
342 },
343}
344
345impl Display for RemotePackageSourceUrl {
346 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347 match self {
348 RemotePackageSourceUrl::Git {
349 url, checkout_ref, ..
350 } => format!("{url}@{checkout_ref}").fmt(f),
351 RemotePackageSourceUrl::Url { url } => url.fmt(f),
352 RemotePackageSourceUrl::File { path } => format!("{}", path.display()).fmt(f),
353 }
354 }
355}
356
357#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
361pub struct LockedPackage {
362 pub(crate) spec: LockedPackageSpec,
363 pub(crate) source: remote::package::Source,
364 pub(crate) source_url: Option<RemotePackageSourceUrl>,
365 pub(crate) hashes: LockedPackageHashes,
366}
367
368impl LockedPackage {
369 pub(crate) fn repin(mut self, pinned: PinnedState) -> Self {
370 self.spec.pinned = pinned;
371 self
372 }
373
374 #[cfg(test)]
375 pub(crate) fn from(
376 package: &package::Spec,
377 constraint: Constraint,
378 source: remote::package::Source,
379 source_url: Option<RemotePackageSourceUrl>,
380 hashes: LockedPackageHashes,
381 ) -> Self {
382 Self::new(
383 LockedPackageSpec::new(
384 package.name(),
385 package.version(),
386 constraint,
387 Vec::default(),
388 Vec::default(),
389 &PinnedState::Unpinned,
390 &OptState::Required,
391 ),
392 source,
393 source_url,
394 hashes,
395 )
396 }
397
398 pub(crate) fn new(
399 spec: LockedPackageSpec,
400 source: remote::package::Source,
401 source_url: Option<RemotePackageSourceUrl>,
402 hashes: LockedPackageHashes,
403 ) -> Self {
404 Self {
405 spec,
406 source,
407 source_url,
408 hashes,
409 }
410 }
411
412 pub fn spec(&self) -> &LockedPackageSpec {
413 &self.spec
414 }
415
416 pub fn into_package_spec(self) -> package::Spec {
417 self.spec.to_package()
418 }
419
420 pub fn as_package_spec(&self) -> package::Spec {
421 self.spec.to_package()
422 }
423
424 pub fn id(&self) -> LockedPackageId {
425 self.spec.id()
426 }
427
428 pub fn name(&self) -> &package::Name {
429 self.spec.name()
430 }
431
432 pub fn version(&self) -> &package::Version {
433 self.spec.version()
434 }
435
436 pub fn pinned(&self) -> PinnedState {
437 self.spec.pinned()
438 }
439
440 pub fn opt(&self) -> OptState {
441 self.spec.opt()
442 }
443
444 pub fn dependencies(&self) -> Vec<&LockedPackageId> {
445 self.spec.dependencies()
446 }
447
448 pub fn build_dependencies(&self) -> Vec<&LockedPackageId> {
449 self.spec.build_dependencies()
450 }
451
452 pub fn constraint(&self) -> Constraint {
453 self.spec.constraint()
454 }
455
456 pub(crate) fn source(&self) -> &remote::package::Source {
457 &self.source
458 }
459
460 pub(crate) fn source_url(&self) -> Option<&RemotePackageSourceUrl> {
461 self.source_url.as_ref()
462 }
463
464 pub fn hashes(&self) -> &LockedPackageHashes {
465 &self.hashes
466 }
467
468 pub fn to_package(&self) -> package::Spec {
469 self.spec.to_package()
470 }
471
472 pub fn into_package_req(self) -> package::Req {
473 self.spec.into_package_req()
474 }
475}
476
477#[derive(Debug, Serialize, Deserialize, Clone)]
478struct LockedPackageIntermediate {
479 name: package::Name,
480 version: package::Version,
481 #[serde(default, skip_serializing_if = "PinnedState::is_default")]
482 pinned: PinnedState,
483 #[serde(default, skip_serializing_if = "OptState::is_default")]
484 opt: OptState,
485 #[serde(default, skip_serializing_if = "Vec::is_empty")]
486 dependencies: Vec<LockedPackageId>,
487 #[serde(default, skip_serializing_if = "Vec::is_empty")]
488 build_dependencies: Vec<LockedPackageId>,
489 #[serde(default, skip_serializing_if = "Option::is_none")]
490 constraint: Option<String>,
491 source: remote::package::Source,
492 #[serde(default, skip_serializing_if = "Option::is_none")]
493 source_url: Option<RemotePackageSourceUrl>,
494 hashes: LockedPackageHashes,
495}
496
497impl TryFrom<LockedPackageIntermediate> for LockedPackage {
498 type Error = constraint::Error;
499
500 fn try_from(value: LockedPackageIntermediate) -> Result<Self, Self::Error> {
501 let constraint = Constraint::try_from(&value.constraint)?;
502 Ok(Self {
503 spec: LockedPackageSpec::new(
504 &value.name,
505 &value.version,
506 constraint,
507 value.dependencies,
508 value.build_dependencies,
509 &value.pinned,
510 &value.opt,
511 ),
512 source: value.source,
513 source_url: value.source_url,
514 hashes: value.hashes,
515 })
516 }
517}
518
519impl From<&LockedPackage> for LockedPackageIntermediate {
520 fn from(value: &LockedPackage) -> Self {
521 Self {
522 name: value.spec.name.clone(),
523 version: value.spec.version.clone(),
524 pinned: value.spec.pinned,
525 opt: value.spec.opt,
526 dependencies: value.spec.dependencies.clone(),
527 build_dependencies: value.spec.build_dependencies.clone(),
528 constraint: value.spec.constraint.clone(),
529 source: value.source.clone(),
530 source_url: value.source_url.clone(),
531 hashes: value.hashes.clone(),
532 }
533 }
534}
535
536impl<'de> Deserialize<'de> for LockedPackage {
537 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
538 where
539 D: serde::Deserializer<'de>,
540 {
541 LockedPackage::try_from(LockedPackageIntermediate::deserialize(deserializer)?)
542 .map_err(de::Error::custom)
543 }
544}
545
546impl Serialize for LockedPackage {
547 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
548 where
549 S: serde::Serializer,
550 {
551 LockedPackageIntermediate::from(self).serialize(serializer)
552 }
553}
554
555#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Hash)]
556pub struct LockedPackageHashes {
557 pub rockspec: Integrity,
558 pub source: Integrity,
559}
560
561impl Ord for LockedPackageHashes {
562 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
563 let a = (self.rockspec.to_hex().1, self.source.to_hex().1);
564 let b = (other.rockspec.to_hex().1, other.source.to_hex().1);
565 a.cmp(&b)
566 }
567}
568
569impl PartialOrd for LockedPackageHashes {
570 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
571 Some(self.cmp(other))
572 }
573}
574
575pub trait LockfilePermissions {}
576#[derive(Clone)]
577pub struct ReadOnly;
578#[derive(Clone)]
579pub struct ReadWrite;
580
581impl LockfilePermissions for ReadOnly {}
582impl LockfilePermissions for ReadWrite {}
583
584#[derive(Clone, Debug, Serialize, Deserialize, Default)]
585pub(crate) struct PackageLock {
586 rocks: BTreeMap<LockedPackageId, LockedPackage>,
589
590 pub(crate) entrypoints: BTreeMap<package::Name, LockedPackageId>,
592}
593
594impl PackageLock {
595 pub(crate) fn from_packages(
596 packages: impl Iterator<Item = (LockedPackage, EntryType)>,
597 ) -> Self {
598 let mut lock = Self::default();
599
600 for (package, entry_type) in packages {
601 if matches!(entry_type, EntryType::Entrypoint) {
602 lock.entrypoints
603 .insert(package.name().clone(), package.id());
604 }
605 lock.rocks.insert(package.id(), package);
606 }
607
608 lock
609 }
610
611 pub(crate) fn merge(&mut self, other: &PackageLock) {
612 self.entrypoints.extend(
613 other
614 .entrypoints
615 .iter()
616 .map(|(name, id)| (name.clone(), id.clone())),
617 );
618 self.rocks.extend(
619 other
620 .rocks
621 .iter()
622 .map(|(id, package)| (id.clone(), package.clone())),
623 );
624 }
625
626 pub(crate) fn get(&self, id: &LockedPackageId) -> Option<&LockedPackage> {
627 self.rocks.get(id)
628 }
629
630 pub(crate) fn is_empty(&self) -> bool {
631 self.rocks.is_empty()
632 }
633
634 pub(crate) fn rocks(&self) -> &BTreeMap<LockedPackageId, LockedPackage> {
635 &self.rocks
636 }
637
638 pub(crate) fn is_entrypoint(&self, package: &LockedPackageId) -> bool {
639 self.entrypoints.values().any(|id| id == package)
640 }
641
642 pub(crate) fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
644 self.entrypoints.get(name).and_then(|id| self.get(id))
645 }
646
647 pub(crate) fn is_dependency(&self, package: &LockedPackageId) -> bool {
648 self.rocks
649 .values()
650 .flat_map(|rock| rock.dependencies())
651 .any(|dep_id| dep_id == package)
652 }
653
654 pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
655 self.rocks()
656 .values()
657 .cloned()
658 .map(|locked_rock| (locked_rock.name().clone(), locked_rock))
659 .into_group_map()
660 }
661
662 pub(crate) fn remove(&mut self, target: &LockedPackage) {
663 self.remove_by_id(&target.id())
664 }
665
666 pub(crate) fn remove_by_id(&mut self, target: &LockedPackageId) {
667 self.rocks.remove(target);
668 self.entrypoints.retain(|_, id| id != target);
669 }
670
671 pub(crate) fn has_rock(
672 &self,
673 req: &package::Req,
674 filter: Option<remote::package::kind::FilterSpec>,
675 ) -> Option<LockedPackage> {
676 self.list()
677 .get(req.name())
678 .map(|packages| {
679 packages
680 .iter()
681 .filter(|package| match &filter {
682 Some(filter_spec) => match &package.source {
683 remote::package::Source::LuarocksRockspec(_) => filter_spec.rockspec,
684 remote::package::Source::LuarocksSrcRock(_) => filter_spec.src,
685 remote::package::Source::LuarocksBinaryRock(_) => filter_spec.binary,
686 remote::package::Source::Wally(_) => true,
687 remote::package::Source::RockspecContent(_) => true,
688 remote::package::Source::Local => true,
689 #[cfg(test)]
690 remote::package::Source::Test => unimplemented!(),
691 },
692 None => true,
693 })
694 .rev()
695 .find(|package| req.version_req().matches(package.version()))
696 })?
697 .cloned()
698 }
699
700 pub(crate) fn has_rock_with_equal_constraint(
701 &self,
702 req: &lua_dependency::Spec,
703 ) -> Option<LockedPackage> {
704 self.list()
705 .get(req.name())
706 .map(|packages| {
707 packages
708 .iter()
709 .rev()
710 .find(|package| package.constraint().matches_version_req(req.version_req()))
711 })?
712 .cloned()
713 }
714
715 pub(crate) fn package_sync_spec(
722 &self,
723 packages: &[lua_dependency::Spec],
724 strategy: &SyncStrategy<'_>,
725 ) -> PackageSyncSpec {
726 let pkg_dir_exists = |pkg: &LockedPackage| match strategy {
727 SyncStrategy::LockfileOnly => true,
728 SyncStrategy::EnsureInstalled(tree) => tree.layout_for(pkg.spec()).root.is_dir(),
729 };
730
731 let entrypoints_to_keep: HashSet<LockedPackage> = self
732 .entrypoints
733 .values()
734 .filter_map(|id| self.get(id))
735 .filter(|local_pkg| {
736 packages.iter().any(|req| {
737 local_pkg
738 .constraint()
739 .matches_version_req(req.version_req())
740 })
741 })
742 .cloned()
743 .collect();
744
745 let packages_to_keep: HashSet<&LockedPackage> = entrypoints_to_keep
746 .iter()
747 .flat_map(|local_pkg| self.get_all_dependencies(&local_pkg.id()))
748 .collect();
749
750 let to_add = packages
751 .iter()
752 .filter(|pkg| {
753 self.has_rock_with_equal_constraint(pkg)
754 .map(|local_pkg| !pkg_dir_exists(&local_pkg))
755 .unwrap_or(true)
756 })
757 .cloned()
758 .collect_vec();
759
760 let to_remove = self
761 .rocks()
762 .values()
763 .filter(|pkg| !packages_to_keep.contains(*pkg))
764 .cloned()
765 .collect_vec();
766
767 PackageSyncSpec { to_add, to_remove }
768 }
769
770 pub(crate) fn get_all_dependencies(&self, id: &LockedPackageId) -> HashSet<&LockedPackage> {
772 let mut packages = HashSet::new();
773 if let Some(local_pkg) = self.get(id) {
774 packages.insert(local_pkg);
775 packages.extend(
776 local_pkg
777 .dependencies()
778 .iter()
779 .flat_map(|id| self.get_all_dependencies(id)),
780 );
781 }
782 packages
783 }
784
785 pub(crate) fn reachable(&self) -> HashSet<&LockedPackage> {
788 self.entrypoints
789 .values()
790 .flat_map(|id| self.get_all_dependencies(id))
791 .collect()
792 }
793}
794
795#[derive(Clone, Debug, Serialize, Deserialize)]
797pub struct Lockfile<P: LockfilePermissions> {
798 #[serde(skip)]
799 filepath: PathBuf,
800 #[serde(skip)]
801 _marker: PhantomData<P>,
802 version: String,
804 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
805 binaries: BTreeMap<LockedPackageId, RockBinaries>,
806 #[serde(flatten)]
807 lock: PackageLock,
808}
809
810#[derive(EnumIter, Debug, Clone, Copy, PartialEq, Eq, Hash)]
811pub enum LockedPackageLockType {
812 Regular,
813 Test,
814 Build,
815}
816
817#[derive(Error, Debug, Diagnostic)]
818#[non_exhaustive]
819pub enum Error {
820 #[error(transparent)]
821 #[diagnostic(transparent)]
822 Fs(#[from] fs::Error),
823 #[error("error parsing lockfile from JSON")]
824 ParseJson(#[source] serde_json::Error),
825 #[error("error writing lockfile to JSON")]
826 WriteJson(#[source] serde_json::Error),
827 #[error("invalid version string in lockfile: {version}")]
828 #[diagnostic(help("did you or a tool modify the lockfile manually?"))]
829 InvalidVersion {
830 version: String,
831 source: semver::Error,
832 },
833 #[error("lockfile '{}' has no `version` field", lockfile.display())]
834 #[diagnostic(
835 code(lux_lib::lockfile::missing_version),
836 help("the lockfile is corrupt or was hand-edited")
837 )]
838 MissingVersion { lockfile: PathBuf },
839 #[error(
840 "incompatible lockfile version in '{}': expected {expected}, found {found}",
841 lockfile.display()
842 )]
843 #[diagnostic(code(lux_lib::lockfile::incompatible_version), help("{help}"))]
844 IncompatibleVersion {
845 lockfile: PathBuf,
846 found: String,
847 expected: String,
848 help: String,
849 },
850 #[error("cannot migrate lockfile '{}'", lockfile.display())]
851 #[diagnostic(code(lux_lib::lockfile::conflicting_entrypoints), help("{help}"))]
852 ConflictingEntrypoints { lockfile: PathBuf, help: String },
853}
854
855#[derive(Error, Debug, Diagnostic)]
856#[non_exhaustive]
857pub enum IntegrityError {
858 #[error(
859 r#"rockspec integrity mismatch.
860- source: {src}
861- expected: {expected}
862- got: {got}
863"#
864 )]
865 #[diagnostic(help(
866 r#"the maintainer may have force-uploaded a different rockspec.
867check the rockspec source, then rerun the command with `--no-lock` to update the hash.
868"#
869 ))]
870 RockspecIntegrityMismatch {
871 src: String,
872 expected: Integrity,
873 got: Integrity,
874 },
875 #[error(
876 r#"source integrity mismatch.
877- source: {src}
878- expected: {expected}
879- got: {got}"#
880 )]
881 #[diagnostic(help(
882 r#"the maintainer may have force-uploaded a different source or moved a tag.
883check the source URL, then rerun the command with `lx --no-lock` to update the hash.
884"#
885 ))]
886 SourceIntegrityMismatch {
887 src: String,
888 expected: Integrity,
889 got: Integrity,
890 },
891 #[error(
892 "package {0} version {1} with pinned state {2} and constraint {3} not found in the lockfile."
893 )]
894 PackageNotFound(package::Name, Box<package::Version>, PinnedState, String),
895}
896
897#[derive(Error, Debug, Diagnostic)]
898#[non_exhaustive]
899#[error("error flushing the lockfile ({})", .filepath.display())]
900#[diagnostic(help("make sure the parent directory is writeable"))]
901pub struct FlushLockfileError {
902 filepath: PathBuf,
903 source: io::Error,
904}
905
906#[derive(Debug, Default)]
908pub(crate) struct PackageSyncSpec {
909 pub to_add: Vec<lua_dependency::Spec>,
910 pub to_remove: Vec<LockedPackage>,
911}
912
913pub(crate) enum SyncStrategy<'a> {
915 LockfileOnly,
917 EnsureInstalled(&'a Tree),
920}
921
922impl<P: LockfilePermissions> Lockfile<P> {
923 pub fn version(&self) -> &String {
924 &self.version
925 }
926
927 pub fn rocks(&self) -> &BTreeMap<LockedPackageId, LockedPackage> {
928 self.lock.rocks()
929 }
930
931 pub fn is_dependency(&self, package: &LockedPackageId) -> bool {
932 self.lock.is_dependency(package)
933 }
934
935 pub fn is_entrypoint(&self, package: &LockedPackageId) -> bool {
936 self.lock.is_entrypoint(package)
937 }
938
939 pub fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
941 self.lock.entrypoint(name)
942 }
943
944 pub fn entrypoints(&self) -> Vec<(&package::Name, &LockedPackage)> {
945 self.lock
946 .entrypoints
947 .iter()
948 .filter_map(|(name, id)| self.lock.get(id).map(|package| (name, package)))
949 .collect()
950 }
951
952 pub fn reachable_rocks(&self) -> Vec<LockedPackage> {
955 self.lock.reachable().into_iter().cloned().collect()
956 }
957
958 pub fn entry_type(&self, package: &LockedPackageId) -> EntryType {
959 if self.lock.is_entrypoint(package) {
960 EntryType::Entrypoint
961 } else {
962 EntryType::DependencyOnly
963 }
964 }
965
966 pub(crate) fn binaries(&self, id: &LockedPackageId) -> Option<&RockBinaries> {
968 self.binaries.get(id)
969 }
970
971 pub(crate) fn local_pkg_lock(&self) -> &PackageLock {
972 &self.lock
973 }
974
975 pub fn get(&self, id: &LockedPackageId) -> Option<&LockedPackage> {
976 self.lock.get(id)
977 }
978
979 pub unsafe fn get_unchecked(&self, id: &LockedPackageId) -> &LockedPackage {
985 self.lock.get(id).unwrap_unchecked()
986 }
987
988 pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
989 self.lock.list()
990 }
991
992 pub(crate) fn has_rock(
993 &self,
994 req: &package::Req,
995 filter: Option<remote::package::kind::FilterSpec>,
996 ) -> Option<LockedPackage> {
997 self.lock.has_rock(req, filter)
998 }
999
1000 pub(crate) fn find_rocks(&self, req: &package::Req) -> Vec<LockedPackageId> {
1002 match self.list().get(req.name()) {
1003 Some(packages) => packages
1004 .iter()
1005 .rev()
1006 .filter(|package| req.version_req().matches(package.version()))
1007 .map(|package| package.id())
1008 .collect_vec(),
1009 None => Vec::default(),
1010 }
1011 }
1012
1013 pub(crate) fn validate_integrity(
1015 &self,
1016 expected_package: &LockedPackage,
1017 ) -> Result<(), IntegrityError> {
1018 match self.list().get(expected_package.name()) {
1021 None => Err(integrity_err_not_found(expected_package)),
1022 Some(rocks) => match rocks
1023 .iter()
1024 .find(|rock| rock.version() == expected_package.version())
1025 {
1026 None => Err(integrity_err_not_found(expected_package)),
1027 Some(installed_package) => {
1028 if expected_package
1029 .hashes
1030 .rockspec
1031 .matches(&installed_package.hashes.rockspec)
1032 .is_none()
1033 {
1034 return Err(IntegrityError::RockspecIntegrityMismatch {
1035 src: expected_package.source.to_string(),
1036 expected: expected_package.hashes.rockspec.clone(),
1037 got: installed_package.hashes.rockspec.clone(),
1038 });
1039 }
1040 if expected_package
1041 .hashes
1042 .source
1043 .matches(&installed_package.hashes.source)
1044 .is_none()
1045 {
1046 return Err(IntegrityError::SourceIntegrityMismatch {
1047 src: expected_package
1048 .source_url
1049 .as_ref()
1050 .map(|url| url.to_string())
1051 .unwrap_or(expected_package.source.to_string()),
1052 expected: expected_package.hashes.source.clone(),
1053 got: installed_package.hashes.source.clone(),
1054 });
1055 }
1056 Ok(())
1057 }
1058 },
1059 }
1060 }
1061
1062 fn flush(&self) -> Result<(), FlushLockfileError> {
1063 let content = serde_json::to_string_pretty(&self).map_err(|err| FlushLockfileError {
1064 filepath: self.filepath.to_path_buf(),
1065 source: io::Error::other(err),
1066 })?;
1067
1068 fs::sync::write_atomic(&self.filepath, content).map_err(|err| FlushLockfileError {
1069 filepath: self.filepath.to_path_buf(),
1070 source: io::Error::other(err),
1071 })
1072 }
1073}
1074
1075impl Lockfile<ReadOnly> {
1076 #[tracing::instrument(level = "trace")]
1078 pub(crate) fn new(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
1079 match File::options().create_new(true).write(true).open(&filepath) {
1081 Ok(mut file) => {
1082 let empty_lockfile: Lockfile<ReadOnly> = Lockfile {
1083 filepath: filepath.clone(),
1084 _marker: PhantomData,
1085 version: LOCKFILE_VERSION_STR.into(),
1086 binaries: BTreeMap::new(),
1087 lock: PackageLock::default(),
1088 };
1089 let json_str = serde_json::to_string(&empty_lockfile).map_err(Error::WriteJson)?;
1090 write!(file, "{json_str}").map_err(|source| fs::Error::Write {
1091 path: filepath.to_path_buf(),
1092 source,
1093 })?;
1094 }
1095 Err(err) if err.kind() == ErrorKind::AlreadyExists => {}
1096 Err(source) => {
1097 return Err(Error::Fs(fs::Error::FileOpen {
1098 path: filepath.to_path_buf(),
1099 source,
1100 }));
1101 }
1102 }
1103
1104 Self::load(filepath)
1105 }
1106
1107 #[tracing::instrument(level = "trace")]
1109 pub fn load(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
1110 let content = fs::sync::read_to_string(&filepath)?;
1111 let tree_dir = filepath.parent().unwrap_or(filepath.as_path());
1112 let help = format!(
1113 "this install tree was created by an incompatible version of Lux.
1114remove the tree at '{}' and reinstall all packages it contained.",
1115 tree_dir.display()
1116 );
1117 let mut lockfile: Lockfile<ReadOnly> = load_lockfile(&content, &filepath, &help)?;
1118 lockfile.filepath = filepath;
1119 Ok(lockfile)
1120 }
1121
1122 pub(crate) fn into_temporary(self) -> Lockfile<ReadWrite> {
1124 Lockfile::<ReadWrite> {
1125 _marker: PhantomData,
1126 filepath: self.filepath,
1127 version: self.version,
1128 binaries: self.binaries,
1129 lock: self.lock,
1130 }
1131 }
1132
1133 pub fn write_guard(self) -> Guard {
1136 Guard::new(self.into_temporary())
1137 }
1138
1139 #[tracing::instrument(level = "trace", skip_all)]
1142 pub fn map_then_flush<T, F, E>(self, cb: F) -> Result<T, FlushLockfileError>
1143 where
1144 F: FnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
1145 E: std::error::Error,
1146 E: From<io::Error>,
1147 E: Into<Box<dyn std::error::Error + Send + Sync>>,
1148 {
1149 let mut writeable_lockfile = self.into_temporary();
1150
1151 let result = cb(&mut writeable_lockfile).map_err(|err| FlushLockfileError {
1152 filepath: writeable_lockfile.filepath.to_path_buf(),
1153 source: io::Error::other(err),
1154 })?;
1155
1156 writeable_lockfile.flush()?;
1157
1158 Ok(result)
1159 }
1160
1161 }
1179
1180impl Lockfile<ReadWrite> {
1181 pub(crate) fn add_entrypoint(&mut self, rock: &LockedPackage) {
1182 self.add(rock);
1183 self.lock.entrypoints.insert(rock.name().clone(), rock.id());
1184 }
1185
1186 pub(crate) fn add(&mut self, rock: &LockedPackage) {
1187 self.lock
1190 .rocks
1191 .entry(rock.id())
1192 .or_insert_with(|| rock.clone());
1193 }
1194
1195 pub(crate) fn add_dependency(&mut self, target: &LockedPackage, dependency: &LockedPackage) {
1197 self.lock
1198 .rocks
1199 .entry(target.id())
1200 .and_modify(|rock| {
1201 let id = dependency.id();
1202 if !rock.spec.dependencies.contains(&id) {
1203 rock.spec.dependencies.push(id);
1204 }
1205 })
1206 .or_insert_with(|| {
1207 let id = dependency.id();
1208 let mut target = target.clone();
1209 if !target.spec.dependencies.contains(&id) {
1210 target.spec.dependencies.push(id);
1211 }
1212 target
1213 });
1214 self.add(dependency);
1215 }
1216
1217 pub(crate) fn add_build_dependency(
1219 &mut self,
1220 target: &LockedPackage,
1221 dependency: &LockedPackage,
1222 ) {
1223 self.lock
1224 .rocks
1225 .entry(target.id())
1226 .and_modify(|rock| {
1227 let id = dependency.id();
1228 if !rock.spec.build_dependencies.contains(&id) {
1229 rock.spec.build_dependencies.push(id);
1230 }
1231 })
1232 .or_insert_with(|| {
1233 let id = dependency.id();
1234 let mut target = target.clone();
1235 if !target.spec.build_dependencies.contains(&id) {
1236 target.spec.build_dependencies.push(id);
1237 }
1238 target
1239 });
1240 }
1241
1242 pub(crate) fn set_binaries(&mut self, package: &LockedPackage, binaries: RockBinaries) {
1244 self.binaries.insert(package.id(), binaries);
1245 }
1246
1247 pub(crate) fn remove(&mut self, target: &LockedPackage) {
1248 self.binaries.remove(&target.id());
1249 self.lock.remove(target)
1250 }
1251
1252 pub(crate) fn remove_by_id(&mut self, target: &LockedPackageId) {
1253 self.binaries.remove(target);
1254 self.lock.remove_by_id(target)
1255 }
1256
1257 pub(crate) fn sync(&mut self, lock: &PackageLock) {
1258 self.lock = lock.clone();
1259 }
1260
1261 }
1263
1264pub(super) fn load_lockfile<T>(content: &str, lockfile: &Path, help: &str) -> Result<T, Error>
1265where
1266 T: serde::de::DeserializeOwned,
1267{
1268 let mut value = parse_lockfile_json(content)?;
1269 if lockfile_version(&value, lockfile)?.major == 1 {
1270 migrate_v1_lockfile(&mut value, lockfile)?;
1271 }
1272 deserialize_lockfile(value, lockfile, help)
1273}
1274
1275fn parse_lockfile_json(content: &str) -> Result<serde_json::Map<String, serde_json::Value>, Error> {
1276 serde_json::from_str(content).map_err(Error::ParseJson)
1277}
1278
1279fn lockfile_version(
1280 value: &serde_json::Map<String, serde_json::Value>,
1281 lockfile: &Path,
1282) -> Result<semver::Version, Error> {
1283 let version = value
1284 .get("version")
1285 .and_then(|version| version.as_str())
1286 .ok_or(Error::MissingVersion {
1287 lockfile: lockfile.to_path_buf(),
1288 })?;
1289 semver::Version::parse(version).map_err(|source| Error::InvalidVersion {
1290 version: version.to_string(),
1291 source,
1292 })
1293}
1294
1295fn deserialize_lockfile<T>(
1296 value: serde_json::Map<String, serde_json::Value>,
1297 lockfile: &Path,
1298 help: &str,
1299) -> Result<T, Error>
1300where
1301 T: serde::de::DeserializeOwned,
1302{
1303 let found = lockfile_version(&value, lockfile)?;
1304 if found.major != LOCKFILE_VERSION {
1305 return Err(Error::IncompatibleVersion {
1306 lockfile: lockfile.to_path_buf(),
1307 found: found.to_string(),
1308 expected: LOCKFILE_VERSION_STR.into(),
1309 help: help.into(),
1310 });
1311 }
1312 serde_json::from_value(serde_json::Value::Object(value)).map_err(Error::ParseJson)
1313}
1314
1315fn migrate_v1_lockfile(
1316 value: &mut serde_json::Map<String, serde_json::Value>,
1317 lockfile: &Path,
1318) -> Result<(), Error> {
1319 let tree_dir = lockfile.parent().unwrap_or(lockfile);
1320 let found = lockfile_version(value, lockfile)?;
1321 if value.contains_key("entrypoint_layout") {
1322 return Err(Error::IncompatibleVersion {
1323 lockfile: lockfile.to_path_buf(),
1324 found: found.to_string(),
1325 expected: LOCKFILE_VERSION_STR.into(),
1326 help: format!(
1327 "this install tree uses a custom entrypoint layout that cannot be migrated automatically.
1328remove the tree at '{}' and reinstall all packages it contained.",
1329 tree_dir.display()
1330 ),
1331 });
1332 }
1333
1334 let conflict_help = format!(
1335 "this lockfile contains entrypoints that cannot be represented in the current format.
1336remove the tree at '{}' and reinstall all packages it contained.",
1337 tree_dir.display()
1338 );
1339
1340 if value.contains_key("entrypoints") {
1341 migrate_entrypoints(value, lockfile, &conflict_help)?;
1342 }
1343 for section in ["dependencies", "test_dependencies", "build_dependencies"] {
1344 if let Some(section) = value
1345 .get_mut(section)
1346 .and_then(|section| section.as_object_mut())
1347 {
1348 migrate_entrypoints(section, lockfile, &conflict_help)?;
1349 }
1350 }
1351 value.insert(
1352 "version".into(),
1353 serde_json::Value::String(LOCKFILE_VERSION_STR.into()),
1354 );
1355 Ok(())
1356}
1357
1358fn migrate_entrypoints(
1359 section: &mut serde_json::Map<String, serde_json::Value>,
1360 lockfile: &Path,
1361 help: &str,
1362) -> Result<(), Error> {
1363 let conflicting_entrypoints = || Error::ConflictingEntrypoints {
1364 lockfile: lockfile.to_path_buf(),
1365 help: help.to_string(),
1366 };
1367
1368 let rocks = section.get("rocks").and_then(|rocks| rocks.as_object());
1369 let mut entrypoints = serde_json::Map::new();
1370 if let Some(old_entrypoints) = section.get("entrypoints") {
1371 for id in old_entrypoints
1372 .as_array()
1373 .ok_or_else(conflicting_entrypoints)?
1374 {
1375 let id = id.as_str().ok_or_else(conflicting_entrypoints)?;
1376 let name = rocks
1377 .and_then(|rocks| rocks.get(id))
1378 .and_then(|package| package.get("name"))
1379 .and_then(|name| name.as_str())
1380 .ok_or_else(conflicting_entrypoints)?;
1381 if entrypoints.contains_key(name) {
1382 return Err(conflicting_entrypoints());
1383 }
1384 entrypoints.insert(name.to_string(), serde_json::Value::String(id.to_string()));
1385 }
1386 }
1387 section.insert("entrypoints".into(), serde_json::Value::Object(entrypoints));
1388 Ok(())
1389}
1390
1391fn integrity_err_not_found(package: &LockedPackage) -> IntegrityError {
1392 IntegrityError::PackageNotFound(
1393 package.name().clone(),
1394 Box::new(package.version().clone()),
1395 package.spec.pinned,
1396 package
1397 .spec
1398 .constraint
1399 .clone()
1400 .unwrap_or("UNCONSTRAINED".into()),
1401 )
1402}
1403
1404fn deserialize_url<'de, D>(deserializer: D) -> Result<Url, D::Error>
1405where
1406 D: serde::Deserializer<'de>,
1407{
1408 let s = String::deserialize(deserializer)?;
1409 Url::parse(&s).map_err(serde::de::Error::custom)
1410}
1411
1412fn serialize_url<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>
1413where
1414 S: Serializer,
1415{
1416 url.as_str().serialize(serializer)
1417}
1418
1419#[cfg(test)]
1420mod tests {
1421 use super::*;
1422 use std::{fs::remove_file, path::PathBuf};
1423
1424 use assert_fs::fixture::PathCopy;
1425 use insta::{assert_json_snapshot, sorted_redaction};
1426
1427 use crate::{config, lua};
1428
1429 #[test]
1430 fn parse_lockfile() {
1431 let temp = assert_fs::TempDir::new().unwrap();
1432 temp.copy_from(
1433 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1434 &["**"],
1435 )
1436 .unwrap();
1437
1438 let config = config::Builder::new()
1439 .unwrap()
1440 .user_tree(Some(temp.to_path_buf()))
1441 .build()
1442 .unwrap();
1443 let tree = config.user_tree(lua::Version::Lua51).unwrap();
1444 let lockfile = tree.lockfile().unwrap();
1445
1446 assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
1447 }
1448
1449 #[test]
1450 fn add_rocks() {
1451 let temp = assert_fs::TempDir::new().unwrap();
1452 temp.copy_from(
1453 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1454 &["**"],
1455 )
1456 .unwrap();
1457
1458 let mock_hashes = LockedPackageHashes {
1459 rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
1460 .parse()
1461 .unwrap(),
1462 source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
1463 .parse()
1464 .unwrap(),
1465 };
1466
1467 let config = config::Builder::new()
1468 .unwrap()
1469 .user_tree(Some(temp.to_path_buf()))
1470 .build()
1471 .unwrap();
1472 let tree = config.user_tree(lua::Version::Lua51).unwrap();
1473 let mut lockfile = tree.lockfile().unwrap().write_guard();
1474
1475 let test_package = package::Spec::parse("test1".to_string(), "0.1.0".to_string()).unwrap();
1476 let test_local_package = LockedPackage::from(
1477 &test_package,
1478 crate::lockfile::Constraint::Unconstrained,
1479 remote::package::Source::Test,
1480 None,
1481 mock_hashes.clone(),
1482 );
1483 lockfile.add_entrypoint(&test_local_package);
1484
1485 let test_dep_package =
1486 package::Spec::parse("test2".to_string(), "0.1.0".to_string()).unwrap();
1487 let mut test_local_dep_package = LockedPackage::from(
1488 &test_dep_package,
1489 crate::lockfile::Constraint::Constrained(">= 1.0.0".parse().unwrap()),
1490 remote::package::Source::Test,
1491 None,
1492 mock_hashes.clone(),
1493 );
1494 test_local_dep_package.spec.pinned = PinnedState::Pinned;
1495 lockfile.add_dependency(&test_local_package, &test_local_dep_package);
1496
1497 assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
1498 }
1499
1500 #[test]
1501 fn parse_nonexistent_lockfile() {
1502 let tree_path =
1503 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
1504
1505 let temp = assert_fs::TempDir::new().unwrap();
1506 temp.copy_from(&tree_path, &["**"]).unwrap();
1507
1508 remove_file(temp.join("5.1/lux.lock")).unwrap();
1509
1510 let config = config::Builder::new()
1511 .unwrap()
1512 .user_tree(Some(temp.to_path_buf()))
1513 .build()
1514 .unwrap();
1515 let tree = config.user_tree(lua::Version::Lua51).unwrap();
1516
1517 let _ = tree.lockfile().unwrap().write_guard(); }
1519
1520 fn get_test_lockfile() -> Lockfile<ReadOnly> {
1521 let sample_tree = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1522 .join("resources/test/sample-tree/5.1/lux.lock");
1523 Lockfile::new(sample_tree).unwrap()
1524 }
1525
1526 #[test]
1527 fn test_sync_spec() {
1528 let lockfile = get_test_lockfile();
1529 let packages = vec![
1530 package::Req::parse("neorg@8.8.1-1").unwrap().into(),
1531 package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1532 package::Req::parse("nonexistent").unwrap().into(),
1533 ];
1534
1535 let sync_spec = lockfile
1536 .lock
1537 .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1538
1539 assert_eq!(sync_spec.to_add.len(), 1);
1540
1541 assert!(!sync_spec
1543 .to_remove
1544 .iter()
1545 .any(|pkg| pkg.name().to_string() == "nvim-nio"
1546 && pkg.constraint()
1547 == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
1548 assert!(!sync_spec
1549 .to_remove
1550 .iter()
1551 .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
1552 && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
1553 assert!(!sync_spec
1554 .to_remove
1555 .iter()
1556 .any(|pkg| pkg.name().to_string() == "plenary.nvim"
1557 && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
1558 assert!(!sync_spec
1559 .to_remove
1560 .iter()
1561 .any(|pkg| pkg.name().to_string() == "nui.nvim"
1562 && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
1563 assert!(!sync_spec
1564 .to_remove
1565 .iter()
1566 .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
1567 && pkg.constraint()
1568 == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
1569 }
1570
1571 #[test]
1572 fn test_sync_spec_remove() {
1573 let lockfile = get_test_lockfile();
1574 let packages = vec![
1575 package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1576 package::Req::parse("nonexistent").unwrap().into(),
1577 ];
1578
1579 let sync_spec = lockfile
1580 .lock
1581 .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1582
1583 assert_eq!(sync_spec.to_add.len(), 1);
1584
1585 assert!(sync_spec
1589 .to_remove
1590 .iter()
1591 .any(|pkg| pkg.name().to_string() == "neorg"
1592 && pkg.version() == &"8.8.1-1".parse().unwrap()));
1593 assert!(sync_spec
1594 .to_remove
1595 .iter()
1596 .any(|pkg| pkg.name().to_string() == "nvim-nio"
1597 && pkg.constraint()
1598 == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
1599 assert!(sync_spec
1600 .to_remove
1601 .iter()
1602 .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
1603 && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
1604 assert!(sync_spec
1605 .to_remove
1606 .iter()
1607 .any(|pkg| pkg.name().to_string() == "plenary.nvim"
1608 && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
1609 assert!(sync_spec
1610 .to_remove
1611 .iter()
1612 .any(|pkg| pkg.name().to_string() == "nui.nvim"
1613 && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
1614 assert!(sync_spec
1615 .to_remove
1616 .iter()
1617 .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
1618 && pkg.constraint()
1619 == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
1620 }
1621
1622 #[test]
1623 fn test_sync_spec_empty() {
1624 let lockfile = get_test_lockfile();
1625 let packages = vec![];
1626 let sync_spec = lockfile
1627 .lock
1628 .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1629
1630 assert!(sync_spec.to_add.is_empty());
1632 assert_eq!(sync_spec.to_remove.len(), lockfile.rocks().len());
1633 }
1634
1635 #[test]
1636 fn test_sync_spec_different_constraints() {
1637 let lockfile = get_test_lockfile();
1638 let packages = vec![package::Req::parse("nvim-nio>=2.0.0").unwrap().into()];
1639 let sync_spec = lockfile
1640 .lock
1641 .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1642
1643 let expected: package::VersionReq = ">=2.0.0".parse().unwrap();
1644 assert!(sync_spec
1645 .to_add
1646 .iter()
1647 .any(|req| req.name().to_string() == "nvim-nio" && req.version_req() == &expected));
1648
1649 assert!(sync_spec
1650 .to_remove
1651 .iter()
1652 .any(|pkg| pkg.name().to_string() == "nvim-nio"));
1653 }
1654
1655 #[test]
1656 fn test_sync_spec_ensure_installed() {
1657 let temp = assert_fs::TempDir::new().unwrap();
1658 temp.copy_from(
1659 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1660 &["**"],
1661 )
1662 .unwrap();
1663
1664 let config = config::Builder::new()
1665 .unwrap()
1666 .user_tree(Some(temp.to_path_buf()))
1667 .build()
1668 .unwrap();
1669 let tree = config.user_tree(lua::Version::Lua51).unwrap();
1670 let lockfile = tree.lockfile().unwrap();
1671
1672 let packages: Vec<lua_dependency::Spec> = vec![
1673 package::Req::parse("neorg@8.8.1-1").unwrap().into(),
1674 package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1676 package::Req::parse("nonexistent").unwrap().into(),
1678 ];
1679
1680 let sync_spec = lockfile
1682 .lock
1683 .package_sync_spec(&packages, &SyncStrategy::EnsureInstalled(&tree));
1684
1685 assert!(!sync_spec
1686 .to_add
1687 .iter()
1688 .any(|req| req.name().to_string() == "neorg"));
1689
1690 assert!(sync_spec
1691 .to_add
1692 .iter()
1693 .any(|req| req.name().to_string() == "lua-cjson"));
1694
1695 assert!(sync_spec
1696 .to_add
1697 .iter()
1698 .any(|req| req.name().to_string() == "nonexistent"));
1699 }
1700
1701 #[test]
1702 fn verify_lockfile_version() {
1703 let deserialize = |version: &str| {
1704 let content = format!(r#"{{"version": "{version}"}}"#);
1705 parse_lockfile_json(&content).and_then(|value| {
1706 deserialize_lockfile::<Lockfile<ReadOnly>>(value, Path::new("lux.lock"), "")
1707 })
1708 };
1709
1710 assert!(matches!(
1711 deserialize("3.0.0"),
1712 Err(Error::IncompatibleVersion { .. })
1713 ));
1714 assert!(matches!(
1715 deserialize("not-a-version"),
1716 Err(Error::InvalidVersion { .. })
1717 ));
1718 }
1719
1720 #[test]
1721 fn migrate_v1_tree_lockfile() {
1722 let sample =
1723 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/lockfile-v1/tree.lock");
1724
1725 let temp = assert_fs::TempDir::new().unwrap();
1726 let lockfile_path = temp.path().join("lux.lock");
1727 std::fs::copy(&sample, &lockfile_path).unwrap();
1728
1729 let lockfile = Lockfile::load(lockfile_path.clone()).unwrap();
1730
1731 let on_disk: serde_json::Value =
1732 serde_json::from_str(&std::fs::read_to_string(&lockfile_path).unwrap()).unwrap();
1733 assert_eq!(on_disk["version"], "1.0.0");
1734 assert!(on_disk["entrypoints"].is_array());
1735
1736 assert_eq!(lockfile.version, "2.0.0");
1737 assert_eq!(lockfile.lock.entrypoints.len(), 3);
1738 }
1739
1740 #[test]
1741 fn refuse_migration_for_custom_layout() {
1742 let lockfile = r#"{"version":"1.0.0","entrypoint_layout":{"root":"site/pack/lux"}}"#;
1743 assert!(matches!(
1744 load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
1745 Err(Error::IncompatibleVersion { .. })
1746 ));
1747 }
1748
1749 #[test]
1750 fn refuse_migration_for_conflicting_entrypoints() {
1751 let lockfile = r#"{
1752 "version": "1.0.0",
1753 "rocks": {
1754 "a": { "name": "foo" },
1755 "b": { "name": "foo" }
1756 },
1757 "entrypoints": ["a", "b"]
1758 }"#;
1759 assert!(matches!(
1760 load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
1761 Err(Error::ConflictingEntrypoints { .. })
1762 ));
1763 }
1764}