beammm 0.1.0

A BeamNG.drive mod manager CLI and library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use crate::{game::ModCfg, Error::*, Result};
use serde::{Deserialize, Serialize};
use std::{
    collections::HashSet,
    ffi::OsStr,
    fs::{self, File},
    io::{BufRead, BufReader, BufWriter, Write},
    path::Path,
};

/// A preset of mods suitable for enabling/disabling groups of mods.
///
/// Presets are stored as JSON files in the BeamMM/presets directory.
///
/// # Examples
/// ```rust
/// use beammm::Preset;
/// # use tempfile::tempdir;
///
/// # let temp_dir = tempdir().unwrap();
/// # let presets_dir = temp_dir.path();
///
/// let mods: Vec<String> = vec!["mod1".into(), "mod2".into()];
///
/// // Create a preset
/// let mut new_preset = Preset::new("preset_name".into(), mods.clone());
/// new_preset.save_to_path(&presets_dir).unwrap();
///
/// // Load a preset
/// let loaded_preset = Preset::load_from_path("preset_name", &presets_dir).unwrap();
/// assert_eq!(loaded_preset.get_mods(), &mods);
/// ```
///
/// See additional preset examples in each function's documentation.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Preset {
    /// The name of the preset.
    name: String,
    /// The mods in the preset.
    mods: Vec<String>,
    /// Whether the preset is enabled.
    enabled: bool,
}

impl Preset {
    /// Get an iterator over currently saved presets.
    ///
    /// # Arguments
    ///
    /// `presets_dir`: Where preset config files are stored.
    ///
    /// # Errors
    ///
    /// Possible IO errors if the path doesn't exist, there is a permission issue,
    /// or if the path is not a directory.
    pub fn list(presets_dir: &Path) -> Result<impl Iterator<Item = String>> {
        Ok(fs::read_dir(presets_dir)?
            .filter_map(|f| f.ok().map(|f| f.path())) // Get rid of errors and map to path type
            .filter(|f| f.is_file() && f.extension().unwrap_or(OsStr::new("")) == "json") // Filter out dirs and non-json files
            // Map to remove the json extension so we just have the preset name and convert to String
            // if the os string into_string fails, it gets converted to None which gets filtered out
            .filter_map(|f| {
                f.with_extension("")
                    .file_name()
                    .and_then(OsStr::to_str)
                    .map(|f| f.to_string())
            }))
    }

    /// Create a new preset.
    ///
    /// # Arguments
    ///
    /// `name`: The name of the preset.
    /// `mods`: The mods to include in the preset.
    pub fn new(name: String, mods: Vec<String>) -> Self {
        Preset {
            name,
            mods,
            enabled: false,
        }
    }

    /// Serialize and save the preset to a writer.
    ///
    /// # Arguments
    ///
    /// `writer`: The writer to save the preset to.
    ///
    /// # Errors
    ///
    /// Possible IO errors if there is an issue writing to the writer.
    pub fn save<W: Write>(&self, mut writer: W) -> Result<()> {
        serde_json::to_writer_pretty(&mut writer, self)?;
        writer.flush()?;

        Ok(())
    }

    /// Serialize and save the preset to a file.
    ///
    /// # Arguments
    ///
    /// `presets_dir`: The directory where the preset will be saved.
    ///
    /// # Errors
    ///
    /// Possible IO errors if there is an issue creating the file or writing to it.
    pub fn save_to_path(&self, presets_dir: &Path) -> Result<()> {
        let file = File::create(presets_dir.join(&self.name).with_extension("json"))?;
        let writer = BufWriter::new(file);
        self.save(writer)
    }

    /// Deserialize and load a preset from a reader.
    ///
    /// # Arguments
    ///
    /// `reader`: The reader to load the preset from.
    ///
    /// # Errors
    ///
    /// Possible serde_json errors if there is an issue reading or deserializing the preset.
    pub fn load<R: BufRead>(reader: R) -> Result<Self> {
        Ok(serde_json::from_reader(reader)?)
    }

    /// Deserialize and load a preset from a file.
    ///
    /// # Arguments
    ///
    /// `name`: The name of the preset to load.
    /// `presets_dir`: The directory where the preset is stored.
    ///
    /// # Errors
    ///
    /// Possible IO errors if there is an issue reading the file or serde_json errors if there is
    /// an issue deserializing the preset.
    pub fn load_from_path(name: &str, presets_dir: &Path) -> Result<Self> {
        let preset_path = presets_dir.join(name).with_extension("json");
        if preset_path.try_exists()? {
            let file = File::open(preset_path)?;
            let reader = BufReader::new(file);
            Self::load(reader)
        } else {
            Err(MissingPreset {
                dir: presets_dir.into(),
                preset: name.into(),
            })
        }
    }

    /// Delete a preset.
    ///
    /// # Arguments
    ///
    /// `name`: The name of the preset to delete.
    /// `presets_dir`: The directory where the preset is stored.
    ///
    /// # Errors
    ///
    /// Possible IO errors if there is an issue deleting the file.
    pub fn delete(name: &str, presets_dir: &Path) -> Result<()> {
        fs::remove_file(presets_dir.join(name).with_extension("json"))?;
        Ok(())
    }

    /// Add a mod to the preset.
    ///
    /// # Arguments
    ///
    /// `mod_name`: The name of the mod to add.
    pub fn add_mod(&mut self, mod_name: &str) {
        self.mods.push(String::from(mod_name))
    }

    /// Add multiple mods to the preset.
    ///
    /// # Arguments
    ///
    /// `mods`: The mods to add.
    pub fn add_mods(&mut self, mods: &[String]) {
        self.mods.extend(mods.iter().cloned())
    }

    /// Remove a mod from the preset.
    ///
    /// Does nothing if the mod isn't in the preset. If the mod is in the preset multiple times,
    /// it removes every one. Duplicate mods is redundant anyway.
    ///
    /// # Arguments
    ///
    /// `mod_name`: The name of the mod to remove.
    pub fn remove_mod(&mut self, mod_name: &str) {
        self.mods.retain(|m| m != mod_name)
    }

    /// Remove multiple mods from the preset.
    ///
    /// Does nothing if any mods aren't in the preset. If a mod is in the preset multiple times,
    /// it removes every one. Duplicate mods is redundant anyway.
    ///
    /// # Arguments
    ///
    /// `mods`: The mods to remove.
    pub fn remove_mods(&mut self, mods: &[String]) {
        // Convert to HashSet so we can O(1) check if a mod is in the mods to remove.
        let values_to_remove: HashSet<&String> = mods.iter().collect();

        self.mods.retain(|m| !values_to_remove.contains(m))
    }

    /// Enable the preset.
    ///
    /// This method is NOT simply fire and forget. It will set this preset as enabled and nothing
    /// more. In order to actually enable the mods in this preset, the following steps must be
    /// taken:
    ///
    /// 1. Call `Preset::enable` on the preset.
    /// 2. Save the preset to the proper presets directory.
    /// 3. Call `ModCfg::apply_presets` on the ModCfg to enable the mods in memory.
    /// 4. Save the ModCfg to the proper mods directory, allowing the game to read the changes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use beammm::{Preset, game::ModCfg};
    /// # use tempfile::tempdir;
    ///
    /// # // Set up temp mock directories
    /// # let temp_presets_dir = tempdir().unwrap();
    /// # let presets_dir = temp_presets_dir.path();
    /// # let temp_mods_dir = tempdir().unwrap();
    /// # let mods_dir = temp_mods_dir.path();
    /// # // Make mods_dir/db.json
    /// # std::fs::write(mods_dir.join("db.json"), "{\"mods\":{\"mod1\":{\"active\":false},\"mod2\":{\"active\":false}}}").unwrap();
    /// #
    /// let mut mod_cfg = ModCfg::load_from_path(&mods_dir).unwrap();
    /// let mut preset = Preset::new("preset_name".into(), vec!["mod1".into(), "mod2".into()]);
    ///
    /// preset.enable();
    /// preset.save_to_path(&presets_dir).unwrap();
    ///
    /// mod_cfg.apply_presets(&presets_dir).unwrap();
    /// mod_cfg.save_to_path(&mods_dir).unwrap();
    /// ```
    pub fn enable(&mut self) {
        self.enabled = true
    }

    /// Disable the preset.
    ///
    /// Similarly to `Preset::enable`, this method is NOT simply fire and forget. It will set this
    /// preset as disabled after modifying the ModCfg in memory. To actually disable the mods in
    /// this preset, the following steps must be taken:
    ///
    /// 1. Call `Preset::disable` on the preset.
    /// 2. Save the preset to the proper presets directory.
    /// 3. Call `ModCfg::apply_presets` on the ModCfg to enable the mods in memory for ENABLED
    ///    presets.
    /// 4. Save the ModCfg to the proper mods directory, allowing the game to read the changes.
    ///
    /// Calling this function does IMMEDIATELY disable the mods in the preset in memory. The reason
    /// this disables mods but still needs to be saved and applied is because the ModCfg needs to
    /// be able to re-enable any mods that are in other enabled presets.
    ///
    /// # Errors
    ///
    /// MissingMods: If one or more mods in the preset doesn't exist in the ModCfg.
    ///
    /// In case of error, ModCfg and this preset will remain unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use beammm::{Preset, game::ModCfg};
    /// # use tempfile::tempdir;
    ///
    /// # // Set up temp mock directories
    /// # let temp_presets_dir = tempdir().unwrap();
    /// # let presets_dir = temp_presets_dir.path();
    /// # let temp_mods_dir = tempdir().unwrap();
    /// # let mods_dir = temp_mods_dir.path();
    /// # // Make mods_dir/db.json
    /// # std::fs::write(mods_dir.join("db.json"), "{\"mods\":{\"mod1\":{\"active\":true},\"mod2\":{\"active\":true}}}").unwrap();
    /// #
    /// let mut mod_cfg = ModCfg::load_from_path(&mods_dir).unwrap();
    /// let mut preset = Preset::new("preset_name".into(), vec!["mod1".into(), "mod2".into()]);
    ///
    /// preset.disable(&mut mod_cfg).unwrap();
    /// preset.save_to_path(&presets_dir).unwrap();
    ///
    /// mod_cfg.apply_presets(&presets_dir).unwrap();
    /// mod_cfg.save_to_path(&mods_dir).unwrap();
    /// ```
    pub fn disable(&mut self, mod_config: &mut ModCfg) -> Result<()> {
        mod_config.set_mods_active(&self.mods, false)?;
        self.enabled = false;
        Ok(())
    }

    /// Force disable the preset.
    ///
    /// This method is similar to `Preset::disable` but it doesn't check if the mods in the preset
    /// exist in the ModCfg. It will simply disable all mods in the preset and set the preset as
    /// disabled. This is helpful if the mod is enabled but the mods in the preset don't exist in
    /// the ModCfg.
    pub fn force_disable(&mut self, mod_config: &mut ModCfg) {
        self.enabled = false;
        for mod_name in &self.mods {
            // We don't care if the mod is already disabled or doesn't exist.
            let _ = mod_config.set_mod_active(mod_name, false);
        }
    }

    /// Get the enabled status of the preset.
    pub fn is_enabled(&self) -> bool {
        self.enabled
    }

    /// Get a list of mods in the preset.
    pub fn get_mods(&self) -> &Vec<String> {
        &self.mods
    }

    /// Check if a preset already exists.
    ///
    /// # Arguments
    ///
    /// `name`: The name of the preset to check for.
    /// `presets_dir`: The directory where the presets are stored.
    #[cfg_attr(coverage_nightly, coverage(off))]
    pub fn exists(name: &str, presets_dir: &Path) -> bool {
        presets_dir.join(name).with_extension("json").exists()
    }
}

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

    #[test]
    fn listing_presets() {
        let mock = MockData::new();
        let presets = Preset::list(&mock.presets_dir).unwrap().collect::<Vec<_>>();
        assert_eq!(presets, vec!["preset1", "preset2"]);
    }

    #[test]
    fn creating_preset() {
        let mods = vec!["mod1".into(), "mod2".into()];
        let preset = Preset::new("preset3".into(), mods.clone());

        assert_eq!(preset.get_mods(), &mods);
    }

    #[test]
    fn saving_and_loading_preset() {
        let mock = MockData::new();
        let mods = vec!["mod1".into(), "mod2".into()];
        let preset = Preset::new("preset3".into(), mods);
        preset.save_to_path(&mock.presets_dir).unwrap();

        // Check that there is now a `preset3.json` file in the presets directory.
        assert!(mock.presets_dir.join("preset3.json").exists());

        let loaded_preset = Preset::load_from_path("preset3", &mock.presets_dir).unwrap();
        assert_eq!(loaded_preset, preset);
    }

    #[test]
    fn load_missing_preset() {
        let mock = MockData::new();
        let result = Preset::load_from_path("missing_preset", &mock.presets_dir);
        assert!(matches!(result, Err(MissingPreset { .. })));
    }

    #[test]
    fn deleting_preset() {
        let mock = MockData::new();
        Preset::delete("preset1", &mock.presets_dir).unwrap();
        let presets = Preset::list(&mock.presets_dir).unwrap().collect::<Vec<_>>();
        assert_eq!(presets, vec!["preset2"]);
    }

    #[test]
    fn adding_mods() {
        let mock = MockData::new();
        let mut preset = mock.preset1;

        preset.add_mod("mod2");
        preset.add_mods(&["mod3".into(), "mod4".into()]);

        assert_eq!(preset.get_mods(), &["mod1", "mod2", "mod3", "mod4"]);
    }

    #[test]
    fn removing_mods() {
        let mut preset = Preset::new(
            "preset5".into(),
            vec!["mod1".into(), "mod2".into(), "mod3".into()],
        );
        preset.remove_mod("mod2");
        // Also remove mod that isn't already in the preset to verify we don't get an error of
        // sorts.
        preset.remove_mods(&["mod1".into(), "mod4".into()]);

        assert_eq!(preset.get_mods(), &["mod3"]);
    }

    #[test]
    fn enabling_preset() {
        let mock = MockData::new();
        // preset2 is disabled in the mock whereas preset1 is enabled.
        let mut preset = mock.preset2;

        preset.enable();
        preset.save_to_path(&mock.presets_dir).unwrap();

        // Here we should apply the preset using ModCfg but that needs to be tested elsewhere. All
        // we care about here is if it successfully enabled the preset.

        let loaded_preset = Preset::load_from_path("preset2", &mock.presets_dir).unwrap();
        assert!(loaded_preset.is_enabled());
    }

    #[test]
    fn disabling_preset() {
        let mock = MockData::new();
        let mut mod_cfg = mock.modcfg;
        let mut preset = mock.preset1;

        preset.disable(&mut mod_cfg).unwrap();

        // Here we should apply the preset using ModCfg but that needs to be tested elsewhere. All
        // we care about here is if it successfully disabled the preset and disabled all its mods
        // in the ModCfg.

        assert!(!preset.is_enabled());
        assert!(!mod_cfg.is_mod_active("mod1").unwrap());
    }

    #[test]
    fn force_disabling_preset() {
        let mock = MockData::new();
        let mut mod_cfg = mock.modcfg;
        let mut preset = mock.preset1;

        preset.add_mod("FakeMod");

        preset.force_disable(&mut mod_cfg);

        assert!(!preset.is_enabled());
        assert!(!mod_cfg.is_mod_active("mod1").unwrap());
    }
}