loadsmith-manifest 0.3.1

Manifest and lockfile format, resolver, and profile state for the loadsmith mod-manager library
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
use std::{
    fmt::Display,
    path::{Path, PathBuf},
    sync::Arc,
};

use camino::Utf8PathBuf;
use loadsmith_core::{Checksum, InstalledPackage, PackageId, PackageRef, Version};
use loadsmith_install::InstallRuleset;
use walkdir::WalkDir;

use crate::{Error, Result};

/// Manages a central, content-addressed store of package files on disk.
///
/// Each package is stored under a sharded path derived from its
/// [`PackageStoreEntry`] (e.g. `au/Author-Name/0.1.0+blake3_<hash>`).
/// The store supports reserving paths for new packages, installing them into
/// a profile, and cleaning up unused entries.
///
/// # Examples
///
/// ```rust
/// # use std::sync::Arc;
/// use loadsmith_manifest::PackageStore;
///
/// let store = PackageStore::open(std::env::temp_dir().join("loadsmith-test-store")).unwrap();
/// assert!(store.base_path().exists());
/// ```
#[derive(Debug, Clone)]
pub struct PackageStore {
    base_path: Arc<Path>,
    no_links: bool,
}

/// A reference to a specific package version in the [`PackageStore`].
///
/// Entries are identified by their package ref (name + version) and an
/// optional checksum that disambiguates revisions at the same version.
///
/// # Examples
///
/// ```rust
/// use loadsmith_core::{PackageRef, Version};
/// use loadsmith_manifest::PackageStoreEntry;
///
/// let entry = PackageStoreEntry::new(
///     PackageRef::new("Author-Mod", Version::new(1, 0, 0)),
///     None,
/// );
/// assert_eq!(entry.package().id().as_str(), "Author-Mod");
/// assert!(entry.checksum().is_none());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PackageStoreEntry {
    package: PackageRef,
    checksum: Option<Checksum>,
}

impl PackageStore {
    /// Open (or create) a package store at the given directory path.
    ///
    /// If the directory does not exist it will be created.
    pub fn open(base_path: impl Into<Arc<Path>>) -> Result<Self> {
        let base_path = base_path.into();
        if !base_path.is_dir() {
            std::fs::create_dir_all(&base_path)?;
        }
        Ok(Self {
            base_path,
            no_links: false,
        })
    }

    /// Configure the store to copy files instead of creating symlinks when
    /// installing into a profile.
    pub fn without_links(mut self) -> Self {
        self.no_links = true;
        self
    }

    /// Borrow the base directory of the package store.
    pub fn base_path(&self) -> &Path {
        &self.base_path
    }

    /// Compute the on-disk path for a store entry within this store's base.
    pub fn path_of(&self, entry: &PackageStoreEntry) -> PathBuf {
        self.base_path.join(entry.path())
    }

    /// Check whether the on-disk directory for a store entry already exists.
    pub fn contains(&self, entry: &PackageStoreEntry) -> bool {
        self.path_of(entry).exists()
    }

    /// Reserve the directory for a store entry, creating it if it does not
    /// exist yet.
    ///
    /// Returns an error if the directory already exists.
    pub fn reserve(&self, entry: &PackageStoreEntry) -> Result<PathBuf> {
        let path = self.path_of(entry);
        if path.exists() {
            return Err(Error::PackageStoreEntryAlreadyExists);
        }

        std::fs::create_dir_all(&path)?;
        Ok(path)
    }

    /// Install a store entry into the given profile directory.
    ///
    /// Returns the installed package metadata together with the list of files
    /// that were overwritten from other packages.
    pub fn install(
        &self,
        entry: PackageStoreEntry,
        ruleset: InstallRuleset,
        profile: impl AsRef<Path>,
    ) -> Result<(InstalledPackage, Vec<Utf8PathBuf>)> {
        let source = self.path_of(&entry);

        let (install, overriden_files) = loadsmith_install::install(
            entry.package,
            ruleset,
            source,
            profile,
            self.no_links,
            entry.checksum,
        )?;

        Ok((install, overriden_files))
    }

    /// Remove a store entry's on-disk directory and any empty parent
    /// directories.
    pub fn remove(&self, entry: &PackageStoreEntry) -> Result<()> {
        let path = self.path_of(entry);
        std::fs::remove_dir_all(&path)?;
        loadsmith_util::remove_empty_parents(path)?;
        Ok(())
    }

    /// Parse a [`PackageStoreEntry`] from an absolute or relative path within
    /// this store's base directory.
    ///
    /// Returns an error if the path is not a valid entry path under the store.
    pub fn entry_from_path(&self, path: impl AsRef<Path>) -> Result<PackageStoreEntry> {
        let path = path.as_ref();
        let relative_path = path
            .strip_prefix(&self.base_path)
            .map_err(|_| Error::InvalidPackageStoreEntryPath)?;

        PackageStoreEntry::try_from_path(relative_path)
    }

    /// Iterate over all store entries that are not referenced by any
    /// [`ProfileState`](crate::ProfileState).
    ///
    /// This is useful for garbage-collecting the store after profiles have
    /// been updated.
    pub fn unused_entries(&self) -> impl Iterator<Item = Result<PackageStoreEntry>> + '_ {
        self.entries().filter(|entry| match entry {
            Ok(entry) => self.is_unused(entry),
            Err(_) => true,
        })
    }

    /// Iterate over every entry currently present in the store directory tree.
    pub fn entries(&self) -> impl Iterator<Item = Result<PackageStoreEntry>> + '_ {
        WalkDir::new(&self.base_path)
            .follow_links(false)
            .min_depth(3)
            .max_depth(3)
            .into_iter()
            .filter_map(|entry| match entry {
                Ok(entry) => {
                    if !entry.file_type().is_dir() {
                        return None;
                    }

                    Some(self.entry_from_path(entry.path()))
                }
                Err(err) => Some(Err(err.into())),
            })
    }

    /// Check whether a store entry is unused (its files have no remaining
    /// hard links).
    ///
    /// On non-Unix platforms this always returns `false`.
    fn is_unused(&self, entry: &PackageStoreEntry) -> bool {
        WalkDir::new(self.path_of(entry))
            .into_iter()
            .filter_map(|entry| entry.ok())
            .filter(|entry| entry.file_type().is_file())
            .all(|#[allow(unused)] file| {
                #[cfg(unix)]
                {
                    use std::os::unix::fs::MetadataExt;

                    let Some(meta) = file.metadata().ok() else {
                        return false;
                    };

                    meta.nlink() <= 1
                }

                #[cfg(not(unix))]
                {
                    false
                }
            })
    }
}

impl PackageStoreEntry {
    /// Create a new store entry from a package reference and an optional
    /// checksum.
    ///
    /// When a checksum is provided it becomes part of the on-disk path,
    /// allowing multiple revisions of the same version to coexist.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use loadsmith_core::{PackageRef, Version};
    /// use loadsmith_manifest::PackageStoreEntry;
    ///
    /// let entry = PackageStoreEntry::new(
    ///     PackageRef::new("Author-Mod", Version::new(1, 0, 0)),
    ///     None,
    /// );
    /// assert_eq!(entry.package().id().as_str(), "Author-Mod");
    /// ```
    pub fn new(package: impl Into<PackageRef>, checksum: Option<Checksum>) -> Self {
        Self {
            package: package.into(),
            checksum,
        }
    }

    /// Borrow the package reference (name + version) of this entry.
    pub fn package(&self) -> &PackageRef {
        &self.package
    }

    /// Borrow the optional checksum that disambiguates this entry.
    pub fn checksum(&self) -> Option<&Checksum> {
        self.checksum.as_ref()
    }

    fn path(&self) -> PathBuf {
        let mut path = PathBuf::new();

        path.push(self.prefix());
        path.push(self.package.id().as_str());

        let version_str = match &self.checksum {
            Some(checksum) => format!(
                "{}+{}_{}",
                self.package.version(),
                checksum.algorithm(),
                checksum.without_algorithm()
            ),
            None => self.package.version().to_string(),
        };

        path.push(version_str);

        path
    }

    fn prefix(&self) -> String {
        self.package
            .id()
            .as_str()
            .chars()
            .take(2)
            .collect::<String>()
            .to_lowercase()
    }

    fn try_from_path(path: impl AsRef<Path>) -> Result<Self> {
        use std::path::Component;

        let path = path.as_ref();

        let mut components = path.components();
        let Some(Component::Normal(prefix)) = components.next() else {
            return Err(Error::InvalidPackageStoreEntryPath);
        };

        let prefix = prefix.to_str().ok_or(Error::NonUtf8Path)?;

        let id = match components.next() {
            Some(Component::Normal(os_str)) => {
                PackageId::new(os_str.to_str().ok_or(Error::NonUtf8Path)?)
            }
            _ => return Err(Error::InvalidPackageStoreEntryPath),
        };

        let (version, checksum) = match components.next() {
            Some(Component::Normal(os_str)) => {
                let str = os_str.to_str().ok_or(Error::NonUtf8Path)?;

                let (version, checksum) = match str.split_once('+') {
                    Some((version, checksum)) => {
                        let checksum: Checksum = checksum
                            .replace('_', ":")
                            .parse()
                            .map_err(Error::InvalidPackageStoreEntryChecksum)?;

                        (version, Some(checksum))
                    }
                    None => (str, None),
                };

                let version: Version = version
                    .parse()
                    .map_err(Error::InvalidPackageStoreEntryVersion)?;

                (version, checksum)
            }
            _ => return Err(Error::InvalidPackageStoreEntryPath),
        };

        if components.next().is_some() {
            return Err(Error::InvalidPackageStoreEntryPath);
        }

        let package = PackageRef::new(id, version);

        let this = Self { package, checksum };

        if this.prefix() != prefix {
            return Err(Error::InvalidPackageStoreEntryPath);
        }

        Ok(this)
    }
}

impl Display for PackageStoreEntry {
    /// Formats the entry as `<package>+<checksum>` (or just `<package>` when
    /// no checksum is present).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use loadsmith_core::{PackageRef, Version};
    /// use loadsmith_manifest::PackageStoreEntry;
    ///
    /// let entry = PackageStoreEntry::new(
    ///     PackageRef::new("Author-Mod", Version::new(1, 0, 0)),
    ///     None,
    /// );
    /// assert_eq!(entry.to_string(), "Author-Mod@1.0.0");
    /// ```
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(checksum) = &self.checksum {
            write!(f, "{}+{}", self.package, checksum)
        } else {
            write!(f, "{}", self.package)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // blake3 hash of "Hello, world!"
    const BLAKE3_HELLO_WORLD: &str =
        "ede5c0b10f2ec4979c69b52f61e42ff5b413519ce09be0f14d098dcfe5f6f98d";

    #[test]
    fn entry_path() {
        let entry =
            PackageStoreEntry::new(PackageRef::new("Author-Name", Version::new(0, 1, 0)), None);
        assert_eq!(entry.path(), PathBuf::from("au/Author-Name/0.1.0"));

        let entry = PackageStoreEntry::new(PackageRef::new("A", Version::new(0, 1, 0)), None);
        assert_eq!(entry.path(), PathBuf::from("a/A/0.1.0"));

        let hash = blake3::hash(b"Hello, world!");
        let entry = PackageStoreEntry::new(
            PackageRef::new("Author-Name", Version::new(0, 1, 0)),
            Some(hash.into()),
        );
        assert_eq!(
            entry.path(),
            PathBuf::from(format!("au/Author-Name/0.1.0+blake3_{BLAKE3_HELLO_WORLD}"))
        );
    }

    #[test]
    fn entry_from_path() {
        let entry = PackageStoreEntry::try_from_path("au/Author-Name/0.1.0").unwrap();
        assert_eq!(
            entry,
            PackageStoreEntry {
                package: PackageRef::new("Author-Name", Version::new(0, 1, 0)),
                checksum: None
            }
        );

        let entry = PackageStoreEntry::try_from_path(format!(
            "au/Author-Name/0.1.0+blake3_{BLAKE3_HELLO_WORLD}"
        ))
        .unwrap();

        let hash = blake3::hash(b"Hello, world!");
        assert_eq!(
            entry,
            PackageStoreEntry {
                package: PackageRef::new("Author-Name", Version::new(0, 1, 0)),
                checksum: Some(hash.into())
            }
        );
    }

    #[test]
    fn entry_from_path_invalid() {
        assert!(PackageStoreEntry::try_from_path("").is_err());
        assert!(PackageStoreEntry::try_from_path("au").is_err());
        assert!(PackageStoreEntry::try_from_path("au/Author-Name").is_err());
        assert!(PackageStoreEntry::try_from_path("au/Author-Name/0.1.0/extra").is_err());
        assert!(PackageStoreEntry::try_from_path("/au/Author-Name/0.1.0").is_err());
        assert!(PackageStoreEntry::try_from_path("C:/au/Author-Name/0.1.0").is_err());
        assert!(PackageStoreEntry::try_from_path("au/Author-Name/0.1.0+invalid_checksum").is_err());
        assert!(PackageStoreEntry::try_from_path("au/Author-Name/invalid_version").is_err());
        assert!(PackageStoreEntry::try_from_path("other-prefix/Author-Name/0.1.0").is_err());
    }

    #[test]
    fn entry_path_roundtrip() {
        let hash = blake3::hash(b"Hello, world!");

        let entry = PackageStoreEntry::new(
            PackageRef::new("Author-Name", Version::new(0, 1, 0)),
            Some(hash.into()),
        );
        let entry2 = PackageStoreEntry::try_from_path(entry.path()).unwrap();

        assert_eq!(entry, entry2);
    }
}