Skip to main content

thunderstore_engine/profile/
modlist.rs

1//! The `mods.yml` model and its read/write.
2//!
3//! `mods.yml` is a YAML array of [`ProfileMod`] and is the authoritative record
4//! of what is installed in a profile. The shape mirrors r2modman's `ManifestV2`
5//! so r2modman can read a profile this engine produced: keys are camelCase, the
6//! `icon` field is never written, and `versionNumber` is a nested object.
7
8#![deny(missing_docs)]
9
10#[cfg(feature = "io")]
11use crate::error::{Error, Result};
12use serde::{Deserialize, Serialize};
13#[cfg(feature = "io")]
14use std::fs;
15#[cfg(feature = "io")]
16use std::path::Path;
17
18/// The `major.minor.patch` version object, serialized as a nested mapping to
19/// match r2modman's `VersionNumber`.
20///
21/// Versions are totally ordered by major, then minor, then patch, each compared
22/// as a number, and one version is newer than another when it compares greater.
23/// A component [`parse`](Self::parse) fills in as `0` orders as `0`, so `1.2`
24/// equals `1.2.0`.
25///
26/// ```
27/// use thunderstore_engine::profile::modlist::SemVer;
28///
29/// assert!(SemVer::parse("1.0.10") > SemVer::parse("1.0.9"));
30/// assert!(SemVer::parse("1.2.1") > SemVer::parse("1.2"));
31/// ```
32// Field order is the comparison order the derived `Ord` uses.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
34pub struct SemVer {
35  /// The major component, or `0` if the source string had none.
36  pub major: u32,
37  /// The minor component, or `0` if the source string had none.
38  pub minor: u32,
39  /// The patch component, or `0` if the source string had none. A prerelease
40  /// suffix is discarded, so `1.2.3-beta` parses to a patch of `3`.
41  pub patch: u32,
42}
43
44impl SemVer {
45  /// Parses the first three dot-separated integer components of `s`; a missing or
46  /// non-numeric component becomes `0` (so `"1.2"` -> `1.2.0`, `"1.2.3-beta"` ->
47  /// `1.2.3`).
48  ///
49  /// Never fails and never panics: an unparseable or overflowing component
50  /// degrades to `0` rather than rejecting a `mods.yml` r2modman itself accepts.
51  ///
52  /// # Examples
53  ///
54  /// ```
55  /// use thunderstore_engine::profile::modlist::SemVer;
56  ///
57  /// assert_eq!(SemVer::parse("1.2.3").to_string(), "1.2.3");
58  /// assert_eq!(SemVer::parse("1.2").to_string(), "1.2.0");
59  /// assert_eq!(SemVer::parse("1.2.3-beta").to_string(), "1.2.3");
60  /// assert_eq!(SemVer::parse("not-a-version").to_string(), "0.0.0");
61  /// ```
62  pub fn parse(s: &str) -> SemVer {
63    let mut parts = s.split('.');
64    let major = parse_leading_u32(parts.next());
65    let minor = parse_leading_u32(parts.next());
66    let patch = parse_leading_u32(parts.next());
67
68    SemVer {
69      major,
70      minor,
71      patch,
72    }
73  }
74}
75
76impl std::fmt::Display for SemVer {
77  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78    write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
79  }
80}
81
82/// Parses the leading run of ASCII digits of an optional component into a `u32`,
83/// yielding `0` for `None`, an empty run, or overflow. This tolerates a
84/// prerelease suffix (`"3-beta"` -> `3`) the way r2modman's parser does.
85fn parse_leading_u32(component: Option<&str>) -> u32 {
86  let text = component.unwrap_or("");
87  let digits: String = text.chars().take_while(|c| c.is_ascii_digit()).collect();
88
89  digits.parse().unwrap_or(0)
90}
91
92/// One installed mod, mirroring r2modman's `ManifestV2`. Field order matches
93/// r2modman's declaration order; `icon` is never serialized.
94///
95/// Reading is as lenient as r2modman's: only `name` and `versionNumber` are
96/// required. A missing `enabled` reads as disabled, as r2modman reads it; every
97/// other missing key reads as `0`, `false`, or empty.
98///
99/// `#[non_exhaustive]`: fields may be added as the schema grows.
100#[derive(Debug, Clone, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102#[non_exhaustive]
103pub struct ProfileMod {
104  /// The `manifest.json` schema version the package declared.
105  #[serde(default)]
106  pub manifest_version: u32,
107  /// The package name, without its owner prefix.
108  pub name: String,
109  /// The package owner, as Thunderstore spells it.
110  #[serde(default)]
111  pub author_name: String,
112  /// The package's homepage, or empty when it declared none.
113  #[serde(default)]
114  pub website_url: String,
115  /// The name to show a user, which may differ from [`Self::name`].
116  #[serde(default)]
117  pub display_name: String,
118  /// The package's own description, shown verbatim. Not validated or truncated,
119  /// so a UI must treat it as untrusted text from an arbitrary uploader.
120  #[serde(default)]
121  pub description: String,
122  /// The game version the package declared, carried through verbatim.
123  #[serde(default)]
124  pub game_version: String,
125  /// r2modman's network-mode marker, carried through verbatim.
126  #[serde(default)]
127  pub network_mode: String,
128  /// r2modman's package-type marker, carried through verbatim.
129  #[serde(default)]
130  pub package_type: String,
131  /// r2modman's install-mode marker, carried through verbatim.
132  #[serde(default)]
133  pub install_mode: String,
134  /// When the mod was installed, as a Unix timestamp in milliseconds.
135  #[serde(default)]
136  pub installed_at_time: u64,
137  /// Mod loaders the package declared support for.
138  #[serde(default)]
139  pub loaders: Vec<String>,
140  /// Full `Owner-Name-Version` dependency strings.
141  #[serde(default)]
142  pub dependencies: Vec<String>,
143  /// Packages this one declares it cannot coexist with.
144  #[serde(default)]
145  pub incompatibilities: Vec<String>,
146  /// Dependencies the package treats as optional.
147  #[serde(default)]
148  pub optional_dependencies: Vec<String>,
149  /// The installed version.
150  pub version_number: SemVer,
151  /// Whether the mod is currently enabled in the profile.
152  #[serde(default)]
153  pub enabled: bool,
154  /// Never written to `mods.yml` (r2modman strips it); ignored on read.
155  #[serde(skip)]
156  pub icon: String,
157  /// Whether the mod came from Thunderstore rather than a local import.
158  #[serde(default)]
159  pub online_source: bool,
160  /// Absent from the `mods.yml` that installed r2modmanPlus versions actually
161  /// write, so it must not be required: demanding it made importing a real
162  /// profile fail with `missing field `trustedPackage`` *after* every file had
163  /// already been copied into place.
164  ///
165  /// Defaulting to `false` cannot change behavior, because nothing in the engine
166  /// branches on this flag; it is carried purely so a round-trip through
167  /// [`read()`]/[`write()`] does not drop a key a newer r2modman does write. `false`
168  /// is also the conservative reading of "is this package trusted".
169  #[serde(default)]
170  pub trusted_package: bool,
171}
172
173/// The `mods.yml` filename within a profile directory.
174#[cfg(feature = "io")]
175const MODS_YML: &str = "mods.yml";
176
177/// Reads `<profile_dir>/mods.yml`. A missing file is an empty list (a fresh
178/// profile), matching r2modman treating an absent list as `[]`.
179///
180/// A read or parse failure names the file in its message, so a caller does not
181/// need to prepend the path itself.
182#[cfg(feature = "io")]
183pub fn read(profile_dir: &Path) -> Result<Vec<ProfileMod>> {
184  let path = profile_dir.join(MODS_YML);
185
186  if !path.exists() {
187    return Ok(Vec::new());
188  }
189
190  let text = fs::read_to_string(&path)
191    .map_err(|e| Error::Profile(format!("reading {}: {}", path.display(), e)))?;
192
193  serde_yaml_ng::from_str(&text)
194    .map_err(|e| Error::Profile(format!("parsing {}: {}", path.display(), e)))
195}
196
197/// Writes `mods` to `<profile_dir>/mods.yml`, creating the directory if needed.
198///
199/// The file is replaced atomically, so a crash mid-write leaves the previous
200/// record whole rather than a truncated one.
201#[cfg(feature = "io")]
202pub fn write(profile_dir: &Path, mods: &[ProfileMod]) -> Result<()> {
203  fs::create_dir_all(profile_dir)
204    .map_err(|e| Error::Profile(format!("creating {}: {}", profile_dir.display(), e)))?;
205
206  let text = serde_yaml_ng::to_string(mods)
207    .map_err(|e| Error::Profile(format!("serializing mods.yml: {}", e)))?;
208
209  let path = profile_dir.join(MODS_YML);
210
211  crate::util::write_atomic(&path, text.as_bytes())
212    .map_err(|e| Error::Profile(format!("writing {}: {}", path.display(), e)))
213}
214
215/// Finds an installed mod by its `Owner-Name` identifier.
216pub fn find<'a>(mods: &'a [ProfileMod], full_name: &str) -> Option<&'a ProfileMod> {
217  mods.iter().find(|m| m.name == full_name)
218}
219
220/// Inserts `entry`, replacing any existing entry with the same `name`.
221pub fn upsert(mods: &mut Vec<ProfileMod>, entry: ProfileMod) {
222  if let Some(existing) = mods.iter_mut().find(|m| m.name == entry.name) {
223    *existing = entry;
224
225    return;
226  }
227
228  mods.push(entry);
229}
230
231/// The current time in the epoch-millisecond encoding [`ProfileMod::installed_at_time`]
232/// records, matching r2modman's `installedAtTime`.
233///
234/// A clock reading before the Unix epoch (a misconfigured system clock) falls
235/// back to `0` rather than failing an install over it: nothing in `mods.yml`
236/// or the install pipeline treats this timestamp as anything but display
237/// metadata, so there is no correctness reason to refuse the install.
238#[cfg(feature = "io")]
239pub fn now_millis() -> u64 {
240  std::time::SystemTime::now()
241    .duration_since(std::time::UNIX_EPOCH)
242    .map(|elapsed| elapsed.as_millis() as u64)
243    .unwrap_or(0)
244}
245
246#[cfg(test)]
247mod tests {
248  use super::*;
249  use std::cmp::Ordering;
250  #[cfg(feature = "io")]
251  use tempfile::tempdir;
252
253  fn sample() -> ProfileMod {
254    ProfileMod {
255      manifest_version: 1,
256      name: "bbepis-BepInExPack".to_string(),
257      author_name: "bbepis".to_string(),
258      website_url: "https://example.com".to_string(),
259      display_name: "BepInExPack".to_string(),
260      description: "pack".to_string(),
261      game_version: "0".to_string(),
262      network_mode: "both".to_string(),
263      package_type: "other".to_string(),
264      install_mode: "managed".to_string(),
265      installed_at_time: 1_699_999_999_999,
266      loaders: vec![],
267      dependencies: vec![],
268      incompatibilities: vec![],
269      optional_dependencies: vec![],
270      version_number: SemVer {
271        major: 5,
272        minor: 4,
273        patch: 2100,
274      },
275      enabled: true,
276      icon: String::new(),
277      online_source: false,
278      trusted_package: false,
279    }
280  }
281
282  #[test]
283  fn semver_parse_takes_first_three_numeric_components() {
284    assert_eq!(
285      SemVer::parse("5.4.2100"),
286      SemVer {
287        major: 5,
288        minor: 4,
289        patch: 2100
290      }
291    );
292    assert_eq!(
293      SemVer::parse("1.2"),
294      SemVer {
295        major: 1,
296        minor: 2,
297        patch: 0
298      }
299    );
300    assert_eq!(
301      SemVer::parse("1.2.3-beta"),
302      SemVer {
303        major: 1,
304        minor: 2,
305        patch: 3
306      }
307    );
308    assert_eq!(
309      SemVer::parse("garbage"),
310      SemVer {
311        major: 0,
312        minor: 0,
313        patch: 0
314      }
315    );
316  }
317
318  #[test]
319  fn serialized_yaml_is_r2modman_readable() {
320    let yaml = serde_yaml_ng::to_string(&vec![sample()]).unwrap();
321
322    // camelCase keys, no `icon`, nested versionNumber.
323    assert!(yaml.contains("manifestVersion:"));
324    assert!(yaml.contains("name: bbepis-BepInExPack"));
325    assert!(yaml.contains("versionNumber:"));
326    assert!(yaml.contains("major: 5"));
327    assert!(yaml.contains("networkMode: both"));
328    assert!(!yaml.contains("icon"));
329    assert!(!yaml.contains("version_number"));
330  }
331
332  #[test]
333  #[cfg(feature = "io")]
334  fn read_write_round_trips_and_missing_is_empty() {
335    let dir = tempdir().unwrap();
336
337    assert_eq!(read(dir.path()).unwrap().len(), 0);
338
339    write(dir.path(), &[sample()]).unwrap();
340    let back = read(dir.path()).unwrap();
341
342    assert_eq!(back.len(), 1);
343    assert_eq!(back[0].name, "bbepis-BepInExPack");
344    assert_eq!(
345      back[0].version_number,
346      SemVer {
347        major: 5,
348        minor: 4,
349        patch: 2100
350      }
351    );
352    assert!(back[0].enabled);
353  }
354
355  /// A write that truncated `mods.yml` in place would show through a handle
356  /// opened before it; a replacing rename leaves that handle on the old file.
357  #[test]
358  #[cfg(all(feature = "io", unix))]
359  fn a_write_replaces_mods_yml_instead_of_truncating_it() {
360    use std::io::Read;
361
362    let dir = tempdir().unwrap();
363
364    write(dir.path(), &[sample()]).unwrap();
365
366    let before = std::fs::read_to_string(dir.path().join(MODS_YML)).unwrap();
367    let mut held = std::fs::File::open(dir.path().join(MODS_YML)).unwrap();
368
369    write(dir.path(), &[]).unwrap();
370
371    let mut seen = String::new();
372
373    held.read_to_string(&mut seen).unwrap();
374
375    assert_eq!(seen, before);
376    assert_eq!(read(dir.path()).unwrap().len(), 0);
377
378    let names: Vec<String> = std::fs::read_dir(dir.path())
379      .unwrap()
380      .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
381      .collect();
382
383    assert_eq!(
384      names,
385      vec![MODS_YML.to_string()],
386      "no temp file is left behind"
387    );
388  }
389
390  #[test]
391  #[cfg(feature = "io")]
392  fn a_failed_write_leaves_no_temp_file_behind() {
393    let dir = tempdir().unwrap();
394
395    std::fs::create_dir(dir.path().join(MODS_YML)).unwrap();
396    std::fs::write(dir.path().join(MODS_YML).join("keep"), "").unwrap();
397
398    assert!(write(dir.path(), &[sample()]).is_err());
399
400    let names: Vec<String> = std::fs::read_dir(dir.path())
401      .unwrap()
402      .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
403      .collect();
404
405    assert_eq!(names, vec![MODS_YML.to_string()]);
406  }
407
408  #[test]
409  fn parses_real_r2modman_sample_ignoring_icon() {
410    // A real-shaped entry, including an `icon` key r2modman would have stripped
411    // but a hand-edited file might carry: it must be ignored, not rejected.
412    let yaml = r#"- manifestVersion: 1
413  name: Author-Mod
414  authorName: Author
415  websiteUrl: ''
416  displayName: Mod
417  description: ''
418  gameVersion: '0'
419  networkMode: both
420  packageType: other
421  installMode: managed
422  installedAtTime: 1699999999999
423  loaders: []
424  dependencies:
425    - Other-Dep-1.2.3
426  incompatibilities: []
427  optionalDependencies: []
428  versionNumber:
429    major: 1
430    minor: 0
431    patch: 0
432  enabled: false
433  icon: /some/path/icon.png
434  onlineSource: true
435  trustedPackage: false
436"#;
437    let mods: Vec<ProfileMod> = serde_yaml_ng::from_str(yaml).unwrap();
438
439    assert_eq!(mods.len(), 1);
440    assert_eq!(mods[0].dependencies, vec!["Other-Dep-1.2.3".to_string()]);
441    assert!(!mods[0].enabled);
442    assert!(mods[0].online_source);
443  }
444
445  /// The shape r2modman actually writes on disk, verbatim from an installed
446  /// r2modmanPlus profile: no `trustedPackage` key at all. Requiring it made
447  /// importing a real profile fail with `missing field `trustedPackage``, after
448  /// the import had already copied every file into place.
449  #[test]
450  fn parses_an_r2modman_entry_with_no_trusted_package_key() {
451    let yaml = r#"- manifestVersion: 1
452  name: denikson-BepInExPack_Valheim
453  authorName: denikson
454  websiteUrl: https://thunderstore.io/c/valheim/p/denikson/BepInExPack_Valheim/
455  displayName: BepInExPack_Valheim
456  description: BepInEx pack for Valheim.
457  gameVersion: '0'
458  networkMode: both
459  packageType: other
460  installMode: managed
461  installedAtTime: 1771107231154
462  loaders: []
463  dependencies: []
464  incompatibilities: []
465  optionalDependencies: []
466  versionNumber:
467    major: 5
468    minor: 4
469    patch: 2333
470  enabled: true
471  onlineSource: false
472"#;
473
474    let mods: Vec<ProfileMod> = serde_yaml_ng::from_str(yaml).unwrap();
475
476    assert_eq!(mods.len(), 1);
477    assert_eq!(mods[0].name, "denikson-BepInExPack_Valheim");
478    assert!(mods[0].enabled);
479
480    // Absent means false: the conservative reading of "is this package trusted",
481    // and nothing in the engine branches on it, so a default cannot change behavior.
482    assert!(!mods[0].trusted_package);
483  }
484
485  /// r2modman's `ManifestV2.fromJsObject` defaults `installedAtTime`,
486  /// `onlineSource`, and `trustedPackage`, and disables an entry with no
487  /// `enabled`, so a sparse entry an older r2modman wrote must still read.
488  #[test]
489  fn parses_a_sparse_r2modman_entry_as_r2modman_does() {
490    let yaml = r#"- name: Author-Mod
491  versionNumber:
492    major: 1
493    minor: 2
494    patch: 3
495"#;
496
497    let mods: Vec<ProfileMod> = serde_yaml_ng::from_str(yaml).unwrap();
498
499    assert_eq!(mods.len(), 1);
500    assert_eq!(mods[0].name, "Author-Mod");
501    assert_eq!(mods[0].version_number, SemVer::parse("1.2.3"));
502    assert!(!mods[0].enabled);
503    assert_eq!(mods[0].installed_at_time, 0);
504    assert!(!mods[0].online_source);
505    assert!(mods[0].dependencies.is_empty());
506  }
507
508  #[test]
509  fn an_entry_without_a_name_or_version_is_refused() {
510    let no_version = "- name: Author-Mod\n";
511    let no_name = "- versionNumber: {major: 1, minor: 0, patch: 0}\n";
512
513    assert!(serde_yaml_ng::from_str::<Vec<ProfileMod>>(no_version).is_err());
514    assert!(serde_yaml_ng::from_str::<Vec<ProfileMod>>(no_name).is_err());
515  }
516
517  #[test]
518  #[cfg(feature = "io")]
519  fn reads_the_json_empty_list_r2modman_creates() {
520    let dir = tempdir().unwrap();
521
522    std::fs::write(dir.path().join(MODS_YML), "[]").unwrap();
523
524    assert!(read(dir.path()).unwrap().is_empty());
525  }
526
527  #[test]
528  fn upsert_replaces_by_name_and_find_locates() {
529    let mut mods = vec![sample()];
530    let mut updated = sample();
531    updated.enabled = false;
532
533    upsert(&mut mods, updated);
534
535    assert_eq!(mods.len(), 1);
536    assert!(!find(&mods, "bbepis-BepInExPack").unwrap().enabled);
537    assert!(find(&mods, "nope").is_none());
538  }
539
540  #[test]
541  fn semver_orders_each_component_numerically() {
542    assert!(SemVer::parse("1.0.10") > SemVer::parse("1.0.9"));
543    assert!(SemVer::parse("1.10.0") > SemVer::parse("1.9.99"));
544    assert!(SemVer::parse("10.0.0") > SemVer::parse("9.99.99"));
545    assert!(SemVer::parse("2.0.0") > SemVer::parse("1.99.99"));
546    assert!(SemVer::parse("1.2.4") > SemVer::parse("1.2.3"));
547  }
548
549  #[test]
550  fn semver_missing_components_order_as_zero() {
551    assert_eq!(
552      SemVer::parse("1.2").cmp(&SemVer::parse("1.2.0")),
553      Ordering::Equal
554    );
555    assert!(SemVer::parse("1.2.1") > SemVer::parse("1.2"));
556    assert!(SemVer::parse("1") < SemVer::parse("1.0.1"));
557  }
558
559  #[test]
560  fn semver_sorts_into_a_total_order() {
561    let mut versions = ["1.0.10", "0.9", "1.0.9", "1.0.0", "1.10.0", "1.2"].map(SemVer::parse);
562
563    versions.sort();
564
565    assert_eq!(
566      versions.map(|v| v.to_string()),
567      ["0.9.0", "1.0.0", "1.0.9", "1.0.10", "1.2.0", "1.10.0"]
568    );
569  }
570
571  #[test]
572  fn semver_renders_as_major_minor_patch() {
573    let version = SemVer {
574      major: 5,
575      minor: 4,
576      patch: 2200,
577    };
578
579    assert_eq!(version.to_string(), "5.4.2200");
580    assert_eq!(format!("{version}"), "5.4.2200");
581  }
582
583  #[test]
584  #[cfg(feature = "io")]
585  fn an_unreadable_record_names_its_path() {
586    let dir = tempdir().unwrap();
587
588    std::fs::write(dir.path().join("mods.yml"), "not: [valid").unwrap();
589
590    let message = read(dir.path()).unwrap_err().to_string();
591
592    assert!(
593      message.contains(&dir.path().join("mods.yml").display().to_string()),
594      "a read failure must name the file, so a caller need not add it; got: {message}"
595    );
596  }
597}