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

Ortham / libloadorder / 10254629017

05 Aug 2024 07:11PM UTC coverage: 91.872% (+0.04%) from 91.834%
10254629017

push

github

Ortham
Fix handling of blueprint plugins

Blueprint plugins were introduced by Starfield.

Plugins that are both blueprint-flagged and master-flagged get loaded after all other plugins and aren't hoisted by non-blueprint plugins.

Some validation of blueprint plugin positions is still missing, because that requires a new Error enum variant, which is a breaking change.

511 of 516 new or added lines in 4 files covered. (99.03%)

96 existing lines in 6 files now uncovered.

7856 of 8551 relevant lines covered (91.87%)

167394.98 hits per line

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

98.87
/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> {
49✔
77
        if plugin.is_blueprint_master() {
49✔
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)
5✔
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
    }
49✔
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))
30,017,967✔
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(
20✔
318
    plugins: &[Plugin],
20✔
319
    early_loading_plugins: &[String],
20✔
320
) -> Result<(), Error> {
20✔
321
    // Check that all early loading plugins that are present load in
20✔
322
    // their hardcoded order.
20✔
323
    let mut missing_plugins_count = 0;
20✔
324
    for (i, plugin_name) in early_loading_plugins.iter().enumerate() {
20✔
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(())
19✔
341
}
20✔
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(
5✔
424
    plugins: &[Plugin],
5✔
425
    plugin: &Plugin,
5✔
426
    index: usize,
5✔
427
) -> Result<(), Error> {
5✔
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() {
5✔
433
        &plugins[..index]
1✔
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 {
16✔
441
        if !preceding_plugin.is_blueprint_master() {
12✔
442
            continue;
11✔
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✔
NEW
454
        }
×
455
    }
456

457
    Ok(())
4✔
458
}
5✔
459

460
fn validate_master_file_index(
25✔
461
    plugins: &[Plugin],
25✔
462
    plugin: &Plugin,
25✔
463
    index: usize,
25✔
464
) -> Result<(), Error> {
25✔
465
    let preceding_plugins = if index < plugins.len() {
25✔
466
        &plugins[..index]
23✔
467
    } else {
468
        plugins
2✔
469
    };
470

471
    // Check that none of the preceding plugins have this plugin as a master.
472
    for preceding_plugin in preceding_plugins {
58✔
473
        let preceding_masters = preceding_plugin.masters()?;
35✔
474
        if preceding_masters
35✔
475
            .iter()
35✔
476
            .any(|m| eq(m.as_str(), plugin.name()))
35✔
477
        {
478
            return Err(Error::UnrepresentedHoist {
2✔
479
                plugin: plugin.name().to_string(),
2✔
480
                master: preceding_plugin.name().to_string(),
2✔
481
            });
2✔
482
        }
33✔
483
    }
484

485
    let previous_master_pos = preceding_plugins
23✔
486
        .iter()
23✔
487
        .rposition(|p| p.is_master_file())
29✔
488
        .unwrap_or(0);
23✔
489

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

493
    // Check that all of the plugins that load between this index and
494
    // the previous plugin are masters of this plugin.
495
    if let Some(n) = preceding_plugins
23✔
496
        .iter()
23✔
497
        .skip(previous_master_pos + 1)
23✔
498
        .find(|p| !master_names.contains(&UniCase::new(p.name())))
23✔
499
    {
500
        return Err(Error::NonMasterBeforeMaster {
3✔
501
            master: plugin.name().to_string(),
3✔
502
            non_master: n.name().to_string(),
3✔
503
        });
3✔
504
    }
20✔
505

506
    // Check that none of the plugins that load after index are
507
    // masters of this plugin.
508
    if let Some(p) = plugins
20✔
509
        .iter()
20✔
510
        .skip(index)
20✔
511
        .find(|p| master_names.contains(&UniCase::new(p.name())))
40✔
512
    {
513
        Err(Error::UnrepresentedHoist {
3✔
514
            plugin: p.name().to_string(),
3✔
515
            master: plugin.name().to_string(),
3✔
516
        })
3✔
517
    } else {
518
        Ok(())
17✔
519
    }
520
}
25✔
521

522
fn validate_non_master_file_index(
16✔
523
    plugins: &[Plugin],
16✔
524
    plugin: &Plugin,
16✔
525
    index: usize,
16✔
526
) -> Result<(), Error> {
16✔
527
    // Check that there aren't any earlier master files that have this
528
    // plugin as a master.
529
    for master_file in plugins.iter().take(index).filter(|p| p.is_master_file()) {
23✔
530
        if master_file
13✔
531
            .masters()?
13✔
532
            .iter()
13✔
533
            .any(|m| plugin.name_matches(m))
13✔
534
        {
UNCOV
535
            return Err(Error::UnrepresentedHoist {
×
UNCOV
536
                plugin: plugin.name().to_string(),
×
UNCOV
537
                master: master_file.name().to_string(),
×
UNCOV
538
            });
×
539
        }
13✔
540
    }
541

542
    // Check that the next master file has this plugin as a master.
543
    let next_master = match plugins.iter().skip(index).find(|p| p.is_master_file()) {
18✔
544
        None => return Ok(()),
9✔
545
        Some(p) => p,
7✔
546
    };
7✔
547

7✔
548
    if next_master
7✔
549
        .masters()?
7✔
550
        .iter()
7✔
551
        .any(|m| plugin.name_matches(m))
7✔
552
    {
553
        Ok(())
4✔
554
    } else {
555
        Err(Error::NonMasterBeforeMaster {
3✔
556
            master: next_master.name().to_string(),
3✔
557
            non_master: plugin.name().to_string(),
3✔
558
        })
3✔
559
    }
560
}
16✔
561

562
fn map_to_plugins<T: ReadableLoadOrderBase + Sync + ?Sized>(
11✔
563
    load_order: &T,
11✔
564
    plugin_names: &[&str],
11✔
565
) -> Result<Vec<Plugin>, Error> {
11✔
566
    plugin_names
11✔
567
        .par_iter()
11✔
568
        .map(|n| to_plugin(n, load_order.plugins(), load_order.game_settings_base()))
51✔
569
        .collect()
11✔
570
}
11✔
571

572
fn insert<T: MutableLoadOrder + ?Sized>(load_order: &mut T, plugin: Plugin) -> usize {
207✔
573
    match load_order.insert_position(&plugin) {
207✔
574
        Some(position) => {
36✔
575
            load_order.plugins_mut().insert(position, plugin);
36✔
576
            position
36✔
577
        }
578
        None => {
579
            load_order.plugins_mut().push(plugin);
171✔
580
            load_order.plugins().len() - 1
171✔
581
        }
582
    }
583
}
207✔
584

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

598
        for value in from_to_indices.values_mut() {
7✔
599
            if *value < from_index && *value > to_index {
4✔
600
                *value += 1;
1✔
601
            }
3✔
602
        }
603
    }
604
}
57✔
605

606
fn get_plugin_to_insert_at<T: MutableLoadOrder + ?Sized>(
19✔
607
    load_order: &mut T,
19✔
608
    plugin_name: &str,
19✔
609
    insert_position: usize,
19✔
610
) -> Result<Plugin, Error> {
19✔
611
    if let Some(p) = load_order.index_of(plugin_name) {
19✔
612
        let plugin = &load_order.plugins()[p];
10✔
613
        load_order.validate_index(plugin, insert_position)?;
10✔
614

615
        Ok(load_order.plugins_mut().remove(p))
6✔
616
    } else {
617
        let plugin = Plugin::new(plugin_name, load_order.game_settings())?;
9✔
618

619
        load_order.validate_index(&plugin, insert_position)?;
8✔
620

621
        Ok(plugin)
5✔
622
    }
623
}
19✔
624

625
fn validate_load_order(plugins: &[Plugin], early_loading_plugins: &[String]) -> Result<(), Error> {
20✔
626
    validate_early_loader_positions(plugins, early_loading_plugins)?;
20✔
627

628
    validate_no_unhoisted_non_masters_before_masters(plugins)?;
19✔
629

630
    validate_plugins_load_before_their_masters(plugins)?;
17✔
631

632
    Ok(())
14✔
633
}
20✔
634

635
fn validate_no_unhoisted_non_masters_before_masters(plugins: &[Plugin]) -> Result<(), Error> {
19✔
636
    let first_non_master_pos = match find_first_non_master_position(plugins) {
19✔
637
        None => plugins.len(),
3✔
638
        Some(x) => x,
16✔
639
    };
640

641
    // Ignore blueprint plugins because they load after non-masters.
642
    let last_master_pos = match plugins
19✔
643
        .iter()
19✔
644
        .rposition(|p| p.is_master_file() && !p.is_blueprint_master())
51✔
645
    {
646
        None => return Ok(()),
1✔
647
        Some(x) => x,
18✔
648
    };
18✔
649

18✔
650
    let mut plugin_names: HashSet<_> = HashSet::new();
18✔
651

18✔
652
    // Add each plugin that isn't a master file to the hashset.
18✔
653
    // When a master file is encountered, remove its masters from the hashset.
18✔
654
    // If there are any plugins left in the hashset, they weren't hoisted there,
18✔
655
    // so fail the check.
18✔
656
    if first_non_master_pos < last_master_pos {
18✔
657
        for plugin in plugins
11✔
658
            .iter()
5✔
659
            .skip(first_non_master_pos)
5✔
660
            .take(last_master_pos - first_non_master_pos + 1)
5✔
661
        {
662
            if !plugin.is_master_file() {
11✔
663
                plugin_names.insert(UniCase::new(plugin.name().to_string()));
5✔
664
            } else {
5✔
665
                for master in plugin.masters()? {
6✔
666
                    plugin_names.remove(&UniCase::new(master.clone()));
3✔
667
                }
3✔
668

669
                if let Some(n) = plugin_names.iter().next() {
6✔
670
                    return Err(Error::NonMasterBeforeMaster {
2✔
671
                        master: plugin.name().to_string(),
2✔
672
                        non_master: n.to_string(),
2✔
673
                    });
2✔
674
                }
4✔
675
            }
676
        }
677
    }
13✔
678

679
    Ok(())
16✔
680
}
19✔
681

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

685
    for plugin in plugins.iter().rev() {
62✔
686
        if plugin.is_master_file() {
62✔
687
            if let Some(m) = plugin
31✔
688
                .masters()?
31✔
689
                .iter()
31✔
690
                .find_map(|m| plugins_map.get(&UniCase::new(m.to_string())))
31✔
691
            {
692
                // Don't error if a non-blueprint plugin depends on a blueprint plugin.
693
                if plugin.is_blueprint_master() || !m.is_blueprint_master() {
4✔
694
                    return Err(Error::UnrepresentedHoist {
3✔
695
                        plugin: m.name().to_string(),
3✔
696
                        master: plugin.name().to_string(),
3✔
697
                    });
3✔
698
                }
1✔
699
            }
27✔
700
        }
31✔
701

702
        plugins_map.insert(UniCase::new(plugin.name().to_string()), plugin);
59✔
703
    }
704

705
    Ok(())
14✔
706
}
17✔
707

708
fn remove_duplicates_icase(
36✔
709
    plugin_tuples: Vec<(String, bool)>,
36✔
710
    filenames: Vec<String>,
36✔
711
) -> Vec<(String, bool)> {
36✔
712
    let mut set: HashSet<_> = HashSet::with_capacity(filenames.len());
36✔
713

36✔
714
    let mut unique_tuples: Vec<(String, bool)> = plugin_tuples
36✔
715
        .into_iter()
36✔
716
        .rev()
36✔
717
        .filter(|(string, _)| set.insert(UniCase::new(trim_dot_ghost(string).to_string())))
67✔
718
        .collect();
36✔
719

36✔
720
    unique_tuples.reverse();
36✔
721

36✔
722
    let unique_file_tuples_iter = filenames
36✔
723
        .into_iter()
36✔
724
        .filter(|string| set.insert(UniCase::new(trim_dot_ghost(string).to_string())))
211✔
725
        .map(|f| (f, false));
150✔
726

36✔
727
    unique_tuples.extend(unique_file_tuples_iter);
36✔
728

36✔
729
    unique_tuples
36✔
730
}
36✔
731

732
fn activate_unvalidated<T: MutableLoadOrder + ?Sized>(
141✔
733
    load_order: &mut T,
141✔
734
    filename: &str,
141✔
735
) -> Result<(), Error> {
141✔
736
    if let Some(plugin) = load_order
141✔
737
        .plugins_mut()
141✔
738
        .iter_mut()
141✔
739
        .find(|p| p.name_matches(filename))
633✔
740
    {
741
        plugin.activate()
38✔
742
    } else {
743
        // Ignore any errors trying to load the plugin to save checking if it's
744
        // valid and then loading it if it is.
745
        Plugin::with_active(filename, load_order.game_settings(), true)
103✔
746
            .map(|plugin| {
103✔
UNCOV
747
                insert(load_order, plugin);
×
748
            })
103✔
749
            .or(Ok(()))
103✔
750
    }
751
}
141✔
752

753
fn find_first_non_master_position(plugins: &[Plugin]) -> Option<usize> {
19,495✔
754
    plugins.iter().position(|p| !p.is_master_file())
43,441,146✔
755
}
19,495✔
756

757
#[cfg(test)]
758
mod tests {
759
    use super::*;
760

761
    use crate::enums::GameId;
762
    use crate::game_settings::GameSettings;
763
    use crate::load_order::tests::*;
764
    use crate::load_order::writable::create_parent_dirs;
765
    use crate::tests::copy_to_test_dir;
766

767
    use tempfile::tempdir;
768

769
    struct TestLoadOrder {
770
        game_settings: GameSettings,
771
        plugins: Vec<Plugin>,
772
    }
773

774
    impl ReadableLoadOrderBase for TestLoadOrder {
775
        fn game_settings_base(&self) -> &GameSettings {
225✔
776
            &self.game_settings
225✔
777
        }
225✔
778

779
        fn plugins(&self) -> &[Plugin] {
271✔
780
            &self.plugins
271✔
781
        }
271✔
782
    }
783

784
    impl MutableLoadOrder for TestLoadOrder {
785
        fn plugins_mut(&mut self) -> &mut Vec<Plugin> {
28✔
786
            &mut self.plugins
28✔
787
        }
28✔
788
    }
789

790
    fn prepare(game_id: GameId, game_path: &Path) -> TestLoadOrder {
67✔
791
        let (game_settings, plugins) = mock_game_files(game_id, game_path);
67✔
792

67✔
793
        TestLoadOrder {
67✔
794
            game_settings,
67✔
795
            plugins,
67✔
796
        }
67✔
797
    }
67✔
798

799
    fn prepare_hoisted(game_id: GameId, game_path: &Path) -> TestLoadOrder {
11✔
800
        let load_order = prepare(game_id, game_path);
11✔
801

11✔
802
        let plugins_dir = &load_order.game_settings().plugins_directory();
11✔
803
        copy_to_test_dir(
11✔
804
            "Blank - Different.esm",
11✔
805
            "Blank - Different.esm",
11✔
806
            load_order.game_settings(),
11✔
807
        );
11✔
808
        set_master_flag(game_id, &plugins_dir.join("Blank - Different.esm"), false).unwrap();
11✔
809
        copy_to_test_dir(
11✔
810
            "Blank - Different Master Dependent.esm",
11✔
811
            "Blank - Different Master Dependent.esm",
11✔
812
            load_order.game_settings(),
11✔
813
        );
11✔
814

11✔
815
        load_order
11✔
816
    }
11✔
817

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

2✔
821
        copy_to_test_dir("Blank.esm", settings.master_file(), &settings);
2✔
822
        copy_to_test_dir(blank_esp_source, "Blank.esp", &settings);
2✔
823

2✔
824
        vec![
2✔
825
            Plugin::new(settings.master_file(), &settings).unwrap(),
2✔
826
            Plugin::new("Blank.esp", &settings).unwrap(),
2✔
827
        ]
2✔
828
    }
2✔
829

830
    #[test]
831
    fn insert_position_should_return_zero_if_given_the_game_master_plugin() {
1✔
832
        let tmp_dir = tempdir().unwrap();
1✔
833
        let load_order = prepare(GameId::Skyrim, &tmp_dir.path());
1✔
834

1✔
835
        let plugin = Plugin::new("Skyrim.esm", &load_order.game_settings()).unwrap();
1✔
836
        let position = load_order.insert_position(&plugin);
1✔
837

1✔
838
        assert_eq!(0, position.unwrap());
1✔
839
    }
1✔
840

841
    #[test]
842
    fn insert_position_should_return_none_for_the_game_master_if_no_plugins_are_loaded() {
1✔
843
        let tmp_dir = tempdir().unwrap();
1✔
844
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
845

1✔
846
        load_order.plugins_mut().clear();
1✔
847

1✔
848
        let plugin = Plugin::new("Skyrim.esm", &load_order.game_settings()).unwrap();
1✔
849
        let position = load_order.insert_position(&plugin);
1✔
850

1✔
851
        assert!(position.is_none());
1✔
852
    }
1✔
853

854
    #[test]
855
    fn insert_position_should_return_the_hardcoded_index_of_an_early_loading_plugin() {
1✔
856
        let tmp_dir = tempdir().unwrap();
1✔
857
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
858

1✔
859
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
860
        load_order.plugins_mut().insert(1, plugin);
1✔
861

1✔
862
        copy_to_test_dir("Blank.esm", "HearthFires.esm", &load_order.game_settings());
1✔
863
        let plugin = Plugin::new("HearthFires.esm", &load_order.game_settings()).unwrap();
1✔
864
        let position = load_order.insert_position(&plugin);
1✔
865

1✔
866
        assert_eq!(1, position.unwrap());
1✔
867
    }
1✔
868

869
    #[test]
870
    fn insert_position_should_not_treat_all_implicitly_active_plugins_as_early_loading_plugins() {
1✔
871
        let tmp_dir = tempdir().unwrap();
1✔
872

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

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

1✔
879
        copy_to_test_dir(
1✔
880
            "Blank.esm",
1✔
881
            "Blank - Different.esm",
1✔
882
            &load_order.game_settings(),
1✔
883
        );
1✔
884
        let plugin = Plugin::new("Blank - Different.esm", &load_order.game_settings()).unwrap();
1✔
885
        load_order.plugins_mut().insert(1, plugin);
1✔
886

1✔
887
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
888
        let position = load_order.insert_position(&plugin);
1✔
889

1✔
890
        assert_eq!(2, position.unwrap());
1✔
891
    }
1✔
892

893
    #[test]
894
    fn insert_position_should_not_count_installed_unloaded_early_loading_plugins() {
1✔
895
        let tmp_dir = tempdir().unwrap();
1✔
896
        let load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
897

1✔
898
        copy_to_test_dir("Blank.esm", "Update.esm", &load_order.game_settings());
1✔
899
        copy_to_test_dir("Blank.esm", "HearthFires.esm", &load_order.game_settings());
1✔
900
        let plugin = Plugin::new("HearthFires.esm", &load_order.game_settings()).unwrap();
1✔
901
        let position = load_order.insert_position(&plugin);
1✔
902

1✔
903
        assert_eq!(1, position.unwrap());
1✔
904
    }
1✔
905

906
    #[test]
907
    fn insert_position_should_not_put_blueprint_plugins_before_non_blueprint_dependents() {
1✔
908
        let tmp_dir = tempdir().unwrap();
1✔
909
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
910

1✔
911
        let dependent_plugin = "Blank - Override.full.esm";
1✔
912
        copy_to_test_dir(
1✔
913
            dependent_plugin,
1✔
914
            dependent_plugin,
1✔
915
            &load_order.game_settings(),
1✔
916
        );
1✔
917

1✔
918
        let plugin = Plugin::new(dependent_plugin, &load_order.game_settings()).unwrap();
1✔
919
        load_order.plugins.insert(1, plugin);
1✔
920

1✔
921
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
922

1✔
923
        let plugin_name = "Blank.full.esm";
1✔
924
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
925

1✔
926
        let plugin = Plugin::new(plugin_name, &load_order.game_settings()).unwrap();
1✔
927
        let position = load_order.insert_position(&plugin);
1✔
928

1✔
929
        assert!(position.is_none());
1✔
930
    }
1✔
931

932
    #[test]
933
    fn insert_position_should_put_blueprint_plugins_before_blueprint_dependents() {
1✔
934
        let tmp_dir = tempdir().unwrap();
1✔
935
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
936

1✔
937
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
938

1✔
939
        let dependent_plugin = "Blank - Override.full.esm";
1✔
940
        copy_to_test_dir(
1✔
941
            dependent_plugin,
1✔
942
            dependent_plugin,
1✔
943
            &load_order.game_settings(),
1✔
944
        );
1✔
945
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
946

1✔
947
        let plugin = Plugin::new(dependent_plugin, &load_order.game_settings()).unwrap();
1✔
948
        load_order.plugins.push(plugin);
1✔
949

1✔
950
        let plugin_name = "Blank.full.esm";
1✔
951
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
952

1✔
953
        let plugin = Plugin::new(plugin_name, &load_order.game_settings()).unwrap();
1✔
954
        let position = load_order.insert_position(&plugin);
1✔
955

1✔
956
        assert_eq!(2, position.unwrap());
1✔
957
    }
1✔
958

959
    #[test]
960
    fn insert_position_should_not_treat_early_loading_blueprint_plugins_as_early_loading() {
1✔
961
        let tmp_dir = tempdir().unwrap();
1✔
962
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
963

1✔
964
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
965

1✔
966
        let plugin_name = "Blank.full.esm";
1✔
967
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
968

1✔
969
        std::fs::write(
1✔
970
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
971
            plugin_name,
1✔
972
        )
1✔
973
        .unwrap();
1✔
974
        load_order
1✔
975
            .game_settings
1✔
976
            .refresh_implicitly_active_plugins()
1✔
977
            .unwrap();
1✔
978

1✔
979
        let plugin = Plugin::new(plugin_name, &load_order.game_settings()).unwrap();
1✔
980
        let position = load_order.insert_position(&plugin);
1✔
981

1✔
982
        assert!(position.is_none());
1✔
983
    }
1✔
984

985
    #[test]
986
    fn insert_position_should_return_none_if_given_a_non_master_plugin() {
1✔
987
        let tmp_dir = tempdir().unwrap();
1✔
988
        let load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
989

1✔
990
        let plugin =
1✔
991
            Plugin::new("Blank - Master Dependent.esp", &load_order.game_settings()).unwrap();
1✔
992
        let position = load_order.insert_position(&plugin);
1✔
993

1✔
994
        assert_eq!(None, position);
1✔
995
    }
1✔
996

997
    #[test]
998
    fn insert_position_should_return_the_first_non_master_plugin_index_if_given_a_master_plugin() {
1✔
999
        let tmp_dir = tempdir().unwrap();
1✔
1000
        let load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1001

1✔
1002
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
1003
        let position = load_order.insert_position(&plugin);
1✔
1004

1✔
1005
        assert_eq!(1, position.unwrap());
1✔
1006
    }
1✔
1007

1008
    #[test]
1009
    fn insert_position_should_return_none_if_no_non_masters_are_present() {
1✔
1010
        let tmp_dir = tempdir().unwrap();
1✔
1011
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1012

1✔
1013
        // Remove non-master plugins from the load order.
1✔
1014
        load_order.plugins_mut().retain(|p| p.is_master_file());
3✔
1015

1✔
1016
        let plugin = Plugin::new("Blank.esm", &load_order.game_settings()).unwrap();
1✔
1017
        let position = load_order.insert_position(&plugin);
1✔
1018

1✔
1019
        assert_eq!(None, position);
1✔
1020
    }
1✔
1021

1022
    #[test]
1023
    fn insert_position_should_return_the_first_non_master_index_if_given_a_light_master() {
1✔
1024
        let tmp_dir = tempdir().unwrap();
1✔
1025
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1026

1✔
1027
        copy_to_test_dir("Blank.esm", "Blank.esl", load_order.game_settings());
1✔
1028
        let plugin = Plugin::new("Blank.esl", &load_order.game_settings()).unwrap();
1✔
1029

1✔
1030
        load_order.plugins_mut().insert(1, plugin);
1✔
1031

1✔
1032
        let position = load_order.insert_position(&load_order.plugins()[1]);
1✔
1033

1✔
1034
        assert_eq!(2, position.unwrap());
1✔
1035

1036
        copy_to_test_dir(
1✔
1037
            "Blank.esp",
1✔
1038
            "Blank - Different.esl",
1✔
1039
            load_order.game_settings(),
1✔
1040
        );
1✔
1041
        let plugin = Plugin::new("Blank - Different.esl", &load_order.game_settings()).unwrap();
1✔
1042

1✔
1043
        let position = load_order.insert_position(&plugin);
1✔
1044

1✔
1045
        assert_eq!(2, position.unwrap());
1✔
1046
    }
1✔
1047

1048
    #[test]
1049
    fn insert_position_should_succeed_for_a_non_master_hoisted_after_another_non_master() {
1✔
1050
        let tmp_dir = tempdir().unwrap();
1✔
1051
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1052

1✔
1053
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1054

1✔
1055
        let plugin = Plugin::new(
1✔
1056
            "Blank - Different Master Dependent.esm",
1✔
1057
            load_order.game_settings(),
1✔
1058
        )
1✔
1059
        .unwrap();
1✔
1060
        load_order.plugins.insert(1, plugin);
1✔
1061

1✔
1062
        let other_non_master = "Blank.esm";
1✔
1063
        set_master_flag(GameId::Oblivion, &plugins_dir.join(other_non_master), false).unwrap();
1✔
1064
        let plugin = Plugin::new(other_non_master, load_order.game_settings()).unwrap();
1✔
1065
        load_order.plugins.insert(1, plugin);
1✔
1066

1✔
1067
        let other_master = "Blank - Master Dependent.esm";
1✔
1068
        copy_to_test_dir(other_master, other_master, load_order.game_settings());
1✔
1069
        let plugin = Plugin::new(other_master, load_order.game_settings()).unwrap();
1✔
1070
        load_order.plugins.insert(2, plugin);
1✔
1071

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

1✔
1074
        let position = load_order.insert_position(&plugin);
1✔
1075

1✔
1076
        assert_eq!(3, position.unwrap());
1✔
1077
    }
1✔
1078

1079
    #[test]
1080
    fn validate_index_should_succeed_for_a_master_plugin_and_index_directly_after_a_master() {
1✔
1081
        let tmp_dir = tempdir().unwrap();
1✔
1082
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1083

1✔
1084
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1085
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1086
    }
1✔
1087

1088
    #[test]
1089
    fn validate_index_should_succeed_for_a_master_plugin_and_index_after_a_hoisted_non_master() {
1✔
1090
        let tmp_dir = tempdir().unwrap();
1✔
1091
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1092

1✔
1093
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1094
        load_order.plugins.insert(1, plugin);
1✔
1095

1✔
1096
        let plugin = Plugin::new(
1✔
1097
            "Blank - Different Master Dependent.esm",
1✔
1098
            load_order.game_settings(),
1✔
1099
        )
1✔
1100
        .unwrap();
1✔
1101
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1102
    }
1✔
1103

1104
    #[test]
1105
    fn validate_index_should_error_for_a_master_plugin_and_index_after_unrelated_non_masters() {
1✔
1106
        let tmp_dir = tempdir().unwrap();
1✔
1107
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1108

1✔
1109
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1110
        load_order.plugins.insert(1, plugin);
1✔
1111

1✔
1112
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1113
        assert!(load_order.validate_index(&plugin, 4).is_err());
1✔
1114
    }
1✔
1115

1116
    #[test]
1117
    fn validate_index_should_error_for_a_master_plugin_that_has_a_later_non_master_as_a_master() {
1✔
1118
        let tmp_dir = tempdir().unwrap();
1✔
1119
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1120

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

1✔
1124
        let plugin = Plugin::new(
1✔
1125
            "Blank - Different Master Dependent.esm",
1✔
1126
            load_order.game_settings(),
1✔
1127
        )
1✔
1128
        .unwrap();
1✔
1129
        assert!(load_order.validate_index(&plugin, 1).is_err());
1✔
1130
    }
1✔
1131

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

1✔
1137
        copy_to_test_dir(
1✔
1138
            "Blank - Master Dependent.esm",
1✔
1139
            "Blank - Master Dependent.esm",
1✔
1140
            load_order.game_settings(),
1✔
1141
        );
1✔
1142
        copy_to_test_dir("Blank.esm", "Blank.esm", load_order.game_settings());
1✔
1143

1✔
1144
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1145
        load_order.plugins.insert(1, plugin);
1✔
1146

1✔
1147
        let plugin =
1✔
1148
            Plugin::new("Blank - Master Dependent.esm", load_order.game_settings()).unwrap();
1✔
1149
        assert!(load_order.validate_index(&plugin, 1).is_err());
1✔
1150
    }
1✔
1151

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

1✔
1157
        copy_to_test_dir(
1✔
1158
            "Blank - Master Dependent.esm",
1✔
1159
            "Blank - Master Dependent.esm",
1✔
1160
            load_order.game_settings(),
1✔
1161
        );
1✔
1162
        copy_to_test_dir("Blank.esm", "Blank.esm", load_order.game_settings());
1✔
1163

1✔
1164
        let plugin =
1✔
1165
            Plugin::new("Blank - Master Dependent.esm", load_order.game_settings()).unwrap();
1✔
1166
        load_order.plugins.insert(1, plugin);
1✔
1167

1✔
1168
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1169
        assert!(load_order.validate_index(&plugin, 2).is_err());
1✔
1170
    }
1✔
1171

1172
    #[test]
1173
    fn validate_index_should_succeed_for_a_non_master_plugin_and_an_index_with_no_later_masters() {
1✔
1174
        let tmp_dir = tempdir().unwrap();
1✔
1175
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1176

1✔
1177
        let plugin =
1✔
1178
            Plugin::new("Blank - Master Dependent.esp", load_order.game_settings()).unwrap();
1✔
1179
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1180
    }
1✔
1181

1182
    #[test]
1183
    fn validate_index_should_succeed_for_a_non_master_plugin_that_is_a_master_of_the_next_master_file(
1✔
1184
    ) {
1✔
1185
        let tmp_dir = tempdir().unwrap();
1✔
1186
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1187

1✔
1188
        let plugin = Plugin::new(
1✔
1189
            "Blank - Different Master Dependent.esm",
1✔
1190
            load_order.game_settings(),
1✔
1191
        )
1✔
1192
        .unwrap();
1✔
1193
        load_order.plugins.insert(1, plugin);
1✔
1194

1✔
1195
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1196
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1197
    }
1✔
1198

1199
    #[test]
1200
    fn validate_index_should_error_for_a_non_master_plugin_that_is_not_a_master_of_the_next_master_file(
1✔
1201
    ) {
1✔
1202
        let tmp_dir = tempdir().unwrap();
1✔
1203
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1204

1✔
1205
        let plugin =
1✔
1206
            Plugin::new("Blank - Master Dependent.esp", load_order.game_settings()).unwrap();
1✔
1207
        assert!(load_order.validate_index(&plugin, 0).is_err());
1✔
1208
    }
1✔
1209

1210
    #[test]
1211
    fn validate_index_should_error_for_a_non_master_plugin_and_an_index_not_before_a_master_that_depends_on_it(
1✔
1212
    ) {
1✔
1213
        let tmp_dir = tempdir().unwrap();
1✔
1214
        let mut load_order = prepare_hoisted(GameId::SkyrimSE, &tmp_dir.path());
1✔
1215

1✔
1216
        let plugin = Plugin::new(
1✔
1217
            "Blank - Different Master Dependent.esm",
1✔
1218
            load_order.game_settings(),
1✔
1219
        )
1✔
1220
        .unwrap();
1✔
1221
        load_order.plugins.insert(1, plugin);
1✔
1222

1✔
1223
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1224
        assert!(load_order.validate_index(&plugin, 2).is_err());
1✔
1225
    }
1✔
1226

1227
    #[test]
1228
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_last() {
1✔
1229
        let tmp_dir = tempdir().unwrap();
1✔
1230
        let load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1231

1✔
1232
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1233

1✔
1234
        let plugin_name = "Blank.full.esm";
1✔
1235
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1236

1✔
1237
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1238
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1239
    }
1✔
1240

1241
    #[test]
1242
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_only_followed_by_other_blueprint_plugins(
1✔
1243
    ) {
1✔
1244
        let tmp_dir = tempdir().unwrap();
1✔
1245
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1246

1✔
1247
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1248

1✔
1249
        let plugin_name = "Blank.full.esm";
1✔
1250
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1251

1✔
1252
        let other_plugin_name = "Blank.medium.esm";
1✔
1253
        set_blueprint_flag(
1✔
1254
            GameId::Starfield,
1✔
1255
            &plugins_dir.join(other_plugin_name),
1✔
1256
            true,
1✔
1257
        )
1✔
1258
        .unwrap();
1✔
1259

1✔
1260
        let other_plugin = Plugin::new(other_plugin_name, load_order.game_settings()).unwrap();
1✔
1261
        load_order.plugins.push(other_plugin);
1✔
1262

1✔
1263
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1264
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1265
    }
1✔
1266

1267
    #[test]
1268
    fn validate_index_should_fail_for_a_blueprint_plugin_index_that_is_after_a_dependent_blueprint_plugin_index(
1✔
1269
    ) {
1✔
1270
        let tmp_dir = tempdir().unwrap();
1✔
1271
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1272

1✔
1273
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1274

1✔
1275
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1276
        copy_to_test_dir(
1✔
1277
            dependent_plugin,
1✔
1278
            dependent_plugin,
1✔
1279
            load_order.game_settings(),
1✔
1280
        );
1✔
1281
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
1282
        let plugin = Plugin::new(dependent_plugin, load_order.game_settings()).unwrap();
1✔
1283
        load_order.plugins.insert(1, plugin);
1✔
1284

1✔
1285
        let plugin_name = "Blank.full.esm";
1✔
1286
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1287

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

1✔
1290
        let index = 3;
1✔
1291
        match load_order.validate_index(&plugin, index).unwrap_err() {
1✔
1292
            Error::UnrepresentedHoist { plugin, master } => {
1✔
1293
                assert_eq!(plugin_name, plugin);
1✔
1294
                assert_eq!(dependent_plugin, master);
1✔
1295
            }
NEW
1296
            e => panic!("Unexpected error type: {:?}", e),
×
1297
        }
1298
    }
1✔
1299

1300
    #[test]
1301
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_after_a_dependent_non_blueprint_plugin_index(
1✔
1302
    ) {
1✔
1303
        let tmp_dir = tempdir().unwrap();
1✔
1304
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1305

1✔
1306
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1307

1✔
1308
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1309
        copy_to_test_dir(
1✔
1310
            dependent_plugin,
1✔
1311
            dependent_plugin,
1✔
1312
            load_order.game_settings(),
1✔
1313
        );
1✔
1314
        let plugin = Plugin::new(dependent_plugin, load_order.game_settings()).unwrap();
1✔
1315
        load_order.plugins.insert(1, plugin);
1✔
1316

1✔
1317
        let plugin_name = "Blank.full.esm";
1✔
1318
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1319

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

1✔
1322
        assert!(load_order.validate_index(&plugin, 3).is_ok());
1✔
1323
    }
1✔
1324

1325
    #[test]
1326
    fn validate_index_should_succeed_when_an_early_loader_is_a_blueprint_plugin() {
1✔
1327
        let tmp_dir = tempdir().unwrap();
1✔
1328
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1329

1✔
1330
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1331

1✔
1332
        let plugin_name = "Blank.full.esm";
1✔
1333
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1334

1✔
1335
        std::fs::write(
1✔
1336
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
1337
            format!("Starfield.esm\n{}", plugin_name),
1✔
1338
        )
1✔
1339
        .unwrap();
1✔
1340
        load_order
1✔
1341
            .game_settings
1✔
1342
            .refresh_implicitly_active_plugins()
1✔
1343
            .unwrap();
1✔
1344

1✔
1345
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1346
        load_order.plugins.push(plugin);
1✔
1347

1✔
1348
        let plugin = Plugin::new("Blank.medium.esm", load_order.game_settings()).unwrap();
1✔
1349
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1350
    }
1✔
1351

1352
    #[test]
1353
    fn validate_index_should_succeed_for_an_early_loader_listed_after_a_blueprint_plugin() {
1✔
1354
        let tmp_dir = tempdir().unwrap();
1✔
1355
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1356

1✔
1357
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1358

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

1✔
1362
        let early_loader = "Blank.medium.esm";
1✔
1363

1✔
1364
        std::fs::write(
1✔
1365
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
1366
            format!("Starfield.esm\n{}\n{}", blueprint_plugin, early_loader),
1✔
1367
        )
1✔
1368
        .unwrap();
1✔
1369
        load_order
1✔
1370
            .game_settings
1✔
1371
            .refresh_implicitly_active_plugins()
1✔
1372
            .unwrap();
1✔
1373

1✔
1374
        let plugin = Plugin::new(blueprint_plugin, load_order.game_settings()).unwrap();
1✔
1375
        load_order.plugins.push(plugin);
1✔
1376

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

1✔
1379
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1380
    }
1✔
1381

1382
    #[test]
1383
    fn set_plugin_index_should_error_if_inserting_a_non_master_before_a_master() {
1✔
1384
        let tmp_dir = tempdir().unwrap();
1✔
1385
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1386

1✔
1387
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1388
        assert!(load_order
1✔
1389
            .set_plugin_index("Blank - Master Dependent.esp", 0)
1✔
1390
            .is_err());
1✔
1391
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1392
    }
1✔
1393

1394
    #[test]
1395
    fn set_plugin_index_should_error_if_moving_a_non_master_before_a_master() {
1✔
1396
        let tmp_dir = tempdir().unwrap();
1✔
1397
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1398

1✔
1399
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1400
        assert!(load_order.set_plugin_index("Blank.esp", 0).is_err());
1✔
1401
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1402
    }
1✔
1403

1404
    #[test]
1405
    fn set_plugin_index_should_error_if_inserting_a_master_after_a_non_master() {
1✔
1406
        let tmp_dir = tempdir().unwrap();
1✔
1407
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1408

1✔
1409
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1410
        assert!(load_order.set_plugin_index("Blank.esm", 2).is_err());
1✔
1411
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1412
    }
1✔
1413

1414
    #[test]
1415
    fn set_plugin_index_should_error_if_moving_a_master_after_a_non_master() {
1✔
1416
        let tmp_dir = tempdir().unwrap();
1✔
1417
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1418

1✔
1419
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1420
        assert!(load_order.set_plugin_index("Morrowind.esm", 2).is_err());
1✔
1421
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1422
    }
1✔
1423

1424
    #[test]
1425
    fn set_plugin_index_should_error_if_setting_the_index_of_an_invalid_plugin() {
1✔
1426
        let tmp_dir = tempdir().unwrap();
1✔
1427
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1428

1✔
1429
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1430
        assert!(load_order.set_plugin_index("missing.esm", 0).is_err());
1✔
1431
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1432
    }
1✔
1433

1434
    #[test]
1435
    fn set_plugin_index_should_error_if_moving_a_plugin_before_an_early_loader() {
1✔
1436
        let tmp_dir = tempdir().unwrap();
1✔
1437
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1438

1✔
1439
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1440

1✔
1441
        match load_order.set_plugin_index("Blank.esp", 0).unwrap_err() {
1✔
1442
            Error::InvalidEarlyLoadingPluginPosition {
1443
                name,
1✔
1444
                pos,
1✔
1445
                expected_pos,
1✔
1446
            } => {
1✔
1447
                assert_eq!("Skyrim.esm", name);
1✔
1448
                assert_eq!(1, pos);
1✔
1449
                assert_eq!(0, expected_pos);
1✔
1450
            }
UNCOV
1451
            e => panic!(
×
UNCOV
1452
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1453
                e
×
UNCOV
1454
            ),
×
1455
        };
1456

1457
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1458
    }
1✔
1459

1460
    #[test]
1461
    fn set_plugin_index_should_error_if_moving_an_early_loader_to_a_different_position() {
1✔
1462
        let tmp_dir = tempdir().unwrap();
1✔
1463
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1464

1✔
1465
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1466

1✔
1467
        match load_order.set_plugin_index("Skyrim.esm", 1).unwrap_err() {
1✔
1468
            Error::InvalidEarlyLoadingPluginPosition {
1469
                name,
1✔
1470
                pos,
1✔
1471
                expected_pos,
1✔
1472
            } => {
1✔
1473
                assert_eq!("Skyrim.esm", name);
1✔
1474
                assert_eq!(1, pos);
1✔
1475
                assert_eq!(0, expected_pos);
1✔
1476
            }
UNCOV
1477
            e => panic!(
×
UNCOV
1478
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1479
                e
×
UNCOV
1480
            ),
×
1481
        };
1482

1483
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1484
    }
1✔
1485

1486
    #[test]
1487
    fn set_plugin_index_should_error_if_inserting_an_early_loader_to_the_wrong_position() {
1✔
1488
        let tmp_dir = tempdir().unwrap();
1✔
1489
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1490

1✔
1491
        load_order.set_plugin_index("Blank.esm", 1).unwrap();
1✔
1492
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1493

1✔
1494
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1495

1✔
1496
        match load_order
1✔
1497
            .set_plugin_index("Dragonborn.esm", 2)
1✔
1498
            .unwrap_err()
1✔
1499
        {
1500
            Error::InvalidEarlyLoadingPluginPosition {
1501
                name,
1✔
1502
                pos,
1✔
1503
                expected_pos,
1✔
1504
            } => {
1✔
1505
                assert_eq!("Dragonborn.esm", name);
1✔
1506
                assert_eq!(2, pos);
1✔
1507
                assert_eq!(1, expected_pos);
1✔
1508
            }
UNCOV
1509
            e => panic!(
×
UNCOV
1510
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1511
                e
×
UNCOV
1512
            ),
×
1513
        };
1514

1515
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1516
    }
1✔
1517

1518
    #[test]
1519
    fn set_plugin_index_should_succeed_if_setting_an_early_loader_to_its_current_position() {
1✔
1520
        let tmp_dir = tempdir().unwrap();
1✔
1521
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1522

1✔
1523
        assert!(load_order.set_plugin_index("Skyrim.esm", 0).is_ok());
1✔
1524
        assert_eq!(
1✔
1525
            vec!["Skyrim.esm", "Blank.esp", "Blank - Different.esp"],
1✔
1526
            load_order.plugin_names()
1✔
1527
        );
1✔
1528
    }
1✔
1529

1530
    #[test]
1531
    fn set_plugin_index_should_succeed_if_inserting_a_new_early_loader() {
1✔
1532
        let tmp_dir = tempdir().unwrap();
1✔
1533
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1534

1✔
1535
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1536

1✔
1537
        assert!(load_order.set_plugin_index("Dragonborn.esm", 1).is_ok());
1✔
1538
        assert_eq!(
1✔
1539
            vec![
1✔
1540
                "Skyrim.esm",
1✔
1541
                "Dragonborn.esm",
1✔
1542
                "Blank.esp",
1✔
1543
                "Blank - Different.esp"
1✔
1544
            ],
1✔
1545
            load_order.plugin_names()
1✔
1546
        );
1✔
1547
    }
1✔
1548

1549
    #[test]
1550
    fn set_plugin_index_should_insert_a_new_plugin() {
1✔
1551
        let tmp_dir = tempdir().unwrap();
1✔
1552
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1553

1✔
1554
        let num_plugins = load_order.plugins().len();
1✔
1555
        assert_eq!(1, load_order.set_plugin_index("Blank.esm", 1).unwrap());
1✔
1556
        assert_eq!(1, load_order.index_of("Blank.esm").unwrap());
1✔
1557
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1558
    }
1✔
1559

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

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

1✔
1567
        load_order.replace_plugins(&filenames).unwrap();
1✔
1568
        assert_eq!(filenames, load_order.plugin_names());
1✔
1569

1570
        let num_plugins = load_order.plugins().len();
1✔
1571
        let index = load_order
1✔
1572
            .set_plugin_index("Blank - Different.esm", 1)
1✔
1573
            .unwrap();
1✔
1574
        assert_eq!(1, index);
1✔
1575
        assert_eq!(1, load_order.index_of("Blank - Different.esm").unwrap());
1✔
1576
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1577
    }
1✔
1578

1579
    #[test]
1580
    fn set_plugin_index_should_allow_a_master_file_to_load_after_another_that_hoists_non_masters() {
1✔
1581
        let tmp_dir = tempdir().unwrap();
1✔
1582
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1583

1✔
1584
        let filenames = vec![
1✔
1585
            "Blank - Different.esm",
1✔
1586
            "Blank - Different Master Dependent.esm",
1✔
1587
        ];
1✔
1588

1✔
1589
        load_order.replace_plugins(&filenames).unwrap();
1✔
1590
        assert_eq!(filenames, load_order.plugin_names());
1✔
1591

1592
        let num_plugins = load_order.plugins().len();
1✔
1593
        assert_eq!(2, load_order.set_plugin_index("Blank.esm", 2).unwrap());
1✔
1594
        assert_eq!(2, load_order.index_of("Blank.esm").unwrap());
1✔
1595
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1596
    }
1✔
1597

1598
    #[test]
1599
    fn set_plugin_index_should_move_an_existing_plugin() {
1✔
1600
        let tmp_dir = tempdir().unwrap();
1✔
1601
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1602

1✔
1603
        let num_plugins = load_order.plugins().len();
1✔
1604
        let index = load_order
1✔
1605
            .set_plugin_index("Blank - Different.esp", 1)
1✔
1606
            .unwrap();
1✔
1607
        assert_eq!(1, index);
1✔
1608
        assert_eq!(1, load_order.index_of("Blank - Different.esp").unwrap());
1✔
1609
        assert_eq!(num_plugins, load_order.plugins().len());
1✔
1610
    }
1✔
1611

1612
    #[test]
1613
    fn set_plugin_index_should_move_an_existing_plugin_later_correctly() {
1✔
1614
        let tmp_dir = tempdir().unwrap();
1✔
1615
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1616

1✔
1617
        load_and_insert(&mut load_order, "Blank - Master Dependent.esp");
1✔
1618
        let num_plugins = load_order.plugins().len();
1✔
1619
        assert_eq!(2, load_order.set_plugin_index("Blank.esp", 2).unwrap());
1✔
1620
        assert_eq!(2, load_order.index_of("Blank.esp").unwrap());
1✔
1621
        assert_eq!(num_plugins, load_order.plugins().len());
1✔
1622
    }
1✔
1623

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

1✔
1629
        load_and_insert(&mut load_order, "Blank - Master Dependent.esp");
1✔
1630
        assert_eq!(2, load_order.set_plugin_index("Blank.esp", 2).unwrap());
1✔
1631
        assert!(load_order.is_active("Blank.esp"));
1✔
1632

1633
        let index = load_order
1✔
1634
            .set_plugin_index("Blank - Different.esp", 2)
1✔
1635
            .unwrap();
1✔
1636
        assert_eq!(2, index);
1✔
1637
        assert!(!load_order.is_active("Blank - Different.esp"));
1✔
1638
    }
1✔
1639

1640
    #[test]
1641
    fn replace_plugins_should_error_if_given_duplicate_plugins() {
1✔
1642
        let tmp_dir = tempdir().unwrap();
1✔
1643
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1644

1✔
1645
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1646
        let filenames = vec!["Blank.esp", "blank.esp"];
1✔
1647
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1648
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1649
    }
1✔
1650

1651
    #[test]
1652
    fn replace_plugins_should_error_if_given_an_invalid_plugin() {
1✔
1653
        let tmp_dir = tempdir().unwrap();
1✔
1654
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1655

1✔
1656
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1657
        let filenames = vec!["Blank.esp", "missing.esp"];
1✔
1658
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1659
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1660
    }
1✔
1661

1662
    #[test]
1663
    fn replace_plugins_should_error_if_given_a_list_with_plugins_before_masters() {
1✔
1664
        let tmp_dir = tempdir().unwrap();
1✔
1665
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1666

1✔
1667
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1668
        let filenames = vec!["Blank.esp", "Blank.esm"];
1✔
1669
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1670
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1671
    }
1✔
1672

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

1✔
1678
        copy_to_test_dir("Blank.esm", "Update.esm", &load_order.game_settings());
1✔
1679

1✔
1680
        let filenames = vec![
1✔
1681
            "Skyrim.esm",
1✔
1682
            "Blank.esm",
1✔
1683
            "Update.esm",
1✔
1684
            "Blank.esp",
1✔
1685
            "Blank - Master Dependent.esp",
1✔
1686
            "Blank - Different.esp",
1✔
1687
            "Blàñk.esp",
1✔
1688
        ];
1✔
1689

1✔
1690
        match load_order.replace_plugins(&filenames).unwrap_err() {
1✔
1691
            Error::InvalidEarlyLoadingPluginPosition {
1692
                name,
1✔
1693
                pos,
1✔
1694
                expected_pos,
1✔
1695
            } => {
1✔
1696
                assert_eq!("Update.esm", name);
1✔
1697
                assert_eq!(2, pos);
1✔
1698
                assert_eq!(1, expected_pos);
1✔
1699
            }
UNCOV
1700
            e => panic!("Wrong error type: {:?}", e),
×
1701
        }
1702
    }
1✔
1703

1704
    #[test]
1705
    fn replace_plugins_should_not_error_if_an_early_loading_plugin_is_missing() {
1✔
1706
        let tmp_dir = tempdir().unwrap();
1✔
1707
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1708

1✔
1709
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1710

1✔
1711
        let filenames = vec![
1✔
1712
            "Skyrim.esm",
1✔
1713
            "Dragonborn.esm",
1✔
1714
            "Blank.esm",
1✔
1715
            "Blank.esp",
1✔
1716
            "Blank - Master Dependent.esp",
1✔
1717
            "Blank - Different.esp",
1✔
1718
            "Blàñk.esp",
1✔
1719
        ];
1✔
1720

1✔
1721
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1722
    }
1✔
1723

1724
    #[test]
1725
    fn replace_plugins_should_not_error_if_a_non_early_loading_implicitly_active_plugin_loads_after_another_plugin(
1✔
1726
    ) {
1✔
1727
        let tmp_dir = tempdir().unwrap();
1✔
1728

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

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

1✔
1735
        let filenames = vec![
1✔
1736
            "Skyrim.esm",
1✔
1737
            "Blank.esm",
1✔
1738
            "Blank.esp",
1✔
1739
            "Blank - Master Dependent.esp",
1✔
1740
            "Blank - Different.esp",
1✔
1741
            "Blàñk.esp",
1✔
1742
        ];
1✔
1743

1✔
1744
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1745
    }
1✔
1746

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

1✔
1752
        copy_to_test_dir(
1✔
1753
            "Blank - Different.esm",
1✔
1754
            "ghosted.esm.ghost",
1✔
1755
            &load_order.game_settings(),
1✔
1756
        );
1✔
1757

1✔
1758
        let filenames = vec![
1✔
1759
            "Morrowind.esm",
1✔
1760
            "Blank.esm",
1✔
1761
            "ghosted.esm",
1✔
1762
            "Blank.esp",
1✔
1763
            "Blank - Master Dependent.esp",
1✔
1764
            "Blank - Different.esp",
1✔
1765
            "Blàñk.esp",
1✔
1766
        ];
1✔
1767

1✔
1768
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1769
    }
1✔
1770

1771
    #[test]
1772
    fn replace_plugins_should_not_insert_missing_plugins() {
1✔
1773
        let tmp_dir = tempdir().unwrap();
1✔
1774
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1775

1✔
1776
        let filenames = vec![
1✔
1777
            "Blank.esm",
1✔
1778
            "Blank.esp",
1✔
1779
            "Blank - Master Dependent.esp",
1✔
1780
            "Blank - Different.esp",
1✔
1781
        ];
1✔
1782
        load_order.replace_plugins(&filenames).unwrap();
1✔
1783

1✔
1784
        assert_eq!(filenames, load_order.plugin_names());
1✔
1785
    }
1✔
1786

1787
    #[test]
1788
    fn replace_plugins_should_not_lose_active_state_of_existing_plugins() {
1✔
1789
        let tmp_dir = tempdir().unwrap();
1✔
1790
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1791

1✔
1792
        let filenames = vec![
1✔
1793
            "Blank.esm",
1✔
1794
            "Blank.esp",
1✔
1795
            "Blank - Master Dependent.esp",
1✔
1796
            "Blank - Different.esp",
1✔
1797
        ];
1✔
1798
        load_order.replace_plugins(&filenames).unwrap();
1✔
1799

1✔
1800
        assert!(load_order.is_active("Blank.esp"));
1✔
1801
    }
1✔
1802

1803
    #[test]
1804
    fn replace_plugins_should_accept_hoisted_non_masters() {
1✔
1805
        let tmp_dir = tempdir().unwrap();
1✔
1806
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1807

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

1✔
1819
        load_order.replace_plugins(&filenames).unwrap();
1✔
1820
        assert_eq!(filenames, load_order.plugin_names());
1✔
1821
    }
1✔
1822

1823
    #[test]
1824
    fn hoist_masters_should_hoist_plugins_that_masters_depend_on_to_load_before_their_first_dependent(
1✔
1825
    ) {
1✔
1826
        let tmp_dir = tempdir().unwrap();
1✔
1827
        let (game_settings, _) = mock_game_files(GameId::SkyrimSE, &tmp_dir.path());
1✔
1828

1✔
1829
        // Test both hoisting a master before a master and a non-master before a master.
1✔
1830

1✔
1831
        let master_dependent_master = "Blank - Master Dependent.esm";
1✔
1832
        copy_to_test_dir(
1✔
1833
            master_dependent_master,
1✔
1834
            master_dependent_master,
1✔
1835
            &game_settings,
1✔
1836
        );
1✔
1837

1✔
1838
        let plugin_dependent_master = "Blank - Plugin Dependent.esm";
1✔
1839
        copy_to_test_dir(
1✔
1840
            "Blank - Plugin Dependent.esp",
1✔
1841
            plugin_dependent_master,
1✔
1842
            &game_settings,
1✔
1843
        );
1✔
1844

1✔
1845
        let plugin_names = vec![
1✔
1846
            "Skyrim.esm",
1✔
1847
            master_dependent_master,
1✔
1848
            "Blank.esm",
1✔
1849
            plugin_dependent_master,
1✔
1850
            "Blank - Master Dependent.esp",
1✔
1851
            "Blank - Different.esp",
1✔
1852
            "Blàñk.esp",
1✔
1853
            "Blank.esp",
1✔
1854
        ];
1✔
1855
        let mut plugins = plugin_names
1✔
1856
            .iter()
1✔
1857
            .map(|n| Plugin::new(n, &game_settings).unwrap())
8✔
1858
            .collect();
1✔
1859

1✔
1860
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1861

1862
        let expected_plugin_names = vec![
1✔
1863
            "Skyrim.esm",
1✔
1864
            "Blank.esm",
1✔
1865
            master_dependent_master,
1✔
1866
            "Blank.esp",
1✔
1867
            plugin_dependent_master,
1✔
1868
            "Blank - Master Dependent.esp",
1✔
1869
            "Blank - Different.esp",
1✔
1870
            "Blàñk.esp",
1✔
1871
        ];
1✔
1872

1✔
1873
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1874
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1875
    }
1✔
1876

1877
    #[test]
1878
    fn hoist_masters_should_not_hoist_blueprint_plugins_that_are_masters_of_non_blueprint_plugins()
1✔
1879
    {
1✔
1880
        let tmp_dir = tempdir().unwrap();
1✔
1881
        let (game_settings, _) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
1882

1✔
1883
        let blueprint_plugin = "Blank.full.esm";
1✔
1884
        set_blueprint_flag(
1✔
1885
            GameId::Starfield,
1✔
1886
            &game_settings.plugins_directory().join(blueprint_plugin),
1✔
1887
            true,
1✔
1888
        )
1✔
1889
        .unwrap();
1✔
1890

1✔
1891
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1892
        copy_to_test_dir(dependent_plugin, dependent_plugin, &game_settings);
1✔
1893

1✔
1894
        let plugin_names = vec![
1✔
1895
            "Starfield.esm",
1✔
1896
            dependent_plugin,
1✔
1897
            "Blank.esp",
1✔
1898
            blueprint_plugin,
1✔
1899
        ];
1✔
1900

1✔
1901
        let mut plugins = plugin_names
1✔
1902
            .iter()
1✔
1903
            .map(|n| Plugin::new(n, &game_settings).unwrap())
4✔
1904
            .collect();
1✔
1905

1✔
1906
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1907

1908
        let expected_plugin_names = plugin_names;
1✔
1909

1✔
1910
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1911
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1912
    }
1✔
1913

1914
    #[test]
1915
    fn hoist_masters_should_hoist_blueprint_plugins_that_are_masters_of_blueprint_plugins() {
1✔
1916
        let tmp_dir = tempdir().unwrap();
1✔
1917
        let (game_settings, _) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
1918

1✔
1919
        let plugins_dir = game_settings.plugins_directory();
1✔
1920

1✔
1921
        let blueprint_plugin = "Blank.full.esm";
1✔
1922
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(blueprint_plugin), true).unwrap();
1✔
1923

1✔
1924
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1925
        copy_to_test_dir(dependent_plugin, dependent_plugin, &game_settings);
1✔
1926
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
1927

1✔
1928
        let plugin_names = vec![
1✔
1929
            "Starfield.esm",
1✔
1930
            "Blank.esp",
1✔
1931
            dependent_plugin,
1✔
1932
            blueprint_plugin,
1✔
1933
        ];
1✔
1934

1✔
1935
        let mut plugins = plugin_names
1✔
1936
            .iter()
1✔
1937
            .map(|n| Plugin::new(n, &game_settings).unwrap())
4✔
1938
            .collect();
1✔
1939

1✔
1940
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1941

1942
        let expected_plugin_names = vec![
1✔
1943
            "Starfield.esm",
1✔
1944
            "Blank.esp",
1✔
1945
            blueprint_plugin,
1✔
1946
            dependent_plugin,
1✔
1947
        ];
1✔
1948

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

1953
    #[test]
1954
    fn find_plugins_in_dirs_should_sort_files_by_modification_timestamp() {
1✔
1955
        let tmp_dir = tempdir().unwrap();
1✔
1956
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1957

1✔
1958
        let result = find_plugins_in_dirs(
1✔
1959
            &[load_order.game_settings.plugins_directory()],
1✔
1960
            load_order.game_settings.id(),
1✔
1961
        );
1✔
1962

1✔
1963
        let plugin_names = [
1✔
1964
            load_order.game_settings.master_file(),
1✔
1965
            "Blank.esm",
1✔
1966
            "Blank.esp",
1✔
1967
            "Blank - Different.esp",
1✔
1968
            "Blank - Master Dependent.esp",
1✔
1969
            "Blàñk.esp",
1✔
1970
        ];
1✔
1971

1✔
1972
        assert_eq!(plugin_names.as_slice(), result);
1✔
1973
    }
1✔
1974

1975
    #[test]
1976
    fn find_plugins_in_dirs_should_sort_files_by_descending_filename_if_timestamps_are_equal() {
1✔
1977
        let tmp_dir = tempdir().unwrap();
1✔
1978
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1979

1✔
1980
        let timestamp = 1321010051;
1✔
1981
        let plugin_path = load_order
1✔
1982
            .game_settings
1✔
1983
            .plugins_directory()
1✔
1984
            .join("Blank - Different.esp");
1✔
1985
        set_file_timestamps(&plugin_path, timestamp);
1✔
1986
        let plugin_path = load_order
1✔
1987
            .game_settings
1✔
1988
            .plugins_directory()
1✔
1989
            .join("Blank - Master Dependent.esp");
1✔
1990
        set_file_timestamps(&plugin_path, timestamp);
1✔
1991

1✔
1992
        let result = find_plugins_in_dirs(
1✔
1993
            &[load_order.game_settings.plugins_directory()],
1✔
1994
            load_order.game_settings.id(),
1✔
1995
        );
1✔
1996

1✔
1997
        let plugin_names = [
1✔
1998
            load_order.game_settings.master_file(),
1✔
1999
            "Blank.esm",
1✔
2000
            "Blank.esp",
1✔
2001
            "Blank - Master Dependent.esp",
1✔
2002
            "Blank - Different.esp",
1✔
2003
            "Blàñk.esp",
1✔
2004
        ];
1✔
2005

1✔
2006
        assert_eq!(plugin_names.as_slice(), result);
1✔
2007
    }
1✔
2008

2009
    #[test]
2010
    fn find_plugins_in_dirs_should_sort_files_by_ascending_filename_if_timestamps_are_equal_and_game_is_starfield(
1✔
2011
    ) {
1✔
2012
        let tmp_dir = tempdir().unwrap();
1✔
2013
        let (game_settings, plugins) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
2014
        let load_order = TestLoadOrder {
1✔
2015
            game_settings,
1✔
2016
            plugins,
1✔
2017
        };
1✔
2018

1✔
2019
        let timestamp = 1321009991;
1✔
2020

1✔
2021
        let plugin_names = [
1✔
2022
            "Blank - Override.esp",
1✔
2023
            "Blank.esp",
1✔
2024
            "Blank.full.esm",
1✔
2025
            "Blank.medium.esm",
1✔
2026
            "Blank.small.esm",
1✔
2027
            "Starfield.esm",
1✔
2028
        ];
1✔
2029

2030
        for plugin_name in plugin_names {
7✔
2031
            let plugin_path = load_order
6✔
2032
                .game_settings
6✔
2033
                .plugins_directory()
6✔
2034
                .join(plugin_name);
6✔
2035
            set_file_timestamps(&plugin_path, timestamp);
6✔
2036
        }
6✔
2037

2038
        let result = find_plugins_in_dirs(
1✔
2039
            &[load_order.game_settings.plugins_directory()],
1✔
2040
            load_order.game_settings.id(),
1✔
2041
        );
1✔
2042

1✔
2043
        assert_eq!(plugin_names.as_slice(), result);
1✔
2044
    }
1✔
2045

2046
    #[test]
2047
    fn move_elements_should_correct_later_indices_to_account_for_earlier_moves() {
1✔
2048
        let mut vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
1✔
2049
        let mut from_to_indices = BTreeMap::new();
1✔
2050
        from_to_indices.insert(6, 3);
1✔
2051
        from_to_indices.insert(5, 2);
1✔
2052
        from_to_indices.insert(7, 1);
1✔
2053

1✔
2054
        move_elements(&mut vec, from_to_indices);
1✔
2055

1✔
2056
        assert_eq!(vec![0, 7, 1, 5, 2, 6, 3, 4, 8], vec);
1✔
2057
    }
1✔
2058

2059
    #[test]
2060
    fn validate_load_order_should_be_ok_if_there_are_only_master_files() {
1✔
2061
        let tmp_dir = tempdir().unwrap();
1✔
2062
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2063

1✔
2064
        let plugins = vec![
1✔
2065
            Plugin::new(settings.master_file(), &settings).unwrap(),
1✔
2066
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2067
        ];
1✔
2068

1✔
2069
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2070
    }
1✔
2071

2072
    #[test]
2073
    fn validate_load_order_should_be_ok_if_there_are_no_master_files() {
1✔
2074
        let tmp_dir = tempdir().unwrap();
1✔
2075
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2076

1✔
2077
        let plugins = vec![
1✔
2078
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2079
            Plugin::new("Blank - Different.esp", &settings).unwrap(),
1✔
2080
        ];
1✔
2081

1✔
2082
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2083
    }
1✔
2084

2085
    #[test]
2086
    fn validate_load_order_should_be_ok_if_master_files_are_before_all_others() {
1✔
2087
        let tmp_dir = tempdir().unwrap();
1✔
2088
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2089

1✔
2090
        let plugins = vec![
1✔
2091
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2092
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2093
        ];
1✔
2094

1✔
2095
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2096
    }
1✔
2097

2098
    #[test]
2099
    fn validate_load_order_should_be_ok_if_hoisted_non_masters_load_before_masters() {
1✔
2100
        let tmp_dir = tempdir().unwrap();
1✔
2101
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2102

1✔
2103
        copy_to_test_dir(
1✔
2104
            "Blank - Plugin Dependent.esp",
1✔
2105
            "Blank - Plugin Dependent.esm",
1✔
2106
            &settings,
1✔
2107
        );
1✔
2108

1✔
2109
        let plugins = vec![
1✔
2110
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2111
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2112
            Plugin::new("Blank - Plugin Dependent.esm", &settings).unwrap(),
1✔
2113
        ];
1✔
2114

1✔
2115
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2116
    }
1✔
2117

2118
    #[test]
2119
    fn validate_load_order_should_error_if_non_masters_are_hoisted_earlier_than_needed() {
1✔
2120
        let tmp_dir = tempdir().unwrap();
1✔
2121
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2122

1✔
2123
        copy_to_test_dir(
1✔
2124
            "Blank - Plugin Dependent.esp",
1✔
2125
            "Blank - Plugin Dependent.esm",
1✔
2126
            &settings,
1✔
2127
        );
1✔
2128

1✔
2129
        let plugins = vec![
1✔
2130
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2131
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2132
            Plugin::new("Blank - Plugin Dependent.esm", &settings).unwrap(),
1✔
2133
        ];
1✔
2134

1✔
2135
        assert!(validate_load_order(&plugins, &[]).is_err());
1✔
2136
    }
1✔
2137

2138
    #[test]
2139
    fn validate_load_order_should_error_if_master_files_load_before_non_masters_they_have_as_masters(
1✔
2140
    ) {
1✔
2141
        let tmp_dir = tempdir().unwrap();
1✔
2142
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2143

1✔
2144
        copy_to_test_dir(
1✔
2145
            "Blank - Plugin Dependent.esp",
1✔
2146
            "Blank - Plugin Dependent.esm",
1✔
2147
            &settings,
1✔
2148
        );
1✔
2149

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

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

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

1✔
2165
        copy_to_test_dir(
1✔
2166
            "Blank - Master Dependent.esm",
1✔
2167
            "Blank - Master Dependent.esm",
1✔
2168
            &settings,
1✔
2169
        );
1✔
2170

1✔
2171
        let plugins = vec![
1✔
2172
            Plugin::new("Blank - Master Dependent.esm", &settings).unwrap(),
1✔
2173
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2174
        ];
1✔
2175

1✔
2176
        assert!(validate_load_order(&plugins, &[]).is_err());
1✔
2177
    }
1✔
2178

2179
    #[test]
2180
    fn validate_load_order_should_succeed_if_a_blueprint_plugin_loads_after_all_non_blueprint_plugins(
1✔
2181
    ) {
1✔
2182
        let tmp_dir = tempdir().unwrap();
1✔
2183
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2184

1✔
2185
        let plugins_dir = settings.plugins_directory();
1✔
2186

1✔
2187
        let plugin_name = "Blank.full.esm";
1✔
2188
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2189

1✔
2190
        let plugins = vec![
1✔
2191
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2192
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2193
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2194
        ];
1✔
2195

1✔
2196
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2197
    }
1✔
2198

2199
    #[test]
2200
    fn validate_load_order_should_succeed_if_a_blueprint_plugin_loads_after_a_non_blueprint_plugin_that_depends_on_it(
1✔
2201
    ) {
1✔
2202
        let tmp_dir = tempdir().unwrap();
1✔
2203
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2204

1✔
2205
        let plugins_dir = settings.plugins_directory();
1✔
2206

1✔
2207
        let plugin_name = "Blank.full.esm";
1✔
2208
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2209

1✔
2210
        let dependent_plugin = "Blank - Override.full.esm";
1✔
2211
        copy_to_test_dir(dependent_plugin, dependent_plugin, &settings);
1✔
2212

1✔
2213
        let plugins = vec![
1✔
2214
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2215
            Plugin::new(dependent_plugin, &settings).unwrap(),
1✔
2216
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2217
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2218
        ];
1✔
2219

1✔
2220
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2221
    }
1✔
2222

2223
    #[test]
2224
    fn validate_load_order_should_fail_if_a_blueprint_plugin_loads_after_a_blueprint_plugin_that_depends_on_it(
1✔
2225
    ) {
1✔
2226
        let tmp_dir = tempdir().unwrap();
1✔
2227
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2228

1✔
2229
        let plugins_dir = settings.plugins_directory();
1✔
2230

1✔
2231
        let plugin_name = "Blank.full.esm";
1✔
2232
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2233

1✔
2234
        let dependent_plugin = "Blank - Override.full.esm";
1✔
2235
        copy_to_test_dir(dependent_plugin, dependent_plugin, &settings);
1✔
2236
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
2237

1✔
2238
        let plugins = vec![
1✔
2239
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2240
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2241
            Plugin::new(dependent_plugin, &settings).unwrap(),
1✔
2242
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2243
        ];
1✔
2244

1✔
2245
        match validate_load_order(&plugins, &[]).unwrap_err() {
1✔
2246
            Error::UnrepresentedHoist { plugin, master } => {
1✔
2247
                assert_eq!(plugin_name, plugin);
1✔
2248
                assert_eq!(dependent_plugin, master);
1✔
2249
            }
NEW
2250
            e => panic!("Unexpected error type: {:?}", e),
×
2251
        }
2252
    }
1✔
2253

2254
    #[test]
2255
    fn find_first_non_master_should_find_a_full_esp() {
1✔
2256
        let tmp_dir = tempdir().unwrap();
1✔
2257
        let plugins = prepare_plugins(&tmp_dir.path(), "Blank.esp");
1✔
2258

1✔
2259
        let first_non_master = super::find_first_non_master_position(&plugins);
1✔
2260
        assert_eq!(1, first_non_master.unwrap());
1✔
2261
    }
1✔
2262

2263
    #[test]
2264
    fn find_first_non_master_should_find_a_light_flagged_esp() {
1✔
2265
        let tmp_dir = tempdir().unwrap();
1✔
2266
        let plugins = prepare_plugins(&tmp_dir.path(), "Blank.esl");
1✔
2267

1✔
2268
        let first_non_master = super::find_first_non_master_position(&plugins);
1✔
2269
        assert_eq!(1, first_non_master.unwrap());
1✔
2270
    }
1✔
2271
}
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