• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Ortham / libloadorder / 10254885716

05 Aug 2024 07:32PM UTC coverage: 91.964% (+0.1%) from 91.832%
10254885716

push

github

Ortham
Add more validation for blueprint plugins

82 of 88 new or added lines in 3 files covered. (93.18%)

48 existing lines in 3 files now uncovered.

7931 of 8624 relevant lines covered (91.96%)

165860.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.76
/src/load_order/mutable.rs
1
/*
2
 * This file is part of libloadorder
3
 *
4
 * Copyright (C) 2017 Oliver Hamlet
5
 *
6
 * libloadorder is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * libloadorder is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with libloadorder. If not, see <http://www.gnu.org/licenses/>.
18
 */
19

20
use std::cmp::Ordering;
21
use std::collections::{BTreeMap, HashMap, HashSet};
22
use std::fs::read_dir;
23
use std::mem;
24
use std::path::{Path, PathBuf};
25

26
use encoding_rs::WINDOWS_1252;
27
use rayon::prelude::*;
28
use unicase::{eq, UniCase};
29

30
use super::readable::{ReadableLoadOrder, ReadableLoadOrderBase};
31
use crate::enums::Error;
32
use crate::game_settings::GameSettings;
33
use crate::plugin::{has_plugin_extension, trim_dot_ghost, Plugin};
34
use crate::GameId;
35

36
pub trait MutableLoadOrder: ReadableLoadOrder + ReadableLoadOrderBase + Sync {
37
    fn plugins_mut(&mut self) -> &mut Vec<Plugin>;
38

39
    fn insert_position(&self, plugin: &Plugin) -> Option<usize> {
19,669✔
40
        if self.plugins().is_empty() {
19,669✔
41
            return None;
35✔
42
        }
19,634✔
43

19,634✔
44
        // A blueprint plugin may be listed as an early loader (e.g. in a CCC
19,634✔
45
        // file) but it still loads as a normal blueprint plugin.
19,634✔
46
        if !plugin.is_blueprint_master() {
19,634✔
47
            let mut loaded_plugin_count = 0;
19,630✔
48
            for plugin_name in self.game_settings().early_loading_plugins() {
19,630✔
49
                if eq(plugin.name(), plugin_name) {
601✔
50
                    return Some(loaded_plugin_count);
22✔
51
                }
579✔
52

579✔
53
                if self.index_of(plugin_name).is_some() {
579✔
54
                    loaded_plugin_count += 1;
143✔
55
                }
436✔
56
            }
57
        }
4✔
58

59
        generic_insert_position(self.plugins(), plugin)
19,612✔
60
    }
19,669✔
61

62
    fn find_plugins(&self) -> Vec<String> {
53✔
63
        // A game might store some plugins outside of its main plugins directory
53✔
64
        // so look for those plugins. They override any of the same names that
53✔
65
        // appear in the main plugins directory, so check for the additional
53✔
66
        // paths first.
53✔
67
        let mut directories = self
53✔
68
            .game_settings()
53✔
69
            .additional_plugins_directories()
53✔
70
            .to_vec();
53✔
71
        directories.push(self.game_settings().plugins_directory());
53✔
72

53✔
73
        find_plugins_in_dirs(&directories, self.game_settings().id())
53✔
74
    }
53✔
75

76
    fn validate_index(&self, plugin: &Plugin, index: usize) -> Result<(), Error> {
50✔
77
        if plugin.is_blueprint_master() {
50✔
78
            // Blueprint plugins load after all non-blueprint plugins of the
79
            // same scale, even non-masters.
80
            validate_blueprint_plugin_index(self.plugins(), plugin, index)
6✔
81
        } else {
82
            self.validate_early_loading_plugin_indexes(plugin.name(), index)?;
44✔
83

84
            if plugin.is_master_file() {
41✔
85
                validate_master_file_index(self.plugins(), plugin, index)
25✔
86
            } else {
87
                validate_non_master_file_index(self.plugins(), plugin, index)
16✔
88
            }
89
        }
90
    }
50✔
91

92
    fn lookup_plugins(&mut self, active_plugin_names: &[&str]) -> Result<Vec<usize>, Error> {
18✔
93
        active_plugin_names
18✔
94
            .par_iter()
18✔
95
            .map(|n| {
15,615✔
96
                self.plugins()
15,615✔
97
                    .par_iter()
15,615✔
98
                    .position_any(|p| p.name_matches(n))
29,969,635✔
99
                    .ok_or_else(|| Error::PluginNotFound(n.to_string()))
15,615✔
100
            })
15,615✔
101
            .collect()
18✔
102
    }
18✔
103

104
    fn set_plugin_index(&mut self, plugin_name: &str, position: usize) -> Result<usize, Error> {
20✔
105
        if let Some(x) = self.index_of(plugin_name) {
20✔
106
            if x == position {
11✔
107
                return Ok(position);
1✔
108
            }
10✔
109
        }
9✔
110

111
        let plugin = get_plugin_to_insert_at(self, plugin_name, position)?;
19✔
112

113
        if position >= self.plugins().len() {
11✔
114
            self.plugins_mut().push(plugin);
3✔
115
            Ok(self.plugins().len() - 1)
3✔
116
        } else {
117
            self.plugins_mut().insert(position, plugin);
8✔
118
            Ok(position)
8✔
119
        }
120
    }
20✔
121

122
    fn deactivate_all(&mut self) {
29✔
123
        for plugin in self.plugins_mut() {
11,960✔
124
            plugin.deactivate();
11,960✔
125
        }
11,960✔
126
    }
29✔
127

128
    fn replace_plugins(&mut self, plugin_names: &[&str]) -> Result<(), Error> {
12✔
129
        let mut unique_plugin_names = HashSet::new();
12✔
130

12✔
131
        let non_unique_plugin = plugin_names
12✔
132
            .iter()
12✔
133
            .find(|n| !unique_plugin_names.insert(UniCase::new(*n)));
53✔
134

135
        if let Some(n) = non_unique_plugin {
12✔
136
            return Err(Error::DuplicatePlugin(n.to_string()));
1✔
137
        }
11✔
138

139
        let mut plugins = map_to_plugins(self, plugin_names)?;
11✔
140

141
        validate_load_order(&plugins, self.game_settings().early_loading_plugins())?;
10✔
142

143
        mem::swap(&mut plugins, self.plugins_mut());
8✔
144

8✔
145
        Ok(())
8✔
146
    }
12✔
147

148
    fn load_unique_plugins(
36✔
149
        &mut self,
36✔
150
        plugin_name_tuples: Vec<(String, bool)>,
36✔
151
        installed_filenames: Vec<String>,
36✔
152
    ) {
36✔
153
        let plugins: Vec<_> = remove_duplicates_icase(plugin_name_tuples, installed_filenames)
36✔
154
            .into_par_iter()
36✔
155
            .filter_map(|(filename, active)| {
217✔
156
                Plugin::with_active(&filename, self.game_settings(), active).ok()
217✔
157
            })
217✔
158
            .collect();
36✔
159

160
        for plugin in plugins {
243✔
161
            insert(self, plugin);
207✔
162
        }
207✔
163
    }
36✔
164

165
    fn add_implicitly_active_plugins(&mut self) -> Result<(), Error> {
53✔
166
        let plugin_names = self.game_settings().implicitly_active_plugins().to_vec();
53✔
167

168
        for plugin_name in plugin_names {
194✔
169
            activate_unvalidated(self, &plugin_name)?;
141✔
170
        }
171

172
        Ok(())
53✔
173
    }
53✔
174

175
    /// Check that the given plugin and index won't cause any early-loading
176
    /// plugins to load in the wrong positions.
177
    fn validate_early_loading_plugin_indexes(
44✔
178
        &self,
44✔
179
        plugin_name: &str,
44✔
180
        position: usize,
44✔
181
    ) -> Result<(), Error> {
44✔
182
        let mut next_index = 0;
44✔
183
        for early_loader in self.game_settings().early_loading_plugins() {
44✔
184
            let names_match = eq(plugin_name, early_loader);
43✔
185

43✔
186
            let early_loader_tuple = self
43✔
187
                .plugins()
43✔
188
                .iter()
43✔
189
                .enumerate()
43✔
190
                .find(|(_, p)| p.name_matches(early_loader));
117✔
191

192
            let expected_index = match early_loader_tuple {
43✔
193
                Some((i, early_loading_plugin)) => {
12✔
194
                    // If the early loader is a blueprint plugin then it doesn't
12✔
195
                    // actually load early and so the index of the next early
12✔
196
                    // loader is unchanged.
12✔
197
                    if !early_loading_plugin.is_blueprint_master() {
12✔
198
                        next_index = i + 1;
10✔
199
                    }
10✔
200

201
                    if !names_match && position == i {
12✔
202
                        return Err(Error::InvalidEarlyLoadingPluginPosition {
1✔
203
                            name: early_loader.to_string(),
1✔
204
                            pos: i + 1,
1✔
205
                            expected_pos: i,
1✔
206
                        });
1✔
207
                    }
11✔
208

11✔
209
                    i
11✔
210
                }
211
                None => next_index,
31✔
212
            };
213

214
            if names_match && position != expected_index {
42✔
215
                return Err(Error::InvalidEarlyLoadingPluginPosition {
2✔
216
                    name: plugin_name.to_string(),
2✔
217
                    pos: position,
2✔
218
                    expected_pos: expected_index,
2✔
219
                });
2✔
220
            }
40✔
221
        }
222

223
        Ok(())
41✔
224
    }
44✔
225
}
226

227
pub fn load_active_plugins<T, F>(load_order: &mut T, line_mapper: F) -> Result<(), Error>
22✔
228
where
22✔
229
    T: MutableLoadOrder,
22✔
230
    F: Fn(&str) -> Option<String> + Send + Sync,
22✔
231
{
22✔
232
    load_order.deactivate_all();
22✔
233

234
    let plugin_names = read_plugin_names(
22✔
235
        load_order.game_settings().active_plugins_file(),
22✔
236
        line_mapper,
22✔
237
    )?;
22✔
238

239
    let plugin_indices: Vec<_> = plugin_names
22✔
240
        .par_iter()
22✔
241
        .filter_map(|p| load_order.index_of(p))
22✔
242
        .collect();
22✔
243

244
    for index in plugin_indices {
37✔
245
        load_order.plugins_mut()[index].activate()?;
15✔
246
    }
247

248
    Ok(())
22✔
249
}
22✔
250

251
pub fn read_plugin_names<F, T>(file_path: &Path, line_mapper: F) -> Result<Vec<T>, Error>
68✔
252
where
68✔
253
    F: FnMut(&str) -> Option<T> + Send + Sync,
68✔
254
    T: Send,
68✔
255
{
68✔
256
    if !file_path.exists() {
68✔
257
        return Ok(Vec::new());
30✔
258
    }
38✔
259

260
    let content =
38✔
261
        std::fs::read(file_path).map_err(|e| Error::IoError(file_path.to_path_buf(), e))?;
38✔
262

263
    // This should never fail, as although Windows-1252 has a few unused bytes
264
    // they get mapped to C1 control characters.
265
    let decoded_content = WINDOWS_1252
38✔
266
        .decode_without_bom_handling_and_without_replacement(&content)
38✔
267
        .ok_or_else(|| Error::DecodeError(content.clone()))?;
38✔
268

269
    Ok(decoded_content.lines().filter_map(line_mapper).collect())
38✔
270
}
68✔
271

272
pub fn plugin_line_mapper(line: &str) -> Option<String> {
103✔
273
    if line.is_empty() || line.starts_with('#') {
103✔
274
        None
1✔
275
    } else {
276
        Some(line.to_owned())
102✔
277
    }
278
}
103✔
279

280
/// If an ESM has a master that is lower down in the load order, the master will
281
/// be loaded directly before the ESM instead of in its usual position. This
282
/// function "hoists" such masters further up the load order to match that
283
/// behaviour.
284
pub fn hoist_masters(plugins: &mut Vec<Plugin>) -> Result<(), Error> {
56✔
285
    // Store plugins' current positions and where they need to move to.
56✔
286
    // Use a BTreeMap so that if a plugin needs to move for more than one ESM,
56✔
287
    // it will move for the earlier one and so also satisfy the later one, and
56✔
288
    // so that it's possible to iterate over content in order.
56✔
289
    let mut from_to_map: BTreeMap<usize, usize> = BTreeMap::new();
56✔
290

291
    for (index, plugin) in plugins.iter().enumerate() {
312✔
292
        if !plugin.is_master_file() {
312✔
293
            continue;
195✔
294
        }
117✔
295

296
        for master in plugin.masters()? {
117✔
297
            let pos = plugins
7✔
298
                .iter()
7✔
299
                .position(|p| {
25✔
300
                    p.name_matches(&master)
25✔
301
                        && (plugin.is_blueprint_master() || !p.is_blueprint_master())
7✔
302
                })
25✔
303
                .unwrap_or(0);
7✔
304
            if pos > index {
7✔
305
                // Need to move the plugin to index, but can't do that while
4✔
306
                // iterating, so store it for later.
4✔
307
                from_to_map.entry(pos).or_insert(index);
4✔
308
            }
4✔
309
        }
310
    }
311

312
    move_elements(plugins, from_to_map);
56✔
313

56✔
314
    Ok(())
56✔
315
}
56✔
316

317
fn validate_early_loader_positions(
21✔
318
    plugins: &[Plugin],
21✔
319
    early_loading_plugins: &[String],
21✔
320
) -> Result<(), Error> {
21✔
321
    // Check that all early loading plugins that are present load in
21✔
322
    // their hardcoded order.
21✔
323
    let mut missing_plugins_count = 0;
21✔
324
    for (i, plugin_name) in early_loading_plugins.iter().enumerate() {
21✔
325
        match plugins.iter().position(|p| eq(p.name(), plugin_name)) {
53✔
326
            Some(pos) => {
5✔
327
                let expected_pos = i - missing_plugins_count;
5✔
328
                if pos != expected_pos {
5✔
329
                    return Err(Error::InvalidEarlyLoadingPluginPosition {
1✔
330
                        name: plugin_name.clone(),
1✔
331
                        pos,
1✔
332
                        expected_pos,
1✔
333
                    });
1✔
334
                }
4✔
335
            }
336
            None => missing_plugins_count += 1,
7✔
337
        }
338
    }
339

340
    Ok(())
20✔
341
}
21✔
342

343
fn generic_insert_position(plugins: &[Plugin], plugin: &Plugin) -> Option<usize> {
19,612✔
344
    let is_master_of = |p: &Plugin| {
43,422,419✔
345
        p.masters()
43,422,419✔
346
            .map(|masters| masters.iter().any(|m| plugin.name_matches(m)))
43,422,419✔
347
            .unwrap_or(false)
43,422,419✔
348
    };
43,422,419✔
349

350
    if plugin.is_blueprint_master() {
19,612✔
351
        // Blueprint plugins load after all other plugins unless they are
352
        // hoisted by another blueprint plugin.
353
        return plugins
4✔
354
            .iter()
4✔
355
            .position(|p| p.is_blueprint_master() && is_master_of(p));
11✔
356
    }
19,608✔
357

19,608✔
358
    // Check that there isn't a master that would hoist this plugin.
19,608✔
359
    let hoisted_index = plugins
19,608✔
360
        .iter()
19,608✔
361
        .position(|p| p.is_master_file() && is_master_of(p));
43,442,887✔
362

19,608✔
363
    hoisted_index.or_else(|| {
19,608✔
364
        if plugin.is_master_file() {
19,602✔
365
            find_first_non_master_position(plugins)
19,474✔
366
        } else {
367
            None
128✔
368
        }
369
    })
19,608✔
370
}
19,612✔
371

372
fn find_plugins_in_dirs(directories: &[PathBuf], game: GameId) -> Vec<String> {
56✔
373
    let mut dir_entries: Vec<_> = directories
56✔
374
        .iter()
56✔
375
        .flat_map(read_dir)
56✔
376
        .flatten()
56✔
377
        .filter_map(Result::ok)
56✔
378
        .filter(|e| e.file_type().map(|f| f.is_file()).unwrap_or(false))
321✔
379
        .filter(|e| {
321✔
380
            e.file_name()
321✔
381
                .to_str()
321✔
382
                .map(|f| has_plugin_extension(f, game))
321✔
383
                .unwrap_or(false)
321✔
384
        })
321✔
385
        .collect();
56✔
386

56✔
387
    // Sort by file modification timestamps, in ascending order. If two timestamps are equal, sort
56✔
388
    // by filenames (in ascending order for Starfield, descending otherwise).
56✔
389
    dir_entries.sort_unstable_by(|e1, e2| {
665✔
390
        let m1 = e1.metadata().and_then(|m| m.modified()).ok();
665✔
391
        let m2 = e2.metadata().and_then(|m| m.modified()).ok();
665✔
392

665✔
393
        match m1.cmp(&m2) {
665✔
394
            Ordering::Equal if game == GameId::Starfield => e1.file_name().cmp(&e2.file_name()),
22✔
395
            Ordering::Equal => e1.file_name().cmp(&e2.file_name()).reverse(),
8✔
396
            x => x,
643✔
397
        }
398
    });
665✔
399

56✔
400
    let mut set = HashSet::new();
56✔
401

56✔
402
    dir_entries
56✔
403
        .into_iter()
56✔
404
        .filter_map(|e| e.file_name().to_str().map(str::to_owned))
321✔
405
        .filter(|filename| set.insert(UniCase::new(trim_dot_ghost(filename).to_string())))
321✔
406
        .collect()
56✔
407
}
56✔
408

409
fn to_plugin(
51✔
410
    plugin_name: &str,
51✔
411
    existing_plugins: &[Plugin],
51✔
412
    game_settings: &GameSettings,
51✔
413
) -> Result<Plugin, Error> {
51✔
414
    existing_plugins
51✔
415
        .par_iter()
51✔
416
        .find_any(|p| p.name_matches(plugin_name))
134✔
417
        .map_or_else(
51✔
418
            || Plugin::new(plugin_name, game_settings),
51✔
419
            |p| Ok(p.clone()),
51✔
420
        )
51✔
421
}
51✔
422

423
fn validate_blueprint_plugin_index(
6✔
424
    plugins: &[Plugin],
6✔
425
    plugin: &Plugin,
6✔
426
    index: usize,
6✔
427
) -> Result<(), Error> {
6✔
428
    // Blueprint plugins should only appear before other blueprint plugins, as
429
    // they get moved after all non-blueprint plugins before conflicts are
430
    // resolved and don't get hoisted by non-blueprint plugins. However, they
431
    // do get hoisted by other blueprint plugins.
432
    let preceding_plugins = if index < plugins.len() {
6✔
433
        &plugins[..index]
2✔
434
    } else {
435
        plugins
4✔
436
    };
437

438
    // Check that none of the preceding blueprint plugins have this plugin as a
439
    // master.
440
    for preceding_plugin in preceding_plugins {
18✔
441
        if !preceding_plugin.is_blueprint_master() {
13✔
442
            continue;
12✔
443
        }
1✔
444

445
        let preceding_masters = preceding_plugin.masters()?;
1✔
446
        if preceding_masters
1✔
447
            .iter()
1✔
448
            .any(|m| eq(m.as_str(), plugin.name()))
1✔
449
        {
450
            return Err(Error::UnrepresentedHoist {
1✔
451
                plugin: plugin.name().to_string(),
1✔
452
                master: preceding_plugin.name().to_string(),
1✔
453
            });
1✔
454
        }
×
455
    }
456

457
    let following_plugins = if index < plugins.len() {
5✔
458
        &plugins[index..]
2✔
459
    } else {
460
        &[]
3✔
461
    };
462

463
    // Check that all of the following plugins are blueprint plugins.
464
    let last_non_blueprint_pos = following_plugins
5✔
465
        .iter()
5✔
466
        .rposition(|p| !p.is_blueprint_master())
5✔
467
        .map(|i| index + i);
5✔
468

5✔
469
    match last_non_blueprint_pos {
5✔
470
        Some(i) => Err(Error::InvalidBlueprintPluginPosition {
1✔
471
            name: plugin.name().to_string(),
1✔
472
            pos: index,
1✔
473
            expected_pos: i + 1,
1✔
474
        }),
1✔
475
        _ => Ok(()),
4✔
476
    }
477
}
6✔
478

479
fn validate_master_file_index(
25✔
480
    plugins: &[Plugin],
25✔
481
    plugin: &Plugin,
25✔
482
    index: usize,
25✔
483
) -> Result<(), Error> {
25✔
484
    let preceding_plugins = if index < plugins.len() {
25✔
485
        &plugins[..index]
23✔
486
    } else {
487
        plugins
2✔
488
    };
489

490
    // Check that none of the preceding plugins have this plugin as a master.
491
    for preceding_plugin in preceding_plugins {
58✔
492
        let preceding_masters = preceding_plugin.masters()?;
35✔
493
        if preceding_masters
35✔
494
            .iter()
35✔
495
            .any(|m| eq(m.as_str(), plugin.name()))
35✔
496
        {
497
            return Err(Error::UnrepresentedHoist {
2✔
498
                plugin: plugin.name().to_string(),
2✔
499
                master: preceding_plugin.name().to_string(),
2✔
500
            });
2✔
501
        }
33✔
502
    }
503

504
    let previous_master_pos = preceding_plugins
23✔
505
        .iter()
23✔
506
        .rposition(|p| p.is_master_file())
29✔
507
        .unwrap_or(0);
23✔
508

509
    let masters = plugin.masters()?;
23✔
510
    let master_names: HashSet<_> = masters.iter().map(|m| UniCase::new(m.as_str())).collect();
23✔
511

512
    // Check that all of the plugins that load between this index and
513
    // the previous plugin are masters of this plugin.
514
    if let Some(n) = preceding_plugins
23✔
515
        .iter()
23✔
516
        .skip(previous_master_pos + 1)
23✔
517
        .find(|p| !master_names.contains(&UniCase::new(p.name())))
23✔
518
    {
519
        return Err(Error::NonMasterBeforeMaster {
3✔
520
            master: plugin.name().to_string(),
3✔
521
            non_master: n.name().to_string(),
3✔
522
        });
3✔
523
    }
20✔
524

525
    // Check that none of the plugins that load after index are
526
    // masters of this plugin.
527
    if let Some(p) = plugins
20✔
528
        .iter()
20✔
529
        .skip(index)
20✔
530
        .find(|p| master_names.contains(&UniCase::new(p.name())))
40✔
531
    {
532
        Err(Error::UnrepresentedHoist {
3✔
533
            plugin: p.name().to_string(),
3✔
534
            master: plugin.name().to_string(),
3✔
535
        })
3✔
536
    } else {
537
        Ok(())
17✔
538
    }
539
}
25✔
540

541
fn validate_non_master_file_index(
16✔
542
    plugins: &[Plugin],
16✔
543
    plugin: &Plugin,
16✔
544
    index: usize,
16✔
545
) -> Result<(), Error> {
16✔
546
    // Check that there aren't any earlier master files that have this
547
    // plugin as a master.
548
    for master_file in plugins.iter().take(index).filter(|p| p.is_master_file()) {
23✔
549
        if master_file
13✔
550
            .masters()?
13✔
551
            .iter()
13✔
552
            .any(|m| plugin.name_matches(m))
13✔
553
        {
UNCOV
554
            return Err(Error::UnrepresentedHoist {
×
UNCOV
555
                plugin: plugin.name().to_string(),
×
UNCOV
556
                master: master_file.name().to_string(),
×
UNCOV
557
            });
×
558
        }
13✔
559
    }
560

561
    // Check that the next master file has this plugin as a master.
562
    let next_master = match plugins.iter().skip(index).find(|p| p.is_master_file()) {
18✔
563
        None => return Ok(()),
9✔
564
        Some(p) => p,
7✔
565
    };
7✔
566

7✔
567
    if next_master
7✔
568
        .masters()?
7✔
569
        .iter()
7✔
570
        .any(|m| plugin.name_matches(m))
7✔
571
    {
572
        Ok(())
4✔
573
    } else {
574
        Err(Error::NonMasterBeforeMaster {
3✔
575
            master: next_master.name().to_string(),
3✔
576
            non_master: plugin.name().to_string(),
3✔
577
        })
3✔
578
    }
579
}
16✔
580

581
fn map_to_plugins<T: ReadableLoadOrderBase + Sync + ?Sized>(
11✔
582
    load_order: &T,
11✔
583
    plugin_names: &[&str],
11✔
584
) -> Result<Vec<Plugin>, Error> {
11✔
585
    plugin_names
11✔
586
        .par_iter()
11✔
587
        .map(|n| to_plugin(n, load_order.plugins(), load_order.game_settings_base()))
51✔
588
        .collect()
11✔
589
}
11✔
590

591
fn insert<T: MutableLoadOrder + ?Sized>(load_order: &mut T, plugin: Plugin) -> usize {
207✔
592
    match load_order.insert_position(&plugin) {
207✔
593
        Some(position) => {
36✔
594
            load_order.plugins_mut().insert(position, plugin);
36✔
595
            position
36✔
596
        }
597
        None => {
598
            load_order.plugins_mut().push(plugin);
171✔
599
            load_order.plugins().len() - 1
171✔
600
        }
601
    }
602
}
207✔
603

604
fn move_elements<T>(vec: &mut Vec<T>, mut from_to_indices: BTreeMap<usize, usize>) {
57✔
605
    // Move elements around. Moving elements doesn't change from_index values,
606
    // as we're iterating from earliest index to latest, but to_index values can
607
    // become incorrect, e.g. (5, 2), (6, 3), (7, 1) will insert an element
608
    // before index 3 so that should become 4, but 1 is still correct.
609
    // Keeping track of what indices need offsets is probably not worth it as
610
    // this function is likely to be called with empty or very small maps, so
611
    // just loop through it after each move and increment any affected to_index
612
    // values.
613
    while let Some((from_index, to_index)) = from_to_indices.pop_first() {
64✔
614
        let element = vec.remove(from_index);
7✔
615
        vec.insert(to_index, element);
7✔
616

617
        for value in from_to_indices.values_mut() {
7✔
618
            if *value < from_index && *value > to_index {
4✔
619
                *value += 1;
1✔
620
            }
3✔
621
        }
622
    }
623
}
57✔
624

625
fn get_plugin_to_insert_at<T: MutableLoadOrder + ?Sized>(
19✔
626
    load_order: &mut T,
19✔
627
    plugin_name: &str,
19✔
628
    insert_position: usize,
19✔
629
) -> Result<Plugin, Error> {
19✔
630
    if let Some(p) = load_order.index_of(plugin_name) {
19✔
631
        let plugin = &load_order.plugins()[p];
10✔
632
        load_order.validate_index(plugin, insert_position)?;
10✔
633

634
        Ok(load_order.plugins_mut().remove(p))
6✔
635
    } else {
636
        let plugin = Plugin::new(plugin_name, load_order.game_settings())?;
9✔
637

638
        load_order.validate_index(&plugin, insert_position)?;
8✔
639

640
        Ok(plugin)
5✔
641
    }
642
}
19✔
643

644
fn validate_load_order(plugins: &[Plugin], early_loading_plugins: &[String]) -> Result<(), Error> {
21✔
645
    validate_early_loader_positions(plugins, early_loading_plugins)?;
21✔
646

647
    validate_no_unhoisted_non_masters_before_masters(plugins)?;
20✔
648

649
    validate_no_non_blueprint_plugins_after_blueprint_plugins(plugins)?;
18✔
650

651
    validate_plugins_load_before_their_masters(plugins)?;
17✔
652

653
    Ok(())
14✔
654
}
21✔
655

656
fn validate_no_unhoisted_non_masters_before_masters(plugins: &[Plugin]) -> Result<(), Error> {
20✔
657
    let first_non_master_pos = match find_first_non_master_position(plugins) {
20✔
658
        None => plugins.len(),
3✔
659
        Some(x) => x,
17✔
660
    };
661

662
    // Ignore blueprint plugins because they load after non-masters.
663
    let last_master_pos = match plugins
20✔
664
        .iter()
20✔
665
        .rposition(|p| p.is_master_file() && !p.is_blueprint_master())
54✔
666
    {
667
        None => return Ok(()),
1✔
668
        Some(x) => x,
19✔
669
    };
19✔
670

19✔
671
    let mut plugin_names: HashSet<_> = HashSet::new();
19✔
672

19✔
673
    // Add each plugin that isn't a master file to the hashset.
19✔
674
    // When a master file is encountered, remove its masters from the hashset.
19✔
675
    // If there are any plugins left in the hashset, they weren't hoisted there,
19✔
676
    // so fail the check.
19✔
677
    if first_non_master_pos < last_master_pos {
19✔
678
        for plugin in plugins
11✔
679
            .iter()
5✔
680
            .skip(first_non_master_pos)
5✔
681
            .take(last_master_pos - first_non_master_pos + 1)
5✔
682
        {
683
            if !plugin.is_master_file() {
11✔
684
                plugin_names.insert(UniCase::new(plugin.name().to_string()));
5✔
685
            } else {
5✔
686
                for master in plugin.masters()? {
6✔
687
                    plugin_names.remove(&UniCase::new(master.clone()));
3✔
688
                }
3✔
689

690
                if let Some(n) = plugin_names.iter().next() {
6✔
691
                    return Err(Error::NonMasterBeforeMaster {
2✔
692
                        master: plugin.name().to_string(),
2✔
693
                        non_master: n.to_string(),
2✔
694
                    });
2✔
695
                }
4✔
696
            }
697
        }
698
    }
14✔
699

700
    Ok(())
17✔
701
}
20✔
702

703
fn validate_no_non_blueprint_plugins_after_blueprint_plugins(
18✔
704
    plugins: &[Plugin],
18✔
705
) -> Result<(), Error> {
18✔
706
    let first_blueprint_plugin = plugins
18✔
707
        .iter()
18✔
708
        .enumerate()
18✔
709
        .find(|(_, p)| p.is_blueprint_master());
66✔
710

711
    if let Some((first_blueprint_pos, first_blueprint_plugin)) = first_blueprint_plugin {
18✔
712
        let last_non_blueprint_pos = plugins.iter().rposition(|p| !p.is_blueprint_master());
8✔
713

714
        if let Some(last_non_blueprint_pos) = last_non_blueprint_pos {
4✔
715
            if last_non_blueprint_pos > first_blueprint_pos {
4✔
716
                return Err(Error::InvalidBlueprintPluginPosition {
1✔
717
                    name: first_blueprint_plugin.name().to_string(),
1✔
718
                    pos: first_blueprint_pos,
1✔
719
                    expected_pos: last_non_blueprint_pos,
1✔
720
                });
1✔
721
            }
3✔
NEW
722
        }
×
723
    }
14✔
724

725
    Ok(())
17✔
726
}
18✔
727

728
fn validate_plugins_load_before_their_masters(plugins: &[Plugin]) -> Result<(), Error> {
17✔
729
    let mut plugins_map: HashMap<UniCase<String>, &Plugin> = HashMap::new();
17✔
730

731
    for plugin in plugins.iter().rev() {
62✔
732
        if plugin.is_master_file() {
62✔
733
            if let Some(m) = plugin
31✔
734
                .masters()?
31✔
735
                .iter()
31✔
736
                .find_map(|m| plugins_map.get(&UniCase::new(m.to_string())))
31✔
737
            {
738
                // Don't error if a non-blueprint plugin depends on a blueprint plugin.
739
                if plugin.is_blueprint_master() || !m.is_blueprint_master() {
4✔
740
                    return Err(Error::UnrepresentedHoist {
3✔
741
                        plugin: m.name().to_string(),
3✔
742
                        master: plugin.name().to_string(),
3✔
743
                    });
3✔
744
                }
1✔
745
            }
27✔
746
        }
31✔
747

748
        plugins_map.insert(UniCase::new(plugin.name().to_string()), plugin);
59✔
749
    }
750

751
    Ok(())
14✔
752
}
17✔
753

754
fn remove_duplicates_icase(
36✔
755
    plugin_tuples: Vec<(String, bool)>,
36✔
756
    filenames: Vec<String>,
36✔
757
) -> Vec<(String, bool)> {
36✔
758
    let mut set: HashSet<_> = HashSet::with_capacity(filenames.len());
36✔
759

36✔
760
    let mut unique_tuples: Vec<(String, bool)> = plugin_tuples
36✔
761
        .into_iter()
36✔
762
        .rev()
36✔
763
        .filter(|(string, _)| set.insert(UniCase::new(trim_dot_ghost(string).to_string())))
67✔
764
        .collect();
36✔
765

36✔
766
    unique_tuples.reverse();
36✔
767

36✔
768
    let unique_file_tuples_iter = filenames
36✔
769
        .into_iter()
36✔
770
        .filter(|string| set.insert(UniCase::new(trim_dot_ghost(string).to_string())))
211✔
771
        .map(|f| (f, false));
150✔
772

36✔
773
    unique_tuples.extend(unique_file_tuples_iter);
36✔
774

36✔
775
    unique_tuples
36✔
776
}
36✔
777

778
fn activate_unvalidated<T: MutableLoadOrder + ?Sized>(
141✔
779
    load_order: &mut T,
141✔
780
    filename: &str,
141✔
781
) -> Result<(), Error> {
141✔
782
    if let Some(plugin) = load_order
141✔
783
        .plugins_mut()
141✔
784
        .iter_mut()
141✔
785
        .find(|p| p.name_matches(filename))
633✔
786
    {
787
        plugin.activate()
38✔
788
    } else {
789
        // Ignore any errors trying to load the plugin to save checking if it's
790
        // valid and then loading it if it is.
791
        Plugin::with_active(filename, load_order.game_settings(), true)
103✔
792
            .map(|plugin| {
103✔
UNCOV
793
                insert(load_order, plugin);
×
794
            })
103✔
795
            .or(Ok(()))
103✔
796
    }
797
}
141✔
798

799
fn find_first_non_master_position(plugins: &[Plugin]) -> Option<usize> {
19,496✔
800
    plugins.iter().position(|p| !p.is_master_file())
43,441,149✔
801
}
19,496✔
802

803
#[cfg(test)]
804
mod tests {
805
    use super::*;
806

807
    use crate::enums::GameId;
808
    use crate::game_settings::GameSettings;
809
    use crate::load_order::tests::*;
810
    use crate::load_order::writable::create_parent_dirs;
811
    use crate::tests::copy_to_test_dir;
812

813
    use tempfile::tempdir;
814

815
    struct TestLoadOrder {
816
        game_settings: GameSettings,
817
        plugins: Vec<Plugin>,
818
    }
819

820
    impl ReadableLoadOrderBase for TestLoadOrder {
821
        fn game_settings_base(&self) -> &GameSettings {
227✔
822
            &self.game_settings
227✔
823
        }
227✔
824

825
        fn plugins(&self) -> &[Plugin] {
272✔
826
            &self.plugins
272✔
827
        }
272✔
828
    }
829

830
    impl MutableLoadOrder for TestLoadOrder {
831
        fn plugins_mut(&mut self) -> &mut Vec<Plugin> {
28✔
832
            &mut self.plugins
28✔
833
        }
28✔
834
    }
835

836
    fn prepare(game_id: GameId, game_path: &Path) -> TestLoadOrder {
69✔
837
        let (game_settings, plugins) = mock_game_files(game_id, game_path);
69✔
838

69✔
839
        TestLoadOrder {
69✔
840
            game_settings,
69✔
841
            plugins,
69✔
842
        }
69✔
843
    }
69✔
844

845
    fn prepare_hoisted(game_id: GameId, game_path: &Path) -> TestLoadOrder {
11✔
846
        let load_order = prepare(game_id, game_path);
11✔
847

11✔
848
        let plugins_dir = &load_order.game_settings().plugins_directory();
11✔
849
        copy_to_test_dir(
11✔
850
            "Blank - Different.esm",
11✔
851
            "Blank - Different.esm",
11✔
852
            load_order.game_settings(),
11✔
853
        );
11✔
854
        set_master_flag(game_id, &plugins_dir.join("Blank - Different.esm"), false).unwrap();
11✔
855
        copy_to_test_dir(
11✔
856
            "Blank - Different Master Dependent.esm",
11✔
857
            "Blank - Different Master Dependent.esm",
11✔
858
            load_order.game_settings(),
11✔
859
        );
11✔
860

11✔
861
        load_order
11✔
862
    }
11✔
863

864
    fn prepare_plugins(game_path: &Path, blank_esp_source: &str) -> Vec<Plugin> {
2✔
865
        let settings = game_settings_for_test(GameId::SkyrimSE, game_path);
2✔
866

2✔
867
        copy_to_test_dir("Blank.esm", settings.master_file(), &settings);
2✔
868
        copy_to_test_dir(blank_esp_source, "Blank.esp", &settings);
2✔
869

2✔
870
        vec![
2✔
871
            Plugin::new(settings.master_file(), &settings).unwrap(),
2✔
872
            Plugin::new("Blank.esp", &settings).unwrap(),
2✔
873
        ]
2✔
874
    }
2✔
875

876
    #[test]
877
    fn insert_position_should_return_zero_if_given_the_game_master_plugin() {
1✔
878
        let tmp_dir = tempdir().unwrap();
1✔
879
        let load_order = prepare(GameId::Skyrim, &tmp_dir.path());
1✔
880

1✔
881
        let plugin = Plugin::new("Skyrim.esm", &load_order.game_settings()).unwrap();
1✔
882
        let position = load_order.insert_position(&plugin);
1✔
883

1✔
884
        assert_eq!(0, position.unwrap());
1✔
885
    }
1✔
886

887
    #[test]
888
    fn insert_position_should_return_none_for_the_game_master_if_no_plugins_are_loaded() {
1✔
889
        let tmp_dir = tempdir().unwrap();
1✔
890
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
891

1✔
892
        load_order.plugins_mut().clear();
1✔
893

1✔
894
        let plugin = Plugin::new("Skyrim.esm", &load_order.game_settings()).unwrap();
1✔
895
        let position = load_order.insert_position(&plugin);
1✔
896

1✔
897
        assert!(position.is_none());
1✔
898
    }
1✔
899

900
    #[test]
901
    fn insert_position_should_return_the_hardcoded_index_of_an_early_loading_plugin() {
1✔
902
        let tmp_dir = tempdir().unwrap();
1✔
903
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
904

1✔
905
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
906
        load_order.plugins_mut().insert(1, plugin);
1✔
907

1✔
908
        copy_to_test_dir("Blank.esm", "HearthFires.esm", &load_order.game_settings());
1✔
909
        let plugin = Plugin::new("HearthFires.esm", &load_order.game_settings()).unwrap();
1✔
910
        let position = load_order.insert_position(&plugin);
1✔
911

1✔
912
        assert_eq!(1, position.unwrap());
1✔
913
    }
1✔
914

915
    #[test]
916
    fn insert_position_should_not_treat_all_implicitly_active_plugins_as_early_loading_plugins() {
1✔
917
        let tmp_dir = tempdir().unwrap();
1✔
918

1✔
919
        let ini_path = tmp_dir.path().join("my games/Skyrim.ini");
1✔
920
        create_parent_dirs(&ini_path).unwrap();
1✔
921
        std::fs::write(&ini_path, "[General]\nsTestFile1=Blank.esm").unwrap();
1✔
922

1✔
923
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
924

1✔
925
        copy_to_test_dir(
1✔
926
            "Blank.esm",
1✔
927
            "Blank - Different.esm",
1✔
928
            &load_order.game_settings(),
1✔
929
        );
1✔
930
        let plugin = Plugin::new("Blank - Different.esm", &load_order.game_settings()).unwrap();
1✔
931
        load_order.plugins_mut().insert(1, plugin);
1✔
932

1✔
933
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
934
        let position = load_order.insert_position(&plugin);
1✔
935

1✔
936
        assert_eq!(2, position.unwrap());
1✔
937
    }
1✔
938

939
    #[test]
940
    fn insert_position_should_not_count_installed_unloaded_early_loading_plugins() {
1✔
941
        let tmp_dir = tempdir().unwrap();
1✔
942
        let load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
943

1✔
944
        copy_to_test_dir("Blank.esm", "Update.esm", &load_order.game_settings());
1✔
945
        copy_to_test_dir("Blank.esm", "HearthFires.esm", &load_order.game_settings());
1✔
946
        let plugin = Plugin::new("HearthFires.esm", &load_order.game_settings()).unwrap();
1✔
947
        let position = load_order.insert_position(&plugin);
1✔
948

1✔
949
        assert_eq!(1, position.unwrap());
1✔
950
    }
1✔
951

952
    #[test]
953
    fn insert_position_should_not_put_blueprint_plugins_before_non_blueprint_dependents() {
1✔
954
        let tmp_dir = tempdir().unwrap();
1✔
955
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
956

1✔
957
        let dependent_plugin = "Blank - Override.full.esm";
1✔
958
        copy_to_test_dir(
1✔
959
            dependent_plugin,
1✔
960
            dependent_plugin,
1✔
961
            &load_order.game_settings(),
1✔
962
        );
1✔
963

1✔
964
        let plugin = Plugin::new(dependent_plugin, &load_order.game_settings()).unwrap();
1✔
965
        load_order.plugins.insert(1, plugin);
1✔
966

1✔
967
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
968

1✔
969
        let plugin_name = "Blank.full.esm";
1✔
970
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
971

1✔
972
        let plugin = Plugin::new(plugin_name, &load_order.game_settings()).unwrap();
1✔
973
        let position = load_order.insert_position(&plugin);
1✔
974

1✔
975
        assert!(position.is_none());
1✔
976
    }
1✔
977

978
    #[test]
979
    fn insert_position_should_put_blueprint_plugins_before_blueprint_dependents() {
1✔
980
        let tmp_dir = tempdir().unwrap();
1✔
981
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
982

1✔
983
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
984

1✔
985
        let dependent_plugin = "Blank - Override.full.esm";
1✔
986
        copy_to_test_dir(
1✔
987
            dependent_plugin,
1✔
988
            dependent_plugin,
1✔
989
            &load_order.game_settings(),
1✔
990
        );
1✔
991
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
992

1✔
993
        let plugin = Plugin::new(dependent_plugin, &load_order.game_settings()).unwrap();
1✔
994
        load_order.plugins.push(plugin);
1✔
995

1✔
996
        let plugin_name = "Blank.full.esm";
1✔
997
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
998

1✔
999
        let plugin = Plugin::new(plugin_name, &load_order.game_settings()).unwrap();
1✔
1000
        let position = load_order.insert_position(&plugin);
1✔
1001

1✔
1002
        assert_eq!(2, position.unwrap());
1✔
1003
    }
1✔
1004

1005
    #[test]
1006
    fn insert_position_should_not_treat_early_loading_blueprint_plugins_as_early_loading() {
1✔
1007
        let tmp_dir = tempdir().unwrap();
1✔
1008
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1009

1✔
1010
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1011

1✔
1012
        let plugin_name = "Blank.full.esm";
1✔
1013
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1014

1✔
1015
        std::fs::write(
1✔
1016
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
1017
            plugin_name,
1✔
1018
        )
1✔
1019
        .unwrap();
1✔
1020
        load_order
1✔
1021
            .game_settings
1✔
1022
            .refresh_implicitly_active_plugins()
1✔
1023
            .unwrap();
1✔
1024

1✔
1025
        let plugin = Plugin::new(plugin_name, &load_order.game_settings()).unwrap();
1✔
1026
        let position = load_order.insert_position(&plugin);
1✔
1027

1✔
1028
        assert!(position.is_none());
1✔
1029
    }
1✔
1030

1031
    #[test]
1032
    fn insert_position_should_return_none_if_given_a_non_master_plugin() {
1✔
1033
        let tmp_dir = tempdir().unwrap();
1✔
1034
        let load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1035

1✔
1036
        let plugin =
1✔
1037
            Plugin::new("Blank - Master Dependent.esp", &load_order.game_settings()).unwrap();
1✔
1038
        let position = load_order.insert_position(&plugin);
1✔
1039

1✔
1040
        assert_eq!(None, position);
1✔
1041
    }
1✔
1042

1043
    #[test]
1044
    fn insert_position_should_return_the_first_non_master_plugin_index_if_given_a_master_plugin() {
1✔
1045
        let tmp_dir = tempdir().unwrap();
1✔
1046
        let load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1047

1✔
1048
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
1049
        let position = load_order.insert_position(&plugin);
1✔
1050

1✔
1051
        assert_eq!(1, position.unwrap());
1✔
1052
    }
1✔
1053

1054
    #[test]
1055
    fn insert_position_should_return_none_if_no_non_masters_are_present() {
1✔
1056
        let tmp_dir = tempdir().unwrap();
1✔
1057
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1058

1✔
1059
        // Remove non-master plugins from the load order.
1✔
1060
        load_order.plugins_mut().retain(|p| p.is_master_file());
3✔
1061

1✔
1062
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
1063
        let position = load_order.insert_position(&plugin);
1✔
1064

1✔
1065
        assert_eq!(None, position);
1✔
1066
    }
1✔
1067

1068
    #[test]
1069
    fn insert_position_should_return_the_first_non_master_index_if_given_a_light_master() {
1✔
1070
        let tmp_dir = tempdir().unwrap();
1✔
1071
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1072

1✔
1073
        copy_to_test_dir("Blank.esm", "Blank.esl", load_order.game_settings());
1✔
1074
        let plugin = Plugin::new("Blank.esl", &load_order.game_settings()).unwrap();
1✔
1075

1✔
1076
        load_order.plugins_mut().insert(1, plugin);
1✔
1077

1✔
1078
        let position = load_order.insert_position(&load_order.plugins()[1]);
1✔
1079

1✔
1080
        assert_eq!(2, position.unwrap());
1✔
1081

1082
        copy_to_test_dir(
1✔
1083
            "Blank.esp",
1✔
1084
            "Blank - Different.esl",
1✔
1085
            load_order.game_settings(),
1✔
1086
        );
1✔
1087
        let plugin = Plugin::new("Blank - Different.esl", &load_order.game_settings()).unwrap();
1✔
1088

1✔
1089
        let position = load_order.insert_position(&plugin);
1✔
1090

1✔
1091
        assert_eq!(2, position.unwrap());
1✔
1092
    }
1✔
1093

1094
    #[test]
1095
    fn insert_position_should_succeed_for_a_non_master_hoisted_after_another_non_master() {
1✔
1096
        let tmp_dir = tempdir().unwrap();
1✔
1097
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1098

1✔
1099
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1100

1✔
1101
        let plugin = Plugin::new(
1✔
1102
            "Blank - Different Master Dependent.esm",
1✔
1103
            load_order.game_settings(),
1✔
1104
        )
1✔
1105
        .unwrap();
1✔
1106
        load_order.plugins.insert(1, plugin);
1✔
1107

1✔
1108
        let other_non_master = "Blank.esm";
1✔
1109
        set_master_flag(GameId::Oblivion, &plugins_dir.join(other_non_master), false).unwrap();
1✔
1110
        let plugin = Plugin::new(other_non_master, load_order.game_settings()).unwrap();
1✔
1111
        load_order.plugins.insert(1, plugin);
1✔
1112

1✔
1113
        let other_master = "Blank - Master Dependent.esm";
1✔
1114
        copy_to_test_dir(other_master, other_master, load_order.game_settings());
1✔
1115
        let plugin = Plugin::new(other_master, load_order.game_settings()).unwrap();
1✔
1116
        load_order.plugins.insert(2, plugin);
1✔
1117

1✔
1118
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1119

1✔
1120
        let position = load_order.insert_position(&plugin);
1✔
1121

1✔
1122
        assert_eq!(3, position.unwrap());
1✔
1123
    }
1✔
1124

1125
    #[test]
1126
    fn validate_index_should_succeed_for_a_master_plugin_and_index_directly_after_a_master() {
1✔
1127
        let tmp_dir = tempdir().unwrap();
1✔
1128
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1129

1✔
1130
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1131
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1132
    }
1✔
1133

1134
    #[test]
1135
    fn validate_index_should_succeed_for_a_master_plugin_and_index_after_a_hoisted_non_master() {
1✔
1136
        let tmp_dir = tempdir().unwrap();
1✔
1137
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1138

1✔
1139
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1140
        load_order.plugins.insert(1, plugin);
1✔
1141

1✔
1142
        let plugin = Plugin::new(
1✔
1143
            "Blank - Different Master Dependent.esm",
1✔
1144
            load_order.game_settings(),
1✔
1145
        )
1✔
1146
        .unwrap();
1✔
1147
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1148
    }
1✔
1149

1150
    #[test]
1151
    fn validate_index_should_error_for_a_master_plugin_and_index_after_unrelated_non_masters() {
1✔
1152
        let tmp_dir = tempdir().unwrap();
1✔
1153
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1154

1✔
1155
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1156
        load_order.plugins.insert(1, plugin);
1✔
1157

1✔
1158
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1159
        assert!(load_order.validate_index(&plugin, 4).is_err());
1✔
1160
    }
1✔
1161

1162
    #[test]
1163
    fn validate_index_should_error_for_a_master_plugin_that_has_a_later_non_master_as_a_master() {
1✔
1164
        let tmp_dir = tempdir().unwrap();
1✔
1165
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1166

1✔
1167
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1168
        load_order.plugins.insert(2, plugin);
1✔
1169

1✔
1170
        let plugin = Plugin::new(
1✔
1171
            "Blank - Different Master Dependent.esm",
1✔
1172
            load_order.game_settings(),
1✔
1173
        )
1✔
1174
        .unwrap();
1✔
1175
        assert!(load_order.validate_index(&plugin, 1).is_err());
1✔
1176
    }
1✔
1177

1178
    #[test]
1179
    fn validate_index_should_error_for_a_master_plugin_that_has_a_later_master_as_a_master() {
1✔
1180
        let tmp_dir = tempdir().unwrap();
1✔
1181
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1182

1✔
1183
        copy_to_test_dir(
1✔
1184
            "Blank - Master Dependent.esm",
1✔
1185
            "Blank - Master Dependent.esm",
1✔
1186
            load_order.game_settings(),
1✔
1187
        );
1✔
1188
        copy_to_test_dir("Blank.esm", "Blank.esm", load_order.game_settings());
1✔
1189

1✔
1190
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1191
        load_order.plugins.insert(1, plugin);
1✔
1192

1✔
1193
        let plugin =
1✔
1194
            Plugin::new("Blank - Master Dependent.esm", load_order.game_settings()).unwrap();
1✔
1195
        assert!(load_order.validate_index(&plugin, 1).is_err());
1✔
1196
    }
1✔
1197

1198
    #[test]
1199
    fn validate_index_should_error_for_a_master_plugin_that_is_a_master_of_an_earlier_master() {
1✔
1200
        let tmp_dir = tempdir().unwrap();
1✔
1201
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1202

1✔
1203
        copy_to_test_dir(
1✔
1204
            "Blank - Master Dependent.esm",
1✔
1205
            "Blank - Master Dependent.esm",
1✔
1206
            load_order.game_settings(),
1✔
1207
        );
1✔
1208
        copy_to_test_dir("Blank.esm", "Blank.esm", load_order.game_settings());
1✔
1209

1✔
1210
        let plugin =
1✔
1211
            Plugin::new("Blank - Master Dependent.esm", load_order.game_settings()).unwrap();
1✔
1212
        load_order.plugins.insert(1, plugin);
1✔
1213

1✔
1214
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1215
        assert!(load_order.validate_index(&plugin, 2).is_err());
1✔
1216
    }
1✔
1217

1218
    #[test]
1219
    fn validate_index_should_succeed_for_a_non_master_plugin_and_an_index_with_no_later_masters() {
1✔
1220
        let tmp_dir = tempdir().unwrap();
1✔
1221
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1222

1✔
1223
        let plugin =
1✔
1224
            Plugin::new("Blank - Master Dependent.esp", load_order.game_settings()).unwrap();
1✔
1225
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1226
    }
1✔
1227

1228
    #[test]
1229
    fn validate_index_should_succeed_for_a_non_master_plugin_that_is_a_master_of_the_next_master_file(
1✔
1230
    ) {
1✔
1231
        let tmp_dir = tempdir().unwrap();
1✔
1232
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1233

1✔
1234
        let plugin = Plugin::new(
1✔
1235
            "Blank - Different Master Dependent.esm",
1✔
1236
            load_order.game_settings(),
1✔
1237
        )
1✔
1238
        .unwrap();
1✔
1239
        load_order.plugins.insert(1, plugin);
1✔
1240

1✔
1241
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1242
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1243
    }
1✔
1244

1245
    #[test]
1246
    fn validate_index_should_error_for_a_non_master_plugin_that_is_not_a_master_of_the_next_master_file(
1✔
1247
    ) {
1✔
1248
        let tmp_dir = tempdir().unwrap();
1✔
1249
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1250

1✔
1251
        let plugin =
1✔
1252
            Plugin::new("Blank - Master Dependent.esp", load_order.game_settings()).unwrap();
1✔
1253
        assert!(load_order.validate_index(&plugin, 0).is_err());
1✔
1254
    }
1✔
1255

1256
    #[test]
1257
    fn validate_index_should_error_for_a_non_master_plugin_and_an_index_not_before_a_master_that_depends_on_it(
1✔
1258
    ) {
1✔
1259
        let tmp_dir = tempdir().unwrap();
1✔
1260
        let mut load_order = prepare_hoisted(GameId::SkyrimSE, &tmp_dir.path());
1✔
1261

1✔
1262
        let plugin = Plugin::new(
1✔
1263
            "Blank - Different Master Dependent.esm",
1✔
1264
            load_order.game_settings(),
1✔
1265
        )
1✔
1266
        .unwrap();
1✔
1267
        load_order.plugins.insert(1, plugin);
1✔
1268

1✔
1269
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1270
        assert!(load_order.validate_index(&plugin, 2).is_err());
1✔
1271
    }
1✔
1272

1273
    #[test]
1274
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_last() {
1✔
1275
        let tmp_dir = tempdir().unwrap();
1✔
1276
        let load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1277

1✔
1278
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1279

1✔
1280
        let plugin_name = "Blank.full.esm";
1✔
1281
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1282

1✔
1283
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1284
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1285
    }
1✔
1286

1287
    #[test]
1288
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_only_followed_by_other_blueprint_plugins(
1✔
1289
    ) {
1✔
1290
        let tmp_dir = tempdir().unwrap();
1✔
1291
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1292

1✔
1293
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1294

1✔
1295
        let plugin_name = "Blank.full.esm";
1✔
1296
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1297

1✔
1298
        let other_plugin_name = "Blank.medium.esm";
1✔
1299
        set_blueprint_flag(
1✔
1300
            GameId::Starfield,
1✔
1301
            &plugins_dir.join(other_plugin_name),
1✔
1302
            true,
1✔
1303
        )
1✔
1304
        .unwrap();
1✔
1305

1✔
1306
        let other_plugin = Plugin::new(other_plugin_name, load_order.game_settings()).unwrap();
1✔
1307
        load_order.plugins.push(other_plugin);
1✔
1308

1✔
1309
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1310
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1311
    }
1✔
1312

1313
    #[test]
1314
    fn validate_index_should_fail_for_a_blueprint_plugin_index_if_any_non_blueprint_plugins_follow_it(
1✔
1315
    ) {
1✔
1316
        let tmp_dir = tempdir().unwrap();
1✔
1317
        let load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1318

1✔
1319
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1320

1✔
1321
        let plugin_name = "Blank.full.esm";
1✔
1322
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1323

1✔
1324
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1325

1✔
1326
        let index = 1;
1✔
1327
        match load_order.validate_index(&plugin, index).unwrap_err() {
1✔
1328
            Error::InvalidBlueprintPluginPosition {
1329
                name,
1✔
1330
                pos,
1✔
1331
                expected_pos,
1✔
1332
            } => {
1✔
1333
                assert_eq!(plugin_name, name);
1✔
1334
                assert_eq!(index, pos);
1✔
1335
                assert_eq!(2, expected_pos);
1✔
1336
            }
NEW
1337
            e => panic!("Unexpected error type: {:?}", e),
×
1338
        }
1339
    }
1✔
1340

1341
    #[test]
1342
    fn validate_index_should_fail_for_a_blueprint_plugin_index_that_is_after_a_dependent_blueprint_plugin_index(
1✔
1343
    ) {
1✔
1344
        let tmp_dir = tempdir().unwrap();
1✔
1345
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1346

1✔
1347
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1348

1✔
1349
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1350
        copy_to_test_dir(
1✔
1351
            dependent_plugin,
1✔
1352
            dependent_plugin,
1✔
1353
            load_order.game_settings(),
1✔
1354
        );
1✔
1355
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
1356
        let plugin = Plugin::new(dependent_plugin, load_order.game_settings()).unwrap();
1✔
1357
        load_order.plugins.insert(1, plugin);
1✔
1358

1✔
1359
        let plugin_name = "Blank.full.esm";
1✔
1360
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1361

1✔
1362
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1363

1✔
1364
        let index = 3;
1✔
1365
        match load_order.validate_index(&plugin, index).unwrap_err() {
1✔
1366
            Error::UnrepresentedHoist { plugin, master } => {
1✔
1367
                assert_eq!(plugin_name, plugin);
1✔
1368
                assert_eq!(dependent_plugin, master);
1✔
1369
            }
UNCOV
1370
            e => panic!("Unexpected error type: {:?}", e),
×
1371
        }
1372
    }
1✔
1373

1374
    #[test]
1375
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_after_a_dependent_non_blueprint_plugin_index(
1✔
1376
    ) {
1✔
1377
        let tmp_dir = tempdir().unwrap();
1✔
1378
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1379

1✔
1380
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1381

1✔
1382
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1383
        copy_to_test_dir(
1✔
1384
            dependent_plugin,
1✔
1385
            dependent_plugin,
1✔
1386
            load_order.game_settings(),
1✔
1387
        );
1✔
1388
        let plugin = Plugin::new(dependent_plugin, load_order.game_settings()).unwrap();
1✔
1389
        load_order.plugins.insert(1, plugin);
1✔
1390

1✔
1391
        let plugin_name = "Blank.full.esm";
1✔
1392
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1393

1✔
1394
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1395

1✔
1396
        assert!(load_order.validate_index(&plugin, 3).is_ok());
1✔
1397
    }
1✔
1398

1399
    #[test]
1400
    fn validate_index_should_succeed_when_an_early_loader_is_a_blueprint_plugin() {
1✔
1401
        let tmp_dir = tempdir().unwrap();
1✔
1402
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1403

1✔
1404
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1405

1✔
1406
        let plugin_name = "Blank.full.esm";
1✔
1407
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1408

1✔
1409
        std::fs::write(
1✔
1410
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
1411
            format!("Starfield.esm\n{}", plugin_name),
1✔
1412
        )
1✔
1413
        .unwrap();
1✔
1414
        load_order
1✔
1415
            .game_settings
1✔
1416
            .refresh_implicitly_active_plugins()
1✔
1417
            .unwrap();
1✔
1418

1✔
1419
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1420
        load_order.plugins.push(plugin);
1✔
1421

1✔
1422
        let plugin = Plugin::new("Blank.medium.esm", load_order.game_settings()).unwrap();
1✔
1423
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1424
    }
1✔
1425

1426
    #[test]
1427
    fn validate_index_should_succeed_for_an_early_loader_listed_after_a_blueprint_plugin() {
1✔
1428
        let tmp_dir = tempdir().unwrap();
1✔
1429
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1430

1✔
1431
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1432

1✔
1433
        let blueprint_plugin = "Blank.full.esm";
1✔
1434
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(blueprint_plugin), true).unwrap();
1✔
1435

1✔
1436
        let early_loader = "Blank.medium.esm";
1✔
1437

1✔
1438
        std::fs::write(
1✔
1439
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
1440
            format!("Starfield.esm\n{}\n{}", blueprint_plugin, early_loader),
1✔
1441
        )
1✔
1442
        .unwrap();
1✔
1443
        load_order
1✔
1444
            .game_settings
1✔
1445
            .refresh_implicitly_active_plugins()
1✔
1446
            .unwrap();
1✔
1447

1✔
1448
        let plugin = Plugin::new(blueprint_plugin, load_order.game_settings()).unwrap();
1✔
1449
        load_order.plugins.push(plugin);
1✔
1450

1✔
1451
        let plugin = Plugin::new(early_loader, load_order.game_settings()).unwrap();
1✔
1452

1✔
1453
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1454
    }
1✔
1455

1456
    #[test]
1457
    fn set_plugin_index_should_error_if_inserting_a_non_master_before_a_master() {
1✔
1458
        let tmp_dir = tempdir().unwrap();
1✔
1459
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1460

1✔
1461
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1462
        assert!(load_order
1✔
1463
            .set_plugin_index("Blank - Master Dependent.esp", 0)
1✔
1464
            .is_err());
1✔
1465
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1466
    }
1✔
1467

1468
    #[test]
1469
    fn set_plugin_index_should_error_if_moving_a_non_master_before_a_master() {
1✔
1470
        let tmp_dir = tempdir().unwrap();
1✔
1471
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1472

1✔
1473
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1474
        assert!(load_order.set_plugin_index("Blank.esp", 0).is_err());
1✔
1475
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1476
    }
1✔
1477

1478
    #[test]
1479
    fn set_plugin_index_should_error_if_inserting_a_master_after_a_non_master() {
1✔
1480
        let tmp_dir = tempdir().unwrap();
1✔
1481
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1482

1✔
1483
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1484
        assert!(load_order.set_plugin_index("Blank.esm", 2).is_err());
1✔
1485
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1486
    }
1✔
1487

1488
    #[test]
1489
    fn set_plugin_index_should_error_if_moving_a_master_after_a_non_master() {
1✔
1490
        let tmp_dir = tempdir().unwrap();
1✔
1491
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1492

1✔
1493
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1494
        assert!(load_order.set_plugin_index("Morrowind.esm", 2).is_err());
1✔
1495
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1496
    }
1✔
1497

1498
    #[test]
1499
    fn set_plugin_index_should_error_if_setting_the_index_of_an_invalid_plugin() {
1✔
1500
        let tmp_dir = tempdir().unwrap();
1✔
1501
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1502

1✔
1503
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1504
        assert!(load_order.set_plugin_index("missing.esm", 0).is_err());
1✔
1505
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1506
    }
1✔
1507

1508
    #[test]
1509
    fn set_plugin_index_should_error_if_moving_a_plugin_before_an_early_loader() {
1✔
1510
        let tmp_dir = tempdir().unwrap();
1✔
1511
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1512

1✔
1513
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1514

1✔
1515
        match load_order.set_plugin_index("Blank.esp", 0).unwrap_err() {
1✔
1516
            Error::InvalidEarlyLoadingPluginPosition {
1517
                name,
1✔
1518
                pos,
1✔
1519
                expected_pos,
1✔
1520
            } => {
1✔
1521
                assert_eq!("Skyrim.esm", name);
1✔
1522
                assert_eq!(1, pos);
1✔
1523
                assert_eq!(0, expected_pos);
1✔
1524
            }
UNCOV
1525
            e => panic!(
×
UNCOV
1526
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1527
                e
×
UNCOV
1528
            ),
×
1529
        };
1530

1531
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1532
    }
1✔
1533

1534
    #[test]
1535
    fn set_plugin_index_should_error_if_moving_an_early_loader_to_a_different_position() {
1✔
1536
        let tmp_dir = tempdir().unwrap();
1✔
1537
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1538

1✔
1539
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1540

1✔
1541
        match load_order.set_plugin_index("Skyrim.esm", 1).unwrap_err() {
1✔
1542
            Error::InvalidEarlyLoadingPluginPosition {
1543
                name,
1✔
1544
                pos,
1✔
1545
                expected_pos,
1✔
1546
            } => {
1✔
1547
                assert_eq!("Skyrim.esm", name);
1✔
1548
                assert_eq!(1, pos);
1✔
1549
                assert_eq!(0, expected_pos);
1✔
1550
            }
UNCOV
1551
            e => panic!(
×
UNCOV
1552
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1553
                e
×
UNCOV
1554
            ),
×
1555
        };
1556

1557
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1558
    }
1✔
1559

1560
    #[test]
1561
    fn set_plugin_index_should_error_if_inserting_an_early_loader_to_the_wrong_position() {
1✔
1562
        let tmp_dir = tempdir().unwrap();
1✔
1563
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1564

1✔
1565
        load_order.set_plugin_index("Blank.esm", 1).unwrap();
1✔
1566
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1567

1✔
1568
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1569

1✔
1570
        match load_order
1✔
1571
            .set_plugin_index("Dragonborn.esm", 2)
1✔
1572
            .unwrap_err()
1✔
1573
        {
1574
            Error::InvalidEarlyLoadingPluginPosition {
1575
                name,
1✔
1576
                pos,
1✔
1577
                expected_pos,
1✔
1578
            } => {
1✔
1579
                assert_eq!("Dragonborn.esm", name);
1✔
1580
                assert_eq!(2, pos);
1✔
1581
                assert_eq!(1, expected_pos);
1✔
1582
            }
UNCOV
1583
            e => panic!(
×
UNCOV
1584
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1585
                e
×
UNCOV
1586
            ),
×
1587
        };
1588

1589
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1590
    }
1✔
1591

1592
    #[test]
1593
    fn set_plugin_index_should_succeed_if_setting_an_early_loader_to_its_current_position() {
1✔
1594
        let tmp_dir = tempdir().unwrap();
1✔
1595
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1596

1✔
1597
        assert!(load_order.set_plugin_index("Skyrim.esm", 0).is_ok());
1✔
1598
        assert_eq!(
1✔
1599
            vec!["Skyrim.esm", "Blank.esp", "Blank - Different.esp"],
1✔
1600
            load_order.plugin_names()
1✔
1601
        );
1✔
1602
    }
1✔
1603

1604
    #[test]
1605
    fn set_plugin_index_should_succeed_if_inserting_a_new_early_loader() {
1✔
1606
        let tmp_dir = tempdir().unwrap();
1✔
1607
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1608

1✔
1609
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1610

1✔
1611
        assert!(load_order.set_plugin_index("Dragonborn.esm", 1).is_ok());
1✔
1612
        assert_eq!(
1✔
1613
            vec![
1✔
1614
                "Skyrim.esm",
1✔
1615
                "Dragonborn.esm",
1✔
1616
                "Blank.esp",
1✔
1617
                "Blank - Different.esp"
1✔
1618
            ],
1✔
1619
            load_order.plugin_names()
1✔
1620
        );
1✔
1621
    }
1✔
1622

1623
    #[test]
1624
    fn set_plugin_index_should_insert_a_new_plugin() {
1✔
1625
        let tmp_dir = tempdir().unwrap();
1✔
1626
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1627

1✔
1628
        let num_plugins = load_order.plugins().len();
1✔
1629
        assert_eq!(1, load_order.set_plugin_index("Blank.esm", 1).unwrap());
1✔
1630
        assert_eq!(1, load_order.index_of("Blank.esm").unwrap());
1✔
1631
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1632
    }
1✔
1633

1634
    #[test]
1635
    fn set_plugin_index_should_allow_non_masters_to_be_hoisted() {
1✔
1636
        let tmp_dir = tempdir().unwrap();
1✔
1637
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1638

1✔
1639
        let filenames = vec!["Blank.esm", "Blank - Different Master Dependent.esm"];
1✔
1640

1✔
1641
        load_order.replace_plugins(&filenames).unwrap();
1✔
1642
        assert_eq!(filenames, load_order.plugin_names());
1✔
1643

1644
        let num_plugins = load_order.plugins().len();
1✔
1645
        let index = load_order
1✔
1646
            .set_plugin_index("Blank - Different.esm", 1)
1✔
1647
            .unwrap();
1✔
1648
        assert_eq!(1, index);
1✔
1649
        assert_eq!(1, load_order.index_of("Blank - Different.esm").unwrap());
1✔
1650
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1651
    }
1✔
1652

1653
    #[test]
1654
    fn set_plugin_index_should_allow_a_master_file_to_load_after_another_that_hoists_non_masters() {
1✔
1655
        let tmp_dir = tempdir().unwrap();
1✔
1656
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1657

1✔
1658
        let filenames = vec![
1✔
1659
            "Blank - Different.esm",
1✔
1660
            "Blank - Different Master Dependent.esm",
1✔
1661
        ];
1✔
1662

1✔
1663
        load_order.replace_plugins(&filenames).unwrap();
1✔
1664
        assert_eq!(filenames, load_order.plugin_names());
1✔
1665

1666
        let num_plugins = load_order.plugins().len();
1✔
1667
        assert_eq!(2, load_order.set_plugin_index("Blank.esm", 2).unwrap());
1✔
1668
        assert_eq!(2, load_order.index_of("Blank.esm").unwrap());
1✔
1669
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1670
    }
1✔
1671

1672
    #[test]
1673
    fn set_plugin_index_should_move_an_existing_plugin() {
1✔
1674
        let tmp_dir = tempdir().unwrap();
1✔
1675
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1676

1✔
1677
        let num_plugins = load_order.plugins().len();
1✔
1678
        let index = load_order
1✔
1679
            .set_plugin_index("Blank - Different.esp", 1)
1✔
1680
            .unwrap();
1✔
1681
        assert_eq!(1, index);
1✔
1682
        assert_eq!(1, load_order.index_of("Blank - Different.esp").unwrap());
1✔
1683
        assert_eq!(num_plugins, load_order.plugins().len());
1✔
1684
    }
1✔
1685

1686
    #[test]
1687
    fn set_plugin_index_should_move_an_existing_plugin_later_correctly() {
1✔
1688
        let tmp_dir = tempdir().unwrap();
1✔
1689
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1690

1✔
1691
        load_and_insert(&mut load_order, "Blank - Master Dependent.esp");
1✔
1692
        let num_plugins = load_order.plugins().len();
1✔
1693
        assert_eq!(2, load_order.set_plugin_index("Blank.esp", 2).unwrap());
1✔
1694
        assert_eq!(2, load_order.index_of("Blank.esp").unwrap());
1✔
1695
        assert_eq!(num_plugins, load_order.plugins().len());
1✔
1696
    }
1✔
1697

1698
    #[test]
1699
    fn set_plugin_index_should_preserve_an_existing_plugins_active_state() {
1✔
1700
        let tmp_dir = tempdir().unwrap();
1✔
1701
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1702

1✔
1703
        load_and_insert(&mut load_order, "Blank - Master Dependent.esp");
1✔
1704
        assert_eq!(2, load_order.set_plugin_index("Blank.esp", 2).unwrap());
1✔
1705
        assert!(load_order.is_active("Blank.esp"));
1✔
1706

1707
        let index = load_order
1✔
1708
            .set_plugin_index("Blank - Different.esp", 2)
1✔
1709
            .unwrap();
1✔
1710
        assert_eq!(2, index);
1✔
1711
        assert!(!load_order.is_active("Blank - Different.esp"));
1✔
1712
    }
1✔
1713

1714
    #[test]
1715
    fn replace_plugins_should_error_if_given_duplicate_plugins() {
1✔
1716
        let tmp_dir = tempdir().unwrap();
1✔
1717
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1718

1✔
1719
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1720
        let filenames = vec!["Blank.esp", "blank.esp"];
1✔
1721
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1722
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1723
    }
1✔
1724

1725
    #[test]
1726
    fn replace_plugins_should_error_if_given_an_invalid_plugin() {
1✔
1727
        let tmp_dir = tempdir().unwrap();
1✔
1728
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1729

1✔
1730
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1731
        let filenames = vec!["Blank.esp", "missing.esp"];
1✔
1732
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1733
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1734
    }
1✔
1735

1736
    #[test]
1737
    fn replace_plugins_should_error_if_given_a_list_with_plugins_before_masters() {
1✔
1738
        let tmp_dir = tempdir().unwrap();
1✔
1739
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1740

1✔
1741
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1742
        let filenames = vec!["Blank.esp", "Blank.esm"];
1✔
1743
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1744
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1745
    }
1✔
1746

1747
    #[test]
1748
    fn replace_plugins_should_error_if_an_early_loading_plugin_loads_after_another_plugin() {
1✔
1749
        let tmp_dir = tempdir().unwrap();
1✔
1750
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1751

1✔
1752
        copy_to_test_dir("Blank.esm", "Update.esm", &load_order.game_settings());
1✔
1753

1✔
1754
        let filenames = vec![
1✔
1755
            "Skyrim.esm",
1✔
1756
            "Blank.esm",
1✔
1757
            "Update.esm",
1✔
1758
            "Blank.esp",
1✔
1759
            "Blank - Master Dependent.esp",
1✔
1760
            "Blank - Different.esp",
1✔
1761
            "Blàñk.esp",
1✔
1762
        ];
1✔
1763

1✔
1764
        match load_order.replace_plugins(&filenames).unwrap_err() {
1✔
1765
            Error::InvalidEarlyLoadingPluginPosition {
1766
                name,
1✔
1767
                pos,
1✔
1768
                expected_pos,
1✔
1769
            } => {
1✔
1770
                assert_eq!("Update.esm", name);
1✔
1771
                assert_eq!(2, pos);
1✔
1772
                assert_eq!(1, expected_pos);
1✔
1773
            }
UNCOV
1774
            e => panic!("Wrong error type: {:?}", e),
×
1775
        }
1776
    }
1✔
1777

1778
    #[test]
1779
    fn replace_plugins_should_not_error_if_an_early_loading_plugin_is_missing() {
1✔
1780
        let tmp_dir = tempdir().unwrap();
1✔
1781
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1782

1✔
1783
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1784

1✔
1785
        let filenames = vec![
1✔
1786
            "Skyrim.esm",
1✔
1787
            "Dragonborn.esm",
1✔
1788
            "Blank.esm",
1✔
1789
            "Blank.esp",
1✔
1790
            "Blank - Master Dependent.esp",
1✔
1791
            "Blank - Different.esp",
1✔
1792
            "Blàñk.esp",
1✔
1793
        ];
1✔
1794

1✔
1795
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1796
    }
1✔
1797

1798
    #[test]
1799
    fn replace_plugins_should_not_error_if_a_non_early_loading_implicitly_active_plugin_loads_after_another_plugin(
1✔
1800
    ) {
1✔
1801
        let tmp_dir = tempdir().unwrap();
1✔
1802

1✔
1803
        let ini_path = tmp_dir.path().join("my games/Skyrim.ini");
1✔
1804
        create_parent_dirs(&ini_path).unwrap();
1✔
1805
        std::fs::write(&ini_path, "[General]\nsTestFile1=Blank - Different.esp").unwrap();
1✔
1806

1✔
1807
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1808

1✔
1809
        let filenames = vec![
1✔
1810
            "Skyrim.esm",
1✔
1811
            "Blank.esm",
1✔
1812
            "Blank.esp",
1✔
1813
            "Blank - Master Dependent.esp",
1✔
1814
            "Blank - Different.esp",
1✔
1815
            "Blàñk.esp",
1✔
1816
        ];
1✔
1817

1✔
1818
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1819
    }
1✔
1820

1821
    #[test]
1822
    fn replace_plugins_should_not_distinguish_between_ghosted_and_unghosted_filenames() {
1✔
1823
        let tmp_dir = tempdir().unwrap();
1✔
1824
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1825

1✔
1826
        copy_to_test_dir(
1✔
1827
            "Blank - Different.esm",
1✔
1828
            "ghosted.esm.ghost",
1✔
1829
            &load_order.game_settings(),
1✔
1830
        );
1✔
1831

1✔
1832
        let filenames = vec![
1✔
1833
            "Morrowind.esm",
1✔
1834
            "Blank.esm",
1✔
1835
            "ghosted.esm",
1✔
1836
            "Blank.esp",
1✔
1837
            "Blank - Master Dependent.esp",
1✔
1838
            "Blank - Different.esp",
1✔
1839
            "Blàñk.esp",
1✔
1840
        ];
1✔
1841

1✔
1842
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1843
    }
1✔
1844

1845
    #[test]
1846
    fn replace_plugins_should_not_insert_missing_plugins() {
1✔
1847
        let tmp_dir = tempdir().unwrap();
1✔
1848
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1849

1✔
1850
        let filenames = vec![
1✔
1851
            "Blank.esm",
1✔
1852
            "Blank.esp",
1✔
1853
            "Blank - Master Dependent.esp",
1✔
1854
            "Blank - Different.esp",
1✔
1855
        ];
1✔
1856
        load_order.replace_plugins(&filenames).unwrap();
1✔
1857

1✔
1858
        assert_eq!(filenames, load_order.plugin_names());
1✔
1859
    }
1✔
1860

1861
    #[test]
1862
    fn replace_plugins_should_not_lose_active_state_of_existing_plugins() {
1✔
1863
        let tmp_dir = tempdir().unwrap();
1✔
1864
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1865

1✔
1866
        let filenames = vec![
1✔
1867
            "Blank.esm",
1✔
1868
            "Blank.esp",
1✔
1869
            "Blank - Master Dependent.esp",
1✔
1870
            "Blank - Different.esp",
1✔
1871
        ];
1✔
1872
        load_order.replace_plugins(&filenames).unwrap();
1✔
1873

1✔
1874
        assert!(load_order.is_active("Blank.esp"));
1✔
1875
    }
1✔
1876

1877
    #[test]
1878
    fn replace_plugins_should_accept_hoisted_non_masters() {
1✔
1879
        let tmp_dir = tempdir().unwrap();
1✔
1880
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1881

1✔
1882
        let filenames = vec![
1✔
1883
            "Blank.esm",
1✔
1884
            "Blank - Different.esm",
1✔
1885
            "Blank - Different Master Dependent.esm",
1✔
1886
            load_order.game_settings().master_file(),
1✔
1887
            "Blank - Master Dependent.esp",
1✔
1888
            "Blank - Different.esp",
1✔
1889
            "Blank.esp",
1✔
1890
            "Blàñk.esp",
1✔
1891
        ];
1✔
1892

1✔
1893
        load_order.replace_plugins(&filenames).unwrap();
1✔
1894
        assert_eq!(filenames, load_order.plugin_names());
1✔
1895
    }
1✔
1896

1897
    #[test]
1898
    fn hoist_masters_should_hoist_plugins_that_masters_depend_on_to_load_before_their_first_dependent(
1✔
1899
    ) {
1✔
1900
        let tmp_dir = tempdir().unwrap();
1✔
1901
        let (game_settings, _) = mock_game_files(GameId::SkyrimSE, &tmp_dir.path());
1✔
1902

1✔
1903
        // Test both hoisting a master before a master and a non-master before a master.
1✔
1904

1✔
1905
        let master_dependent_master = "Blank - Master Dependent.esm";
1✔
1906
        copy_to_test_dir(
1✔
1907
            master_dependent_master,
1✔
1908
            master_dependent_master,
1✔
1909
            &game_settings,
1✔
1910
        );
1✔
1911

1✔
1912
        let plugin_dependent_master = "Blank - Plugin Dependent.esm";
1✔
1913
        copy_to_test_dir(
1✔
1914
            "Blank - Plugin Dependent.esp",
1✔
1915
            plugin_dependent_master,
1✔
1916
            &game_settings,
1✔
1917
        );
1✔
1918

1✔
1919
        let plugin_names = vec![
1✔
1920
            "Skyrim.esm",
1✔
1921
            master_dependent_master,
1✔
1922
            "Blank.esm",
1✔
1923
            plugin_dependent_master,
1✔
1924
            "Blank - Master Dependent.esp",
1✔
1925
            "Blank - Different.esp",
1✔
1926
            "Blàñk.esp",
1✔
1927
            "Blank.esp",
1✔
1928
        ];
1✔
1929
        let mut plugins = plugin_names
1✔
1930
            .iter()
1✔
1931
            .map(|n| Plugin::new(n, &game_settings).unwrap())
8✔
1932
            .collect();
1✔
1933

1✔
1934
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1935

1936
        let expected_plugin_names = vec![
1✔
1937
            "Skyrim.esm",
1✔
1938
            "Blank.esm",
1✔
1939
            master_dependent_master,
1✔
1940
            "Blank.esp",
1✔
1941
            plugin_dependent_master,
1✔
1942
            "Blank - Master Dependent.esp",
1✔
1943
            "Blank - Different.esp",
1✔
1944
            "Blàñk.esp",
1✔
1945
        ];
1✔
1946

1✔
1947
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1948
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1949
    }
1✔
1950

1951
    #[test]
1952
    fn hoist_masters_should_not_hoist_blueprint_plugins_that_are_masters_of_non_blueprint_plugins()
1✔
1953
    {
1✔
1954
        let tmp_dir = tempdir().unwrap();
1✔
1955
        let (game_settings, _) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
1956

1✔
1957
        let blueprint_plugin = "Blank.full.esm";
1✔
1958
        set_blueprint_flag(
1✔
1959
            GameId::Starfield,
1✔
1960
            &game_settings.plugins_directory().join(blueprint_plugin),
1✔
1961
            true,
1✔
1962
        )
1✔
1963
        .unwrap();
1✔
1964

1✔
1965
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1966
        copy_to_test_dir(dependent_plugin, dependent_plugin, &game_settings);
1✔
1967

1✔
1968
        let plugin_names = vec![
1✔
1969
            "Starfield.esm",
1✔
1970
            dependent_plugin,
1✔
1971
            "Blank.esp",
1✔
1972
            blueprint_plugin,
1✔
1973
        ];
1✔
1974

1✔
1975
        let mut plugins = plugin_names
1✔
1976
            .iter()
1✔
1977
            .map(|n| Plugin::new(n, &game_settings).unwrap())
4✔
1978
            .collect();
1✔
1979

1✔
1980
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1981

1982
        let expected_plugin_names = plugin_names;
1✔
1983

1✔
1984
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1985
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1986
    }
1✔
1987

1988
    #[test]
1989
    fn hoist_masters_should_hoist_blueprint_plugins_that_are_masters_of_blueprint_plugins() {
1✔
1990
        let tmp_dir = tempdir().unwrap();
1✔
1991
        let (game_settings, _) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
1992

1✔
1993
        let plugins_dir = game_settings.plugins_directory();
1✔
1994

1✔
1995
        let blueprint_plugin = "Blank.full.esm";
1✔
1996
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(blueprint_plugin), true).unwrap();
1✔
1997

1✔
1998
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1999
        copy_to_test_dir(dependent_plugin, dependent_plugin, &game_settings);
1✔
2000
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
2001

1✔
2002
        let plugin_names = vec![
1✔
2003
            "Starfield.esm",
1✔
2004
            "Blank.esp",
1✔
2005
            dependent_plugin,
1✔
2006
            blueprint_plugin,
1✔
2007
        ];
1✔
2008

1✔
2009
        let mut plugins = plugin_names
1✔
2010
            .iter()
1✔
2011
            .map(|n| Plugin::new(n, &game_settings).unwrap())
4✔
2012
            .collect();
1✔
2013

1✔
2014
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
2015

2016
        let expected_plugin_names = vec![
1✔
2017
            "Starfield.esm",
1✔
2018
            "Blank.esp",
1✔
2019
            blueprint_plugin,
1✔
2020
            dependent_plugin,
1✔
2021
        ];
1✔
2022

1✔
2023
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
2024
        assert_eq!(expected_plugin_names, plugin_names);
1✔
2025
    }
1✔
2026

2027
    #[test]
2028
    fn find_plugins_in_dirs_should_sort_files_by_modification_timestamp() {
1✔
2029
        let tmp_dir = tempdir().unwrap();
1✔
2030
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
2031

1✔
2032
        let result = find_plugins_in_dirs(
1✔
2033
            &[load_order.game_settings.plugins_directory()],
1✔
2034
            load_order.game_settings.id(),
1✔
2035
        );
1✔
2036

1✔
2037
        let plugin_names = [
1✔
2038
            load_order.game_settings.master_file(),
1✔
2039
            "Blank.esm",
1✔
2040
            "Blank.esp",
1✔
2041
            "Blank - Different.esp",
1✔
2042
            "Blank - Master Dependent.esp",
1✔
2043
            "Blàñk.esp",
1✔
2044
        ];
1✔
2045

1✔
2046
        assert_eq!(plugin_names.as_slice(), result);
1✔
2047
    }
1✔
2048

2049
    #[test]
2050
    fn find_plugins_in_dirs_should_sort_files_by_descending_filename_if_timestamps_are_equal() {
1✔
2051
        let tmp_dir = tempdir().unwrap();
1✔
2052
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
2053

1✔
2054
        let timestamp = 1321010051;
1✔
2055
        let plugin_path = load_order
1✔
2056
            .game_settings
1✔
2057
            .plugins_directory()
1✔
2058
            .join("Blank - Different.esp");
1✔
2059
        set_file_timestamps(&plugin_path, timestamp);
1✔
2060
        let plugin_path = load_order
1✔
2061
            .game_settings
1✔
2062
            .plugins_directory()
1✔
2063
            .join("Blank - Master Dependent.esp");
1✔
2064
        set_file_timestamps(&plugin_path, timestamp);
1✔
2065

1✔
2066
        let result = find_plugins_in_dirs(
1✔
2067
            &[load_order.game_settings.plugins_directory()],
1✔
2068
            load_order.game_settings.id(),
1✔
2069
        );
1✔
2070

1✔
2071
        let plugin_names = [
1✔
2072
            load_order.game_settings.master_file(),
1✔
2073
            "Blank.esm",
1✔
2074
            "Blank.esp",
1✔
2075
            "Blank - Master Dependent.esp",
1✔
2076
            "Blank - Different.esp",
1✔
2077
            "Blàñk.esp",
1✔
2078
        ];
1✔
2079

1✔
2080
        assert_eq!(plugin_names.as_slice(), result);
1✔
2081
    }
1✔
2082

2083
    #[test]
2084
    fn find_plugins_in_dirs_should_sort_files_by_ascending_filename_if_timestamps_are_equal_and_game_is_starfield(
1✔
2085
    ) {
1✔
2086
        let tmp_dir = tempdir().unwrap();
1✔
2087
        let (game_settings, plugins) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
2088
        let load_order = TestLoadOrder {
1✔
2089
            game_settings,
1✔
2090
            plugins,
1✔
2091
        };
1✔
2092

1✔
2093
        let timestamp = 1321009991;
1✔
2094

1✔
2095
        let plugin_names = [
1✔
2096
            "Blank - Override.esp",
1✔
2097
            "Blank.esp",
1✔
2098
            "Blank.full.esm",
1✔
2099
            "Blank.medium.esm",
1✔
2100
            "Blank.small.esm",
1✔
2101
            "Starfield.esm",
1✔
2102
        ];
1✔
2103

2104
        for plugin_name in plugin_names {
7✔
2105
            let plugin_path = load_order
6✔
2106
                .game_settings
6✔
2107
                .plugins_directory()
6✔
2108
                .join(plugin_name);
6✔
2109
            set_file_timestamps(&plugin_path, timestamp);
6✔
2110
        }
6✔
2111

2112
        let result = find_plugins_in_dirs(
1✔
2113
            &[load_order.game_settings.plugins_directory()],
1✔
2114
            load_order.game_settings.id(),
1✔
2115
        );
1✔
2116

1✔
2117
        assert_eq!(plugin_names.as_slice(), result);
1✔
2118
    }
1✔
2119

2120
    #[test]
2121
    fn move_elements_should_correct_later_indices_to_account_for_earlier_moves() {
1✔
2122
        let mut vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
1✔
2123
        let mut from_to_indices = BTreeMap::new();
1✔
2124
        from_to_indices.insert(6, 3);
1✔
2125
        from_to_indices.insert(5, 2);
1✔
2126
        from_to_indices.insert(7, 1);
1✔
2127

1✔
2128
        move_elements(&mut vec, from_to_indices);
1✔
2129

1✔
2130
        assert_eq!(vec![0, 7, 1, 5, 2, 6, 3, 4, 8], vec);
1✔
2131
    }
1✔
2132

2133
    #[test]
2134
    fn validate_load_order_should_be_ok_if_there_are_only_master_files() {
1✔
2135
        let tmp_dir = tempdir().unwrap();
1✔
2136
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2137

1✔
2138
        let plugins = vec![
1✔
2139
            Plugin::new(settings.master_file(), &settings).unwrap(),
1✔
2140
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2141
        ];
1✔
2142

1✔
2143
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2144
    }
1✔
2145

2146
    #[test]
2147
    fn validate_load_order_should_be_ok_if_there_are_no_master_files() {
1✔
2148
        let tmp_dir = tempdir().unwrap();
1✔
2149
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2150

1✔
2151
        let plugins = vec![
1✔
2152
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2153
            Plugin::new("Blank - Different.esp", &settings).unwrap(),
1✔
2154
        ];
1✔
2155

1✔
2156
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2157
    }
1✔
2158

2159
    #[test]
2160
    fn validate_load_order_should_be_ok_if_master_files_are_before_all_others() {
1✔
2161
        let tmp_dir = tempdir().unwrap();
1✔
2162
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2163

1✔
2164
        let plugins = vec![
1✔
2165
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2166
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2167
        ];
1✔
2168

1✔
2169
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2170
    }
1✔
2171

2172
    #[test]
2173
    fn validate_load_order_should_be_ok_if_hoisted_non_masters_load_before_masters() {
1✔
2174
        let tmp_dir = tempdir().unwrap();
1✔
2175
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2176

1✔
2177
        copy_to_test_dir(
1✔
2178
            "Blank - Plugin Dependent.esp",
1✔
2179
            "Blank - Plugin Dependent.esm",
1✔
2180
            &settings,
1✔
2181
        );
1✔
2182

1✔
2183
        let plugins = vec![
1✔
2184
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2185
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2186
            Plugin::new("Blank - Plugin Dependent.esm", &settings).unwrap(),
1✔
2187
        ];
1✔
2188

1✔
2189
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2190
    }
1✔
2191

2192
    #[test]
2193
    fn validate_load_order_should_error_if_non_masters_are_hoisted_earlier_than_needed() {
1✔
2194
        let tmp_dir = tempdir().unwrap();
1✔
2195
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2196

1✔
2197
        copy_to_test_dir(
1✔
2198
            "Blank - Plugin Dependent.esp",
1✔
2199
            "Blank - Plugin Dependent.esm",
1✔
2200
            &settings,
1✔
2201
        );
1✔
2202

1✔
2203
        let plugins = vec![
1✔
2204
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2205
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2206
            Plugin::new("Blank - Plugin Dependent.esm", &settings).unwrap(),
1✔
2207
        ];
1✔
2208

1✔
2209
        assert!(validate_load_order(&plugins, &[]).is_err());
1✔
2210
    }
1✔
2211

2212
    #[test]
2213
    fn validate_load_order_should_error_if_master_files_load_before_non_masters_they_have_as_masters(
1✔
2214
    ) {
1✔
2215
        let tmp_dir = tempdir().unwrap();
1✔
2216
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2217

1✔
2218
        copy_to_test_dir(
1✔
2219
            "Blank - Plugin Dependent.esp",
1✔
2220
            "Blank - Plugin Dependent.esm",
1✔
2221
            &settings,
1✔
2222
        );
1✔
2223

1✔
2224
        let plugins = vec![
1✔
2225
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2226
            Plugin::new("Blank - Plugin Dependent.esm", &settings).unwrap(),
1✔
2227
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2228
        ];
1✔
2229

1✔
2230
        assert!(validate_load_order(&plugins, &[]).is_err());
1✔
2231
    }
1✔
2232

2233
    #[test]
2234
    fn validate_load_order_should_error_if_master_files_load_before_other_masters_they_have_as_masters(
1✔
2235
    ) {
1✔
2236
        let tmp_dir = tempdir().unwrap();
1✔
2237
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2238

1✔
2239
        copy_to_test_dir(
1✔
2240
            "Blank - Master Dependent.esm",
1✔
2241
            "Blank - Master Dependent.esm",
1✔
2242
            &settings,
1✔
2243
        );
1✔
2244

1✔
2245
        let plugins = vec![
1✔
2246
            Plugin::new("Blank - Master Dependent.esm", &settings).unwrap(),
1✔
2247
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2248
        ];
1✔
2249

1✔
2250
        assert!(validate_load_order(&plugins, &[]).is_err());
1✔
2251
    }
1✔
2252

2253
    #[test]
2254
    fn validate_load_order_should_succeed_if_a_blueprint_plugin_loads_after_all_non_blueprint_plugins(
1✔
2255
    ) {
1✔
2256
        let tmp_dir = tempdir().unwrap();
1✔
2257
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2258

1✔
2259
        let plugins_dir = settings.plugins_directory();
1✔
2260

1✔
2261
        let plugin_name = "Blank.full.esm";
1✔
2262
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2263

1✔
2264
        let plugins = vec![
1✔
2265
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2266
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2267
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2268
        ];
1✔
2269

1✔
2270
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2271
    }
1✔
2272

2273
    #[test]
2274
    fn validate_load_order_should_succeed_if_a_blueprint_plugin_loads_after_a_non_blueprint_plugin_that_depends_on_it(
1✔
2275
    ) {
1✔
2276
        let tmp_dir = tempdir().unwrap();
1✔
2277
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2278

1✔
2279
        let plugins_dir = settings.plugins_directory();
1✔
2280

1✔
2281
        let plugin_name = "Blank.full.esm";
1✔
2282
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2283

1✔
2284
        let dependent_plugin = "Blank - Override.full.esm";
1✔
2285
        copy_to_test_dir(dependent_plugin, dependent_plugin, &settings);
1✔
2286

1✔
2287
        let plugins = vec![
1✔
2288
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2289
            Plugin::new(dependent_plugin, &settings).unwrap(),
1✔
2290
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2291
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2292
        ];
1✔
2293

1✔
2294
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2295
    }
1✔
2296

2297
    #[test]
2298
    fn validate_load_order_should_fail_if_a_blueprint_plugin_loads_before_a_non_blueprint_plugin() {
1✔
2299
        let tmp_dir = tempdir().unwrap();
1✔
2300
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2301

1✔
2302
        let plugins_dir = settings.plugins_directory();
1✔
2303

1✔
2304
        let plugin_name = "Blank.full.esm";
1✔
2305
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2306

1✔
2307
        let plugins = vec![
1✔
2308
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2309
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2310
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2311
        ];
1✔
2312

1✔
2313
        match validate_load_order(&plugins, &[]).unwrap_err() {
1✔
2314
            Error::InvalidBlueprintPluginPosition {
2315
                name,
1✔
2316
                pos,
1✔
2317
                expected_pos,
1✔
2318
            } => {
1✔
2319
                assert_eq!(plugin_name, name);
1✔
2320
                assert_eq!(1, pos);
1✔
2321
                assert_eq!(2, expected_pos);
1✔
2322
            }
NEW
2323
            e => panic!("Unexpected error type: {:?}", e),
×
2324
        }
2325
    }
1✔
2326

2327
    #[test]
2328
    fn validate_load_order_should_fail_if_a_blueprint_plugin_loads_after_a_blueprint_plugin_that_depends_on_it(
1✔
2329
    ) {
1✔
2330
        let tmp_dir = tempdir().unwrap();
1✔
2331
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2332

1✔
2333
        let plugins_dir = settings.plugins_directory();
1✔
2334

1✔
2335
        let plugin_name = "Blank.full.esm";
1✔
2336
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2337

1✔
2338
        let dependent_plugin = "Blank - Override.full.esm";
1✔
2339
        copy_to_test_dir(dependent_plugin, dependent_plugin, &settings);
1✔
2340
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
2341

1✔
2342
        let plugins = vec![
1✔
2343
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2344
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2345
            Plugin::new(dependent_plugin, &settings).unwrap(),
1✔
2346
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2347
        ];
1✔
2348

1✔
2349
        match validate_load_order(&plugins, &[]).unwrap_err() {
1✔
2350
            Error::UnrepresentedHoist { plugin, master } => {
1✔
2351
                assert_eq!(plugin_name, plugin);
1✔
2352
                assert_eq!(dependent_plugin, master);
1✔
2353
            }
UNCOV
2354
            e => panic!("Unexpected error type: {:?}", e),
×
2355
        }
2356
    }
1✔
2357

2358
    #[test]
2359
    fn find_first_non_master_should_find_a_full_esp() {
1✔
2360
        let tmp_dir = tempdir().unwrap();
1✔
2361
        let plugins = prepare_plugins(&tmp_dir.path(), "Blank.esp");
1✔
2362

1✔
2363
        let first_non_master = super::find_first_non_master_position(&plugins);
1✔
2364
        assert_eq!(1, first_non_master.unwrap());
1✔
2365
    }
1✔
2366

2367
    #[test]
2368
    fn find_first_non_master_should_find_a_light_flagged_esp() {
1✔
2369
        let tmp_dir = tempdir().unwrap();
1✔
2370
        let plugins = prepare_plugins(&tmp_dir.path(), "Blank.esl");
1✔
2371

1✔
2372
        let first_non_master = super::find_first_non_master_position(&plugins);
1✔
2373
        assert_eq!(1, first_non_master.unwrap());
1✔
2374
    }
1✔
2375
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc