Skip to main content

lux_lib/lockfile/
mod.rs

1use crate::package;
2use std::collections::{BTreeMap, HashSet};
3use std::fmt::Display;
4use std::io::{self, Write};
5use std::marker::PhantomData;
6use std::ops::{Deref, DerefMut};
7use std::{
8    collections::HashMap,
9    fs::File,
10    io::ErrorKind,
11    path::{Path, PathBuf},
12};
13
14use itertools::Itertools;
15
16use miette::Diagnostic;
17use serde::{de, Deserialize, Serialize, Serializer};
18use sha2::{Digest, Sha256};
19use ssri::Integrity;
20use strum_macros::EnumIter;
21use thiserror::Error;
22use url::Url;
23
24use crate::fs;
25use crate::remote;
26use crate::rockspec::lua_dependency;
27use crate::rockspec::RockBinaries;
28use crate::tree::{EntryType, InstallTree, Tree};
29
30pub mod constraint;
31
32pub use constraint::Constraint;
33
34/// Bump this whenever an incompatible change is made to the lockfile format.
35/// Lockfiles with a different major version are rejected on load.
36const LOCKFILE_VERSION: u64 = 2;
37const LOCKFILE_VERSION_STR: &str = "2.0.0";
38
39#[derive(Copy, Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord, Default)]
40pub enum PinnedState {
41    /// Unpinned packages can be updated
42    #[default]
43    Unpinned,
44    /// Pinned packages cannot be updated
45    Pinned,
46}
47
48impl Display for PinnedState {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        match &self {
51            PinnedState::Unpinned => "unpinned".fmt(f),
52            PinnedState::Pinned => "pinned".fmt(f),
53        }
54    }
55}
56
57impl From<bool> for PinnedState {
58    fn from(value: bool) -> Self {
59        if value {
60            Self::Pinned
61        } else {
62            Self::Unpinned
63        }
64    }
65}
66
67impl PinnedState {
68    pub fn as_bool(&self) -> bool {
69        match self {
70            Self::Unpinned => false,
71            Self::Pinned => true,
72        }
73    }
74
75    fn is_default(&self) -> bool {
76        &Self::default() == self
77    }
78}
79
80impl Serialize for PinnedState {
81    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
82    where
83        S: serde::Serializer,
84    {
85        serializer.serialize_bool(self.as_bool())
86    }
87}
88
89impl<'de> Deserialize<'de> for PinnedState {
90    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
91    where
92        D: serde::Deserializer<'de>,
93    {
94        Ok(match bool::deserialize(deserializer)? {
95            false => Self::Unpinned,
96            true => Self::Pinned,
97        })
98    }
99}
100
101#[derive(Copy, Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord, Default)]
102pub enum OptState {
103    /// A required package
104    #[default]
105    Required,
106    /// An optional package
107    Optional,
108}
109
110impl OptState {
111    pub(crate) fn as_bool(&self) -> bool {
112        match self {
113            Self::Required => false,
114            Self::Optional => true,
115        }
116    }
117
118    fn is_default(&self) -> bool {
119        &Self::default() == self
120    }
121}
122
123impl From<bool> for OptState {
124    fn from(value: bool) -> Self {
125        if value {
126            Self::Optional
127        } else {
128            Self::Required
129        }
130    }
131}
132
133impl Display for OptState {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        match &self {
136            OptState::Required => "required".fmt(f),
137            OptState::Optional => "optional".fmt(f),
138        }
139    }
140}
141
142impl Serialize for OptState {
143    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
144    where
145        S: serde::Serializer,
146    {
147        serializer.serialize_bool(self.as_bool())
148    }
149}
150
151impl<'de> Deserialize<'de> for OptState {
152    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
153    where
154        D: serde::Deserializer<'de>,
155    {
156        Ok(match bool::deserialize(deserializer)? {
157            false => Self::Required,
158            true => Self::Optional,
159        })
160    }
161}
162
163#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
164pub struct LockedPackageSpec {
165    name: package::Name,
166    version: package::Version,
167    pinned: PinnedState,
168    opt: OptState,
169    dependencies: Vec<LockedPackageId>,
170    build_dependencies: Vec<LockedPackageId>,
171    // TODO: Deserialize this directly into a `LuaPackageReq`
172    constraint: Option<String>,
173}
174
175/// ID of a local package, a hash that is comprised of:
176/// - name
177/// - version
178/// - pinned state
179/// - opt state
180/// - lock constraint
181#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Clone)]
182pub struct LockedPackageId(String);
183
184impl LockedPackageId {
185    pub fn new(
186        name: &package::Name,
187        version: &package::Version,
188        pinned: PinnedState,
189        opt: OptState,
190        constraint: Constraint,
191    ) -> Self {
192        let mut hasher = Sha256::new();
193
194        hasher.update(format!(
195            "{}{}{}{}{}",
196            name,
197            version,
198            pinned.as_bool(),
199            opt.as_bool(),
200            match constraint {
201                Constraint::Unconstrained => String::default(),
202                Constraint::Constrained(version_req) => version_req.to_string(),
203            },
204        ));
205
206        Self(hex::encode(hasher.finalize()))
207    }
208
209    /// Constructs a package ID from a hashed string.
210    ///
211    /// # Safety
212    ///
213    /// Ensure that the hash you are providing to this function
214    /// is not malformed and resolves to a valid package ID for the target
215    /// tree you are working with.
216    pub unsafe fn from_unchecked(str: String) -> Self {
217        Self(str)
218    }
219
220    pub fn into_string(self) -> String {
221        self.0
222    }
223}
224
225impl Display for LockedPackageId {
226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        self.0.fmt(f)
228    }
229}
230
231impl LockedPackageSpec {
232    #[allow(clippy::too_many_arguments)]
233    pub(crate) fn new(
234        name: &package::Name,
235        version: &package::Version,
236        constraint: Constraint,
237        dependencies: Vec<LockedPackageId>,
238        build_dependencies: Vec<LockedPackageId>,
239        pinned: &PinnedState,
240        opt: &OptState,
241    ) -> Self {
242        Self {
243            name: name.clone(),
244            version: version.clone(),
245            pinned: *pinned,
246            opt: *opt,
247            dependencies,
248            build_dependencies,
249            constraint: match constraint {
250                Constraint::Unconstrained => None,
251                Constraint::Constrained(version_req) => Some(version_req.to_string()),
252            },
253        }
254    }
255
256    pub fn id(&self) -> LockedPackageId {
257        LockedPackageId::new(
258            self.name(),
259            self.version(),
260            self.pinned,
261            self.opt,
262            match &self.constraint {
263                None => Constraint::Unconstrained,
264                Some(_) => self.constraint(),
265            },
266        )
267    }
268
269    pub fn constraint(&self) -> Constraint {
270        // Safe to unwrap as the data can only end up in the struct as a valid constraint
271        unsafe { Constraint::try_from(&self.constraint).unwrap_unchecked() }
272    }
273
274    pub fn name(&self) -> &package::Name {
275        &self.name
276    }
277
278    pub fn version(&self) -> &package::Version {
279        &self.version
280    }
281
282    pub fn pinned(&self) -> PinnedState {
283        self.pinned
284    }
285
286    pub fn opt(&self) -> OptState {
287        self.opt
288    }
289
290    pub fn dependencies(&self) -> Vec<&LockedPackageId> {
291        self.dependencies.iter().collect()
292    }
293
294    pub fn build_dependencies(&self) -> Vec<&LockedPackageId> {
295        self.build_dependencies.iter().collect()
296    }
297
298    pub fn to_package(&self) -> package::Spec {
299        package::Spec::new(self.name.clone(), self.version.clone())
300    }
301
302    pub fn into_package_req(self) -> package::Req {
303        match self.constraint() {
304            Constraint::Unconstrained => self.name.into(),
305            Constraint::Constrained(version_req) => package::Req {
306                name: self.name,
307                version_req,
308            },
309        }
310    }
311
312    pub(crate) fn as_package_req(&self) -> package::Req {
313        match self.constraint() {
314            Constraint::Unconstrained => self.name.clone().into(),
315            Constraint::Constrained(version_req) => package::Req {
316                name: self.name.clone(),
317                version_req: version_req.clone(),
318            },
319        }
320    }
321}
322
323#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
324#[serde(rename_all = "lowercase", tag = "type")]
325pub(crate) enum RemotePackageSourceUrl {
326    Git {
327        url: String,
328        #[serde(rename = "ref")]
329        checkout_ref: String,
330        /// Whether the source repository contains git submodules that must be
331        /// fetched for the package to build.
332        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
333        submodules: bool,
334    }, // GitUrl doesn't have all the trait instances we need
335    Url {
336        #[serde(deserialize_with = "deserialize_url", serialize_with = "serialize_url")]
337        url: Url,
338    },
339    File {
340        path: PathBuf,
341    },
342}
343
344impl Display for RemotePackageSourceUrl {
345    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        match self {
347            RemotePackageSourceUrl::Git {
348                url, checkout_ref, ..
349            } => format!("{url}@{checkout_ref}").fmt(f),
350            RemotePackageSourceUrl::Url { url } => url.fmt(f),
351            RemotePackageSourceUrl::File { path } => format!("{}", path.display()).fmt(f),
352        }
353    }
354}
355
356// TODO(vhyrro): Move to `package/local.rs`
357
358/// A package whose source has been downloaded, hashed and which is installed in a tree.
359#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
360pub struct LockedPackage {
361    pub(crate) spec: LockedPackageSpec,
362    pub(crate) source: remote::package::Source,
363    pub(crate) source_url: Option<RemotePackageSourceUrl>,
364    pub(crate) hashes: LockedPackageHashes,
365}
366
367impl LockedPackage {
368    pub(crate) fn repin(mut self, pinned: PinnedState) -> Self {
369        self.spec.pinned = pinned;
370        self
371    }
372
373    #[cfg(test)]
374    pub(crate) fn from(
375        package: &package::Spec,
376        constraint: Constraint,
377        source: remote::package::Source,
378        source_url: Option<RemotePackageSourceUrl>,
379        hashes: LockedPackageHashes,
380    ) -> Self {
381        Self::new(
382            LockedPackageSpec::new(
383                package.name(),
384                package.version(),
385                constraint,
386                Vec::default(),
387                Vec::default(),
388                &PinnedState::Unpinned,
389                &OptState::Required,
390            ),
391            source,
392            source_url,
393            hashes,
394        )
395    }
396
397    pub(crate) fn new(
398        spec: LockedPackageSpec,
399        source: remote::package::Source,
400        source_url: Option<RemotePackageSourceUrl>,
401        hashes: LockedPackageHashes,
402    ) -> Self {
403        Self {
404            spec,
405            source,
406            source_url,
407            hashes,
408        }
409    }
410
411    pub fn spec(&self) -> &LockedPackageSpec {
412        &self.spec
413    }
414
415    pub fn into_package_spec(self) -> package::Spec {
416        self.spec.to_package()
417    }
418
419    pub fn as_package_spec(&self) -> package::Spec {
420        self.spec.to_package()
421    }
422
423    pub fn id(&self) -> LockedPackageId {
424        self.spec.id()
425    }
426
427    pub fn name(&self) -> &package::Name {
428        self.spec.name()
429    }
430
431    pub fn version(&self) -> &package::Version {
432        self.spec.version()
433    }
434
435    pub fn pinned(&self) -> PinnedState {
436        self.spec.pinned()
437    }
438
439    pub fn opt(&self) -> OptState {
440        self.spec.opt()
441    }
442
443    pub fn dependencies(&self) -> Vec<&LockedPackageId> {
444        self.spec.dependencies()
445    }
446
447    pub fn build_dependencies(&self) -> Vec<&LockedPackageId> {
448        self.spec.build_dependencies()
449    }
450
451    pub fn constraint(&self) -> Constraint {
452        self.spec.constraint()
453    }
454
455    pub(crate) fn source(&self) -> &remote::package::Source {
456        &self.source
457    }
458
459    pub(crate) fn source_url(&self) -> Option<&RemotePackageSourceUrl> {
460        self.source_url.as_ref()
461    }
462
463    pub fn hashes(&self) -> &LockedPackageHashes {
464        &self.hashes
465    }
466
467    pub fn to_package(&self) -> package::Spec {
468        self.spec.to_package()
469    }
470
471    pub fn into_package_req(self) -> package::Req {
472        self.spec.into_package_req()
473    }
474}
475
476#[derive(Debug, Serialize, Deserialize, Clone)]
477struct LockedPackageIntermediate {
478    name: package::Name,
479    version: package::Version,
480    #[serde(default, skip_serializing_if = "PinnedState::is_default")]
481    pinned: PinnedState,
482    #[serde(default, skip_serializing_if = "OptState::is_default")]
483    opt: OptState,
484    #[serde(default, skip_serializing_if = "Vec::is_empty")]
485    dependencies: Vec<LockedPackageId>,
486    #[serde(default, skip_serializing_if = "Vec::is_empty")]
487    build_dependencies: Vec<LockedPackageId>,
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    constraint: Option<String>,
490    source: remote::package::Source,
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    source_url: Option<RemotePackageSourceUrl>,
493    hashes: LockedPackageHashes,
494}
495
496impl TryFrom<LockedPackageIntermediate> for LockedPackage {
497    type Error = constraint::Error;
498
499    fn try_from(value: LockedPackageIntermediate) -> Result<Self, Self::Error> {
500        let constraint = Constraint::try_from(&value.constraint)?;
501        Ok(Self {
502            spec: LockedPackageSpec::new(
503                &value.name,
504                &value.version,
505                constraint,
506                value.dependencies,
507                value.build_dependencies,
508                &value.pinned,
509                &value.opt,
510            ),
511            source: value.source,
512            source_url: value.source_url,
513            hashes: value.hashes,
514        })
515    }
516}
517
518impl From<&LockedPackage> for LockedPackageIntermediate {
519    fn from(value: &LockedPackage) -> Self {
520        Self {
521            name: value.spec.name.clone(),
522            version: value.spec.version.clone(),
523            pinned: value.spec.pinned,
524            opt: value.spec.opt,
525            dependencies: value.spec.dependencies.clone(),
526            build_dependencies: value.spec.build_dependencies.clone(),
527            constraint: value.spec.constraint.clone(),
528            source: value.source.clone(),
529            source_url: value.source_url.clone(),
530            hashes: value.hashes.clone(),
531        }
532    }
533}
534
535impl<'de> Deserialize<'de> for LockedPackage {
536    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
537    where
538        D: serde::Deserializer<'de>,
539    {
540        LockedPackage::try_from(LockedPackageIntermediate::deserialize(deserializer)?)
541            .map_err(de::Error::custom)
542    }
543}
544
545impl Serialize for LockedPackage {
546    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
547    where
548        S: serde::Serializer,
549    {
550        LockedPackageIntermediate::from(self).serialize(serializer)
551    }
552}
553
554#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Hash)]
555pub struct LockedPackageHashes {
556    pub rockspec: Integrity,
557    pub source: Integrity,
558}
559
560impl Ord for LockedPackageHashes {
561    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
562        let a = (self.rockspec.to_hex().1, self.source.to_hex().1);
563        let b = (other.rockspec.to_hex().1, other.source.to_hex().1);
564        a.cmp(&b)
565    }
566}
567
568impl PartialOrd for LockedPackageHashes {
569    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
570        Some(self.cmp(other))
571    }
572}
573
574pub trait LockfilePermissions {}
575#[derive(Clone)]
576pub struct ReadOnly;
577#[derive(Clone)]
578pub struct ReadWrite;
579
580impl LockfilePermissions for ReadOnly {}
581impl LockfilePermissions for ReadWrite {}
582
583#[derive(Clone, Debug, Serialize, Deserialize, Default)]
584pub(crate) struct PackageLock {
585    // NOTE: We cannot directly serialize to a `Sha256` object as they don't implement serde traits.
586    // NOTE: We want to retain ordering of rocks when de/serializing.
587    rocks: BTreeMap<LockedPackageId, LockedPackage>,
588
589    /// The entrypoints of the tree. Enforces one entrypoint per package name.
590    entrypoints: BTreeMap<package::Name, LockedPackageId>,
591}
592
593impl PackageLock {
594    pub(crate) fn from_packages(
595        packages: impl Iterator<Item = (LockedPackage, EntryType)>,
596    ) -> Self {
597        let mut lock = Self::default();
598
599        for (package, entry_type) in packages {
600            if matches!(entry_type, EntryType::Entrypoint) {
601                lock.entrypoints
602                    .insert(package.name().clone(), package.id());
603            }
604            lock.rocks.insert(package.id(), package);
605        }
606
607        lock
608    }
609
610    pub(crate) fn merge(&mut self, other: &PackageLock) {
611        self.entrypoints.extend(
612            other
613                .entrypoints
614                .iter()
615                .map(|(name, id)| (name.clone(), id.clone())),
616        );
617        self.rocks.extend(
618            other
619                .rocks
620                .iter()
621                .map(|(id, package)| (id.clone(), package.clone())),
622        );
623    }
624
625    fn get(&self, id: &LockedPackageId) -> Option<&LockedPackage> {
626        self.rocks.get(id)
627    }
628
629    fn is_empty(&self) -> bool {
630        self.rocks.is_empty()
631    }
632
633    pub(crate) fn rocks(&self) -> &BTreeMap<LockedPackageId, LockedPackage> {
634        &self.rocks
635    }
636
637    fn is_entrypoint(&self, package: &LockedPackageId) -> bool {
638        self.entrypoints.values().any(|id| id == package)
639    }
640
641    /// Returns the entrypoint with the given package name, if any.
642    pub(crate) fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
643        self.entrypoints.get(name).and_then(|id| self.get(id))
644    }
645
646    fn is_dependency(&self, package: &LockedPackageId) -> bool {
647        self.rocks
648            .values()
649            .flat_map(|rock| rock.dependencies())
650            .any(|dep_id| dep_id == package)
651    }
652
653    fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
654        self.rocks()
655            .values()
656            .cloned()
657            .map(|locked_rock| (locked_rock.name().clone(), locked_rock))
658            .into_group_map()
659    }
660
661    fn remove(&mut self, target: &LockedPackage) {
662        self.remove_by_id(&target.id())
663    }
664
665    fn remove_by_id(&mut self, target: &LockedPackageId) {
666        self.rocks.remove(target);
667        self.entrypoints.retain(|_, id| id != target);
668    }
669
670    pub(crate) fn has_rock(
671        &self,
672        req: &package::Req,
673        filter: Option<remote::package::kind::FilterSpec>,
674    ) -> Option<LockedPackage> {
675        self.list()
676            .get(req.name())
677            .map(|packages| {
678                packages
679                    .iter()
680                    .filter(|package| match &filter {
681                        Some(filter_spec) => match &package.source {
682                            remote::package::Source::LuarocksRockspec(_) => filter_spec.rockspec,
683                            remote::package::Source::LuarocksSrcRock(_) => filter_spec.src,
684                            remote::package::Source::LuarocksBinaryRock(_) => filter_spec.binary,
685                            remote::package::Source::Wally(_) => true,
686                            remote::package::Source::RockspecContent(_) => true,
687                            remote::package::Source::Local => true,
688                            #[cfg(test)]
689                            remote::package::Source::Test => unimplemented!(),
690                        },
691                        None => true,
692                    })
693                    .rev()
694                    .find(|package| req.version_req().matches(package.version()))
695            })?
696            .cloned()
697    }
698
699    fn has_rock_with_equal_constraint(&self, req: &lua_dependency::Spec) -> Option<LockedPackage> {
700        self.list()
701            .get(req.name())
702            .map(|packages| {
703                packages
704                    .iter()
705                    .rev()
706                    .find(|package| package.constraint().matches_version_req(req.version_req()))
707            })?
708            .cloned()
709    }
710
711    /// Synchronise a list of packages with this lock,
712    /// producing a report of packages to add and packages to remove,
713    /// based on the version constraint and the given [`SyncStrategy`].
714    ///
715    /// NOTE: The reason we produce a report and don't add/remove packages
716    /// here is because packages need to be installed in order to be added.
717    pub(crate) fn package_sync_spec(
718        &self,
719        packages: &[lua_dependency::Spec],
720        strategy: &SyncStrategy<'_>,
721    ) -> PackageSyncSpec {
722        let pkg_dir_exists = |pkg: &LockedPackage| match strategy {
723            SyncStrategy::LockfileOnly => true,
724            SyncStrategy::EnsureInstalled(tree) => tree.layout_for(pkg.spec()).root.is_dir(),
725        };
726
727        let entrypoints_to_keep: HashSet<LockedPackage> = self
728            .entrypoints
729            .values()
730            .filter_map(|id| self.get(id))
731            .filter(|local_pkg| {
732                packages.iter().any(|req| {
733                    local_pkg
734                        .constraint()
735                        .matches_version_req(req.version_req())
736                })
737            })
738            .cloned()
739            .collect();
740
741        let packages_to_keep: HashSet<&LockedPackage> = entrypoints_to_keep
742            .iter()
743            .flat_map(|local_pkg| self.get_all_dependencies(&local_pkg.id()))
744            .collect();
745
746        let to_add = packages
747            .iter()
748            .filter(|pkg| {
749                self.has_rock_with_equal_constraint(pkg)
750                    .map(|local_pkg| !pkg_dir_exists(&local_pkg))
751                    .unwrap_or(true)
752            })
753            .cloned()
754            .collect_vec();
755
756        let to_remove = self
757            .rocks()
758            .values()
759            .filter(|pkg| !packages_to_keep.contains(*pkg))
760            .cloned()
761            .collect_vec();
762
763        PackageSyncSpec { to_add, to_remove }
764    }
765
766    /// Return all dependencies of a package, including itself
767    fn get_all_dependencies(&self, id: &LockedPackageId) -> HashSet<&LockedPackage> {
768        let mut packages = HashSet::new();
769        if let Some(local_pkg) = self.get(id) {
770            packages.insert(local_pkg);
771            packages.extend(
772                local_pkg
773                    .dependencies()
774                    .iter()
775                    .flat_map(|id| self.get_all_dependencies(id)),
776            );
777        }
778        packages
779    }
780
781    /// The set of all packages reachable from the entrypoints via the
782    /// dependency graph.
783    fn reachable(&self) -> HashSet<&LockedPackage> {
784        self.entrypoints
785            .values()
786            .flat_map(|id| self.get_all_dependencies(id))
787            .collect()
788    }
789}
790
791/// A lockfile for an install tree
792#[derive(Clone, Debug, Serialize, Deserialize)]
793pub struct Lockfile<P: LockfilePermissions> {
794    #[serde(skip)]
795    filepath: PathBuf,
796    #[serde(skip)]
797    _marker: PhantomData<P>,
798    // TODO: Serialize this directly into a `Version`
799    version: String,
800    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
801    binaries: BTreeMap<LockedPackageId, RockBinaries>,
802    #[serde(flatten)]
803    lock: PackageLock,
804}
805
806#[derive(EnumIter, Debug, Clone, Copy, PartialEq, Eq, Hash)]
807pub enum LockedPackageLockType {
808    Regular,
809    Test,
810    Build,
811}
812
813/// A lockfile for a Lua project
814#[derive(Clone, Debug, Serialize, Deserialize)]
815pub struct WorkspaceLockfile<P: LockfilePermissions> {
816    #[serde(skip)]
817    filepath: PathBuf,
818    #[serde(skip)]
819    _marker: PhantomData<P>,
820    version: String,
821    #[serde(default, skip_serializing_if = "PackageLock::is_empty")]
822    dependencies: PackageLock,
823    #[serde(default, skip_serializing_if = "PackageLock::is_empty")]
824    test_dependencies: PackageLock,
825    #[serde(default, skip_serializing_if = "PackageLock::is_empty")]
826    build_dependencies: PackageLock,
827}
828
829#[derive(Error, Debug, Diagnostic)]
830#[non_exhaustive]
831pub enum Error {
832    #[error(transparent)]
833    #[diagnostic(transparent)]
834    Fs(#[from] fs::Error),
835    #[error("error parsing lockfile from JSON")]
836    ParseJson(#[source] serde_json::Error),
837    #[error("error writing lockfile to JSON")]
838    WriteJson(#[source] serde_json::Error),
839    #[error("invalid version string in lockfile: {version}")]
840    #[diagnostic(help("did you or a tool modify the lockfile manually?"))]
841    InvalidVersion {
842        version: String,
843        source: semver::Error,
844    },
845    #[error("lockfile '{}' has no `version` field", lockfile.display())]
846    #[diagnostic(
847        code(lux_lib::lockfile::missing_version),
848        help("the lockfile is corrupt or was hand-edited")
849    )]
850    MissingVersion { lockfile: PathBuf },
851    #[error(
852        "incompatible lockfile version in '{}': expected {expected}, found {found}",
853        lockfile.display()
854    )]
855    #[diagnostic(code(lux_lib::lockfile::incompatible_version), help("{help}"))]
856    IncompatibleVersion {
857        lockfile: PathBuf,
858        found: String,
859        expected: String,
860        help: String,
861    },
862    #[error("cannot migrate lockfile '{}'", lockfile.display())]
863    #[diagnostic(code(lux_lib::lockfile::conflicting_entrypoints), help("{help}"))]
864    ConflictingEntrypoints { lockfile: PathBuf, help: String },
865}
866
867#[derive(Error, Debug, Diagnostic)]
868#[non_exhaustive]
869pub enum IntegrityError {
870    #[error(
871        r#"rockspec integrity mismatch.
872- source: {src}
873- expected: {expected}
874- got: {got}
875"#
876    )]
877    #[diagnostic(help(
878        r#"the maintainer may have force-uploaded a different rockspec.
879check the rockspec source, then rerun the command with `--no-lock` to update the hash.
880"#
881    ))]
882    RockspecIntegrityMismatch {
883        src: String,
884        expected: Integrity,
885        got: Integrity,
886    },
887    #[error(
888        r#"source integrity mismatch.
889- source: {src}
890- expected: {expected}
891- got: {got}"#
892    )]
893    #[diagnostic(help(
894        r#"the maintainer may have force-uploaded a different source or moved a tag.
895check the source URL, then rerun the command with `lx --no-lock` to update the hash.
896"#
897    ))]
898    SourceIntegrityMismatch {
899        src: String,
900        expected: Integrity,
901        got: Integrity,
902    },
903    #[error(
904        "package {0} version {1} with pinned state {2} and constraint {3} not found in the lockfile."
905    )]
906    PackageNotFound(package::Name, Box<package::Version>, PinnedState, String),
907}
908
909#[derive(Error, Debug, Diagnostic)]
910#[non_exhaustive]
911#[error("error flushing the lockfile ({})", .filepath.display())]
912#[diagnostic(help("make sure the parent directory is writeable"))]
913pub struct FlushLockfileError {
914    filepath: PathBuf,
915    source: io::Error,
916}
917
918/// A specification for syncing a list of packages with a lockfile
919#[derive(Debug, Default)]
920pub(crate) struct PackageSyncSpec {
921    pub to_add: Vec<lua_dependency::Spec>,
922    pub to_remove: Vec<LockedPackage>,
923}
924
925/// Controls how `package_sync_spec` determines whether a package exists.
926pub(crate) enum SyncStrategy<'a> {
927    /// Only check the lockfile for constraint matches.
928    LockfileOnly,
929    /// In addition to checking lockfile constraints, verify that each
930    /// package's installation directory exists in the given tree.
931    EnsureInstalled(&'a Tree),
932}
933
934impl<P: LockfilePermissions> Lockfile<P> {
935    pub fn version(&self) -> &String {
936        &self.version
937    }
938
939    pub fn rocks(&self) -> &BTreeMap<LockedPackageId, LockedPackage> {
940        self.lock.rocks()
941    }
942
943    pub fn is_dependency(&self, package: &LockedPackageId) -> bool {
944        self.lock.is_dependency(package)
945    }
946
947    pub fn is_entrypoint(&self, package: &LockedPackageId) -> bool {
948        self.lock.is_entrypoint(package)
949    }
950
951    /// Returns the entrypoint with the given package name, if any.
952    pub fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
953        self.lock.entrypoint(name)
954    }
955
956    pub fn entrypoints(&self) -> Vec<(&package::Name, &LockedPackage)> {
957        self.lock
958            .entrypoints
959            .iter()
960            .filter_map(|(name, id)| self.lock.get(id).map(|package| (name, package)))
961            .collect()
962    }
963
964    /// Returns all rocks in the lockfile that are reachable from an entrypoint
965    /// via the dependency graph.
966    pub fn reachable_rocks(&self) -> Vec<LockedPackage> {
967        self.lock.reachable().into_iter().cloned().collect()
968    }
969
970    pub fn entry_type(&self, package: &LockedPackageId) -> EntryType {
971        if self.lock.is_entrypoint(package) {
972            EntryType::Entrypoint
973        } else {
974            EntryType::DependencyOnly
975        }
976    }
977
978    /// The binaries installed in the tree for a given package.
979    pub(crate) fn binaries(&self, id: &LockedPackageId) -> Option<&RockBinaries> {
980        self.binaries.get(id)
981    }
982
983    pub(crate) fn local_pkg_lock(&self) -> &PackageLock {
984        &self.lock
985    }
986
987    pub fn get(&self, id: &LockedPackageId) -> Option<&LockedPackage> {
988        self.lock.get(id)
989    }
990
991    /// Unsafe because this assumes a prior check if the package is present
992    ///
993    /// # Safety
994    ///
995    /// Ensure that the package is present in the lockfile before calling this function.
996    pub unsafe fn get_unchecked(&self, id: &LockedPackageId) -> &LockedPackage {
997        self.lock.get(id).unwrap_unchecked()
998    }
999
1000    pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
1001        self.lock.list()
1002    }
1003
1004    pub(crate) fn has_rock(
1005        &self,
1006        req: &package::Req,
1007        filter: Option<remote::package::kind::FilterSpec>,
1008    ) -> Option<LockedPackage> {
1009        self.lock.has_rock(req, filter)
1010    }
1011
1012    /// Find all rocks that match the requirement
1013    pub(crate) fn find_rocks(&self, req: &package::Req) -> Vec<LockedPackageId> {
1014        match self.list().get(req.name()) {
1015            Some(packages) => packages
1016                .iter()
1017                .rev()
1018                .filter(|package| req.version_req().matches(package.version()))
1019                .map(|package| package.id())
1020                .collect_vec(),
1021            None => Vec::default(),
1022        }
1023    }
1024
1025    /// Validate the integrity of an installed package with the entry in this lockfile.
1026    pub(crate) fn validate_integrity(
1027        &self,
1028        expected_package: &LockedPackage,
1029    ) -> Result<(), IntegrityError> {
1030        // NOTE: We can't query by ID, because when installing from a lockfile (e.g. during sync),
1031        // the constraint is always `==`.
1032        match self.list().get(expected_package.name()) {
1033            None => Err(integrity_err_not_found(expected_package)),
1034            Some(rocks) => match rocks
1035                .iter()
1036                .find(|rock| rock.version() == expected_package.version())
1037            {
1038                None => Err(integrity_err_not_found(expected_package)),
1039                Some(installed_package) => {
1040                    if expected_package
1041                        .hashes
1042                        .rockspec
1043                        .matches(&installed_package.hashes.rockspec)
1044                        .is_none()
1045                    {
1046                        return Err(IntegrityError::RockspecIntegrityMismatch {
1047                            src: expected_package.source.to_string(),
1048                            expected: expected_package.hashes.rockspec.clone(),
1049                            got: installed_package.hashes.rockspec.clone(),
1050                        });
1051                    }
1052                    if expected_package
1053                        .hashes
1054                        .source
1055                        .matches(&installed_package.hashes.source)
1056                        .is_none()
1057                    {
1058                        return Err(IntegrityError::SourceIntegrityMismatch {
1059                            src: expected_package
1060                                .source_url
1061                                .as_ref()
1062                                .map(|url| url.to_string())
1063                                .unwrap_or(expected_package.source.to_string()),
1064                            expected: expected_package.hashes.source.clone(),
1065                            got: installed_package.hashes.source.clone(),
1066                        });
1067                    }
1068                    Ok(())
1069                }
1070            },
1071        }
1072    }
1073
1074    fn flush(&self) -> Result<(), FlushLockfileError> {
1075        let content = serde_json::to_string_pretty(&self).map_err(|err| FlushLockfileError {
1076            filepath: self.filepath.to_path_buf(),
1077            source: io::Error::other(err),
1078        })?;
1079
1080        fs::sync::write_atomic(&self.filepath, content).map_err(|err| FlushLockfileError {
1081            filepath: self.filepath.to_path_buf(),
1082            source: io::Error::other(err),
1083        })
1084    }
1085}
1086
1087impl<P: LockfilePermissions> WorkspaceLockfile<P> {
1088    pub(crate) fn rocks(
1089        &self,
1090        deps: &LockedPackageLockType,
1091    ) -> &BTreeMap<LockedPackageId, LockedPackage> {
1092        match deps {
1093            LockedPackageLockType::Regular => self.dependencies.rocks(),
1094            LockedPackageLockType::Test => self.test_dependencies.rocks(),
1095            LockedPackageLockType::Build => self.build_dependencies.rocks(),
1096        }
1097    }
1098
1099    pub(crate) fn get(
1100        &self,
1101        id: &LockedPackageId,
1102        deps: &LockedPackageLockType,
1103    ) -> Option<&LockedPackage> {
1104        match deps {
1105            LockedPackageLockType::Regular => self.dependencies.get(id),
1106            LockedPackageLockType::Test => self.test_dependencies.get(id),
1107            LockedPackageLockType::Build => self.build_dependencies.get(id),
1108        }
1109    }
1110
1111    pub(crate) fn is_entrypoint(
1112        &self,
1113        package: &LockedPackageId,
1114        deps: &LockedPackageLockType,
1115    ) -> bool {
1116        match deps {
1117            LockedPackageLockType::Regular => self.dependencies.is_entrypoint(package),
1118            LockedPackageLockType::Test => self.test_dependencies.is_entrypoint(package),
1119            LockedPackageLockType::Build => self.build_dependencies.is_entrypoint(package),
1120        }
1121    }
1122
1123    pub(crate) fn package_sync_spec(
1124        &self,
1125        packages: &[lua_dependency::Spec],
1126        deps: &LockedPackageLockType,
1127        strategy: &SyncStrategy<'_>,
1128    ) -> PackageSyncSpec {
1129        match deps {
1130            LockedPackageLockType::Regular => {
1131                self.dependencies.package_sync_spec(packages, strategy)
1132            }
1133            LockedPackageLockType::Test => {
1134                self.test_dependencies.package_sync_spec(packages, strategy)
1135            }
1136            LockedPackageLockType::Build => self
1137                .build_dependencies
1138                .package_sync_spec(packages, strategy),
1139        }
1140    }
1141
1142    pub(crate) fn local_pkg_lock(&self, deps: &LockedPackageLockType) -> &PackageLock {
1143        match deps {
1144            LockedPackageLockType::Regular => &self.dependencies,
1145            LockedPackageLockType::Test => &self.test_dependencies,
1146            LockedPackageLockType::Build => &self.build_dependencies,
1147        }
1148    }
1149
1150    pub(crate) fn local_pkg_locks(&self) -> Vec<PackageLock> {
1151        vec![
1152            self.dependencies.clone(),
1153            self.test_dependencies.clone(),
1154            self.build_dependencies.clone(),
1155        ]
1156    }
1157
1158    fn flush(&self) -> io::Result<()> {
1159        let content = serde_json::to_string_pretty(&self)?;
1160
1161        fs::sync::write_atomic(&self.filepath, content).map_err(io::Error::other)?;
1162
1163        Ok(())
1164    }
1165}
1166
1167impl Lockfile<ReadOnly> {
1168    /// Create a new `Lockfile`, writing an empty file if none exists.
1169    #[tracing::instrument(level = "trace")]
1170    pub(crate) fn new(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
1171        // Ensure that the lockfile exists
1172        match File::options().create_new(true).write(true).open(&filepath) {
1173            Ok(mut file) => {
1174                let empty_lockfile: Lockfile<ReadOnly> = Lockfile {
1175                    filepath: filepath.clone(),
1176                    _marker: PhantomData,
1177                    version: LOCKFILE_VERSION_STR.into(),
1178                    binaries: BTreeMap::new(),
1179                    lock: PackageLock::default(),
1180                };
1181                let json_str = serde_json::to_string(&empty_lockfile).map_err(Error::WriteJson)?;
1182                write!(file, "{json_str}").map_err(|source| fs::Error::Write {
1183                    path: filepath.to_path_buf(),
1184                    source,
1185                })?;
1186            }
1187            Err(err) if err.kind() == ErrorKind::AlreadyExists => {}
1188            Err(source) => {
1189                return Err(Error::Fs(fs::Error::FileOpen {
1190                    path: filepath.to_path_buf(),
1191                    source,
1192                }));
1193            }
1194        }
1195
1196        Self::load(filepath)
1197    }
1198
1199    /// Load a `Lockfile`, failing if none exists.
1200    #[tracing::instrument(level = "trace")]
1201    pub fn load(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
1202        let content = fs::sync::read_to_string(&filepath)?;
1203        let tree_dir = filepath.parent().unwrap_or(filepath.as_path());
1204        let help = format!(
1205            "this install tree was created by an incompatible version of Lux.
1206remove the tree at '{}' and reinstall all packages it contained.",
1207            tree_dir.display()
1208        );
1209        let mut lockfile: Lockfile<ReadOnly> = load_lockfile(&content, &filepath, &help)?;
1210        lockfile.filepath = filepath;
1211        Ok(lockfile)
1212    }
1213
1214    /// Creates a temporary, writeable lockfile which can never flush.
1215    pub(crate) fn into_temporary(self) -> Lockfile<ReadWrite> {
1216        Lockfile::<ReadWrite> {
1217            _marker: PhantomData,
1218            filepath: self.filepath,
1219            version: self.version,
1220            binaries: self.binaries,
1221            lock: self.lock,
1222        }
1223    }
1224
1225    /// Creates a lockfile guard, flushing the lockfile automatically
1226    /// once the guard goes out of scope.
1227    pub fn write_guard(self) -> LockfileGuard {
1228        LockfileGuard(self.into_temporary())
1229    }
1230
1231    /// Converts the current lockfile into a writeable one, executes `cb` and flushes
1232    /// the lockfile.
1233    #[tracing::instrument(level = "trace", skip_all)]
1234    pub fn map_then_flush<T, F, E>(self, cb: F) -> Result<T, FlushLockfileError>
1235    where
1236        F: FnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
1237        E: std::error::Error,
1238        E: From<io::Error>,
1239        E: Into<Box<dyn std::error::Error + Send + Sync>>,
1240    {
1241        let mut writeable_lockfile = self.into_temporary();
1242
1243        let result = cb(&mut writeable_lockfile).map_err(|err| FlushLockfileError {
1244            filepath: writeable_lockfile.filepath.to_path_buf(),
1245            source: io::Error::other(err),
1246        })?;
1247
1248        writeable_lockfile.flush()?;
1249
1250        Ok(result)
1251    }
1252
1253    // TODO: Add this once async closures are stabilized
1254    // Converts the current lockfile into a writeable one, executes `cb` asynchronously and flushes
1255    // the lockfile.
1256    //pub async fn map_then_flush_async<T, F, E, Fut>(self, cb: F) -> Result<T, E>
1257    //where
1258    //    F: AsyncFnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
1259    //    E: Error,
1260    //    E: From<io::Error>,
1261    //{
1262    //    let mut writeable_lockfile = self.into_temporary();
1263    //
1264    //    let result = cb(&mut writeable_lockfile).await?;
1265    //
1266    //    writeable_lockfile.flush()?;
1267    //
1268    //    Ok(result)
1269    //}
1270}
1271
1272impl WorkspaceLockfile<ReadOnly> {
1273    /// Create a new `ProjectLockfile`, writing an empty file if none exists.
1274    #[tracing::instrument(level = "trace")]
1275    pub fn new(filepath: PathBuf) -> Result<WorkspaceLockfile<ReadOnly>, Error> {
1276        // Ensure that the lockfile exists
1277        match File::options().create_new(true).write(true).open(&filepath) {
1278            Ok(mut file) => {
1279                let empty_lockfile: WorkspaceLockfile<ReadOnly> = WorkspaceLockfile {
1280                    filepath: filepath.clone(),
1281                    _marker: PhantomData,
1282                    version: LOCKFILE_VERSION_STR.into(),
1283                    dependencies: PackageLock::default(),
1284                    test_dependencies: PackageLock::default(),
1285                    build_dependencies: PackageLock::default(),
1286                };
1287                let json_str = serde_json::to_string(&empty_lockfile).map_err(Error::WriteJson)?;
1288                write!(file, "{json_str}").map_err(|source| fs::Error::Write {
1289                    path: filepath.to_path_buf(),
1290                    source,
1291                })?;
1292            }
1293            Err(err) if err.kind() == ErrorKind::AlreadyExists => {}
1294            Err(source) => {
1295                return Err(Error::Fs(fs::Error::FileOpen {
1296                    path: filepath.to_path_buf(),
1297                    source,
1298                }));
1299            }
1300        }
1301
1302        Self::load(filepath)
1303    }
1304
1305    /// Load a `ProjectLockfile`, failing if none exists.
1306    #[tracing::instrument(level = "trace")]
1307    pub fn load(filepath: PathBuf) -> Result<WorkspaceLockfile<ReadOnly>, Error> {
1308        let content = fs::sync::read_to_string(&filepath)?;
1309        let mut lockfile: WorkspaceLockfile<ReadOnly> = load_lockfile(
1310            &content,
1311            &filepath,
1312            "this lockfile was created by an incompatible version of Lux.
1313remove the `lux.lock` and run `lx sync` to regenerate it.",
1314        )?;
1315
1316        lockfile.filepath = filepath;
1317
1318        Ok(lockfile)
1319    }
1320
1321    /// Creates a temporary, writeable project lockfile which can never flush.
1322    fn into_temporary(self) -> WorkspaceLockfile<ReadWrite> {
1323        WorkspaceLockfile::<ReadWrite> {
1324            _marker: PhantomData,
1325            filepath: self.filepath,
1326            version: self.version,
1327            dependencies: self.dependencies,
1328            test_dependencies: self.test_dependencies,
1329            build_dependencies: self.build_dependencies,
1330        }
1331    }
1332
1333    /// Creates a project lockfile guard, flushing the lockfile automatically
1334    /// once the guard goes out of scope.
1335    pub fn write_guard(self) -> ProjectLockfileGuard {
1336        ProjectLockfileGuard(self.into_temporary())
1337    }
1338}
1339
1340impl Lockfile<ReadWrite> {
1341    pub(crate) fn add_entrypoint(&mut self, rock: &LockedPackage) {
1342        self.add(rock);
1343        self.lock.entrypoints.insert(rock.name().clone(), rock.id());
1344    }
1345
1346    pub(crate) fn add(&mut self, rock: &LockedPackage) {
1347        // Since rocks entries are mutable, we only add the dependency if it
1348        // has not already been added.
1349        self.lock
1350            .rocks
1351            .entry(rock.id())
1352            .or_insert_with(|| rock.clone());
1353    }
1354
1355    /// Add a dependency for a package.
1356    pub(crate) fn add_dependency(&mut self, target: &LockedPackage, dependency: &LockedPackage) {
1357        self.lock
1358            .rocks
1359            .entry(target.id())
1360            .and_modify(|rock| {
1361                let id = dependency.id();
1362                if !rock.spec.dependencies.contains(&id) {
1363                    rock.spec.dependencies.push(id);
1364                }
1365            })
1366            .or_insert_with(|| {
1367                let id = dependency.id();
1368                let mut target = target.clone();
1369                if !target.spec.dependencies.contains(&id) {
1370                    target.spec.dependencies.push(id);
1371                }
1372                target
1373            });
1374        self.add(dependency);
1375    }
1376
1377    /// Add a build dependency for a package.
1378    pub(crate) fn add_build_dependency(
1379        &mut self,
1380        target: &LockedPackage,
1381        dependency: &LockedPackage,
1382    ) {
1383        self.lock
1384            .rocks
1385            .entry(target.id())
1386            .and_modify(|rock| {
1387                let id = dependency.id();
1388                if !rock.spec.build_dependencies.contains(&id) {
1389                    rock.spec.build_dependencies.push(id);
1390                }
1391            })
1392            .or_insert_with(|| {
1393                let id = dependency.id();
1394                let mut target = target.clone();
1395                if !target.spec.build_dependencies.contains(&id) {
1396                    target.spec.build_dependencies.push(id);
1397                }
1398                target
1399            });
1400    }
1401
1402    /// Record the binaries installed for `package` into the tree lockfile.
1403    pub(crate) fn set_binaries(&mut self, package: &LockedPackage, binaries: RockBinaries) {
1404        self.binaries.insert(package.id(), binaries);
1405    }
1406
1407    pub(crate) fn remove(&mut self, target: &LockedPackage) {
1408        self.binaries.remove(&target.id());
1409        self.lock.remove(target)
1410    }
1411
1412    pub(crate) fn remove_by_id(&mut self, target: &LockedPackageId) {
1413        self.binaries.remove(target);
1414        self.lock.remove_by_id(target)
1415    }
1416
1417    pub(crate) fn sync(&mut self, lock: &PackageLock) {
1418        self.lock = lock.clone();
1419    }
1420
1421    // TODO: `fn entrypoints() -> Vec<LockedRock>`
1422}
1423
1424impl WorkspaceLockfile<ReadWrite> {
1425    pub(crate) fn remove(&mut self, target: &LockedPackage, deps: &LockedPackageLockType) {
1426        match deps {
1427            LockedPackageLockType::Regular => self.dependencies.remove(target),
1428            LockedPackageLockType::Test => self.test_dependencies.remove(target),
1429            LockedPackageLockType::Build => self.build_dependencies.remove(target),
1430        }
1431    }
1432
1433    pub(crate) fn sync(&mut self, lock: &PackageLock, deps: &LockedPackageLockType) {
1434        match deps {
1435            LockedPackageLockType::Regular => {
1436                self.dependencies = lock.clone();
1437            }
1438            LockedPackageLockType::Test => {
1439                self.test_dependencies = lock.clone();
1440            }
1441            LockedPackageLockType::Build => {
1442                self.build_dependencies = lock.clone();
1443            }
1444        }
1445    }
1446
1447    pub(crate) fn merge(&mut self, lock: &PackageLock, deps: &LockedPackageLockType) {
1448        match deps {
1449            LockedPackageLockType::Regular => self.dependencies.merge(lock),
1450            LockedPackageLockType::Test => self.test_dependencies.merge(lock),
1451            LockedPackageLockType::Build => self.build_dependencies.merge(lock),
1452        }
1453    }
1454}
1455
1456/// Flushes a lockfile automatically when it goes out of scope
1457pub struct LockfileGuard(Lockfile<ReadWrite>);
1458
1459pub struct ProjectLockfileGuard(WorkspaceLockfile<ReadWrite>);
1460
1461impl Serialize for LockfileGuard {
1462    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1463    where
1464        S: serde::Serializer,
1465    {
1466        self.0.serialize(serializer)
1467    }
1468}
1469
1470impl Serialize for ProjectLockfileGuard {
1471    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1472    where
1473        S: serde::Serializer,
1474    {
1475        self.0.serialize(serializer)
1476    }
1477}
1478
1479impl<'de> Deserialize<'de> for LockfileGuard {
1480    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1481    where
1482        D: serde::Deserializer<'de>,
1483    {
1484        Ok(LockfileGuard(Lockfile::<ReadWrite>::deserialize(
1485            deserializer,
1486        )?))
1487    }
1488}
1489
1490impl<'de> Deserialize<'de> for ProjectLockfileGuard {
1491    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1492    where
1493        D: serde::Deserializer<'de>,
1494    {
1495        Ok(ProjectLockfileGuard(
1496            WorkspaceLockfile::<ReadWrite>::deserialize(deserializer)?,
1497        ))
1498    }
1499}
1500
1501impl Deref for LockfileGuard {
1502    type Target = Lockfile<ReadWrite>;
1503
1504    fn deref(&self) -> &Self::Target {
1505        &self.0
1506    }
1507}
1508
1509impl Deref for ProjectLockfileGuard {
1510    type Target = WorkspaceLockfile<ReadWrite>;
1511
1512    fn deref(&self) -> &Self::Target {
1513        &self.0
1514    }
1515}
1516
1517impl DerefMut for LockfileGuard {
1518    fn deref_mut(&mut self) -> &mut Self::Target {
1519        &mut self.0
1520    }
1521}
1522
1523impl DerefMut for ProjectLockfileGuard {
1524    fn deref_mut(&mut self) -> &mut Self::Target {
1525        &mut self.0
1526    }
1527}
1528
1529impl Drop for LockfileGuard {
1530    fn drop(&mut self) {
1531        let _ = self.flush();
1532    }
1533}
1534
1535impl Drop for ProjectLockfileGuard {
1536    fn drop(&mut self) {
1537        let _ = self.flush();
1538    }
1539}
1540
1541fn load_lockfile<T>(content: &str, lockfile: &Path, help: &str) -> Result<T, Error>
1542where
1543    T: serde::de::DeserializeOwned,
1544{
1545    let mut value = parse_lockfile_json(content)?;
1546    if lockfile_version(&value, lockfile)?.major == 1 {
1547        migrate_v1_lockfile(&mut value, lockfile)?;
1548    }
1549    deserialize_lockfile(value, lockfile, help)
1550}
1551
1552fn parse_lockfile_json(content: &str) -> Result<serde_json::Map<String, serde_json::Value>, Error> {
1553    serde_json::from_str(content).map_err(Error::ParseJson)
1554}
1555
1556fn lockfile_version(
1557    value: &serde_json::Map<String, serde_json::Value>,
1558    lockfile: &Path,
1559) -> Result<semver::Version, Error> {
1560    let version = value
1561        .get("version")
1562        .and_then(|version| version.as_str())
1563        .ok_or(Error::MissingVersion {
1564            lockfile: lockfile.to_path_buf(),
1565        })?;
1566    semver::Version::parse(version).map_err(|source| Error::InvalidVersion {
1567        version: version.to_string(),
1568        source,
1569    })
1570}
1571
1572fn deserialize_lockfile<T>(
1573    value: serde_json::Map<String, serde_json::Value>,
1574    lockfile: &Path,
1575    help: &str,
1576) -> Result<T, Error>
1577where
1578    T: serde::de::DeserializeOwned,
1579{
1580    let found = lockfile_version(&value, lockfile)?;
1581    if found.major != LOCKFILE_VERSION {
1582        return Err(Error::IncompatibleVersion {
1583            lockfile: lockfile.to_path_buf(),
1584            found: found.to_string(),
1585            expected: LOCKFILE_VERSION_STR.into(),
1586            help: help.into(),
1587        });
1588    }
1589    serde_json::from_value(serde_json::Value::Object(value)).map_err(Error::ParseJson)
1590}
1591
1592fn migrate_v1_lockfile(
1593    value: &mut serde_json::Map<String, serde_json::Value>,
1594    lockfile: &Path,
1595) -> Result<(), Error> {
1596    let tree_dir = lockfile.parent().unwrap_or(lockfile);
1597    let found = lockfile_version(value, lockfile)?;
1598    if value.contains_key("entrypoint_layout") {
1599        return Err(Error::IncompatibleVersion {
1600            lockfile: lockfile.to_path_buf(),
1601            found: found.to_string(),
1602            expected: LOCKFILE_VERSION_STR.into(),
1603            help: format!(
1604                "this install tree uses a custom entrypoint layout that cannot be migrated automatically.
1605remove the tree at '{}' and reinstall all packages it contained.",
1606                tree_dir.display()
1607            ),
1608        });
1609    }
1610
1611    let conflict_help = format!(
1612        "this lockfile contains entrypoints that cannot be represented in the current format.
1613remove the tree at '{}' and reinstall all packages it contained.",
1614        tree_dir.display()
1615    );
1616
1617    if value.contains_key("entrypoints") {
1618        migrate_entrypoints(value, lockfile, &conflict_help)?;
1619    }
1620    for section in ["dependencies", "test_dependencies", "build_dependencies"] {
1621        if let Some(section) = value
1622            .get_mut(section)
1623            .and_then(|section| section.as_object_mut())
1624        {
1625            migrate_entrypoints(section, lockfile, &conflict_help)?;
1626        }
1627    }
1628    value.insert(
1629        "version".into(),
1630        serde_json::Value::String(LOCKFILE_VERSION_STR.into()),
1631    );
1632    Ok(())
1633}
1634
1635fn migrate_entrypoints(
1636    section: &mut serde_json::Map<String, serde_json::Value>,
1637    lockfile: &Path,
1638    help: &str,
1639) -> Result<(), Error> {
1640    let conflicting_entrypoints = || Error::ConflictingEntrypoints {
1641        lockfile: lockfile.to_path_buf(),
1642        help: help.to_string(),
1643    };
1644
1645    let rocks = section.get("rocks").and_then(|rocks| rocks.as_object());
1646    let mut entrypoints = serde_json::Map::new();
1647    if let Some(old_entrypoints) = section.get("entrypoints") {
1648        for id in old_entrypoints
1649            .as_array()
1650            .ok_or_else(conflicting_entrypoints)?
1651        {
1652            let id = id.as_str().ok_or_else(conflicting_entrypoints)?;
1653            let name = rocks
1654                .and_then(|rocks| rocks.get(id))
1655                .and_then(|package| package.get("name"))
1656                .and_then(|name| name.as_str())
1657                .ok_or_else(conflicting_entrypoints)?;
1658            if entrypoints.contains_key(name) {
1659                return Err(conflicting_entrypoints());
1660            }
1661            entrypoints.insert(name.to_string(), serde_json::Value::String(id.to_string()));
1662        }
1663    }
1664    section.insert("entrypoints".into(), serde_json::Value::Object(entrypoints));
1665    Ok(())
1666}
1667
1668fn integrity_err_not_found(package: &LockedPackage) -> IntegrityError {
1669    IntegrityError::PackageNotFound(
1670        package.name().clone(),
1671        Box::new(package.version().clone()),
1672        package.spec.pinned,
1673        package
1674            .spec
1675            .constraint
1676            .clone()
1677            .unwrap_or("UNCONSTRAINED".into()),
1678    )
1679}
1680
1681fn deserialize_url<'de, D>(deserializer: D) -> Result<Url, D::Error>
1682where
1683    D: serde::Deserializer<'de>,
1684{
1685    let s = String::deserialize(deserializer)?;
1686    Url::parse(&s).map_err(serde::de::Error::custom)
1687}
1688
1689fn serialize_url<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>
1690where
1691    S: Serializer,
1692{
1693    url.as_str().serialize(serializer)
1694}
1695
1696#[cfg(test)]
1697mod tests {
1698    use super::*;
1699    use std::{fs::remove_file, path::PathBuf};
1700
1701    use assert_fs::fixture::PathCopy;
1702    use insta::{assert_json_snapshot, sorted_redaction};
1703
1704    use crate::{config, lua};
1705
1706    #[test]
1707    fn parse_lockfile() {
1708        let temp = assert_fs::TempDir::new().unwrap();
1709        temp.copy_from(
1710            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1711            &["**"],
1712        )
1713        .unwrap();
1714
1715        let config = config::Builder::new()
1716            .unwrap()
1717            .user_tree(Some(temp.to_path_buf()))
1718            .build()
1719            .unwrap();
1720        let tree = config.user_tree(lua::Version::Lua51).unwrap();
1721        let lockfile = tree.lockfile().unwrap();
1722
1723        assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
1724    }
1725
1726    #[test]
1727    fn add_rocks() {
1728        let temp = assert_fs::TempDir::new().unwrap();
1729        temp.copy_from(
1730            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1731            &["**"],
1732        )
1733        .unwrap();
1734
1735        let mock_hashes = LockedPackageHashes {
1736            rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
1737                .parse()
1738                .unwrap(),
1739            source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
1740                .parse()
1741                .unwrap(),
1742        };
1743
1744        let config = config::Builder::new()
1745            .unwrap()
1746            .user_tree(Some(temp.to_path_buf()))
1747            .build()
1748            .unwrap();
1749        let tree = config.user_tree(lua::Version::Lua51).unwrap();
1750        let mut lockfile = tree.lockfile().unwrap().write_guard();
1751
1752        let test_package = package::Spec::parse("test1".to_string(), "0.1.0".to_string()).unwrap();
1753        let test_local_package = LockedPackage::from(
1754            &test_package,
1755            crate::lockfile::Constraint::Unconstrained,
1756            remote::package::Source::Test,
1757            None,
1758            mock_hashes.clone(),
1759        );
1760        lockfile.add_entrypoint(&test_local_package);
1761
1762        let test_dep_package =
1763            package::Spec::parse("test2".to_string(), "0.1.0".to_string()).unwrap();
1764        let mut test_local_dep_package = LockedPackage::from(
1765            &test_dep_package,
1766            crate::lockfile::Constraint::Constrained(">= 1.0.0".parse().unwrap()),
1767            remote::package::Source::Test,
1768            None,
1769            mock_hashes.clone(),
1770        );
1771        test_local_dep_package.spec.pinned = PinnedState::Pinned;
1772        lockfile.add_dependency(&test_local_package, &test_local_dep_package);
1773
1774        assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
1775    }
1776
1777    #[test]
1778    fn parse_nonexistent_lockfile() {
1779        let tree_path =
1780            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
1781
1782        let temp = assert_fs::TempDir::new().unwrap();
1783        temp.copy_from(&tree_path, &["**"]).unwrap();
1784
1785        remove_file(temp.join("5.1/lux.lock")).unwrap();
1786
1787        let config = config::Builder::new()
1788            .unwrap()
1789            .user_tree(Some(temp.to_path_buf()))
1790            .build()
1791            .unwrap();
1792        let tree = config.user_tree(lua::Version::Lua51).unwrap();
1793
1794        let _ = tree.lockfile().unwrap().write_guard(); // Try to create the lockfile but don't actually do anything with it.
1795    }
1796
1797    fn get_test_lockfile() -> Lockfile<ReadOnly> {
1798        let sample_tree = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1799            .join("resources/test/sample-tree/5.1/lux.lock");
1800        Lockfile::new(sample_tree).unwrap()
1801    }
1802
1803    #[test]
1804    fn test_sync_spec() {
1805        let lockfile = get_test_lockfile();
1806        let packages = vec![
1807            package::Req::parse("neorg@8.8.1-1").unwrap().into(),
1808            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1809            package::Req::parse("nonexistent").unwrap().into(),
1810        ];
1811
1812        let sync_spec = lockfile
1813            .lock
1814            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1815
1816        assert_eq!(sync_spec.to_add.len(), 1);
1817
1818        // Should keep dependencies of neorg 8.8.1-1
1819        assert!(!sync_spec
1820            .to_remove
1821            .iter()
1822            .any(|pkg| pkg.name().to_string() == "nvim-nio"
1823                && pkg.constraint()
1824                    == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
1825        assert!(!sync_spec
1826            .to_remove
1827            .iter()
1828            .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
1829                && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
1830        assert!(!sync_spec
1831            .to_remove
1832            .iter()
1833            .any(|pkg| pkg.name().to_string() == "plenary.nvim"
1834                && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
1835        assert!(!sync_spec
1836            .to_remove
1837            .iter()
1838            .any(|pkg| pkg.name().to_string() == "nui.nvim"
1839                && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
1840        assert!(!sync_spec
1841            .to_remove
1842            .iter()
1843            .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
1844                && pkg.constraint()
1845                    == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
1846    }
1847
1848    #[test]
1849    fn test_sync_spec_remove() {
1850        let lockfile = get_test_lockfile();
1851        let packages = vec![
1852            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1853            package::Req::parse("nonexistent").unwrap().into(),
1854        ];
1855
1856        let sync_spec = lockfile
1857            .lock
1858            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1859
1860        assert_eq!(sync_spec.to_add.len(), 1);
1861
1862        // Should remove:
1863        // - neorg
1864        // - dependencies unique to neorg
1865        assert!(sync_spec
1866            .to_remove
1867            .iter()
1868            .any(|pkg| pkg.name().to_string() == "neorg"
1869                && pkg.version() == &"8.8.1-1".parse().unwrap()));
1870        assert!(sync_spec
1871            .to_remove
1872            .iter()
1873            .any(|pkg| pkg.name().to_string() == "nvim-nio"
1874                && pkg.constraint()
1875                    == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
1876        assert!(sync_spec
1877            .to_remove
1878            .iter()
1879            .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
1880                && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
1881        assert!(sync_spec
1882            .to_remove
1883            .iter()
1884            .any(|pkg| pkg.name().to_string() == "plenary.nvim"
1885                && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
1886        assert!(sync_spec
1887            .to_remove
1888            .iter()
1889            .any(|pkg| pkg.name().to_string() == "nui.nvim"
1890                && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
1891        assert!(sync_spec
1892            .to_remove
1893            .iter()
1894            .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
1895                && pkg.constraint()
1896                    == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
1897    }
1898
1899    #[test]
1900    fn test_sync_spec_empty() {
1901        let lockfile = get_test_lockfile();
1902        let packages = vec![];
1903        let sync_spec = lockfile
1904            .lock
1905            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1906
1907        // Should remove all packages
1908        assert!(sync_spec.to_add.is_empty());
1909        assert_eq!(sync_spec.to_remove.len(), lockfile.rocks().len());
1910    }
1911
1912    #[test]
1913    fn test_sync_spec_different_constraints() {
1914        let lockfile = get_test_lockfile();
1915        let packages = vec![package::Req::parse("nvim-nio>=2.0.0").unwrap().into()];
1916        let sync_spec = lockfile
1917            .lock
1918            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1919
1920        let expected: package::VersionReq = ">=2.0.0".parse().unwrap();
1921        assert!(sync_spec
1922            .to_add
1923            .iter()
1924            .any(|req| req.name().to_string() == "nvim-nio" && req.version_req() == &expected));
1925
1926        assert!(sync_spec
1927            .to_remove
1928            .iter()
1929            .any(|pkg| pkg.name().to_string() == "nvim-nio"));
1930    }
1931
1932    #[test]
1933    fn test_sync_spec_ensure_installed() {
1934        let temp = assert_fs::TempDir::new().unwrap();
1935        temp.copy_from(
1936            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1937            &["**"],
1938        )
1939        .unwrap();
1940
1941        let config = config::Builder::new()
1942            .unwrap()
1943            .user_tree(Some(temp.to_path_buf()))
1944            .build()
1945            .unwrap();
1946        let tree = config.user_tree(lua::Version::Lua51).unwrap();
1947        let lockfile = tree.lockfile().unwrap();
1948
1949        let packages: Vec<lua_dependency::Spec> = vec![
1950            package::Req::parse("neorg@8.8.1-1").unwrap().into(),
1951            // This package isn't installed in the tree
1952            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1953            // And neither is this
1954            package::Req::parse("nonexistent").unwrap().into(),
1955        ];
1956
1957        // Since lua-cjson is not present in the tree, it should get put into `to_add`
1958        let sync_spec = lockfile
1959            .lock
1960            .package_sync_spec(&packages, &SyncStrategy::EnsureInstalled(&tree));
1961
1962        assert!(!sync_spec
1963            .to_add
1964            .iter()
1965            .any(|req| req.name().to_string() == "neorg"));
1966
1967        assert!(sync_spec
1968            .to_add
1969            .iter()
1970            .any(|req| req.name().to_string() == "lua-cjson"));
1971
1972        assert!(sync_spec
1973            .to_add
1974            .iter()
1975            .any(|req| req.name().to_string() == "nonexistent"));
1976    }
1977
1978    #[test]
1979    fn verify_lockfile_version() {
1980        let deserialize = |version: &str| {
1981            let content = format!(r#"{{"version": "{version}"}}"#);
1982            parse_lockfile_json(&content).and_then(|value| {
1983                deserialize_lockfile::<Lockfile<ReadOnly>>(value, Path::new("lux.lock"), "")
1984            })
1985        };
1986
1987        assert!(matches!(
1988            deserialize("3.0.0"),
1989            Err(Error::IncompatibleVersion { .. })
1990        ));
1991        assert!(matches!(
1992            deserialize("not-a-version"),
1993            Err(Error::InvalidVersion { .. })
1994        ));
1995    }
1996
1997    #[test]
1998    fn migrate_v1_tree_lockfile() {
1999        let sample =
2000            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/lockfile-v1/tree.lock");
2001
2002        let temp = assert_fs::TempDir::new().unwrap();
2003        let lockfile_path = temp.path().join("lux.lock");
2004        std::fs::copy(&sample, &lockfile_path).unwrap();
2005
2006        let lockfile = Lockfile::load(lockfile_path.clone()).unwrap();
2007
2008        let on_disk: serde_json::Value =
2009            serde_json::from_str(&std::fs::read_to_string(&lockfile_path).unwrap()).unwrap();
2010        assert_eq!(on_disk["version"], "1.0.0");
2011        assert!(on_disk["entrypoints"].is_array());
2012
2013        assert_eq!(lockfile.version, "2.0.0");
2014        assert_eq!(lockfile.lock.entrypoints.len(), 3);
2015    }
2016
2017    #[test]
2018    fn refuse_migration_for_custom_layout() {
2019        let lockfile = r#"{"version":"1.0.0","entrypoint_layout":{"root":"site/pack/lux"}}"#;
2020        assert!(matches!(
2021            load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
2022            Err(Error::IncompatibleVersion { .. })
2023        ));
2024    }
2025
2026    #[test]
2027    fn refuse_migration_for_conflicting_entrypoints() {
2028        let lockfile = r#"{
2029            "version": "1.0.0",
2030            "rocks": {
2031                "a": { "name": "foo" },
2032                "b": { "name": "foo" }
2033            },
2034            "entrypoints": ["a", "b"]
2035        }"#;
2036        assert!(matches!(
2037            load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
2038            Err(Error::ConflictingEntrypoints { .. })
2039        ));
2040    }
2041
2042    #[test]
2043    fn migrate_v1_workspace_lockfile() {
2044        let sample = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2045            .join("resources/test/lockfile-v1/workspace.lock");
2046
2047        let temp = assert_fs::TempDir::new().unwrap();
2048        let lockfile_path = temp.path().join("lux.lock");
2049        std::fs::copy(&sample, &lockfile_path).unwrap();
2050
2051        let lockfile = WorkspaceLockfile::load(lockfile_path.clone()).unwrap();
2052
2053        let on_disk: serde_json::Value =
2054            serde_json::from_str(&std::fs::read_to_string(&lockfile_path).unwrap()).unwrap();
2055        assert_eq!(on_disk["version"], "1.0.0");
2056        assert!(on_disk["dependencies"]["entrypoints"].is_array());
2057
2058        assert_eq!(lockfile.version, "2.0.0");
2059        assert_eq!(lockfile.dependencies.entrypoints.len(), 3);
2060    }
2061}