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::{
7    collections::HashMap,
8    fs::File,
9    io::ErrorKind,
10    path::{Path, PathBuf},
11};
12
13use itertools::Itertools;
14
15use miette::Diagnostic;
16use serde::{Deserialize, Serialize, Serializer};
17use ssri::Integrity;
18use strum_macros::EnumIter;
19use thiserror::Error;
20use url::Url;
21
22use crate::fs;
23use crate::remote;
24use crate::rockspec::lua_dependency;
25use crate::rockspec::RockBinaries;
26use crate::tree::{EntryType, InstallTree, Tree};
27
28pub mod constraint;
29mod guard;
30pub mod locked_package;
31mod opt_state;
32mod pinned_state;
33
34use locked_package::integrity_err_not_found;
35
36pub use constraint::Constraint;
37pub use guard::Guard;
38pub use locked_package::LockedPackage;
39pub use opt_state::OptState;
40pub use pinned_state::PinnedState;
41
42/// Bump this whenever an incompatible change is made to the lockfile format.
43/// Lockfiles with a different major version are rejected on load.
44const LOCKFILE_VERSION: u64 = 2;
45pub(crate) const LOCKFILE_VERSION_STR: &str = "2.0.0";
46
47#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48#[serde(rename_all = "lowercase", tag = "type")]
49pub(crate) enum RemotePackageSourceUrl {
50    Git {
51        url: String,
52        #[serde(rename = "ref")]
53        checkout_ref: String,
54        /// Whether the source repository contains git submodules that must be
55        /// fetched for the package to build.
56        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57        submodules: bool,
58    }, // GitUrl doesn't have all the trait instances we need
59    Url {
60        #[serde(deserialize_with = "deserialize_url", serialize_with = "serialize_url")]
61        url: Url,
62    },
63    File {
64        path: PathBuf,
65    },
66}
67
68impl Display for RemotePackageSourceUrl {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        match self {
71            RemotePackageSourceUrl::Git {
72                url, checkout_ref, ..
73            } => format!("{url}@{checkout_ref}").fmt(f),
74            RemotePackageSourceUrl::Url { url } => url.fmt(f),
75            RemotePackageSourceUrl::File { path } => format!("{}", path.display()).fmt(f),
76        }
77    }
78}
79
80pub trait LockfilePermissions {}
81#[derive(Clone)]
82pub struct ReadOnly;
83#[derive(Clone)]
84pub struct ReadWrite;
85
86impl LockfilePermissions for ReadOnly {}
87impl LockfilePermissions for ReadWrite {}
88
89#[derive(Clone, Debug, Serialize, Deserialize, Default)]
90pub(crate) struct PackageLock {
91    // NOTE: We cannot directly serialize to a `Sha256` object as they don't implement serde traits.
92    // NOTE: We want to retain ordering of rocks when de/serializing.
93    rocks: BTreeMap<locked_package::ID, LockedPackage>,
94
95    /// The entrypoints of the tree. Enforces one entrypoint per package name.
96    pub(crate) entrypoints: BTreeMap<package::Name, locked_package::ID>,
97}
98
99impl PackageLock {
100    pub(crate) fn from_packages(
101        packages: impl Iterator<Item = (LockedPackage, EntryType)>,
102    ) -> Self {
103        let mut lock = Self::default();
104
105        for (package, entry_type) in packages {
106            if matches!(entry_type, EntryType::Entrypoint) {
107                lock.entrypoints
108                    .insert(package.name().clone(), package.id());
109            }
110            lock.rocks.insert(package.id(), package);
111        }
112
113        lock
114    }
115
116    pub(crate) fn merge(&mut self, other: &PackageLock) {
117        self.entrypoints.extend(
118            other
119                .entrypoints
120                .iter()
121                .map(|(name, id)| (name.clone(), id.clone())),
122        );
123        self.rocks.extend(
124            other
125                .rocks
126                .iter()
127                .map(|(id, package)| (id.clone(), package.clone())),
128        );
129    }
130
131    pub(crate) fn get(&self, id: &locked_package::ID) -> Option<&LockedPackage> {
132        self.rocks.get(id)
133    }
134
135    pub(crate) fn is_empty(&self) -> bool {
136        self.rocks.is_empty()
137    }
138
139    pub(crate) fn rocks(&self) -> &BTreeMap<locked_package::ID, LockedPackage> {
140        &self.rocks
141    }
142
143    pub(crate) fn is_entrypoint(&self, package: &locked_package::ID) -> bool {
144        self.entrypoints.values().any(|id| id == package)
145    }
146
147    /// Returns the entrypoint with the given package name, if any.
148    pub(crate) fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
149        self.entrypoints.get(name).and_then(|id| self.get(id))
150    }
151
152    pub(crate) fn is_dependency(&self, package: &locked_package::ID) -> bool {
153        self.rocks
154            .values()
155            .flat_map(|rock| rock.dependencies())
156            .any(|dep_id| dep_id == package)
157    }
158
159    pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
160        self.rocks()
161            .values()
162            .cloned()
163            .map(|locked_rock| (locked_rock.name().clone(), locked_rock))
164            .into_group_map()
165    }
166
167    pub(crate) fn remove(&mut self, target: &LockedPackage) {
168        self.remove_by_id(&target.id())
169    }
170
171    pub(crate) fn remove_by_id(&mut self, target: &locked_package::ID) {
172        self.rocks.remove(target);
173        self.entrypoints.retain(|_, id| id != target);
174    }
175
176    pub(crate) fn has_rock(
177        &self,
178        req: &package::Req,
179        filter: Option<remote::package::kind::FilterSpec>,
180    ) -> Option<LockedPackage> {
181        self.list()
182            .get(req.name())
183            .map(|packages| {
184                packages
185                    .iter()
186                    .filter(|package| match &filter {
187                        Some(filter_spec) => match &package.source {
188                            remote::package::Source::LuarocksRockspec(_) => filter_spec.rockspec,
189                            remote::package::Source::LuarocksSrcRock(_) => filter_spec.src,
190                            remote::package::Source::LuarocksBinaryRock(_) => filter_spec.binary,
191                            remote::package::Source::Wally(_) => true,
192                            remote::package::Source::RockspecContent(_) => true,
193                            remote::package::Source::Local => true,
194                            #[cfg(test)]
195                            remote::package::Source::Test => unimplemented!(),
196                        },
197                        None => true,
198                    })
199                    .rev()
200                    .find(|package| req.version_req().matches(package.version()))
201            })?
202            .cloned()
203    }
204
205    pub(crate) fn has_rock_with_equal_constraint(
206        &self,
207        req: &lua_dependency::Spec,
208    ) -> Option<LockedPackage> {
209        self.list()
210            .get(req.name())
211            .map(|packages| {
212                packages
213                    .iter()
214                    .rev()
215                    .find(|package| package.constraint().matches_version_req(req.version_req()))
216            })?
217            .cloned()
218    }
219
220    /// Synchronise a list of packages with this lock,
221    /// producing a report of packages to add and packages to remove,
222    /// based on the version constraint and the given [`SyncStrategy`].
223    ///
224    /// NOTE: The reason we produce a report and don't add/remove packages
225    /// here is because packages need to be installed in order to be added.
226    pub(crate) fn package_sync_spec(
227        &self,
228        packages: &[lua_dependency::Spec],
229        strategy: &SyncStrategy<'_>,
230    ) -> PackageSyncSpec {
231        let pkg_dir_exists = |pkg: &LockedPackage| match strategy {
232            SyncStrategy::LockfileOnly => true,
233            SyncStrategy::EnsureInstalled(tree) => tree.layout_for(pkg.spec()).root.is_dir(),
234        };
235
236        let entrypoints_to_keep: HashSet<LockedPackage> = self
237            .entrypoints
238            .values()
239            .filter_map(|id| self.get(id))
240            .filter(|local_pkg| {
241                packages.iter().any(|req| {
242                    local_pkg
243                        .constraint()
244                        .matches_version_req(req.version_req())
245                })
246            })
247            .cloned()
248            .collect();
249
250        let packages_to_keep: HashSet<&LockedPackage> = entrypoints_to_keep
251            .iter()
252            .flat_map(|local_pkg| self.get_all_dependencies(&local_pkg.id()))
253            .collect();
254
255        let to_add = packages
256            .iter()
257            .filter(|pkg| {
258                self.has_rock_with_equal_constraint(pkg)
259                    .map(|local_pkg| !pkg_dir_exists(&local_pkg))
260                    .unwrap_or(true)
261            })
262            .cloned()
263            .collect_vec();
264
265        let to_remove = self
266            .rocks()
267            .values()
268            .filter(|pkg| !packages_to_keep.contains(*pkg))
269            .cloned()
270            .collect_vec();
271
272        PackageSyncSpec { to_add, to_remove }
273    }
274
275    /// Return all dependencies of a package, including itself
276    pub(crate) fn get_all_dependencies(&self, id: &locked_package::ID) -> HashSet<&LockedPackage> {
277        let mut packages = HashSet::new();
278        if let Some(local_pkg) = self.get(id) {
279            packages.insert(local_pkg);
280            packages.extend(
281                local_pkg
282                    .dependencies()
283                    .iter()
284                    .flat_map(|id| self.get_all_dependencies(id)),
285            );
286        }
287        packages
288    }
289
290    /// The set of all packages reachable from the entrypoints via the
291    /// dependency graph.
292    pub(crate) fn reachable(&self) -> HashSet<&LockedPackage> {
293        self.entrypoints
294            .values()
295            .flat_map(|id| self.get_all_dependencies(id))
296            .collect()
297    }
298}
299
300/// A lockfile for an install tree
301#[derive(Clone, Debug, Serialize, Deserialize)]
302pub struct Lockfile<P: LockfilePermissions> {
303    #[serde(skip)]
304    filepath: PathBuf,
305    #[serde(skip)]
306    _marker: PhantomData<P>,
307    // TODO: Serialize this directly into a `Version`
308    version: String,
309    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
310    binaries: BTreeMap<locked_package::ID, RockBinaries>,
311    #[serde(flatten)]
312    lock: PackageLock,
313}
314
315#[derive(EnumIter, Debug, Clone, Copy, PartialEq, Eq, Hash)]
316pub enum LockedPackageLockType {
317    Regular,
318    Test,
319    Build,
320}
321
322#[derive(Error, Debug, Diagnostic)]
323#[non_exhaustive]
324pub enum Error {
325    #[error(transparent)]
326    #[diagnostic(transparent)]
327    Fs(#[from] fs::Error),
328    #[error("error parsing lockfile from JSON")]
329    ParseJson(#[source] serde_json::Error),
330    #[error("error writing lockfile to JSON")]
331    WriteJson(#[source] serde_json::Error),
332    #[error("invalid version string in lockfile: {version}")]
333    #[diagnostic(help("did you or a tool modify the lockfile manually?"))]
334    InvalidVersion {
335        version: String,
336        source: semver::Error,
337    },
338    #[error("lockfile '{}' has no `version` field", lockfile.display())]
339    #[diagnostic(
340        code(lux_lib::lockfile::missing_version),
341        help("the lockfile is corrupt or was hand-edited")
342    )]
343    MissingVersion { lockfile: PathBuf },
344    #[error(
345        "incompatible lockfile version in '{}': expected {expected}, found {found}",
346        lockfile.display()
347    )]
348    #[diagnostic(code(lux_lib::lockfile::incompatible_version), help("{help}"))]
349    IncompatibleVersion {
350        lockfile: PathBuf,
351        found: String,
352        expected: String,
353        help: String,
354    },
355    #[error("cannot migrate lockfile '{}'", lockfile.display())]
356    #[diagnostic(code(lux_lib::lockfile::conflicting_entrypoints), help("{help}"))]
357    ConflictingEntrypoints { lockfile: PathBuf, help: String },
358}
359
360#[derive(Error, Debug, Diagnostic)]
361#[non_exhaustive]
362pub enum IntegrityError {
363    #[error(
364        r#"rockspec integrity mismatch.
365- source: {src}
366- expected: {expected}
367- got: {got}
368"#
369    )]
370    #[diagnostic(help(
371        r#"the maintainer may have force-uploaded a different rockspec.
372check the rockspec source, then rerun the command with `--no-lock` to update the hash.
373"#
374    ))]
375    RockspecIntegrityMismatch {
376        src: String,
377        expected: Integrity,
378        got: Integrity,
379    },
380    #[error(
381        r#"source integrity mismatch.
382- source: {src}
383- expected: {expected}
384- got: {got}"#
385    )]
386    #[diagnostic(help(
387        r#"the maintainer may have force-uploaded a different source or moved a tag.
388check the source URL, then rerun the command with `lx --no-lock` to update the hash.
389"#
390    ))]
391    SourceIntegrityMismatch {
392        src: String,
393        expected: Integrity,
394        got: Integrity,
395    },
396    #[error(
397        "package {0} version {1} with pinned state {2} and constraint {3} not found in the lockfile."
398    )]
399    PackageNotFound(package::Name, Box<package::Version>, PinnedState, String),
400}
401
402#[derive(Error, Debug, Diagnostic)]
403#[non_exhaustive]
404#[error("error flushing the lockfile ({})", .filepath.display())]
405#[diagnostic(help("make sure the parent directory is writeable"))]
406pub struct FlushLockfileError {
407    filepath: PathBuf,
408    source: io::Error,
409}
410
411/// A specification for syncing a list of packages with a lockfile
412#[derive(Debug, Default)]
413pub(crate) struct PackageSyncSpec {
414    pub to_add: Vec<lua_dependency::Spec>,
415    pub to_remove: Vec<LockedPackage>,
416}
417
418/// Controls how `package_sync_spec` determines whether a package exists.
419pub(crate) enum SyncStrategy<'a> {
420    /// Only check the lockfile for constraint matches.
421    LockfileOnly,
422    /// In addition to checking lockfile constraints, verify that each
423    /// package's installation directory exists in the given tree.
424    EnsureInstalled(&'a Tree),
425}
426
427impl<P: LockfilePermissions> Lockfile<P> {
428    pub fn version(&self) -> &String {
429        &self.version
430    }
431
432    pub fn rocks(&self) -> &BTreeMap<locked_package::ID, LockedPackage> {
433        self.lock.rocks()
434    }
435
436    pub fn is_dependency(&self, package: &locked_package::ID) -> bool {
437        self.lock.is_dependency(package)
438    }
439
440    pub fn is_entrypoint(&self, package: &locked_package::ID) -> bool {
441        self.lock.is_entrypoint(package)
442    }
443
444    /// Returns the entrypoint with the given package name, if any.
445    pub fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
446        self.lock.entrypoint(name)
447    }
448
449    pub fn entrypoints(&self) -> Vec<(&package::Name, &LockedPackage)> {
450        self.lock
451            .entrypoints
452            .iter()
453            .filter_map(|(name, id)| self.lock.get(id).map(|package| (name, package)))
454            .collect()
455    }
456
457    /// Returns all rocks in the lockfile that are reachable from an entrypoint
458    /// via the dependency graph.
459    pub fn reachable_rocks(&self) -> Vec<LockedPackage> {
460        self.lock.reachable().into_iter().cloned().collect()
461    }
462
463    pub fn entry_type(&self, package: &locked_package::ID) -> EntryType {
464        if self.lock.is_entrypoint(package) {
465            EntryType::Entrypoint
466        } else {
467            EntryType::DependencyOnly
468        }
469    }
470
471    /// The binaries installed in the tree for a given package.
472    pub(crate) fn binaries(&self, id: &locked_package::ID) -> Option<&RockBinaries> {
473        self.binaries.get(id)
474    }
475
476    pub(crate) fn local_pkg_lock(&self) -> &PackageLock {
477        &self.lock
478    }
479
480    pub fn get(&self, id: &locked_package::ID) -> Option<&LockedPackage> {
481        self.lock.get(id)
482    }
483
484    /// Unsafe because this assumes a prior check if the package is present
485    ///
486    /// # Safety
487    ///
488    /// Ensure that the package is present in the lockfile before calling this function.
489    pub unsafe fn get_unchecked(&self, id: &locked_package::ID) -> &LockedPackage {
490        self.lock.get(id).unwrap_unchecked()
491    }
492
493    pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
494        self.lock.list()
495    }
496
497    pub(crate) fn has_rock(
498        &self,
499        req: &package::Req,
500        filter: Option<remote::package::kind::FilterSpec>,
501    ) -> Option<LockedPackage> {
502        self.lock.has_rock(req, filter)
503    }
504
505    /// Find all rocks that match the requirement
506    pub(crate) fn find_rocks(&self, req: &package::Req) -> Vec<locked_package::ID> {
507        match self.list().get(req.name()) {
508            Some(packages) => packages
509                .iter()
510                .rev()
511                .filter(|package| req.version_req().matches(package.version()))
512                .map(|package| package.id())
513                .collect_vec(),
514            None => Vec::default(),
515        }
516    }
517
518    /// Validate the integrity of an installed package with the entry in this lockfile.
519    pub(crate) fn validate_integrity(
520        &self,
521        expected_package: &LockedPackage,
522    ) -> Result<(), IntegrityError> {
523        // NOTE: We can't query by ID, because when installing from a lockfile (e.g. during sync),
524        // the constraint is always `==`.
525        match self.list().get(expected_package.name()) {
526            None => Err(integrity_err_not_found(expected_package)),
527            Some(rocks) => match rocks
528                .iter()
529                .find(|rock| rock.version() == expected_package.version())
530            {
531                None => Err(integrity_err_not_found(expected_package)),
532                Some(installed_package) => {
533                    if expected_package
534                        .hashes
535                        .rockspec
536                        .matches(&installed_package.hashes.rockspec)
537                        .is_none()
538                    {
539                        return Err(IntegrityError::RockspecIntegrityMismatch {
540                            src: expected_package.source.to_string(),
541                            expected: expected_package.hashes.rockspec.clone(),
542                            got: installed_package.hashes.rockspec.clone(),
543                        });
544                    }
545                    if expected_package
546                        .hashes
547                        .source
548                        .matches(&installed_package.hashes.source)
549                        .is_none()
550                    {
551                        return Err(IntegrityError::SourceIntegrityMismatch {
552                            src: expected_package
553                                .source_url
554                                .as_ref()
555                                .map(|url| url.to_string())
556                                .unwrap_or(expected_package.source.to_string()),
557                            expected: expected_package.hashes.source.clone(),
558                            got: installed_package.hashes.source.clone(),
559                        });
560                    }
561                    Ok(())
562                }
563            },
564        }
565    }
566
567    fn flush(&self) -> Result<(), FlushLockfileError> {
568        let content = serde_json::to_string_pretty(&self).map_err(|err| FlushLockfileError {
569            filepath: self.filepath.to_path_buf(),
570            source: io::Error::other(err),
571        })?;
572
573        fs::sync::write_atomic(&self.filepath, content).map_err(|err| FlushLockfileError {
574            filepath: self.filepath.to_path_buf(),
575            source: io::Error::other(err),
576        })
577    }
578}
579
580impl Lockfile<ReadOnly> {
581    /// Create a new `Lockfile`, writing an empty file if none exists.
582    #[tracing::instrument(level = "trace")]
583    pub(crate) fn new(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
584        // Ensure that the lockfile exists
585        match File::options().create_new(true).write(true).open(&filepath) {
586            Ok(mut file) => {
587                let empty_lockfile: Lockfile<ReadOnly> = Lockfile {
588                    filepath: filepath.clone(),
589                    _marker: PhantomData,
590                    version: LOCKFILE_VERSION_STR.into(),
591                    binaries: BTreeMap::new(),
592                    lock: PackageLock::default(),
593                };
594                let json_str = serde_json::to_string(&empty_lockfile).map_err(Error::WriteJson)?;
595                write!(file, "{json_str}").map_err(|source| fs::Error::Write {
596                    path: filepath.to_path_buf(),
597                    source,
598                })?;
599            }
600            Err(err) if err.kind() == ErrorKind::AlreadyExists => {}
601            Err(source) => {
602                return Err(Error::Fs(fs::Error::FileOpen {
603                    path: filepath.to_path_buf(),
604                    source,
605                }));
606            }
607        }
608
609        Self::load(filepath)
610    }
611
612    /// Load a `Lockfile`, failing if none exists.
613    #[tracing::instrument(level = "trace")]
614    pub fn load(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
615        let content = fs::sync::read_to_string(&filepath)?;
616        let tree_dir = filepath.parent().unwrap_or(filepath.as_path());
617        let help = format!(
618            "this install tree was created by an incompatible version of Lux.
619remove the tree at '{}' and reinstall all packages it contained.",
620            tree_dir.display()
621        );
622        let mut lockfile: Lockfile<ReadOnly> = load_lockfile(&content, &filepath, &help)?;
623        lockfile.filepath = filepath;
624        Ok(lockfile)
625    }
626
627    /// Creates a temporary, writeable lockfile which can never flush.
628    pub(crate) fn into_temporary(self) -> Lockfile<ReadWrite> {
629        Lockfile::<ReadWrite> {
630            _marker: PhantomData,
631            filepath: self.filepath,
632            version: self.version,
633            binaries: self.binaries,
634            lock: self.lock,
635        }
636    }
637
638    /// Creates a lockfile guard, flushing the lockfile automatically
639    /// once the guard goes out of scope.
640    pub fn write_guard(self) -> Guard {
641        Guard::new(self.into_temporary())
642    }
643
644    /// Converts the current lockfile into a writeable one, executes `cb` and flushes
645    /// the lockfile.
646    #[tracing::instrument(level = "trace", skip_all)]
647    pub fn map_then_flush<T, F, E>(self, cb: F) -> Result<T, FlushLockfileError>
648    where
649        F: FnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
650        E: std::error::Error,
651        E: From<io::Error>,
652        E: Into<Box<dyn std::error::Error + Send + Sync>>,
653    {
654        let mut writeable_lockfile = self.into_temporary();
655
656        let result = cb(&mut writeable_lockfile).map_err(|err| FlushLockfileError {
657            filepath: writeable_lockfile.filepath.to_path_buf(),
658            source: io::Error::other(err),
659        })?;
660
661        writeable_lockfile.flush()?;
662
663        Ok(result)
664    }
665
666    // TODO: Add this once async closures are stabilized
667    // Converts the current lockfile into a writeable one, executes `cb` asynchronously and flushes
668    // the lockfile.
669    //pub async fn map_then_flush_async<T, F, E, Fut>(self, cb: F) -> Result<T, E>
670    //where
671    //    F: AsyncFnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
672    //    E: Error,
673    //    E: From<io::Error>,
674    //{
675    //    let mut writeable_lockfile = self.into_temporary();
676    //
677    //    let result = cb(&mut writeable_lockfile).await?;
678    //
679    //    writeable_lockfile.flush()?;
680    //
681    //    Ok(result)
682    //}
683}
684
685impl Lockfile<ReadWrite> {
686    pub(crate) fn add_entrypoint(&mut self, rock: &LockedPackage) {
687        self.add(rock);
688        self.lock.entrypoints.insert(rock.name().clone(), rock.id());
689    }
690
691    pub(crate) fn add(&mut self, rock: &LockedPackage) {
692        // Since rocks entries are mutable, we only add the dependency if it
693        // has not already been added.
694        self.lock
695            .rocks
696            .entry(rock.id())
697            .or_insert_with(|| rock.clone());
698    }
699
700    /// Add a dependency for a package.
701    pub(crate) fn add_dependency(&mut self, target: &LockedPackage, dependency: &LockedPackage) {
702        self.lock
703            .rocks
704            .entry(target.id())
705            .and_modify(|rock| {
706                let id = dependency.id();
707                if !rock.spec.dependencies.contains(&id) {
708                    rock.spec.dependencies.push(id);
709                }
710            })
711            .or_insert_with(|| {
712                let id = dependency.id();
713                let mut target = target.clone();
714                if !target.spec.dependencies.contains(&id) {
715                    target.spec.dependencies.push(id);
716                }
717                target
718            });
719        self.add(dependency);
720    }
721
722    /// Add a build dependency for a package.
723    pub(crate) fn add_build_dependency(
724        &mut self,
725        target: &LockedPackage,
726        dependency: &LockedPackage,
727    ) {
728        self.lock
729            .rocks
730            .entry(target.id())
731            .and_modify(|rock| {
732                let id = dependency.id();
733                if !rock.spec.build_dependencies.contains(&id) {
734                    rock.spec.build_dependencies.push(id);
735                }
736            })
737            .or_insert_with(|| {
738                let id = dependency.id();
739                let mut target = target.clone();
740                if !target.spec.build_dependencies.contains(&id) {
741                    target.spec.build_dependencies.push(id);
742                }
743                target
744            });
745    }
746
747    /// Record the binaries installed for `package` into the tree lockfile.
748    pub(crate) fn set_binaries(&mut self, package: &LockedPackage, binaries: RockBinaries) {
749        self.binaries.insert(package.id(), binaries);
750    }
751
752    pub(crate) fn remove(&mut self, target: &LockedPackage) {
753        self.binaries.remove(&target.id());
754        self.lock.remove(target)
755    }
756
757    pub(crate) fn remove_by_id(&mut self, target: &locked_package::ID) {
758        self.binaries.remove(target);
759        self.lock.remove_by_id(target)
760    }
761
762    pub(crate) fn sync(&mut self, lock: &PackageLock) {
763        self.lock = lock.clone();
764    }
765
766    // TODO: `fn entrypoints() -> Vec<LockedRock>`
767}
768
769pub(super) fn load_lockfile<T>(content: &str, lockfile: &Path, help: &str) -> Result<T, Error>
770where
771    T: serde::de::DeserializeOwned,
772{
773    let mut value = parse_lockfile_json(content)?;
774    if lockfile_version(&value, lockfile)?.major == 1 {
775        migrate_v1_lockfile(&mut value, lockfile)?;
776    }
777    deserialize_lockfile(value, lockfile, help)
778}
779
780fn parse_lockfile_json(content: &str) -> Result<serde_json::Map<String, serde_json::Value>, Error> {
781    serde_json::from_str(content).map_err(Error::ParseJson)
782}
783
784fn lockfile_version(
785    value: &serde_json::Map<String, serde_json::Value>,
786    lockfile: &Path,
787) -> Result<semver::Version, Error> {
788    let version = value
789        .get("version")
790        .and_then(|version| version.as_str())
791        .ok_or(Error::MissingVersion {
792            lockfile: lockfile.to_path_buf(),
793        })?;
794    semver::Version::parse(version).map_err(|source| Error::InvalidVersion {
795        version: version.to_string(),
796        source,
797    })
798}
799
800fn deserialize_lockfile<T>(
801    value: serde_json::Map<String, serde_json::Value>,
802    lockfile: &Path,
803    help: &str,
804) -> Result<T, Error>
805where
806    T: serde::de::DeserializeOwned,
807{
808    let found = lockfile_version(&value, lockfile)?;
809    if found.major != LOCKFILE_VERSION {
810        return Err(Error::IncompatibleVersion {
811            lockfile: lockfile.to_path_buf(),
812            found: found.to_string(),
813            expected: LOCKFILE_VERSION_STR.into(),
814            help: help.into(),
815        });
816    }
817    serde_json::from_value(serde_json::Value::Object(value)).map_err(Error::ParseJson)
818}
819
820fn migrate_v1_lockfile(
821    value: &mut serde_json::Map<String, serde_json::Value>,
822    lockfile: &Path,
823) -> Result<(), Error> {
824    let tree_dir = lockfile.parent().unwrap_or(lockfile);
825    let found = lockfile_version(value, lockfile)?;
826    if value.contains_key("entrypoint_layout") {
827        return Err(Error::IncompatibleVersion {
828            lockfile: lockfile.to_path_buf(),
829            found: found.to_string(),
830            expected: LOCKFILE_VERSION_STR.into(),
831            help: format!(
832                "this install tree uses a custom entrypoint layout that cannot be migrated automatically.
833remove the tree at '{}' and reinstall all packages it contained.",
834                tree_dir.display()
835            ),
836        });
837    }
838
839    let conflict_help = format!(
840        "this lockfile contains entrypoints that cannot be represented in the current format.
841remove the tree at '{}' and reinstall all packages it contained.",
842        tree_dir.display()
843    );
844
845    if value.contains_key("entrypoints") {
846        migrate_entrypoints(value, lockfile, &conflict_help)?;
847    }
848    for section in ["dependencies", "test_dependencies", "build_dependencies"] {
849        if let Some(section) = value
850            .get_mut(section)
851            .and_then(|section| section.as_object_mut())
852        {
853            migrate_entrypoints(section, lockfile, &conflict_help)?;
854        }
855    }
856    value.insert(
857        "version".into(),
858        serde_json::Value::String(LOCKFILE_VERSION_STR.into()),
859    );
860    Ok(())
861}
862
863fn migrate_entrypoints(
864    section: &mut serde_json::Map<String, serde_json::Value>,
865    lockfile: &Path,
866    help: &str,
867) -> Result<(), Error> {
868    let conflicting_entrypoints = || Error::ConflictingEntrypoints {
869        lockfile: lockfile.to_path_buf(),
870        help: help.to_string(),
871    };
872
873    let rocks = section.get("rocks").and_then(|rocks| rocks.as_object());
874    let mut entrypoints = serde_json::Map::new();
875    if let Some(old_entrypoints) = section.get("entrypoints") {
876        for id in old_entrypoints
877            .as_array()
878            .ok_or_else(conflicting_entrypoints)?
879        {
880            let id = id.as_str().ok_or_else(conflicting_entrypoints)?;
881            let name = rocks
882                .and_then(|rocks| rocks.get(id))
883                .and_then(|package| package.get("name"))
884                .and_then(|name| name.as_str())
885                .ok_or_else(conflicting_entrypoints)?;
886            if entrypoints.contains_key(name) {
887                return Err(conflicting_entrypoints());
888            }
889            entrypoints.insert(name.to_string(), serde_json::Value::String(id.to_string()));
890        }
891    }
892    section.insert("entrypoints".into(), serde_json::Value::Object(entrypoints));
893    Ok(())
894}
895
896fn deserialize_url<'de, D>(deserializer: D) -> Result<Url, D::Error>
897where
898    D: serde::Deserializer<'de>,
899{
900    let s = String::deserialize(deserializer)?;
901    Url::parse(&s).map_err(serde::de::Error::custom)
902}
903
904fn serialize_url<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>
905where
906    S: Serializer,
907{
908    url.as_str().serialize(serializer)
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914    use crate::{config, lua};
915    use assert_fs::fixture::PathCopy;
916    use insta::{assert_json_snapshot, sorted_redaction};
917    use std::{fs::remove_file, path::PathBuf};
918
919    #[test]
920    fn parse_lockfile() {
921        let temp = assert_fs::TempDir::new().unwrap();
922        temp.copy_from(
923            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
924            &["**"],
925        )
926        .unwrap();
927
928        let config = config::Builder::new()
929            .unwrap()
930            .user_tree(Some(temp.to_path_buf()))
931            .build()
932            .unwrap();
933        let tree = config.user_tree(lua::Version::Lua51).unwrap();
934        let lockfile = tree.lockfile().unwrap();
935
936        assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
937    }
938
939    #[test]
940    fn add_rocks() {
941        let temp = assert_fs::TempDir::new().unwrap();
942        temp.copy_from(
943            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
944            &["**"],
945        )
946        .unwrap();
947
948        let mock_hashes = locked_package::Hashes {
949            rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
950                .parse()
951                .unwrap(),
952            source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
953                .parse()
954                .unwrap(),
955        };
956
957        let config = config::Builder::new()
958            .unwrap()
959            .user_tree(Some(temp.to_path_buf()))
960            .build()
961            .unwrap();
962        let tree = config.user_tree(lua::Version::Lua51).unwrap();
963        let mut lockfile = tree.lockfile().unwrap().write_guard();
964
965        let test_package = package::Spec::parse("test1".to_string(), "0.1.0".to_string()).unwrap();
966        let test_local_package = LockedPackage::from(
967            &test_package,
968            crate::lockfile::Constraint::Unconstrained,
969            remote::package::Source::Test,
970            None,
971            mock_hashes.clone(),
972        );
973        lockfile.add_entrypoint(&test_local_package);
974
975        let test_dep_package =
976            package::Spec::parse("test2".to_string(), "0.1.0".to_string()).unwrap();
977        let mut test_local_dep_package = LockedPackage::from(
978            &test_dep_package,
979            crate::lockfile::Constraint::Constrained(">= 1.0.0".parse().unwrap()),
980            remote::package::Source::Test,
981            None,
982            mock_hashes.clone(),
983        );
984        test_local_dep_package.spec.pinned = PinnedState::Pinned;
985        lockfile.add_dependency(&test_local_package, &test_local_dep_package);
986
987        assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
988    }
989
990    #[test]
991    fn parse_nonexistent_lockfile() {
992        let tree_path =
993            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
994
995        let temp = assert_fs::TempDir::new().unwrap();
996        temp.copy_from(&tree_path, &["**"]).unwrap();
997
998        remove_file(temp.join("5.1/lux.lock")).unwrap();
999
1000        let config = config::Builder::new()
1001            .unwrap()
1002            .user_tree(Some(temp.to_path_buf()))
1003            .build()
1004            .unwrap();
1005        let tree = config.user_tree(lua::Version::Lua51).unwrap();
1006
1007        let _ = tree.lockfile().unwrap().write_guard(); // Try to create the lockfile but don't actually do anything with it.
1008    }
1009
1010    fn get_test_lockfile() -> Lockfile<ReadOnly> {
1011        let sample_tree = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1012            .join("resources/test/sample-tree/5.1/lux.lock");
1013        Lockfile::new(sample_tree).unwrap()
1014    }
1015
1016    #[test]
1017    fn test_sync_spec() {
1018        let lockfile = get_test_lockfile();
1019        let packages = vec![
1020            package::Req::parse("neorg@8.8.1-1").unwrap().into(),
1021            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1022            package::Req::parse("nonexistent").unwrap().into(),
1023        ];
1024
1025        let sync_spec = lockfile
1026            .lock
1027            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1028
1029        assert_eq!(sync_spec.to_add.len(), 1);
1030
1031        // Should keep dependencies of neorg 8.8.1-1
1032        assert!(!sync_spec
1033            .to_remove
1034            .iter()
1035            .any(|pkg| pkg.name().to_string() == "nvim-nio"
1036                && pkg.constraint()
1037                    == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
1038        assert!(!sync_spec
1039            .to_remove
1040            .iter()
1041            .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
1042                && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
1043        assert!(!sync_spec
1044            .to_remove
1045            .iter()
1046            .any(|pkg| pkg.name().to_string() == "plenary.nvim"
1047                && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
1048        assert!(!sync_spec
1049            .to_remove
1050            .iter()
1051            .any(|pkg| pkg.name().to_string() == "nui.nvim"
1052                && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
1053        assert!(!sync_spec
1054            .to_remove
1055            .iter()
1056            .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
1057                && pkg.constraint()
1058                    == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
1059    }
1060
1061    #[test]
1062    fn test_sync_spec_remove() {
1063        let lockfile = get_test_lockfile();
1064        let packages = vec![
1065            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1066            package::Req::parse("nonexistent").unwrap().into(),
1067        ];
1068
1069        let sync_spec = lockfile
1070            .lock
1071            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1072
1073        assert_eq!(sync_spec.to_add.len(), 1);
1074
1075        // Should remove:
1076        // - neorg
1077        // - dependencies unique to neorg
1078        assert!(sync_spec
1079            .to_remove
1080            .iter()
1081            .any(|pkg| pkg.name().to_string() == "neorg"
1082                && pkg.version() == &"8.8.1-1".parse().unwrap()));
1083        assert!(sync_spec
1084            .to_remove
1085            .iter()
1086            .any(|pkg| pkg.name().to_string() == "nvim-nio"
1087                && pkg.constraint()
1088                    == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
1089        assert!(sync_spec
1090            .to_remove
1091            .iter()
1092            .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
1093                && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
1094        assert!(sync_spec
1095            .to_remove
1096            .iter()
1097            .any(|pkg| pkg.name().to_string() == "plenary.nvim"
1098                && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
1099        assert!(sync_spec
1100            .to_remove
1101            .iter()
1102            .any(|pkg| pkg.name().to_string() == "nui.nvim"
1103                && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
1104        assert!(sync_spec
1105            .to_remove
1106            .iter()
1107            .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
1108                && pkg.constraint()
1109                    == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
1110    }
1111
1112    #[test]
1113    fn test_sync_spec_empty() {
1114        let lockfile = get_test_lockfile();
1115        let packages = vec![];
1116        let sync_spec = lockfile
1117            .lock
1118            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1119
1120        // Should remove all packages
1121        assert!(sync_spec.to_add.is_empty());
1122        assert_eq!(sync_spec.to_remove.len(), lockfile.rocks().len());
1123    }
1124
1125    #[test]
1126    fn test_sync_spec_different_constraints() {
1127        let lockfile = get_test_lockfile();
1128        let packages = vec![package::Req::parse("nvim-nio>=2.0.0").unwrap().into()];
1129        let sync_spec = lockfile
1130            .lock
1131            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);
1132
1133        let expected: package::VersionReq = ">=2.0.0".parse().unwrap();
1134        assert!(sync_spec
1135            .to_add
1136            .iter()
1137            .any(|req| req.name().to_string() == "nvim-nio" && req.version_req() == &expected));
1138
1139        assert!(sync_spec
1140            .to_remove
1141            .iter()
1142            .any(|pkg| pkg.name().to_string() == "nvim-nio"));
1143    }
1144
1145    #[test]
1146    fn test_sync_spec_ensure_installed() {
1147        let temp = assert_fs::TempDir::new().unwrap();
1148        temp.copy_from(
1149            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
1150            &["**"],
1151        )
1152        .unwrap();
1153
1154        let config = config::Builder::new()
1155            .unwrap()
1156            .user_tree(Some(temp.to_path_buf()))
1157            .build()
1158            .unwrap();
1159        let tree = config.user_tree(lua::Version::Lua51).unwrap();
1160        let lockfile = tree.lockfile().unwrap();
1161
1162        let packages: Vec<lua_dependency::Spec> = vec![
1163            package::Req::parse("neorg@8.8.1-1").unwrap().into(),
1164            // This package isn't installed in the tree
1165            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
1166            // And neither is this
1167            package::Req::parse("nonexistent").unwrap().into(),
1168        ];
1169
1170        // Since lua-cjson is not present in the tree, it should get put into `to_add`
1171        let sync_spec = lockfile
1172            .lock
1173            .package_sync_spec(&packages, &SyncStrategy::EnsureInstalled(&tree));
1174
1175        assert!(!sync_spec
1176            .to_add
1177            .iter()
1178            .any(|req| req.name().to_string() == "neorg"));
1179
1180        assert!(sync_spec
1181            .to_add
1182            .iter()
1183            .any(|req| req.name().to_string() == "lua-cjson"));
1184
1185        assert!(sync_spec
1186            .to_add
1187            .iter()
1188            .any(|req| req.name().to_string() == "nonexistent"));
1189    }
1190
1191    #[test]
1192    fn verify_lockfile_version() {
1193        let deserialize = |version: &str| {
1194            let content = format!(r#"{{"version": "{version}"}}"#);
1195            parse_lockfile_json(&content).and_then(|value| {
1196                deserialize_lockfile::<Lockfile<ReadOnly>>(value, Path::new("lux.lock"), "")
1197            })
1198        };
1199
1200        assert!(matches!(
1201            deserialize("3.0.0"),
1202            Err(Error::IncompatibleVersion { .. })
1203        ));
1204        assert!(matches!(
1205            deserialize("not-a-version"),
1206            Err(Error::InvalidVersion { .. })
1207        ));
1208    }
1209
1210    #[test]
1211    fn migrate_v1_tree_lockfile() {
1212        let sample =
1213            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/lockfile-v1/tree.lock");
1214
1215        let temp = assert_fs::TempDir::new().unwrap();
1216        let lockfile_path = temp.path().join("lux.lock");
1217        std::fs::copy(&sample, &lockfile_path).unwrap();
1218
1219        let lockfile = Lockfile::load(lockfile_path.clone()).unwrap();
1220
1221        let on_disk: serde_json::Value =
1222            serde_json::from_str(&std::fs::read_to_string(&lockfile_path).unwrap()).unwrap();
1223        assert_eq!(on_disk["version"], "1.0.0");
1224        assert!(on_disk["entrypoints"].is_array());
1225
1226        assert_eq!(lockfile.version, "2.0.0");
1227        assert_eq!(lockfile.lock.entrypoints.len(), 3);
1228    }
1229
1230    #[test]
1231    fn refuse_migration_for_custom_layout() {
1232        let lockfile = r#"{"version":"1.0.0","entrypoint_layout":{"root":"site/pack/lux"}}"#;
1233        assert!(matches!(
1234            load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
1235            Err(Error::IncompatibleVersion { .. })
1236        ));
1237    }
1238
1239    #[test]
1240    fn refuse_migration_for_conflicting_entrypoints() {
1241        let lockfile = r#"{
1242            "version": "1.0.0",
1243            "rocks": {
1244                "a": { "name": "foo" },
1245                "b": { "name": "foo" }
1246            },
1247            "entrypoints": ["a", "b"]
1248        }"#;
1249        assert!(matches!(
1250            load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
1251            Err(Error::ConflictingEntrypoints { .. })
1252        ));
1253    }
1254}