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

Ortham / libloadorder / 10151892208

29 Jul 2024 09:09PM UTC coverage: 91.807% (+0.4%) from 91.407%
10151892208

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.

592 of 603 new or added lines in 6 files covered. (98.18%)

100 existing lines in 5 files now uncovered.

7911 of 8617 relevant lines covered (91.81%)

166037.51 hits per line

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

98.74
/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,668✔
40
        if self.plugins().is_empty() {
19,668✔
41
            return None;
35✔
42
        }
19,633✔
43

19,633✔
44
        // A blueprint plugin may be listed as an early loader (e.g. in a CCC
19,633✔
45
        // file) but it still loads as a normal blueprint plugin.
19,633✔
46
        if !plugin.is_blueprint_plugin() {
19,633✔
47
            let mut loaded_plugin_count = 0;
19,629✔
48
            for plugin_name in self.game_settings().early_loading_plugins() {
19,629✔
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,611✔
60
    }
19,668✔
61

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

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

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

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

92
    fn lookup_plugins(&mut self, active_plugin_names: &[&str]) -> Result<Vec<usize>, Error> {
18✔
93
        active_plugin_names
18✔
94
            .par_iter()
18✔
95
            .map(|n| {
15,616✔
96
                self.plugins()
15,616✔
97
                    .par_iter()
15,616✔
98
                    .position_any(|p| p.name_matches(n))
29,981,328✔
99
                    .ok_or_else(|| Error::PluginNotFound(n.to_string()))
15,616✔
100
            })
15,616✔
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_plugin() {
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_plugin() || !p.is_blueprint_plugin())
7✔
302
                })
25✔
303
                .unwrap_or(0);
7✔
304
            if pos > index {
7✔
305
                // Need to move the plugin to index, but can't do that while
4✔
306
                // iterating, so store it for later.
4✔
307
                from_to_map.entry(pos).or_insert(index);
4✔
308
            }
4✔
309
        }
310
    }
311

312
    move_elements(plugins, from_to_map);
56✔
313

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

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

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

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

350
    if plugin.is_blueprint_plugin() {
19,611✔
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_plugin() && is_master_of(p));
11✔
356
    }
19,607✔
357

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

19,607✔
363
    hoisted_index.or_else(|| {
19,607✔
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,607✔
370
}
19,611✔
371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

647
    validate_no_unhoisted_non_masters_before_masters(plugins)?;
20✔
648

649
    validate_no_non_blueprint_plugins_after_blueprint_plugins(plugins)?;
18✔
650

651
    validate_plugins_load_before_their_masters(plugins)?;
17✔
652

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

36✔
775
    unique_tuples
36✔
776
}
36✔
777

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

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

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

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

813
    use tempfile::tempdir;
814

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

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

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

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

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

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

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

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

10✔
861
        load_order
10✔
862
    }
10✔
863

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1✔
1099
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1100
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1101
    }
1✔
1102

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

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

1✔
1111
        let plugin = Plugin::new(
1✔
1112
            "Blank - Different Master Dependent.esm",
1✔
1113
            load_order.game_settings(),
1✔
1114
        )
1✔
1115
        .unwrap();
1✔
1116
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1117
    }
1✔
1118

1119
    #[test]
1120
    fn validate_index_should_error_for_a_master_plugin_and_index_after_unrelated_non_masters() {
1✔
1121
        let tmp_dir = tempdir().unwrap();
1✔
1122
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1123

1✔
1124
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1125
        load_order.plugins.insert(1, plugin);
1✔
1126

1✔
1127
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1128
        assert!(load_order.validate_index(&plugin, 4).is_err());
1✔
1129
    }
1✔
1130

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

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

1✔
1139
        let plugin = Plugin::new(
1✔
1140
            "Blank - Different Master Dependent.esm",
1✔
1141
            load_order.game_settings(),
1✔
1142
        )
1✔
1143
        .unwrap();
1✔
1144
        assert!(load_order.validate_index(&plugin, 1).is_err());
1✔
1145
    }
1✔
1146

1147
    #[test]
1148
    fn validate_index_should_error_for_a_master_plugin_that_has_a_later_master_as_a_master() {
1✔
1149
        let tmp_dir = tempdir().unwrap();
1✔
1150
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1151

1✔
1152
        copy_to_test_dir(
1✔
1153
            "Blank - Master Dependent.esm",
1✔
1154
            "Blank - Master Dependent.esm",
1✔
1155
            load_order.game_settings(),
1✔
1156
        );
1✔
1157
        copy_to_test_dir("Blank.esm", "Blank.esm", load_order.game_settings());
1✔
1158

1✔
1159
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1160
        load_order.plugins.insert(1, plugin);
1✔
1161

1✔
1162
        let plugin =
1✔
1163
            Plugin::new("Blank - Master Dependent.esm", load_order.game_settings()).unwrap();
1✔
1164
        assert!(load_order.validate_index(&plugin, 1).is_err());
1✔
1165
    }
1✔
1166

1167
    #[test]
1168
    fn validate_index_should_error_for_a_master_plugin_that_is_a_master_of_an_earlier_master() {
1✔
1169
        let tmp_dir = tempdir().unwrap();
1✔
1170
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1171

1✔
1172
        copy_to_test_dir(
1✔
1173
            "Blank - Master Dependent.esm",
1✔
1174
            "Blank - Master Dependent.esm",
1✔
1175
            load_order.game_settings(),
1✔
1176
        );
1✔
1177
        copy_to_test_dir("Blank.esm", "Blank.esm", load_order.game_settings());
1✔
1178

1✔
1179
        let plugin =
1✔
1180
            Plugin::new("Blank - Master Dependent.esm", load_order.game_settings()).unwrap();
1✔
1181
        load_order.plugins.insert(1, plugin);
1✔
1182

1✔
1183
        let plugin = Plugin::new("Blank.esm", load_order.game_settings()).unwrap();
1✔
1184
        assert!(load_order.validate_index(&plugin, 2).is_err());
1✔
1185
    }
1✔
1186

1187
    #[test]
1188
    fn validate_index_should_succeed_for_a_non_master_plugin_and_an_index_with_no_later_masters() {
1✔
1189
        let tmp_dir = tempdir().unwrap();
1✔
1190
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1191

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

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

1✔
1203
        let plugin = Plugin::new(
1✔
1204
            "Blank - Different Master Dependent.esm",
1✔
1205
            load_order.game_settings(),
1✔
1206
        )
1✔
1207
        .unwrap();
1✔
1208
        load_order.plugins.insert(1, plugin);
1✔
1209

1✔
1210
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1211
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1212
    }
1✔
1213

1214
    #[test]
1215
    fn validate_index_should_error_for_a_non_master_plugin_that_is_not_a_master_of_the_next_master_file(
1✔
1216
    ) {
1✔
1217
        let tmp_dir = tempdir().unwrap();
1✔
1218
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
1219

1✔
1220
        let plugin =
1✔
1221
            Plugin::new("Blank - Master Dependent.esp", load_order.game_settings()).unwrap();
1✔
1222
        assert!(load_order.validate_index(&plugin, 0).is_err());
1✔
1223
    }
1✔
1224

1225
    #[test]
1226
    fn validate_index_should_error_for_a_non_master_plugin_and_an_index_not_before_a_master_that_depends_on_it(
1✔
1227
    ) {
1✔
1228
        let tmp_dir = tempdir().unwrap();
1✔
1229
        let mut load_order = prepare_hoisted(GameId::SkyrimSE, &tmp_dir.path());
1✔
1230

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

1✔
1238
        let plugin = Plugin::new("Blank - Different.esm", load_order.game_settings()).unwrap();
1✔
1239
        assert!(load_order.validate_index(&plugin, 2).is_err());
1✔
1240
    }
1✔
1241

1242
    #[test]
1243
    fn validate_index_should_succeed_for_a_blueprint_plugin_index_that_is_last() {
1✔
1244
        let tmp_dir = tempdir().unwrap();
1✔
1245
        let 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 plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1253
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1254
    }
1✔
1255

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

1✔
1262
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1263

1✔
1264
        let plugin_name = "Blank.full.esm";
1✔
1265
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1266

1✔
1267
        let other_plugin_name = "Blank.medium.esm";
1✔
1268
        set_blueprint_flag(
1✔
1269
            GameId::Starfield,
1✔
1270
            &plugins_dir.join(other_plugin_name),
1✔
1271
            true,
1✔
1272
        )
1✔
1273
        .unwrap();
1✔
1274

1✔
1275
        let other_plugin = Plugin::new(other_plugin_name, load_order.game_settings()).unwrap();
1✔
1276
        load_order.plugins.push(other_plugin);
1✔
1277

1✔
1278
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1279
        assert!(load_order.validate_index(&plugin, 2).is_ok());
1✔
1280
    }
1✔
1281

1282
    #[test]
1283
    fn validate_index_should_fail_for_a_blueprint_plugin_index_if_any_non_blueprint_plugins_follow_it(
1✔
1284
    ) {
1✔
1285
        let tmp_dir = tempdir().unwrap();
1✔
1286
        let load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1287

1✔
1288
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1289

1✔
1290
        let plugin_name = "Blank.full.esm";
1✔
1291
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1292

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

1✔
1295
        let index = 1;
1✔
1296
        match load_order.validate_index(&plugin, index).unwrap_err() {
1✔
1297
            Error::InvalidBlueprintPluginPosition {
1298
                name,
1✔
1299
                pos,
1✔
1300
                expected_pos,
1✔
1301
            } => {
1✔
1302
                assert_eq!(plugin_name, name);
1✔
1303
                assert_eq!(index, pos);
1✔
1304
                assert_eq!(2, expected_pos);
1✔
1305
            }
NEW
1306
            e => panic!("Unexpected error type: {:?}", e),
×
1307
        }
1308
    }
1✔
1309

1310
    #[test]
1311
    fn validate_index_should_fail_for_a_blueprint_plugin_index_that_is_after_a_dependent_blueprint_plugin_index(
1✔
1312
    ) {
1✔
1313
        let tmp_dir = tempdir().unwrap();
1✔
1314
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1315

1✔
1316
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1317

1✔
1318
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1319
        copy_to_test_dir(
1✔
1320
            dependent_plugin,
1✔
1321
            dependent_plugin,
1✔
1322
            load_order.game_settings(),
1✔
1323
        );
1✔
1324
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
1325
        let plugin = Plugin::new(dependent_plugin, load_order.game_settings()).unwrap();
1✔
1326
        load_order.plugins.insert(1, plugin);
1✔
1327

1✔
1328
        let plugin_name = "Blank.full.esm";
1✔
1329
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1330

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

1✔
1333
        let index = 3;
1✔
1334
        match load_order.validate_index(&plugin, index).unwrap_err() {
1✔
1335
            Error::UnrepresentedHoist { plugin, master } => {
1✔
1336
                assert_eq!(plugin_name, plugin);
1✔
1337
                assert_eq!(dependent_plugin, master);
1✔
1338
            }
NEW
1339
            e => panic!("Unexpected error type: {:?}", e),
×
1340
        }
1341
    }
1✔
1342

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

1✔
1349
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1350

1✔
1351
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1352
        copy_to_test_dir(
1✔
1353
            dependent_plugin,
1✔
1354
            dependent_plugin,
1✔
1355
            load_order.game_settings(),
1✔
1356
        );
1✔
1357
        let plugin = Plugin::new(dependent_plugin, load_order.game_settings()).unwrap();
1✔
1358
        load_order.plugins.insert(1, plugin);
1✔
1359

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

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

1✔
1365
        assert!(load_order.validate_index(&plugin, 3).is_ok());
1✔
1366
    }
1✔
1367

1368
    #[test]
1369
    fn validate_index_should_succeed_when_an_early_loader_is_a_blueprint_plugin() {
1✔
1370
        let tmp_dir = tempdir().unwrap();
1✔
1371
        let mut load_order = prepare(GameId::Starfield, &tmp_dir.path());
1✔
1372

1✔
1373
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1374

1✔
1375
        let plugin_name = "Blank.full.esm";
1✔
1376
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
1377

1✔
1378
        std::fs::write(
1✔
1379
            plugins_dir.parent().unwrap().join("Starfield.ccc"),
1✔
1380
            format!("Starfield.esm\n{}", plugin_name),
1✔
1381
        )
1✔
1382
        .unwrap();
1✔
1383
        load_order
1✔
1384
            .game_settings
1✔
1385
            .refresh_implicitly_active_plugins()
1✔
1386
            .unwrap();
1✔
1387

1✔
1388
        let plugin = Plugin::new(plugin_name, load_order.game_settings()).unwrap();
1✔
1389
        load_order.plugins.push(plugin);
1✔
1390

1✔
1391
        let plugin = Plugin::new("Blank.medium.esm", load_order.game_settings()).unwrap();
1✔
1392
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1393
    }
1✔
1394

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

1✔
1400
        let plugins_dir = load_order.game_settings().plugins_directory();
1✔
1401

1✔
1402
        let blueprint_plugin = "Blank.full.esm";
1✔
1403
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(blueprint_plugin), true).unwrap();
1✔
1404

1✔
1405
        let early_loader = "Blank.medium.esm";
1✔
1406

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

1✔
1417
        let plugin = Plugin::new(blueprint_plugin, load_order.game_settings()).unwrap();
1✔
1418
        load_order.plugins.push(plugin);
1✔
1419

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

1✔
1422
        assert!(load_order.validate_index(&plugin, 1).is_ok());
1✔
1423
    }
1✔
1424

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

1✔
1430
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1431
        assert!(load_order
1✔
1432
            .set_plugin_index("Blank - Master Dependent.esp", 0)
1✔
1433
            .is_err());
1✔
1434
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1435
    }
1✔
1436

1437
    #[test]
1438
    fn set_plugin_index_should_error_if_moving_a_non_master_before_a_master() {
1✔
1439
        let tmp_dir = tempdir().unwrap();
1✔
1440
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1441

1✔
1442
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1443
        assert!(load_order.set_plugin_index("Blank.esp", 0).is_err());
1✔
1444
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1445
    }
1✔
1446

1447
    #[test]
1448
    fn set_plugin_index_should_error_if_inserting_a_master_after_a_non_master() {
1✔
1449
        let tmp_dir = tempdir().unwrap();
1✔
1450
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1451

1✔
1452
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1453
        assert!(load_order.set_plugin_index("Blank.esm", 2).is_err());
1✔
1454
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1455
    }
1✔
1456

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

1✔
1462
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1463
        assert!(load_order.set_plugin_index("Morrowind.esm", 2).is_err());
1✔
1464
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1465
    }
1✔
1466

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

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

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

1✔
1482
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1483

1✔
1484
        match load_order.set_plugin_index("Blank.esp", 0).unwrap_err() {
1✔
1485
            Error::InvalidEarlyLoadingPluginPosition {
1486
                name,
1✔
1487
                pos,
1✔
1488
                expected_pos,
1✔
1489
            } => {
1✔
1490
                assert_eq!("Skyrim.esm", name);
1✔
1491
                assert_eq!(1, pos);
1✔
1492
                assert_eq!(0, expected_pos);
1✔
1493
            }
UNCOV
1494
            e => panic!(
×
UNCOV
1495
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1496
                e
×
UNCOV
1497
            ),
×
1498
        };
1499

1500
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1501
    }
1✔
1502

1503
    #[test]
1504
    fn set_plugin_index_should_error_if_moving_an_early_loader_to_a_different_position() {
1✔
1505
        let tmp_dir = tempdir().unwrap();
1✔
1506
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1507

1✔
1508
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1509

1✔
1510
        match load_order.set_plugin_index("Skyrim.esm", 1).unwrap_err() {
1✔
1511
            Error::InvalidEarlyLoadingPluginPosition {
1512
                name,
1✔
1513
                pos,
1✔
1514
                expected_pos,
1✔
1515
            } => {
1✔
1516
                assert_eq!("Skyrim.esm", name);
1✔
1517
                assert_eq!(1, pos);
1✔
1518
                assert_eq!(0, expected_pos);
1✔
1519
            }
UNCOV
1520
            e => panic!(
×
UNCOV
1521
                "Expected InvalidEarlyLoadingPluginPosition error, got {:?}",
×
UNCOV
1522
                e
×
UNCOV
1523
            ),
×
1524
        };
1525

1526
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1527
    }
1✔
1528

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

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

1✔
1537
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1538

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

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

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

1✔
1566
        assert!(load_order.set_plugin_index("Skyrim.esm", 0).is_ok());
1✔
1567
        assert_eq!(
1✔
1568
            vec!["Skyrim.esm", "Blank.esp", "Blank - Different.esp"],
1✔
1569
            load_order.plugin_names()
1✔
1570
        );
1✔
1571
    }
1✔
1572

1573
    #[test]
1574
    fn set_plugin_index_should_succeed_if_inserting_a_new_early_loader() {
1✔
1575
        let tmp_dir = tempdir().unwrap();
1✔
1576
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1577

1✔
1578
        copy_to_test_dir("Blank.esm", "Dragonborn.esm", &load_order.game_settings());
1✔
1579

1✔
1580
        assert!(load_order.set_plugin_index("Dragonborn.esm", 1).is_ok());
1✔
1581
        assert_eq!(
1✔
1582
            vec![
1✔
1583
                "Skyrim.esm",
1✔
1584
                "Dragonborn.esm",
1✔
1585
                "Blank.esp",
1✔
1586
                "Blank - Different.esp"
1✔
1587
            ],
1✔
1588
            load_order.plugin_names()
1✔
1589
        );
1✔
1590
    }
1✔
1591

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

1✔
1597
        let num_plugins = load_order.plugins().len();
1✔
1598
        assert_eq!(1, load_order.set_plugin_index("Blank.esm", 1).unwrap());
1✔
1599
        assert_eq!(1, load_order.index_of("Blank.esm").unwrap());
1✔
1600
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1601
    }
1✔
1602

1603
    #[test]
1604
    fn set_plugin_index_should_allow_non_masters_to_be_hoisted() {
1✔
1605
        let tmp_dir = tempdir().unwrap();
1✔
1606
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1607

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

1✔
1610
        load_order.replace_plugins(&filenames).unwrap();
1✔
1611
        assert_eq!(filenames, load_order.plugin_names());
1✔
1612

1613
        let num_plugins = load_order.plugins().len();
1✔
1614
        let index = load_order
1✔
1615
            .set_plugin_index("Blank - Different.esm", 1)
1✔
1616
            .unwrap();
1✔
1617
        assert_eq!(1, index);
1✔
1618
        assert_eq!(1, load_order.index_of("Blank - Different.esm").unwrap());
1✔
1619
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1620
    }
1✔
1621

1622
    #[test]
1623
    fn set_plugin_index_should_allow_a_master_file_to_load_after_another_that_hoists_non_masters() {
1✔
1624
        let tmp_dir = tempdir().unwrap();
1✔
1625
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1626

1✔
1627
        let filenames = vec![
1✔
1628
            "Blank - Different.esm",
1✔
1629
            "Blank - Different Master Dependent.esm",
1✔
1630
        ];
1✔
1631

1✔
1632
        load_order.replace_plugins(&filenames).unwrap();
1✔
1633
        assert_eq!(filenames, load_order.plugin_names());
1✔
1634

1635
        let num_plugins = load_order.plugins().len();
1✔
1636
        assert_eq!(2, load_order.set_plugin_index("Blank.esm", 2).unwrap());
1✔
1637
        assert_eq!(2, load_order.index_of("Blank.esm").unwrap());
1✔
1638
        assert_eq!(num_plugins + 1, load_order.plugins().len());
1✔
1639
    }
1✔
1640

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

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

1655
    #[test]
1656
    fn set_plugin_index_should_move_an_existing_plugin_later_correctly() {
1✔
1657
        let tmp_dir = tempdir().unwrap();
1✔
1658
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1659

1✔
1660
        load_and_insert(&mut load_order, "Blank - Master Dependent.esp");
1✔
1661
        let num_plugins = load_order.plugins().len();
1✔
1662
        assert_eq!(2, load_order.set_plugin_index("Blank.esp", 2).unwrap());
1✔
1663
        assert_eq!(2, load_order.index_of("Blank.esp").unwrap());
1✔
1664
        assert_eq!(num_plugins, load_order.plugins().len());
1✔
1665
    }
1✔
1666

1667
    #[test]
1668
    fn set_plugin_index_should_preserve_an_existing_plugins_active_state() {
1✔
1669
        let tmp_dir = tempdir().unwrap();
1✔
1670
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1671

1✔
1672
        load_and_insert(&mut load_order, "Blank - Master Dependent.esp");
1✔
1673
        assert_eq!(2, load_order.set_plugin_index("Blank.esp", 2).unwrap());
1✔
1674
        assert!(load_order.is_active("Blank.esp"));
1✔
1675

1676
        let index = load_order
1✔
1677
            .set_plugin_index("Blank - Different.esp", 2)
1✔
1678
            .unwrap();
1✔
1679
        assert_eq!(2, index);
1✔
1680
        assert!(!load_order.is_active("Blank - Different.esp"));
1✔
1681
    }
1✔
1682

1683
    #[test]
1684
    fn replace_plugins_should_error_if_given_duplicate_plugins() {
1✔
1685
        let tmp_dir = tempdir().unwrap();
1✔
1686
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1687

1✔
1688
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1689
        let filenames = vec!["Blank.esp", "blank.esp"];
1✔
1690
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1691
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1692
    }
1✔
1693

1694
    #[test]
1695
    fn replace_plugins_should_error_if_given_an_invalid_plugin() {
1✔
1696
        let tmp_dir = tempdir().unwrap();
1✔
1697
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1698

1✔
1699
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1700
        let filenames = vec!["Blank.esp", "missing.esp"];
1✔
1701
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1702
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1703
    }
1✔
1704

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

1✔
1710
        let existing_filenames = to_owned(load_order.plugin_names());
1✔
1711
        let filenames = vec!["Blank.esp", "Blank.esm"];
1✔
1712
        assert!(load_order.replace_plugins(&filenames).is_err());
1✔
1713
        assert_eq!(existing_filenames, load_order.plugin_names());
1✔
1714
    }
1✔
1715

1716
    #[test]
1717
    fn replace_plugins_should_error_if_an_early_loading_plugin_loads_after_another_plugin() {
1✔
1718
        let tmp_dir = tempdir().unwrap();
1✔
1719
        let mut load_order = prepare(GameId::SkyrimSE, &tmp_dir.path());
1✔
1720

1✔
1721
        copy_to_test_dir("Blank.esm", "Update.esm", &load_order.game_settings());
1✔
1722

1✔
1723
        let filenames = vec![
1✔
1724
            "Skyrim.esm",
1✔
1725
            "Blank.esm",
1✔
1726
            "Update.esm",
1✔
1727
            "Blank.esp",
1✔
1728
            "Blank - Master Dependent.esp",
1✔
1729
            "Blank - Different.esp",
1✔
1730
            "Blàñk.esp",
1✔
1731
        ];
1✔
1732

1✔
1733
        match load_order.replace_plugins(&filenames).unwrap_err() {
1✔
1734
            Error::InvalidEarlyLoadingPluginPosition {
1735
                name,
1✔
1736
                pos,
1✔
1737
                expected_pos,
1✔
1738
            } => {
1✔
1739
                assert_eq!("Update.esm", name);
1✔
1740
                assert_eq!(2, pos);
1✔
1741
                assert_eq!(1, expected_pos);
1✔
1742
            }
UNCOV
1743
            e => panic!("Wrong error type: {:?}", e),
×
1744
        }
1745
    }
1✔
1746

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

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

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

1✔
1764
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1765
    }
1✔
1766

1767
    #[test]
1768
    fn replace_plugins_should_not_error_if_a_non_early_loading_implicitly_active_plugin_loads_after_another_plugin(
1✔
1769
    ) {
1✔
1770
        let tmp_dir = tempdir().unwrap();
1✔
1771

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

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

1✔
1778
        let filenames = vec![
1✔
1779
            "Skyrim.esm",
1✔
1780
            "Blank.esm",
1✔
1781
            "Blank.esp",
1✔
1782
            "Blank - Master Dependent.esp",
1✔
1783
            "Blank - Different.esp",
1✔
1784
            "Blàñk.esp",
1✔
1785
        ];
1✔
1786

1✔
1787
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1788
    }
1✔
1789

1790
    #[test]
1791
    fn replace_plugins_should_not_distinguish_between_ghosted_and_unghosted_filenames() {
1✔
1792
        let tmp_dir = tempdir().unwrap();
1✔
1793
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1794

1✔
1795
        copy_to_test_dir(
1✔
1796
            "Blank - Different.esm",
1✔
1797
            "ghosted.esm.ghost",
1✔
1798
            &load_order.game_settings(),
1✔
1799
        );
1✔
1800

1✔
1801
        let filenames = vec![
1✔
1802
            "Morrowind.esm",
1✔
1803
            "Blank.esm",
1✔
1804
            "ghosted.esm",
1✔
1805
            "Blank.esp",
1✔
1806
            "Blank - Master Dependent.esp",
1✔
1807
            "Blank - Different.esp",
1✔
1808
            "Blàñk.esp",
1✔
1809
        ];
1✔
1810

1✔
1811
        assert!(load_order.replace_plugins(&filenames).is_ok());
1✔
1812
    }
1✔
1813

1814
    #[test]
1815
    fn replace_plugins_should_not_insert_missing_plugins() {
1✔
1816
        let tmp_dir = tempdir().unwrap();
1✔
1817
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1818

1✔
1819
        let filenames = vec![
1✔
1820
            "Blank.esm",
1✔
1821
            "Blank.esp",
1✔
1822
            "Blank - Master Dependent.esp",
1✔
1823
            "Blank - Different.esp",
1✔
1824
        ];
1✔
1825
        load_order.replace_plugins(&filenames).unwrap();
1✔
1826

1✔
1827
        assert_eq!(filenames, load_order.plugin_names());
1✔
1828
    }
1✔
1829

1830
    #[test]
1831
    fn replace_plugins_should_not_lose_active_state_of_existing_plugins() {
1✔
1832
        let tmp_dir = tempdir().unwrap();
1✔
1833
        let mut load_order = prepare(GameId::Morrowind, &tmp_dir.path());
1✔
1834

1✔
1835
        let filenames = vec![
1✔
1836
            "Blank.esm",
1✔
1837
            "Blank.esp",
1✔
1838
            "Blank - Master Dependent.esp",
1✔
1839
            "Blank - Different.esp",
1✔
1840
        ];
1✔
1841
        load_order.replace_plugins(&filenames).unwrap();
1✔
1842

1✔
1843
        assert!(load_order.is_active("Blank.esp"));
1✔
1844
    }
1✔
1845

1846
    #[test]
1847
    fn replace_plugins_should_accept_hoisted_non_masters() {
1✔
1848
        let tmp_dir = tempdir().unwrap();
1✔
1849
        let mut load_order = prepare_hoisted(GameId::Oblivion, &tmp_dir.path());
1✔
1850

1✔
1851
        let filenames = vec![
1✔
1852
            "Blank.esm",
1✔
1853
            "Blank - Different.esm",
1✔
1854
            "Blank - Different Master Dependent.esm",
1✔
1855
            load_order.game_settings().master_file(),
1✔
1856
            "Blank - Master Dependent.esp",
1✔
1857
            "Blank - Different.esp",
1✔
1858
            "Blank.esp",
1✔
1859
            "Blàñk.esp",
1✔
1860
        ];
1✔
1861

1✔
1862
        load_order.replace_plugins(&filenames).unwrap();
1✔
1863
        assert_eq!(filenames, load_order.plugin_names());
1✔
1864
    }
1✔
1865

1866
    #[test]
1867
    fn hoist_masters_should_hoist_plugins_that_masters_depend_on_to_load_before_their_first_dependent(
1✔
1868
    ) {
1✔
1869
        let tmp_dir = tempdir().unwrap();
1✔
1870
        let (game_settings, _) = mock_game_files(GameId::SkyrimSE, &tmp_dir.path());
1✔
1871

1✔
1872
        // Test both hoisting a master before a master and a non-master before a master.
1✔
1873

1✔
1874
        let master_dependent_master = "Blank - Master Dependent.esm";
1✔
1875
        copy_to_test_dir(
1✔
1876
            master_dependent_master,
1✔
1877
            master_dependent_master,
1✔
1878
            &game_settings,
1✔
1879
        );
1✔
1880

1✔
1881
        let plugin_dependent_master = "Blank - Plugin Dependent.esm";
1✔
1882
        copy_to_test_dir(
1✔
1883
            "Blank - Plugin Dependent.esp",
1✔
1884
            plugin_dependent_master,
1✔
1885
            &game_settings,
1✔
1886
        );
1✔
1887

1✔
1888
        let plugin_names = vec![
1✔
1889
            "Skyrim.esm",
1✔
1890
            master_dependent_master,
1✔
1891
            "Blank.esm",
1✔
1892
            plugin_dependent_master,
1✔
1893
            "Blank - Master Dependent.esp",
1✔
1894
            "Blank - Different.esp",
1✔
1895
            "Blàñk.esp",
1✔
1896
            "Blank.esp",
1✔
1897
        ];
1✔
1898
        let mut plugins = plugin_names
1✔
1899
            .iter()
1✔
1900
            .map(|n| Plugin::new(n, &game_settings).unwrap())
8✔
1901
            .collect();
1✔
1902

1✔
1903
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1904

1905
        let expected_plugin_names = vec![
1✔
1906
            "Skyrim.esm",
1✔
1907
            "Blank.esm",
1✔
1908
            master_dependent_master,
1✔
1909
            "Blank.esp",
1✔
1910
            plugin_dependent_master,
1✔
1911
            "Blank - Master Dependent.esp",
1✔
1912
            "Blank - Different.esp",
1✔
1913
            "Blàñk.esp",
1✔
1914
        ];
1✔
1915

1✔
1916
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1917
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1918
    }
1✔
1919

1920
    #[test]
1921
    fn hoist_masters_should_not_hoist_blueprint_plugins_that_are_masters_of_non_blueprint_plugins()
1✔
1922
    {
1✔
1923
        let tmp_dir = tempdir().unwrap();
1✔
1924
        let (game_settings, _) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
1925

1✔
1926
        let blueprint_plugin = "Blank.full.esm";
1✔
1927
        set_blueprint_flag(
1✔
1928
            GameId::Starfield,
1✔
1929
            &game_settings.plugins_directory().join(blueprint_plugin),
1✔
1930
            true,
1✔
1931
        )
1✔
1932
        .unwrap();
1✔
1933

1✔
1934
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1935
        copy_to_test_dir(dependent_plugin, dependent_plugin, &game_settings);
1✔
1936

1✔
1937
        let plugin_names = vec![
1✔
1938
            "Starfield.esm",
1✔
1939
            dependent_plugin,
1✔
1940
            "Blank.esp",
1✔
1941
            blueprint_plugin,
1✔
1942
        ];
1✔
1943

1✔
1944
        let mut plugins = plugin_names
1✔
1945
            .iter()
1✔
1946
            .map(|n| Plugin::new(n, &game_settings).unwrap())
4✔
1947
            .collect();
1✔
1948

1✔
1949
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1950

1951
        let expected_plugin_names = plugin_names;
1✔
1952

1✔
1953
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1954
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1955
    }
1✔
1956

1957
    #[test]
1958
    fn hoist_masters_should_hoist_blueprint_plugins_that_are_masters_of_blueprint_plugins() {
1✔
1959
        let tmp_dir = tempdir().unwrap();
1✔
1960
        let (game_settings, _) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
1961

1✔
1962
        let plugins_dir = game_settings.plugins_directory();
1✔
1963

1✔
1964
        let blueprint_plugin = "Blank.full.esm";
1✔
1965
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(blueprint_plugin), true).unwrap();
1✔
1966

1✔
1967
        let dependent_plugin = "Blank - Override.full.esm";
1✔
1968
        copy_to_test_dir(dependent_plugin, dependent_plugin, &game_settings);
1✔
1969
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
1970

1✔
1971
        let plugin_names = vec![
1✔
1972
            "Starfield.esm",
1✔
1973
            "Blank.esp",
1✔
1974
            dependent_plugin,
1✔
1975
            blueprint_plugin,
1✔
1976
        ];
1✔
1977

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

1✔
1983
        assert!(hoist_masters(&mut plugins).is_ok());
1✔
1984

1985
        let expected_plugin_names = vec![
1✔
1986
            "Starfield.esm",
1✔
1987
            "Blank.esp",
1✔
1988
            blueprint_plugin,
1✔
1989
            dependent_plugin,
1✔
1990
        ];
1✔
1991

1✔
1992
        let plugin_names: Vec<_> = plugins.iter().map(Plugin::name).collect();
1✔
1993
        assert_eq!(expected_plugin_names, plugin_names);
1✔
1994
    }
1✔
1995

1996
    #[test]
1997
    fn find_plugins_in_dirs_should_sort_files_by_modification_timestamp() {
1✔
1998
        let tmp_dir = tempdir().unwrap();
1✔
1999
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
2000

1✔
2001
        let result = find_plugins_in_dirs(
1✔
2002
            &[load_order.game_settings.plugins_directory()],
1✔
2003
            load_order.game_settings.id(),
1✔
2004
        );
1✔
2005

1✔
2006
        let plugin_names = [
1✔
2007
            load_order.game_settings.master_file(),
1✔
2008
            "Blank.esm",
1✔
2009
            "Blank.esp",
1✔
2010
            "Blank - Different.esp",
1✔
2011
            "Blank - Master Dependent.esp",
1✔
2012
            "Blàñk.esp",
1✔
2013
        ];
1✔
2014

1✔
2015
        assert_eq!(plugin_names.as_slice(), result);
1✔
2016
    }
1✔
2017

2018
    #[test]
2019
    fn find_plugins_in_dirs_should_sort_files_by_descending_filename_if_timestamps_are_equal() {
1✔
2020
        let tmp_dir = tempdir().unwrap();
1✔
2021
        let load_order = prepare(GameId::Oblivion, &tmp_dir.path());
1✔
2022

1✔
2023
        let timestamp = 1321010051;
1✔
2024
        let plugin_path = load_order
1✔
2025
            .game_settings
1✔
2026
            .plugins_directory()
1✔
2027
            .join("Blank - Different.esp");
1✔
2028
        set_file_timestamps(&plugin_path, timestamp);
1✔
2029
        let plugin_path = load_order
1✔
2030
            .game_settings
1✔
2031
            .plugins_directory()
1✔
2032
            .join("Blank - Master Dependent.esp");
1✔
2033
        set_file_timestamps(&plugin_path, timestamp);
1✔
2034

1✔
2035
        let result = find_plugins_in_dirs(
1✔
2036
            &[load_order.game_settings.plugins_directory()],
1✔
2037
            load_order.game_settings.id(),
1✔
2038
        );
1✔
2039

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

1✔
2049
        assert_eq!(plugin_names.as_slice(), result);
1✔
2050
    }
1✔
2051

2052
    #[test]
2053
    fn find_plugins_in_dirs_should_sort_files_by_ascending_filename_if_timestamps_are_equal_and_game_is_starfield(
1✔
2054
    ) {
1✔
2055
        let tmp_dir = tempdir().unwrap();
1✔
2056
        let (game_settings, plugins) = mock_game_files(GameId::Starfield, &tmp_dir.path());
1✔
2057
        let load_order = TestLoadOrder {
1✔
2058
            game_settings,
1✔
2059
            plugins,
1✔
2060
        };
1✔
2061

1✔
2062
        let timestamp = 1321009991;
1✔
2063

1✔
2064
        let plugin_names = [
1✔
2065
            "Blank - Override.esp",
1✔
2066
            "Blank.esp",
1✔
2067
            "Blank.full.esm",
1✔
2068
            "Blank.medium.esm",
1✔
2069
            "Blank.small.esm",
1✔
2070
            "Starfield.esm",
1✔
2071
        ];
1✔
2072

2073
        for plugin_name in plugin_names {
7✔
2074
            let plugin_path = load_order
6✔
2075
                .game_settings
6✔
2076
                .plugins_directory()
6✔
2077
                .join(plugin_name);
6✔
2078
            set_file_timestamps(&plugin_path, timestamp);
6✔
2079
        }
6✔
2080

2081
        let result = find_plugins_in_dirs(
1✔
2082
            &[load_order.game_settings.plugins_directory()],
1✔
2083
            load_order.game_settings.id(),
1✔
2084
        );
1✔
2085

1✔
2086
        assert_eq!(plugin_names.as_slice(), result);
1✔
2087
    }
1✔
2088

2089
    #[test]
2090
    fn move_elements_should_correct_later_indices_to_account_for_earlier_moves() {
1✔
2091
        let mut vec = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
1✔
2092
        let mut from_to_indices = BTreeMap::new();
1✔
2093
        from_to_indices.insert(6, 3);
1✔
2094
        from_to_indices.insert(5, 2);
1✔
2095
        from_to_indices.insert(7, 1);
1✔
2096

1✔
2097
        move_elements(&mut vec, from_to_indices);
1✔
2098

1✔
2099
        assert_eq!(vec![0, 7, 1, 5, 2, 6, 3, 4, 8], vec);
1✔
2100
    }
1✔
2101

2102
    #[test]
2103
    fn validate_load_order_should_be_ok_if_there_are_only_master_files() {
1✔
2104
        let tmp_dir = tempdir().unwrap();
1✔
2105
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2106

1✔
2107
        let plugins = vec![
1✔
2108
            Plugin::new(settings.master_file(), &settings).unwrap(),
1✔
2109
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2110
        ];
1✔
2111

1✔
2112
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2113
    }
1✔
2114

2115
    #[test]
2116
    fn validate_load_order_should_be_ok_if_there_are_no_master_files() {
1✔
2117
        let tmp_dir = tempdir().unwrap();
1✔
2118
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2119

1✔
2120
        let plugins = vec![
1✔
2121
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2122
            Plugin::new("Blank - Different.esp", &settings).unwrap(),
1✔
2123
        ];
1✔
2124

1✔
2125
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2126
    }
1✔
2127

2128
    #[test]
2129
    fn validate_load_order_should_be_ok_if_master_files_are_before_all_others() {
1✔
2130
        let tmp_dir = tempdir().unwrap();
1✔
2131
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2132

1✔
2133
        let plugins = vec![
1✔
2134
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2135
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2136
        ];
1✔
2137

1✔
2138
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2139
    }
1✔
2140

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

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

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

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

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

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

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

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

2181
    #[test]
2182
    fn validate_load_order_should_error_if_master_files_load_before_non_masters_they_have_as_masters(
1✔
2183
    ) {
1✔
2184
        let tmp_dir = tempdir().unwrap();
1✔
2185
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2186

1✔
2187
        copy_to_test_dir(
1✔
2188
            "Blank - Plugin Dependent.esp",
1✔
2189
            "Blank - Plugin Dependent.esm",
1✔
2190
            &settings,
1✔
2191
        );
1✔
2192

1✔
2193
        let plugins = vec![
1✔
2194
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2195
            Plugin::new("Blank - Plugin Dependent.esm", &settings).unwrap(),
1✔
2196
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2197
        ];
1✔
2198

1✔
2199
        assert!(validate_load_order(&plugins, &[]).is_err());
1✔
2200
    }
1✔
2201

2202
    #[test]
2203
    fn validate_load_order_should_error_if_master_files_load_before_other_masters_they_have_as_masters(
1✔
2204
    ) {
1✔
2205
        let tmp_dir = tempdir().unwrap();
1✔
2206
        let settings = prepare(GameId::SkyrimSE, &tmp_dir.path()).game_settings;
1✔
2207

1✔
2208
        copy_to_test_dir(
1✔
2209
            "Blank - Master Dependent.esm",
1✔
2210
            "Blank - Master Dependent.esm",
1✔
2211
            &settings,
1✔
2212
        );
1✔
2213

1✔
2214
        let plugins = vec![
1✔
2215
            Plugin::new("Blank - Master Dependent.esm", &settings).unwrap(),
1✔
2216
            Plugin::new("Blank.esm", &settings).unwrap(),
1✔
2217
        ];
1✔
2218

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

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

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

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

1✔
2233
        let plugins = vec![
1✔
2234
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2235
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2236
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2237
        ];
1✔
2238

1✔
2239
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2240
    }
1✔
2241

2242
    #[test]
2243
    fn validate_load_order_should_succeed_if_a_blueprint_plugin_loads_after_a_non_blueprint_plugin_that_depends_on_it(
1✔
2244
    ) {
1✔
2245
        let tmp_dir = tempdir().unwrap();
1✔
2246
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2247

1✔
2248
        let plugins_dir = settings.plugins_directory();
1✔
2249

1✔
2250
        let plugin_name = "Blank.full.esm";
1✔
2251
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2252

1✔
2253
        let dependent_plugin = "Blank - Override.full.esm";
1✔
2254
        copy_to_test_dir(dependent_plugin, dependent_plugin, &settings);
1✔
2255

1✔
2256
        let plugins = vec![
1✔
2257
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2258
            Plugin::new(dependent_plugin, &settings).unwrap(),
1✔
2259
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2260
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2261
        ];
1✔
2262

1✔
2263
        assert!(validate_load_order(&plugins, &[]).is_ok());
1✔
2264
    }
1✔
2265

2266
    #[test]
2267
    fn validate_load_order_should_fail_if_a_blueprint_plugin_loads_before_a_non_blueprint_plugin() {
1✔
2268
        let tmp_dir = tempdir().unwrap();
1✔
2269
        let settings = prepare(GameId::Starfield, &tmp_dir.path()).game_settings;
1✔
2270

1✔
2271
        let plugins_dir = settings.plugins_directory();
1✔
2272

1✔
2273
        let plugin_name = "Blank.full.esm";
1✔
2274
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(plugin_name), true).unwrap();
1✔
2275

1✔
2276
        let plugins = vec![
1✔
2277
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2278
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2279
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2280
        ];
1✔
2281

1✔
2282
        match validate_load_order(&plugins, &[]).unwrap_err() {
1✔
2283
            Error::InvalidBlueprintPluginPosition {
2284
                name,
1✔
2285
                pos,
1✔
2286
                expected_pos,
1✔
2287
            } => {
1✔
2288
                assert_eq!(plugin_name, name);
1✔
2289
                assert_eq!(1, pos);
1✔
2290
                assert_eq!(2, expected_pos);
1✔
2291
            }
NEW
2292
            e => panic!("Unexpected error type: {:?}", e),
×
2293
        }
2294
    }
1✔
2295

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

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

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

1✔
2307
        let dependent_plugin = "Blank - Override.full.esm";
1✔
2308
        copy_to_test_dir(dependent_plugin, dependent_plugin, &settings);
1✔
2309
        set_blueprint_flag(GameId::Starfield, &plugins_dir.join(dependent_plugin), true).unwrap();
1✔
2310

1✔
2311
        let plugins = vec![
1✔
2312
            Plugin::new("Starfield.esm", &settings).unwrap(),
1✔
2313
            Plugin::new("Blank.esp", &settings).unwrap(),
1✔
2314
            Plugin::new(dependent_plugin, &settings).unwrap(),
1✔
2315
            Plugin::new(plugin_name, &settings).unwrap(),
1✔
2316
        ];
1✔
2317

1✔
2318
        match validate_load_order(&plugins, &[]).unwrap_err() {
1✔
2319
            Error::UnrepresentedHoist { plugin, master } => {
1✔
2320
                assert_eq!(plugin_name, plugin);
1✔
2321
                assert_eq!(dependent_plugin, master);
1✔
2322
            }
NEW
2323
            e => panic!("Unexpected error type: {:?}", e),
×
2324
        }
2325
    }
1✔
2326

2327
    #[test]
2328
    fn find_first_non_master_should_find_a_full_esp() {
1✔
2329
        let tmp_dir = tempdir().unwrap();
1✔
2330
        let plugins = prepare_plugins(&tmp_dir.path(), "Blank.esp");
1✔
2331

1✔
2332
        let first_non_master = super::find_first_non_master_position(&plugins);
1✔
2333
        assert_eq!(1, first_non_master.unwrap());
1✔
2334
    }
1✔
2335

2336
    #[test]
2337
    fn find_first_non_master_should_find_a_light_flagged_esp() {
1✔
2338
        let tmp_dir = tempdir().unwrap();
1✔
2339
        let plugins = prepare_plugins(&tmp_dir.path(), "Blank.esl");
1✔
2340

1✔
2341
        let first_non_master = super::find_first_non_master_position(&plugins);
1✔
2342
        assert_eq!(1, first_non_master.unwrap());
1✔
2343
    }
1✔
2344
}
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