loadsmith-install 0.3.1

Install, remove, and list mod files 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
use std::borrow::Cow;

use camino::{Utf8Path, Utf8PathBuf};
use loadsmith_core::PackageRef;
use serde::{Deserialize, Serialize};

use crate::ConflictStrategy;

/// A route-based install rule that maps files by directory name and file extension.
///
/// A `RouteRule` looks for a named directory component in the input path and maps
/// the remaining suffix into the target directory. File extensions can be used as
/// an additional matching criterion.
///
/// # Examples
///
/// ```rust
/// use camino::Utf8PathBuf;
/// use loadsmith_core::{PackageRef, PackageId, Version};
/// use loadsmith_install::RouteRule;
///
/// let rule = RouteRule::new_static("BepInEx\\plugins")
///     .with_file_extension("dll");
/// let pkg = PackageRef::new(PackageId::new("x753-More_Suits"), Version::new(1, 0, 3));
///
/// assert!(rule.matches("MyPlugin.dll"));
/// assert!(rule.matches_path("BepInEx\\plugins\\MyPlugin.dll"));
/// assert_eq!(
///     rule.map_file("plugins\\MyPlugin.dll", &pkg),
///     Some(Utf8PathBuf::from("BepInEx\\plugins\\x753-More_Suits\\MyPlugin.dll"))
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RouteRule {
    name: Cow<'static, str>,
    pub(super) target: Cow<'static, Utf8Path>,
    file_extensions: Vec<Cow<'static, str>>,
    subdir: bool,
    flatten: bool,
    mutable: bool,
}

impl RouteRule {
    /// Creates a route rule from a static path string. The rule name is derived
    /// from the last path component.
    pub fn new_static(path: &'static str) -> Self {
        Self::new(Cow::Borrowed(Utf8Path::new(path)))
    }

    /// Creates a route rule from any path. The rule name is derived from the
    /// last path component.
    pub fn new(path: impl Into<Cow<'static, Utf8Path>>) -> Self {
        let path = path.into();

        let name = match path {
            Cow::Borrowed(borrowed) => borrowed.file_name().map(Cow::Borrowed),
            Cow::Owned(_) => path.file_name().map(|s| Cow::Owned(s.to_string())),
        }
        .unwrap_or_default();

        Self::new_with_target(name, path)
    }

    /// Creates a route rule with an explicit name and target path.
    ///
    /// The `name` is the directory component that triggers a match; `target` is
    /// the directory where matched files are installed.
    pub fn new_with_target(
        name: impl Into<Cow<'static, str>>,
        target: impl Into<Cow<'static, Utf8Path>>,
    ) -> Self {
        Self {
            name: name.into(),
            target: target.into(),
            file_extensions: Vec::new(),
            flatten: true,
            subdir: true,
            mutable: false,
        }
    }

    /// Adds a file extension to the matching set.
    pub fn with_file_extension(mut self, extension: impl Into<Cow<'static, str>>) -> Self {
        self.file_extensions.push(extension.into());
        self
    }

    /// Replaces the entire set of matching file extensions.
    pub fn with_file_extensions(mut self, extensions: Vec<Cow<'static, str>>) -> Self {
        self.file_extensions = extensions;
        self
    }

    /// Sets whether to flatten the mapped path (remove intermediate directories).
    pub fn with_flatten(mut self, flatten: bool) -> Self {
        self.flatten = flatten;
        self
    }

    /// Sets whether to create a subdirectory named after the package ID inside
    /// the target directory.
    pub fn with_subdir(mut self, subdir: bool) -> Self {
        self.subdir = subdir;
        self
    }

    /// Sets whether the rule allows mutable (user-modifiable) files.
    pub fn with_mutable(mut self, mutable: bool) -> Self {
        self.mutable = mutable;
        self
    }

    /// Returns `true` if the path matches by extension or by route name.
    pub fn matches(&self, path: impl AsRef<Utf8Path>) -> bool {
        let path = path.as_ref();
        self.matches_extension(path) || self.matches_path(path)
    }

    /// Returns `true` if the file name has one of the rule's registered extensions.
    pub fn matches_extension(&self, path: impl AsRef<Utf8Path>) -> bool {
        // check the whole extension, that is everything after the first dot in the file name
        path.as_ref()
            .file_name()
            .and_then(|name| name.split_once('.'))
            .map(|(_, ext)| self.file_extensions.iter().any(|e| e == ext))
            .unwrap_or(false)
    }

    /// Returns `true` if the path contains the route's name as a path component.
    pub fn matches_path(&self, path: impl AsRef<Utf8Path>) -> bool {
        self.split_path(path.as_ref()).is_some()
    }

    fn split_path(&self, path: &Utf8Path) -> Option<(Utf8PathBuf, Utf8PathBuf)> {
        // eat components until we find the route name
        let Some(route_name_index) = path
            .components()
            .position(|comp| comp.as_str().eq_ignore_ascii_case(self.name.as_ref()))
        else {
            // no match
            return None;
        };

        let prefix = path.components().take(route_name_index).collect();
        let suffix = path.components().skip(route_name_index + 1).collect();

        Some((prefix, suffix))
    }

    /// Maps a file path to its install destination under the rule's target directory.
    ///
    /// If the path contains the route name, the part before the route name becomes
    /// the prefix; otherwise the parent directory becomes the prefix. When `subdir`
    /// is enabled the package ID is inserted as an intermediate directory. When
    /// `flatten` is disabled the prefix is preserved in the output.
    pub fn map_file(
        &self,
        path: impl AsRef<Utf8Path>,
        package: &PackageRef,
    ) -> Option<Utf8PathBuf> {
        let path = path.as_ref();
        let (prefix, suffix) = self.split_path(path).unwrap_or_else(|| {
            let mut components = path.components();
            let file_name = components
                .next_back()
                .map(|file_name| file_name.as_str())
                .unwrap_or_default();
            let prefix = components.collect();

            (prefix, Utf8PathBuf::from(file_name))
        });

        let mut target_path = Utf8PathBuf::from(self.target.as_ref());

        if self.subdir {
            target_path.push(package.id().as_str());
        }

        if !self.flatten {
            target_path.push(prefix);
        }

        target_path.push(suffix);

        Some(target_path)
    }

    /// Returns `true` if the rule prefers hard links over file copies.
    ///
    /// Links are used when the rule is not marked as mutable.
    pub fn use_links(&self) -> bool {
        !self.mutable
    }

    /// Returns the conflict strategy for this route rule (always [`Skip`](ConflictStrategy::Skip)).
    ///
    /// Route rules never overwrite existing files and never error; they silently skip.
    pub fn conflict_strategy(&self) -> ConflictStrategy {
        ConflictStrategy::Skip
    }
}

#[cfg(test)]
mod tests {
    use loadsmith_core::{PackageId, Version};

    use super::*;

    #[test]
    fn new() {
        let rule = RouteRule::new(Utf8Path::new("BepInEx/plugins"));

        assert_eq!(rule.name, "plugins");
        assert_eq!(rule.target, Utf8Path::new("BepInEx/plugins"));

        let rule = RouteRule::new(Utf8Path::new("MelonLoader"));

        assert_eq!(rule.name, "MelonLoader");
        assert_eq!(rule.target, Utf8Path::new("MelonLoader"));

        let rule = RouteRule::new(Utf8Path::new(""));

        assert_eq!(rule.name, "");
        assert_eq!(rule.target, Utf8Path::new(""));
    }

    #[test]
    fn defaults() {
        let rule = RouteRule::new_static("BepInEx/plugins");

        assert!(rule.flatten);
        assert!(rule.subdir);
        assert!(!rule.mutable);
    }

    #[test]
    fn matches_path() {
        let rule = RouteRule::new_static("BepInEx/plugins");

        assert!(rule.matches("BepInEx/plugins/myplugin.dll"));
        assert!(rule.matches("plugins/myplugin.dll"));
        assert!(rule.matches("Plugins/myplugin.dll"));
        assert!(rule.matches("Nested/BepInEx/plugins/myplugin.dll"));
        assert!(!rule.matches("BepInEx/core/myplugin.dll"));
        assert!(!rule.matches("myplugin.dll"));
    }

    #[test]
    fn matches_extension() {
        let rule = RouteRule::new_static("BepInEx/monomod").with_file_extension("mm.dll");

        assert!(rule.matches("BepInEx/monomod/myplugin.mm.dll"));
        assert!(rule.matches("BepInEx/monomod/myplugin.dll"));
        assert!(rule.matches("myplugin.mm.dll"));
        assert!(!rule.matches("myplugin.dll"));
    }

    #[test]
    fn match_extension_with_dot() {
        let rule1 = RouteRule::new_static("plugins").with_file_extension("dll");

        assert!(rule1.matches("myplugin.dll"));
        assert!(!rule1.matches("myplugin.mm.dll"));
        assert!(!rule1.matches("myplugin.dll.mm"));
        assert!(!rule1.matches("myplugin.dll.dll"));

        let rule2 = RouteRule::new_static("monomod").with_file_extension("mm.dll");

        assert!(!rule2.matches("myplugin.dll"));
        assert!(rule2.matches("myplugin.mm.dll"));
        assert!(!rule2.matches("myplugin.mm"));
        assert!(!rule2.matches("myplugin.mm.mm.dll"));
    }

    macro_rules! assert_map {
        ($rule:expr, $file:expr, $package:expr => None) => {
            assert_eq!($rule.map_file($file, $package), None);
        };
        ($rule:expr, $file:expr, $package:expr => $expected:expr) => {
            assert_eq!(
                $rule.map_file($file, $package),
                Some(Utf8PathBuf::from($expected))
            );
        };
    }

    #[test]
    fn map_file() {
        let rule = RouteRule::new_static("BepInEx/plugins")
            .with_file_extension("plugin")
            .with_subdir(true)
            .with_flatten(true);

        let package = PackageRef::new(PackageId::new("Author-Name"), Version::new(1, 0, 0));

        // defaults correctly when name is not present in the path
        assert_map!(rule, "MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // removes the matched "plugins" component
        assert_map!(rule, "plugins/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // removes the matched "pluguins" component and flattens the "BepInEx" component
        assert_map!(rule, "BepInEx/plugins/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // case-insensitive match of "plugins"
        assert_map!(rule, "BepInEx/Plugins/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // flattens the "Nested" component
        assert_map!(rule, "Nested/plugins/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // flattens the "Nested" component
        assert_map!(rule, "Nested/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // retains nesting after the matched "plugins" component but flattens before
        assert_map!(rule, "Before/plugins/After/MyPlugin.plugin", &package => "BepInEx/plugins/Author-Name/After/MyPlugin.plugin");
    }

    #[test]
    fn map_file_flatten() {
        let rule = RouteRule::new_static("BepInEx/plugins")
            .with_flatten(true)
            .with_subdir(true)
            .with_file_extension("plugin");

        let package = PackageRef::new(PackageId::new("Author-Name"), Version::new(1, 0, 0));

        // Flattened routing keeps only the file name and package folder.
        assert_map!(rule, "MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // When the route name is already present, it is removed from the output path.
        assert_map!(rule, "plugins/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // A fully qualified route path still collapses down to the target folder.
        assert_map!(rule, "BepInEx/plugins/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/MyPlugin.dll");

        // Extra nesting after the route name is preserved even when flattening.
        assert_map!(rule, "plugins/Nested/MyPlugin.dll", &package => "BepInEx/plugins/Author-Name/Nested/MyPlugin.dll");

        // File extension matching does not change the mapped directory layout.
        assert_map!(rule, "plugins/Nested/MyPlugin.plugin", &package => "BepInEx/plugins/Author-Name/Nested/MyPlugin.plugin");

        // Paths without the route name still map relative to the file name.
        assert_map!(rule, "Nested/MyPlugin.plugin", &package => "BepInEx/plugins/Author-Name/MyPlugin.plugin");
    }

    #[test]
    fn map_file_no_subdir_flatten() {
        let rule = RouteRule::new_static("BepInEx/plugins")
            .with_subdir(false)
            .with_flatten(true)
            .with_file_extension("plugin");

        let package = PackageRef::new(PackageId::new("Author-Name"), Version::new(1, 0, 0));

        // Without subdir support, the package id is never inserted.
        assert_map!(rule, "MyPlugin.dll", &package => "BepInEx/plugins/MyPlugin.dll");

        // The route prefix is still stripped when it appears in the input path.
        assert_map!(rule, "plugins/MyPlugin.dll", &package => "BepInEx/plugins/MyPlugin.dll");

        // Flattening keeps fully qualified paths at the target root.
        assert_map!(rule, "BepInEx/plugins/MyPlugin.dll", &package => "BepInEx/plugins/MyPlugin.dll");

        // Nested content stays nested when flattening does not remove it.
        assert_map!(rule, "plugins/Nested/MyPlugin.plugin", &package => "BepInEx/plugins/Nested/MyPlugin.plugin");

        // Nested content stays nested when flattening does not remove it.
        assert_map!(rule, "BepInEx/plugins/Nested/MyPlugin.plugin", &package => "BepInEx/plugins/Nested/MyPlugin.plugin");
    }

    #[test]
    fn map_file_no_subdir_no_flatten() {
        let rule = RouteRule::new_static("BepInEx/plugins")
            .with_subdir(false)
            .with_flatten(false)
            .with_file_extension("plugin");

        let package = PackageRef::new(PackageId::new("Author-Name"), Version::new(1, 0, 0));

        // No package folder is inserted when subdir is disabled.
        assert_map!(rule, "MyPlugin.dll", &package => "BepInEx/plugins/MyPlugin.dll");

        // Nested routes are preserved even when the route name doesn't appear.
        assert_map!(rule, "other/MyPlugin.dll", &package => "BepInEx/plugins/other/MyPlugin.dll");

        // A matching route component is removed before the remainder is appended.
        assert_map!(rule, "plugins/MyPlugin.dll", &package => "BepInEx/plugins/MyPlugin.dll");

        // Without flattening, the unmatched prefix is preserved in the output path.
        assert_map!(rule, "BepInEx/plugins/MyPlugin.dll", &package => "BepInEx/plugins/BepInEx/MyPlugin.dll");

        // Nested content remains nested when the route name is stripped.
        assert_map!(rule, "plugins/Nested/MyPlugin.plugin", &package => "BepInEx/plugins/Nested/MyPlugin.plugin");
    }

    #[test]
    fn map_file_empty() {
        let rule = RouteRule::new_static("BepInEx/plugins").with_flatten(false);

        // An empty path falls back to the package directory when flattening is off.
        assert_map!(
            rule,
            "",
            &PackageRef::new(PackageId::new("Author-Name"), Version::new(1, 0, 0)) => "BepInEx/plugins/Author-Name"
        );
    }
}