lux-lib 0.75.0

Library for the lux package manager for Lua
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
use crate::package;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Display;
use std::io::{self, Write};
use std::marker::PhantomData;
use std::{
    collections::HashMap,
    fs::File,
    io::ErrorKind,
    path::{Path, PathBuf},
};

use itertools::Itertools;

use miette::Diagnostic;
use serde::{Deserialize, Serialize, Serializer};
use ssri::Integrity;
use strum_macros::EnumIter;
use thiserror::Error;
use url::Url;

use crate::fs;
use crate::remote;
use crate::rockspec::lua_dependency;
use crate::rockspec::RockBinaries;
use crate::tree::{EntryType, InstallTree, Tree};

pub mod constraint;
mod guard;
pub mod locked_package;
mod opt_state;
mod pinned_state;

use locked_package::integrity_err_not_found;

pub use constraint::Constraint;
pub use guard::Guard;
pub use locked_package::LockedPackage;
pub use opt_state::OptState;
pub use pinned_state::PinnedState;

/// Bump this whenever an incompatible change is made to the lockfile format.
/// Lockfiles with a different major version are rejected on load.
const LOCKFILE_VERSION: u64 = 2;
pub(crate) const LOCKFILE_VERSION_STR: &str = "2.0.0";

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", tag = "type")]
pub(crate) enum RemotePackageSourceUrl {
    Git {
        url: String,
        #[serde(rename = "ref")]
        checkout_ref: String,
        /// Whether the source repository contains git submodules that must be
        /// fetched for the package to build.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        submodules: bool,
    }, // GitUrl doesn't have all the trait instances we need
    Url {
        #[serde(deserialize_with = "deserialize_url", serialize_with = "serialize_url")]
        url: Url,
    },
    File {
        path: PathBuf,
    },
}

impl Display for RemotePackageSourceUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RemotePackageSourceUrl::Git {
                url, checkout_ref, ..
            } => format!("{url}@{checkout_ref}").fmt(f),
            RemotePackageSourceUrl::Url { url } => url.fmt(f),
            RemotePackageSourceUrl::File { path } => format!("{}", path.display()).fmt(f),
        }
    }
}

pub trait LockfilePermissions {}
#[derive(Clone)]
pub struct ReadOnly;
#[derive(Clone)]
pub struct ReadWrite;

impl LockfilePermissions for ReadOnly {}
impl LockfilePermissions for ReadWrite {}

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub(crate) struct PackageLock {
    // NOTE: We cannot directly serialize to a `Sha256` object as they don't implement serde traits.
    // NOTE: We want to retain ordering of rocks when de/serializing.
    rocks: BTreeMap<locked_package::ID, LockedPackage>,

    /// The entrypoints of the tree. Enforces one entrypoint per package name.
    pub(crate) entrypoints: BTreeMap<package::Name, locked_package::ID>,
}

impl PackageLock {
    pub(crate) fn from_packages(
        packages: impl Iterator<Item = (LockedPackage, EntryType)>,
    ) -> Self {
        let mut lock = Self::default();

        for (package, entry_type) in packages {
            if matches!(entry_type, EntryType::Entrypoint) {
                lock.entrypoints
                    .insert(package.name().clone(), package.id());
            }
            lock.rocks.insert(package.id(), package);
        }

        lock
    }

    pub(crate) fn merge(&mut self, other: &PackageLock) {
        self.entrypoints.extend(
            other
                .entrypoints
                .iter()
                .map(|(name, id)| (name.clone(), id.clone())),
        );
        self.rocks.extend(
            other
                .rocks
                .iter()
                .map(|(id, package)| (id.clone(), package.clone())),
        );
    }

    pub(crate) fn get(&self, id: &locked_package::ID) -> Option<&LockedPackage> {
        self.rocks.get(id)
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.rocks.is_empty()
    }

    pub(crate) fn rocks(&self) -> &BTreeMap<locked_package::ID, LockedPackage> {
        &self.rocks
    }

    pub(crate) fn is_entrypoint(&self, package: &locked_package::ID) -> bool {
        self.entrypoints.values().any(|id| id == package)
    }

    /// Returns the entrypoint with the given package name, if any.
    pub(crate) fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
        self.entrypoints.get(name).and_then(|id| self.get(id))
    }

    pub(crate) fn is_dependency(&self, package: &locked_package::ID) -> bool {
        self.rocks
            .values()
            .flat_map(|rock| rock.dependencies())
            .any(|dep_id| dep_id == package)
    }

    pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
        self.rocks()
            .values()
            .cloned()
            .map(|locked_rock| (locked_rock.name().clone(), locked_rock))
            .into_group_map()
    }

    pub(crate) fn remove(&mut self, target: &LockedPackage) {
        self.remove_by_id(&target.id())
    }

    pub(crate) fn remove_by_id(&mut self, target: &locked_package::ID) {
        self.rocks.remove(target);
        self.entrypoints.retain(|_, id| id != target);
    }

    pub(crate) fn has_rock(
        &self,
        req: &package::Req,
        filter: Option<remote::package::kind::FilterSpec>,
    ) -> Option<LockedPackage> {
        self.list()
            .get(req.name())
            .map(|packages| {
                packages
                    .iter()
                    .filter(|package| match &filter {
                        Some(filter_spec) => match &package.source {
                            remote::package::Source::LuarocksRockspec(_) => filter_spec.rockspec,
                            remote::package::Source::LuarocksSrcRock(_) => filter_spec.src,
                            remote::package::Source::LuarocksBinaryRock(_) => filter_spec.binary,
                            remote::package::Source::Wally(_) => true,
                            remote::package::Source::RockspecContent(_) => true,
                            remote::package::Source::Local => true,
                            #[cfg(test)]
                            remote::package::Source::Test => unimplemented!(),
                        },
                        None => true,
                    })
                    .rev()
                    .find(|package| req.version_req().matches(package.version()))
            })?
            .cloned()
    }

    pub(crate) fn has_rock_with_equal_constraint(
        &self,
        req: &lua_dependency::Spec,
    ) -> Option<LockedPackage> {
        self.list()
            .get(req.name())
            .map(|packages| {
                packages
                    .iter()
                    .rev()
                    .find(|package| package.constraint().matches_version_req(req.version_req()))
            })?
            .cloned()
    }

    /// Synchronise a list of packages with this lock,
    /// producing a report of packages to add and packages to remove,
    /// based on the version constraint and the given [`SyncStrategy`].
    ///
    /// NOTE: The reason we produce a report and don't add/remove packages
    /// here is because packages need to be installed in order to be added.
    pub(crate) fn package_sync_spec(
        &self,
        packages: &[lua_dependency::Spec],
        strategy: &SyncStrategy<'_>,
    ) -> PackageSyncSpec {
        let pkg_dir_exists = |pkg: &LockedPackage| match strategy {
            SyncStrategy::LockfileOnly => true,
            SyncStrategy::EnsureInstalled(tree) => tree.layout_for(pkg.spec()).root.is_dir(),
        };

        let entrypoints_to_keep: HashSet<LockedPackage> = self
            .entrypoints
            .values()
            .filter_map(|id| self.get(id))
            .filter(|local_pkg| {
                packages.iter().any(|req| {
                    local_pkg
                        .constraint()
                        .matches_version_req(req.version_req())
                })
            })
            .cloned()
            .collect();

        let packages_to_keep: HashSet<&LockedPackage> = entrypoints_to_keep
            .iter()
            .flat_map(|local_pkg| self.get_all_dependencies(&local_pkg.id()))
            .collect();

        let to_add = packages
            .iter()
            .filter(|pkg| {
                self.has_rock_with_equal_constraint(pkg)
                    .map(|local_pkg| !pkg_dir_exists(&local_pkg))
                    .unwrap_or(true)
            })
            .cloned()
            .collect_vec();

        let to_remove = self
            .rocks()
            .values()
            .filter(|pkg| !packages_to_keep.contains(*pkg))
            .cloned()
            .collect_vec();

        PackageSyncSpec { to_add, to_remove }
    }

    /// Return all dependencies of a package, including itself
    pub(crate) fn get_all_dependencies(&self, id: &locked_package::ID) -> HashSet<&LockedPackage> {
        let mut packages = HashSet::new();
        if let Some(local_pkg) = self.get(id) {
            packages.insert(local_pkg);
            packages.extend(
                local_pkg
                    .dependencies()
                    .iter()
                    .flat_map(|id| self.get_all_dependencies(id)),
            );
        }
        packages
    }

    /// The set of all packages reachable from the entrypoints via the
    /// dependency graph.
    pub(crate) fn reachable(&self) -> HashSet<&LockedPackage> {
        self.entrypoints
            .values()
            .flat_map(|id| self.get_all_dependencies(id))
            .collect()
    }
}

/// A lockfile for an install tree
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Lockfile<P: LockfilePermissions> {
    #[serde(skip)]
    filepath: PathBuf,
    #[serde(skip)]
    _marker: PhantomData<P>,
    // TODO: Serialize this directly into a `Version`
    version: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    binaries: BTreeMap<locked_package::ID, RockBinaries>,
    #[serde(flatten)]
    lock: PackageLock,
}

#[derive(EnumIter, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LockedPackageLockType {
    Regular,
    Test,
    Build,
}

#[derive(Error, Debug, Diagnostic)]
#[non_exhaustive]
pub enum Error {
    #[error(transparent)]
    #[diagnostic(transparent)]
    Fs(#[from] fs::Error),
    #[error("error parsing lockfile from JSON")]
    ParseJson(#[source] serde_json::Error),
    #[error("error writing lockfile to JSON")]
    WriteJson(#[source] serde_json::Error),
    #[error("invalid version string in lockfile: {version}")]
    #[diagnostic(help("did you or a tool modify the lockfile manually?"))]
    InvalidVersion {
        version: String,
        source: semver::Error,
    },
    #[error("lockfile '{}' has no `version` field", lockfile.display())]
    #[diagnostic(
        code(lux_lib::lockfile::missing_version),
        help("the lockfile is corrupt or was hand-edited")
    )]
    MissingVersion { lockfile: PathBuf },
    #[error(
        "incompatible lockfile version in '{}': expected {expected}, found {found}",
        lockfile.display()
    )]
    #[diagnostic(code(lux_lib::lockfile::incompatible_version), help("{help}"))]
    IncompatibleVersion {
        lockfile: PathBuf,
        found: String,
        expected: String,
        help: String,
    },
    #[error("cannot migrate lockfile '{}'", lockfile.display())]
    #[diagnostic(code(lux_lib::lockfile::conflicting_entrypoints), help("{help}"))]
    ConflictingEntrypoints { lockfile: PathBuf, help: String },
}

#[derive(Error, Debug, Diagnostic)]
#[non_exhaustive]
pub enum IntegrityError {
    #[error(
        r#"rockspec integrity mismatch.
- source: {src}
- expected: {expected}
- got: {got}
"#
    )]
    #[diagnostic(help(
        r#"the maintainer may have force-uploaded a different rockspec.
check the rockspec source, then rerun the command with `--no-lock` to update the hash.
"#
    ))]
    RockspecIntegrityMismatch {
        src: String,
        expected: Integrity,
        got: Integrity,
    },
    #[error(
        r#"source integrity mismatch.
- source: {src}
- expected: {expected}
- got: {got}"#
    )]
    #[diagnostic(help(
        r#"the maintainer may have force-uploaded a different source or moved a tag.
check the source URL, then rerun the command with `lx --no-lock` to update the hash.
"#
    ))]
    SourceIntegrityMismatch {
        src: String,
        expected: Integrity,
        got: Integrity,
    },
    #[error(
        "package {0} version {1} with pinned state {2} and constraint {3} not found in the lockfile."
    )]
    PackageNotFound(package::Name, Box<package::Version>, PinnedState, String),
}

#[derive(Error, Debug, Diagnostic)]
#[non_exhaustive]
#[error("error flushing the lockfile ({})", .filepath.display())]
#[diagnostic(help("make sure the parent directory is writeable"))]
pub struct FlushLockfileError {
    filepath: PathBuf,
    source: io::Error,
}

/// A specification for syncing a list of packages with a lockfile
#[derive(Debug, Default)]
pub(crate) struct PackageSyncSpec {
    pub to_add: Vec<lua_dependency::Spec>,
    pub to_remove: Vec<LockedPackage>,
}

/// Controls how `package_sync_spec` determines whether a package exists.
pub(crate) enum SyncStrategy<'a> {
    /// Only check the lockfile for constraint matches.
    LockfileOnly,
    /// In addition to checking lockfile constraints, verify that each
    /// package's installation directory exists in the given tree.
    EnsureInstalled(&'a Tree),
}

impl<P: LockfilePermissions> Lockfile<P> {
    pub fn version(&self) -> &String {
        &self.version
    }

    pub fn rocks(&self) -> &BTreeMap<locked_package::ID, LockedPackage> {
        self.lock.rocks()
    }

    pub fn is_dependency(&self, package: &locked_package::ID) -> bool {
        self.lock.is_dependency(package)
    }

    pub fn is_entrypoint(&self, package: &locked_package::ID) -> bool {
        self.lock.is_entrypoint(package)
    }

    /// Returns the entrypoint with the given package name, if any.
    pub fn entrypoint(&self, name: &package::Name) -> Option<&LockedPackage> {
        self.lock.entrypoint(name)
    }

    pub fn entrypoints(&self) -> Vec<(&package::Name, &LockedPackage)> {
        self.lock
            .entrypoints
            .iter()
            .filter_map(|(name, id)| self.lock.get(id).map(|package| (name, package)))
            .collect()
    }

    /// Returns all rocks in the lockfile that are reachable from an entrypoint
    /// via the dependency graph.
    pub fn reachable_rocks(&self) -> Vec<LockedPackage> {
        self.lock.reachable().into_iter().cloned().collect()
    }

    pub fn entry_type(&self, package: &locked_package::ID) -> EntryType {
        if self.lock.is_entrypoint(package) {
            EntryType::Entrypoint
        } else {
            EntryType::DependencyOnly
        }
    }

    /// The binaries installed in the tree for a given package.
    pub(crate) fn binaries(&self, id: &locked_package::ID) -> Option<&RockBinaries> {
        self.binaries.get(id)
    }

    pub(crate) fn local_pkg_lock(&self) -> &PackageLock {
        &self.lock
    }

    pub fn get(&self, id: &locked_package::ID) -> Option<&LockedPackage> {
        self.lock.get(id)
    }

    /// Unsafe because this assumes a prior check if the package is present
    ///
    /// # Safety
    ///
    /// Ensure that the package is present in the lockfile before calling this function.
    pub unsafe fn get_unchecked(&self, id: &locked_package::ID) -> &LockedPackage {
        self.lock.get(id).unwrap_unchecked()
    }

    pub(crate) fn list(&self) -> HashMap<package::Name, Vec<LockedPackage>> {
        self.lock.list()
    }

    pub(crate) fn has_rock(
        &self,
        req: &package::Req,
        filter: Option<remote::package::kind::FilterSpec>,
    ) -> Option<LockedPackage> {
        self.lock.has_rock(req, filter)
    }

    /// Find all rocks that match the requirement
    pub(crate) fn find_rocks(&self, req: &package::Req) -> Vec<locked_package::ID> {
        match self.list().get(req.name()) {
            Some(packages) => packages
                .iter()
                .rev()
                .filter(|package| req.version_req().matches(package.version()))
                .map(|package| package.id())
                .collect_vec(),
            None => Vec::default(),
        }
    }

    /// Validate the integrity of an installed package with the entry in this lockfile.
    pub(crate) fn validate_integrity(
        &self,
        expected_package: &LockedPackage,
    ) -> Result<(), IntegrityError> {
        // NOTE: We can't query by ID, because when installing from a lockfile (e.g. during sync),
        // the constraint is always `==`.
        match self.list().get(expected_package.name()) {
            None => Err(integrity_err_not_found(expected_package)),
            Some(rocks) => match rocks
                .iter()
                .find(|rock| rock.version() == expected_package.version())
            {
                None => Err(integrity_err_not_found(expected_package)),
                Some(installed_package) => {
                    if expected_package
                        .hashes
                        .rockspec
                        .matches(&installed_package.hashes.rockspec)
                        .is_none()
                    {
                        return Err(IntegrityError::RockspecIntegrityMismatch {
                            src: expected_package.source.to_string(),
                            expected: expected_package.hashes.rockspec.clone(),
                            got: installed_package.hashes.rockspec.clone(),
                        });
                    }
                    if expected_package
                        .hashes
                        .source
                        .matches(&installed_package.hashes.source)
                        .is_none()
                    {
                        return Err(IntegrityError::SourceIntegrityMismatch {
                            src: expected_package
                                .source_url
                                .as_ref()
                                .map(|url| url.to_string())
                                .unwrap_or(expected_package.source.to_string()),
                            expected: expected_package.hashes.source.clone(),
                            got: installed_package.hashes.source.clone(),
                        });
                    }
                    Ok(())
                }
            },
        }
    }

    fn flush(&self) -> Result<(), FlushLockfileError> {
        let content = serde_json::to_string_pretty(&self).map_err(|err| FlushLockfileError {
            filepath: self.filepath.to_path_buf(),
            source: io::Error::other(err),
        })?;

        fs::sync::write_atomic(&self.filepath, content).map_err(|err| FlushLockfileError {
            filepath: self.filepath.to_path_buf(),
            source: io::Error::other(err),
        })
    }
}

impl Lockfile<ReadOnly> {
    /// Create a new `Lockfile`, writing an empty file if none exists.
    #[tracing::instrument(level = "trace")]
    pub(crate) fn new(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
        // Ensure that the lockfile exists
        match File::options().create_new(true).write(true).open(&filepath) {
            Ok(mut file) => {
                let empty_lockfile: Lockfile<ReadOnly> = Lockfile {
                    filepath: filepath.clone(),
                    _marker: PhantomData,
                    version: LOCKFILE_VERSION_STR.into(),
                    binaries: BTreeMap::new(),
                    lock: PackageLock::default(),
                };
                let json_str = serde_json::to_string(&empty_lockfile).map_err(Error::WriteJson)?;
                write!(file, "{json_str}").map_err(|source| fs::Error::Write {
                    path: filepath.to_path_buf(),
                    source,
                })?;
            }
            Err(err) if err.kind() == ErrorKind::AlreadyExists => {}
            Err(source) => {
                return Err(Error::Fs(fs::Error::FileOpen {
                    path: filepath.to_path_buf(),
                    source,
                }));
            }
        }

        Self::load(filepath)
    }

    /// Load a `Lockfile`, failing if none exists.
    #[tracing::instrument(level = "trace")]
    pub fn load(filepath: PathBuf) -> Result<Lockfile<ReadOnly>, Error> {
        let content = fs::sync::read_to_string(&filepath)?;
        let tree_dir = filepath.parent().unwrap_or(filepath.as_path());
        let help = format!(
            "this install tree was created by an incompatible version of Lux.
remove the tree at '{}' and reinstall all packages it contained.",
            tree_dir.display()
        );
        let mut lockfile: Lockfile<ReadOnly> = load_lockfile(&content, &filepath, &help)?;
        lockfile.filepath = filepath;
        Ok(lockfile)
    }

    /// Creates a temporary, writeable lockfile which can never flush.
    pub(crate) fn into_temporary(self) -> Lockfile<ReadWrite> {
        Lockfile::<ReadWrite> {
            _marker: PhantomData,
            filepath: self.filepath,
            version: self.version,
            binaries: self.binaries,
            lock: self.lock,
        }
    }

    /// Creates a lockfile guard, flushing the lockfile automatically
    /// once the guard goes out of scope.
    pub fn write_guard(self) -> Guard {
        Guard::new(self.into_temporary())
    }

    /// Converts the current lockfile into a writeable one, executes `cb` and flushes
    /// the lockfile.
    #[tracing::instrument(level = "trace", skip_all)]
    pub fn map_then_flush<T, F, E>(self, cb: F) -> Result<T, FlushLockfileError>
    where
        F: FnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
        E: std::error::Error,
        E: From<io::Error>,
        E: Into<Box<dyn std::error::Error + Send + Sync>>,
    {
        let mut writeable_lockfile = self.into_temporary();

        let result = cb(&mut writeable_lockfile).map_err(|err| FlushLockfileError {
            filepath: writeable_lockfile.filepath.to_path_buf(),
            source: io::Error::other(err),
        })?;

        writeable_lockfile.flush()?;

        Ok(result)
    }

    // TODO: Add this once async closures are stabilized
    // Converts the current lockfile into a writeable one, executes `cb` asynchronously and flushes
    // the lockfile.
    //pub async fn map_then_flush_async<T, F, E, Fut>(self, cb: F) -> Result<T, E>
    //where
    //    F: AsyncFnOnce(&mut Lockfile<ReadWrite>) -> Result<T, E>,
    //    E: Error,
    //    E: From<io::Error>,
    //{
    //    let mut writeable_lockfile = self.into_temporary();
    //
    //    let result = cb(&mut writeable_lockfile).await?;
    //
    //    writeable_lockfile.flush()?;
    //
    //    Ok(result)
    //}
}

impl Lockfile<ReadWrite> {
    pub(crate) fn add_entrypoint(&mut self, rock: &LockedPackage) {
        self.add(rock);
        self.lock.entrypoints.insert(rock.name().clone(), rock.id());
    }

    pub(crate) fn add(&mut self, rock: &LockedPackage) {
        // Since rocks entries are mutable, we only add the dependency if it
        // has not already been added.
        self.lock
            .rocks
            .entry(rock.id())
            .or_insert_with(|| rock.clone());
    }

    /// Add a dependency for a package.
    pub(crate) fn add_dependency(&mut self, target: &LockedPackage, dependency: &LockedPackage) {
        self.lock
            .rocks
            .entry(target.id())
            .and_modify(|rock| {
                let id = dependency.id();
                if !rock.spec.dependencies.contains(&id) {
                    rock.spec.dependencies.push(id);
                }
            })
            .or_insert_with(|| {
                let id = dependency.id();
                let mut target = target.clone();
                if !target.spec.dependencies.contains(&id) {
                    target.spec.dependencies.push(id);
                }
                target
            });
        self.add(dependency);
    }

    /// Add a build dependency for a package.
    pub(crate) fn add_build_dependency(
        &mut self,
        target: &LockedPackage,
        dependency: &LockedPackage,
    ) {
        self.lock
            .rocks
            .entry(target.id())
            .and_modify(|rock| {
                let id = dependency.id();
                if !rock.spec.build_dependencies.contains(&id) {
                    rock.spec.build_dependencies.push(id);
                }
            })
            .or_insert_with(|| {
                let id = dependency.id();
                let mut target = target.clone();
                if !target.spec.build_dependencies.contains(&id) {
                    target.spec.build_dependencies.push(id);
                }
                target
            });
    }

    /// Record the binaries installed for `package` into the tree lockfile.
    pub(crate) fn set_binaries(&mut self, package: &LockedPackage, binaries: RockBinaries) {
        self.binaries.insert(package.id(), binaries);
    }

    pub(crate) fn remove(&mut self, target: &LockedPackage) {
        self.binaries.remove(&target.id());
        self.lock.remove(target)
    }

    pub(crate) fn remove_by_id(&mut self, target: &locked_package::ID) {
        self.binaries.remove(target);
        self.lock.remove_by_id(target)
    }

    pub(crate) fn sync(&mut self, lock: &PackageLock) {
        self.lock = lock.clone();
    }

    // TODO: `fn entrypoints() -> Vec<LockedRock>`
}

pub(super) fn load_lockfile<T>(content: &str, lockfile: &Path, help: &str) -> Result<T, Error>
where
    T: serde::de::DeserializeOwned,
{
    let mut value = parse_lockfile_json(content)?;
    if lockfile_version(&value, lockfile)?.major == 1 {
        migrate_v1_lockfile(&mut value, lockfile)?;
    }
    deserialize_lockfile(value, lockfile, help)
}

fn parse_lockfile_json(content: &str) -> Result<serde_json::Map<String, serde_json::Value>, Error> {
    serde_json::from_str(content).map_err(Error::ParseJson)
}

fn lockfile_version(
    value: &serde_json::Map<String, serde_json::Value>,
    lockfile: &Path,
) -> Result<semver::Version, Error> {
    let version = value
        .get("version")
        .and_then(|version| version.as_str())
        .ok_or(Error::MissingVersion {
            lockfile: lockfile.to_path_buf(),
        })?;
    semver::Version::parse(version).map_err(|source| Error::InvalidVersion {
        version: version.to_string(),
        source,
    })
}

fn deserialize_lockfile<T>(
    value: serde_json::Map<String, serde_json::Value>,
    lockfile: &Path,
    help: &str,
) -> Result<T, Error>
where
    T: serde::de::DeserializeOwned,
{
    let found = lockfile_version(&value, lockfile)?;
    if found.major != LOCKFILE_VERSION {
        return Err(Error::IncompatibleVersion {
            lockfile: lockfile.to_path_buf(),
            found: found.to_string(),
            expected: LOCKFILE_VERSION_STR.into(),
            help: help.into(),
        });
    }
    serde_json::from_value(serde_json::Value::Object(value)).map_err(Error::ParseJson)
}

fn migrate_v1_lockfile(
    value: &mut serde_json::Map<String, serde_json::Value>,
    lockfile: &Path,
) -> Result<(), Error> {
    let tree_dir = lockfile.parent().unwrap_or(lockfile);
    let found = lockfile_version(value, lockfile)?;
    if value.contains_key("entrypoint_layout") {
        return Err(Error::IncompatibleVersion {
            lockfile: lockfile.to_path_buf(),
            found: found.to_string(),
            expected: LOCKFILE_VERSION_STR.into(),
            help: format!(
                "this install tree uses a custom entrypoint layout that cannot be migrated automatically.
remove the tree at '{}' and reinstall all packages it contained.",
                tree_dir.display()
            ),
        });
    }

    let conflict_help = format!(
        "this lockfile contains entrypoints that cannot be represented in the current format.
remove the tree at '{}' and reinstall all packages it contained.",
        tree_dir.display()
    );

    if value.contains_key("entrypoints") {
        migrate_entrypoints(value, lockfile, &conflict_help)?;
    }
    for section in ["dependencies", "test_dependencies", "build_dependencies"] {
        if let Some(section) = value
            .get_mut(section)
            .and_then(|section| section.as_object_mut())
        {
            migrate_entrypoints(section, lockfile, &conflict_help)?;
        }
    }
    value.insert(
        "version".into(),
        serde_json::Value::String(LOCKFILE_VERSION_STR.into()),
    );
    Ok(())
}

fn migrate_entrypoints(
    section: &mut serde_json::Map<String, serde_json::Value>,
    lockfile: &Path,
    help: &str,
) -> Result<(), Error> {
    let conflicting_entrypoints = || Error::ConflictingEntrypoints {
        lockfile: lockfile.to_path_buf(),
        help: help.to_string(),
    };

    let rocks = section.get("rocks").and_then(|rocks| rocks.as_object());
    let mut entrypoints = serde_json::Map::new();
    if let Some(old_entrypoints) = section.get("entrypoints") {
        for id in old_entrypoints
            .as_array()
            .ok_or_else(conflicting_entrypoints)?
        {
            let id = id.as_str().ok_or_else(conflicting_entrypoints)?;
            let name = rocks
                .and_then(|rocks| rocks.get(id))
                .and_then(|package| package.get("name"))
                .and_then(|name| name.as_str())
                .ok_or_else(conflicting_entrypoints)?;
            if entrypoints.contains_key(name) {
                return Err(conflicting_entrypoints());
            }
            entrypoints.insert(name.to_string(), serde_json::Value::String(id.to_string()));
        }
    }
    section.insert("entrypoints".into(), serde_json::Value::Object(entrypoints));
    Ok(())
}

fn deserialize_url<'de, D>(deserializer: D) -> Result<Url, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    Url::parse(&s).map_err(serde::de::Error::custom)
}

fn serialize_url<S>(url: &Url, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    url.as_str().serialize(serializer)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{config, lua};
    use assert_fs::fixture::PathCopy;
    use insta::{assert_json_snapshot, sorted_redaction};
    use std::{fs::remove_file, path::PathBuf};

    #[test]
    fn parse_lockfile() {
        let temp = assert_fs::TempDir::new().unwrap();
        temp.copy_from(
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
            &["**"],
        )
        .unwrap();

        let config = config::Builder::new()
            .unwrap()
            .user_tree(Some(temp.to_path_buf()))
            .build()
            .unwrap();
        let tree = config.user_tree(lua::Version::Lua51).unwrap();
        let lockfile = tree.lockfile().unwrap();

        assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
    }

    #[test]
    fn add_rocks() {
        let temp = assert_fs::TempDir::new().unwrap();
        temp.copy_from(
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
            &["**"],
        )
        .unwrap();

        let mock_hashes = locked_package::Hashes {
            rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
                .parse()
                .unwrap(),
            source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
                .parse()
                .unwrap(),
        };

        let config = config::Builder::new()
            .unwrap()
            .user_tree(Some(temp.to_path_buf()))
            .build()
            .unwrap();
        let tree = config.user_tree(lua::Version::Lua51).unwrap();
        let mut lockfile = tree.lockfile().unwrap().write_guard();

        let test_package = package::Spec::parse("test1".to_string(), "0.1.0".to_string()).unwrap();
        let test_local_package = LockedPackage::from(
            &test_package,
            crate::lockfile::Constraint::Unconstrained,
            remote::package::Source::Test,
            None,
            mock_hashes.clone(),
        );
        lockfile.add_entrypoint(&test_local_package);

        let test_dep_package =
            package::Spec::parse("test2".to_string(), "0.1.0".to_string()).unwrap();
        let mut test_local_dep_package = LockedPackage::from(
            &test_dep_package,
            crate::lockfile::Constraint::Constrained(">= 1.0.0".parse().unwrap()),
            remote::package::Source::Test,
            None,
            mock_hashes.clone(),
        );
        test_local_dep_package.spec.pinned = PinnedState::Pinned;
        lockfile.add_dependency(&test_local_package, &test_local_dep_package);

        assert_json_snapshot!(lockfile, { ".**" => sorted_redaction() });
    }

    #[test]
    fn parse_nonexistent_lockfile() {
        let tree_path =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");

        let temp = assert_fs::TempDir::new().unwrap();
        temp.copy_from(&tree_path, &["**"]).unwrap();

        remove_file(temp.join("5.1/lux.lock")).unwrap();

        let config = config::Builder::new()
            .unwrap()
            .user_tree(Some(temp.to_path_buf()))
            .build()
            .unwrap();
        let tree = config.user_tree(lua::Version::Lua51).unwrap();

        let _ = tree.lockfile().unwrap().write_guard(); // Try to create the lockfile but don't actually do anything with it.
    }

    fn get_test_lockfile() -> Lockfile<ReadOnly> {
        let sample_tree = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("resources/test/sample-tree/5.1/lux.lock");
        Lockfile::new(sample_tree).unwrap()
    }

    #[test]
    fn test_sync_spec() {
        let lockfile = get_test_lockfile();
        let packages = vec![
            package::Req::parse("neorg@8.8.1-1").unwrap().into(),
            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
            package::Req::parse("nonexistent").unwrap().into(),
        ];

        let sync_spec = lockfile
            .lock
            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);

        assert_eq!(sync_spec.to_add.len(), 1);

        // Should keep dependencies of neorg 8.8.1-1
        assert!(!sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "nvim-nio"
                && pkg.constraint()
                    == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
        assert!(!sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
                && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
        assert!(!sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "plenary.nvim"
                && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
        assert!(!sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "nui.nvim"
                && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
        assert!(!sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
                && pkg.constraint()
                    == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
    }

    #[test]
    fn test_sync_spec_remove() {
        let lockfile = get_test_lockfile();
        let packages = vec![
            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
            package::Req::parse("nonexistent").unwrap().into(),
        ];

        let sync_spec = lockfile
            .lock
            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);

        assert_eq!(sync_spec.to_add.len(), 1);

        // Should remove:
        // - neorg
        // - dependencies unique to neorg
        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "neorg"
                && pkg.version() == &"8.8.1-1".parse().unwrap()));
        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "nvim-nio"
                && pkg.constraint()
                    == Constraint::Constrained(">=1.7.0, <1.8.0".parse().unwrap())));
        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "lua-utils.nvim"
                && pkg.constraint() == Constraint::Constrained("=1.0.2".parse().unwrap())));
        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "plenary.nvim"
                && pkg.constraint() == Constraint::Constrained("=0.1.4".parse().unwrap())));
        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "nui.nvim"
                && pkg.constraint() == Constraint::Constrained("=0.3.0".parse().unwrap())));
        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "pathlib.nvim"
                && pkg.constraint()
                    == Constraint::Constrained(">=2.2.0, <2.3.0".parse().unwrap())));
    }

    #[test]
    fn test_sync_spec_empty() {
        let lockfile = get_test_lockfile();
        let packages = vec![];
        let sync_spec = lockfile
            .lock
            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);

        // Should remove all packages
        assert!(sync_spec.to_add.is_empty());
        assert_eq!(sync_spec.to_remove.len(), lockfile.rocks().len());
    }

    #[test]
    fn test_sync_spec_different_constraints() {
        let lockfile = get_test_lockfile();
        let packages = vec![package::Req::parse("nvim-nio>=2.0.0").unwrap().into()];
        let sync_spec = lockfile
            .lock
            .package_sync_spec(&packages, &SyncStrategy::LockfileOnly);

        let expected: package::VersionReq = ">=2.0.0".parse().unwrap();
        assert!(sync_spec
            .to_add
            .iter()
            .any(|req| req.name().to_string() == "nvim-nio" && req.version_req() == &expected));

        assert!(sync_spec
            .to_remove
            .iter()
            .any(|pkg| pkg.name().to_string() == "nvim-nio"));
    }

    #[test]
    fn test_sync_spec_ensure_installed() {
        let temp = assert_fs::TempDir::new().unwrap();
        temp.copy_from(
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree"),
            &["**"],
        )
        .unwrap();

        let config = config::Builder::new()
            .unwrap()
            .user_tree(Some(temp.to_path_buf()))
            .build()
            .unwrap();
        let tree = config.user_tree(lua::Version::Lua51).unwrap();
        let lockfile = tree.lockfile().unwrap();

        let packages: Vec<lua_dependency::Spec> = vec![
            package::Req::parse("neorg@8.8.1-1").unwrap().into(),
            // This package isn't installed in the tree
            package::Req::parse("lua-cjson@2.1.0").unwrap().into(),
            // And neither is this
            package::Req::parse("nonexistent").unwrap().into(),
        ];

        // Since lua-cjson is not present in the tree, it should get put into `to_add`
        let sync_spec = lockfile
            .lock
            .package_sync_spec(&packages, &SyncStrategy::EnsureInstalled(&tree));

        assert!(!sync_spec
            .to_add
            .iter()
            .any(|req| req.name().to_string() == "neorg"));

        assert!(sync_spec
            .to_add
            .iter()
            .any(|req| req.name().to_string() == "lua-cjson"));

        assert!(sync_spec
            .to_add
            .iter()
            .any(|req| req.name().to_string() == "nonexistent"));
    }

    #[test]
    fn verify_lockfile_version() {
        let deserialize = |version: &str| {
            let content = format!(r#"{{"version": "{version}"}}"#);
            parse_lockfile_json(&content).and_then(|value| {
                deserialize_lockfile::<Lockfile<ReadOnly>>(value, Path::new("lux.lock"), "")
            })
        };

        assert!(matches!(
            deserialize("3.0.0"),
            Err(Error::IncompatibleVersion { .. })
        ));
        assert!(matches!(
            deserialize("not-a-version"),
            Err(Error::InvalidVersion { .. })
        ));
    }

    #[test]
    fn migrate_v1_tree_lockfile() {
        let sample =
            PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/lockfile-v1/tree.lock");

        let temp = assert_fs::TempDir::new().unwrap();
        let lockfile_path = temp.path().join("lux.lock");
        std::fs::copy(&sample, &lockfile_path).unwrap();

        let lockfile = Lockfile::load(lockfile_path.clone()).unwrap();

        let on_disk: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&lockfile_path).unwrap()).unwrap();
        assert_eq!(on_disk["version"], "1.0.0");
        assert!(on_disk["entrypoints"].is_array());

        assert_eq!(lockfile.version, "2.0.0");
        assert_eq!(lockfile.lock.entrypoints.len(), 3);
    }

    #[test]
    fn refuse_migration_for_custom_layout() {
        let lockfile = r#"{"version":"1.0.0","entrypoint_layout":{"root":"site/pack/lux"}}"#;
        assert!(matches!(
            load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
            Err(Error::IncompatibleVersion { .. })
        ));
    }

    #[test]
    fn refuse_migration_for_conflicting_entrypoints() {
        let lockfile = r#"{
            "version": "1.0.0",
            "rocks": {
                "a": { "name": "foo" },
                "b": { "name": "foo" }
            },
            "entrypoints": ["a", "b"]
        }"#;
        assert!(matches!(
            load_lockfile::<Lockfile<ReadOnly>>(lockfile, Path::new("lux.lock"), ""),
            Err(Error::ConflictingEntrypoints { .. })
        ));
    }
}