Skip to main content

lux_lib/lockfile/
mod.rs

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