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/// `#[non_exhaustive]`: fields may be added as the schema grows.
96#[derive(Debug, Clone, Serialize, Deserialize)]
97#[serde(rename_all = "camelCase")]
98#[non_exhaustive]
99pub struct ProfileMod {
100  /// The `manifest.json` schema version the package declared.
101  pub manifest_version: u32,
102  /// The package name, without its owner prefix.
103  pub name: String,
104  /// The package owner, as Thunderstore spells it.
105  pub author_name: String,
106  /// The package's homepage, or empty when it declared none.
107  pub website_url: String,
108  /// The name to show a user, which may differ from [`Self::name`].
109  pub display_name: String,
110  /// The package's own description, shown verbatim. Not validated or truncated,
111  /// so a UI must treat it as untrusted text from an arbitrary uploader.
112  pub description: String,
113  /// The game version the package declared, carried through verbatim.
114  pub game_version: String,
115  /// r2modman's network-mode marker, carried through verbatim.
116  pub network_mode: String,
117  /// r2modman's package-type marker, carried through verbatim.
118  pub package_type: String,
119  /// r2modman's install-mode marker, carried through verbatim.
120  pub install_mode: String,
121  /// When the mod was installed, as a Unix timestamp in milliseconds.
122  pub installed_at_time: u64,
123  /// Mod loaders the package declared support for.
124  pub loaders: Vec<String>,
125  /// Full `Owner-Name-Version` dependency strings.
126  pub dependencies: Vec<String>,
127  /// Packages this one declares it cannot coexist with.
128  pub incompatibilities: Vec<String>,
129  /// Dependencies the package treats as optional.
130  pub optional_dependencies: Vec<String>,
131  /// The installed version.
132  pub version_number: SemVer,
133  /// Whether the mod is currently enabled in the profile.
134  pub enabled: bool,
135  /// Never written to `mods.yml` (r2modman strips it); ignored on read.
136  #[serde(skip)]
137  pub icon: String,
138  /// Whether the mod came from Thunderstore rather than a local import.
139  pub online_source: bool,
140  /// Absent from the `mods.yml` that installed r2modmanPlus versions actually
141  /// write, so it must not be required: demanding it made importing a real
142  /// profile fail with `missing field `trustedPackage`` *after* every file had
143  /// already been copied into place.
144  ///
145  /// Defaulting to `false` cannot change behavior, because nothing in the engine
146  /// branches on this flag; it is carried purely so a round-trip through
147  /// [`read()`]/[`write()`] does not drop a key a newer r2modman does write. `false`
148  /// is also the conservative reading of "is this package trusted".
149  #[serde(default)]
150  pub trusted_package: bool,
151}
152
153/// The `mods.yml` filename within a profile directory.
154#[cfg(feature = "io")]
155const MODS_YML: &str = "mods.yml";
156
157/// Reads `<profile_dir>/mods.yml`. A missing file is an empty list (a fresh
158/// profile), matching r2modman treating an absent list as `[]`.
159///
160/// A read or parse failure names the file in its message, so a caller does not
161/// need to prepend the path itself.
162#[cfg(feature = "io")]
163pub fn read(profile_dir: &Path) -> Result<Vec<ProfileMod>> {
164  let path = profile_dir.join(MODS_YML);
165
166  if !path.exists() {
167    return Ok(Vec::new());
168  }
169
170  let text = fs::read_to_string(&path)
171    .map_err(|e| Error::Profile(format!("reading {}: {}", path.display(), e)))?;
172
173  serde_yaml_ng::from_str(&text)
174    .map_err(|e| Error::Profile(format!("parsing {}: {}", path.display(), e)))
175}
176
177/// Writes `mods` to `<profile_dir>/mods.yml`, creating the directory if needed.
178///
179/// The file is replaced atomically, so a crash mid-write leaves the previous
180/// record whole rather than a truncated one.
181#[cfg(feature = "io")]
182pub fn write(profile_dir: &Path, mods: &[ProfileMod]) -> Result<()> {
183  fs::create_dir_all(profile_dir)
184    .map_err(|e| Error::Profile(format!("creating {}: {}", profile_dir.display(), e)))?;
185
186  let text = serde_yaml_ng::to_string(mods)
187    .map_err(|e| Error::Profile(format!("serializing mods.yml: {}", e)))?;
188
189  let path = profile_dir.join(MODS_YML);
190
191  crate::util::write_atomic(&path, text.as_bytes())
192    .map_err(|e| Error::Profile(format!("writing {}: {}", path.display(), e)))
193}
194
195/// Finds an installed mod by its `Owner-Name` identifier.
196pub fn find<'a>(mods: &'a [ProfileMod], full_name: &str) -> Option<&'a ProfileMod> {
197  mods.iter().find(|m| m.name == full_name)
198}
199
200/// Inserts `entry`, replacing any existing entry with the same `name`.
201pub fn upsert(mods: &mut Vec<ProfileMod>, entry: ProfileMod) {
202  if let Some(existing) = mods.iter_mut().find(|m| m.name == entry.name) {
203    *existing = entry;
204
205    return;
206  }
207
208  mods.push(entry);
209}
210
211/// The current time in the epoch-millisecond encoding [`ProfileMod::installed_at_time`]
212/// records, matching r2modman's `installedAtTime`.
213///
214/// A clock reading before the Unix epoch (a misconfigured system clock) falls
215/// back to `0` rather than failing an install over it: nothing in `mods.yml`
216/// or the install pipeline treats this timestamp as anything but display
217/// metadata, so there is no correctness reason to refuse the install.
218#[cfg(feature = "io")]
219pub fn now_millis() -> u64 {
220  std::time::SystemTime::now()
221    .duration_since(std::time::UNIX_EPOCH)
222    .map(|elapsed| elapsed.as_millis() as u64)
223    .unwrap_or(0)
224}
225
226#[cfg(test)]
227mod tests {
228  use super::*;
229  use std::cmp::Ordering;
230  #[cfg(feature = "io")]
231  use tempfile::tempdir;
232
233  fn sample() -> ProfileMod {
234    ProfileMod {
235      manifest_version: 1,
236      name: "bbepis-BepInExPack".to_string(),
237      author_name: "bbepis".to_string(),
238      website_url: "https://example.com".to_string(),
239      display_name: "BepInExPack".to_string(),
240      description: "pack".to_string(),
241      game_version: "0".to_string(),
242      network_mode: "both".to_string(),
243      package_type: "other".to_string(),
244      install_mode: "managed".to_string(),
245      installed_at_time: 1_699_999_999_999,
246      loaders: vec![],
247      dependencies: vec![],
248      incompatibilities: vec![],
249      optional_dependencies: vec![],
250      version_number: SemVer {
251        major: 5,
252        minor: 4,
253        patch: 2100,
254      },
255      enabled: true,
256      icon: String::new(),
257      online_source: false,
258      trusted_package: false,
259    }
260  }
261
262  #[test]
263  fn semver_parse_takes_first_three_numeric_components() {
264    assert_eq!(
265      SemVer::parse("5.4.2100"),
266      SemVer {
267        major: 5,
268        minor: 4,
269        patch: 2100
270      }
271    );
272    assert_eq!(
273      SemVer::parse("1.2"),
274      SemVer {
275        major: 1,
276        minor: 2,
277        patch: 0
278      }
279    );
280    assert_eq!(
281      SemVer::parse("1.2.3-beta"),
282      SemVer {
283        major: 1,
284        minor: 2,
285        patch: 3
286      }
287    );
288    assert_eq!(
289      SemVer::parse("garbage"),
290      SemVer {
291        major: 0,
292        minor: 0,
293        patch: 0
294      }
295    );
296  }
297
298  #[test]
299  fn serialized_yaml_is_r2modman_readable() {
300    let yaml = serde_yaml_ng::to_string(&vec![sample()]).unwrap();
301
302    // camelCase keys, no `icon`, nested versionNumber.
303    assert!(yaml.contains("manifestVersion:"));
304    assert!(yaml.contains("name: bbepis-BepInExPack"));
305    assert!(yaml.contains("versionNumber:"));
306    assert!(yaml.contains("major: 5"));
307    assert!(yaml.contains("networkMode: both"));
308    assert!(!yaml.contains("icon"));
309    assert!(!yaml.contains("version_number"));
310  }
311
312  #[test]
313  #[cfg(feature = "io")]
314  fn read_write_round_trips_and_missing_is_empty() {
315    let dir = tempdir().unwrap();
316
317    assert_eq!(read(dir.path()).unwrap().len(), 0);
318
319    write(dir.path(), &[sample()]).unwrap();
320    let back = read(dir.path()).unwrap();
321
322    assert_eq!(back.len(), 1);
323    assert_eq!(back[0].name, "bbepis-BepInExPack");
324    assert_eq!(
325      back[0].version_number,
326      SemVer {
327        major: 5,
328        minor: 4,
329        patch: 2100
330      }
331    );
332    assert!(back[0].enabled);
333  }
334
335  /// A write that truncated `mods.yml` in place would show through a handle
336  /// opened before it; a replacing rename leaves that handle on the old file.
337  #[test]
338  #[cfg(all(feature = "io", unix))]
339  fn a_write_replaces_mods_yml_instead_of_truncating_it() {
340    use std::io::Read;
341
342    let dir = tempdir().unwrap();
343
344    write(dir.path(), &[sample()]).unwrap();
345
346    let before = std::fs::read_to_string(dir.path().join(MODS_YML)).unwrap();
347    let mut held = std::fs::File::open(dir.path().join(MODS_YML)).unwrap();
348
349    write(dir.path(), &[]).unwrap();
350
351    let mut seen = String::new();
352
353    held.read_to_string(&mut seen).unwrap();
354
355    assert_eq!(seen, before);
356    assert_eq!(read(dir.path()).unwrap().len(), 0);
357
358    let names: Vec<String> = std::fs::read_dir(dir.path())
359      .unwrap()
360      .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
361      .collect();
362
363    assert_eq!(
364      names,
365      vec![MODS_YML.to_string()],
366      "no temp file is left behind"
367    );
368  }
369
370  #[test]
371  #[cfg(feature = "io")]
372  fn a_failed_write_leaves_no_temp_file_behind() {
373    let dir = tempdir().unwrap();
374
375    std::fs::create_dir(dir.path().join(MODS_YML)).unwrap();
376    std::fs::write(dir.path().join(MODS_YML).join("keep"), "").unwrap();
377
378    assert!(write(dir.path(), &[sample()]).is_err());
379
380    let names: Vec<String> = std::fs::read_dir(dir.path())
381      .unwrap()
382      .map(|entry| entry.unwrap().file_name().to_string_lossy().to_string())
383      .collect();
384
385    assert_eq!(names, vec![MODS_YML.to_string()]);
386  }
387
388  #[test]
389  fn parses_real_r2modman_sample_ignoring_icon() {
390    // A real-shaped entry, including an `icon` key r2modman would have stripped
391    // but a hand-edited file might carry: it must be ignored, not rejected.
392    let yaml = r#"- manifestVersion: 1
393  name: Author-Mod
394  authorName: Author
395  websiteUrl: ''
396  displayName: Mod
397  description: ''
398  gameVersion: '0'
399  networkMode: both
400  packageType: other
401  installMode: managed
402  installedAtTime: 1699999999999
403  loaders: []
404  dependencies:
405    - Other-Dep-1.2.3
406  incompatibilities: []
407  optionalDependencies: []
408  versionNumber:
409    major: 1
410    minor: 0
411    patch: 0
412  enabled: false
413  icon: /some/path/icon.png
414  onlineSource: true
415  trustedPackage: false
416"#;
417    let mods: Vec<ProfileMod> = serde_yaml_ng::from_str(yaml).unwrap();
418
419    assert_eq!(mods.len(), 1);
420    assert_eq!(mods[0].dependencies, vec!["Other-Dep-1.2.3".to_string()]);
421    assert!(!mods[0].enabled);
422    assert!(mods[0].online_source);
423  }
424
425  /// The shape r2modman actually writes on disk, verbatim from an installed
426  /// r2modmanPlus profile: no `trustedPackage` key at all. Requiring it made
427  /// importing a real profile fail with `missing field `trustedPackage``, after
428  /// the import had already copied every file into place.
429  #[test]
430  fn parses_an_r2modman_entry_with_no_trusted_package_key() {
431    let yaml = r#"- manifestVersion: 1
432  name: denikson-BepInExPack_Valheim
433  authorName: denikson
434  websiteUrl: https://thunderstore.io/c/valheim/p/denikson/BepInExPack_Valheim/
435  displayName: BepInExPack_Valheim
436  description: BepInEx pack for Valheim.
437  gameVersion: '0'
438  networkMode: both
439  packageType: other
440  installMode: managed
441  installedAtTime: 1771107231154
442  loaders: []
443  dependencies: []
444  incompatibilities: []
445  optionalDependencies: []
446  versionNumber:
447    major: 5
448    minor: 4
449    patch: 2333
450  enabled: true
451  onlineSource: false
452"#;
453
454    let mods: Vec<ProfileMod> = serde_yaml_ng::from_str(yaml).unwrap();
455
456    assert_eq!(mods.len(), 1);
457    assert_eq!(mods[0].name, "denikson-BepInExPack_Valheim");
458    assert!(mods[0].enabled);
459
460    // Absent means false: the conservative reading of "is this package trusted",
461    // and nothing in the engine branches on it, so a default cannot change behavior.
462    assert!(!mods[0].trusted_package);
463  }
464
465  #[test]
466  fn upsert_replaces_by_name_and_find_locates() {
467    let mut mods = vec![sample()];
468    let mut updated = sample();
469    updated.enabled = false;
470
471    upsert(&mut mods, updated);
472
473    assert_eq!(mods.len(), 1);
474    assert!(!find(&mods, "bbepis-BepInExPack").unwrap().enabled);
475    assert!(find(&mods, "nope").is_none());
476  }
477
478  #[test]
479  fn semver_orders_each_component_numerically() {
480    assert!(SemVer::parse("1.0.10") > SemVer::parse("1.0.9"));
481    assert!(SemVer::parse("1.10.0") > SemVer::parse("1.9.99"));
482    assert!(SemVer::parse("10.0.0") > SemVer::parse("9.99.99"));
483    assert!(SemVer::parse("2.0.0") > SemVer::parse("1.99.99"));
484    assert!(SemVer::parse("1.2.4") > SemVer::parse("1.2.3"));
485  }
486
487  #[test]
488  fn semver_missing_components_order_as_zero() {
489    assert_eq!(
490      SemVer::parse("1.2").cmp(&SemVer::parse("1.2.0")),
491      Ordering::Equal
492    );
493    assert!(SemVer::parse("1.2.1") > SemVer::parse("1.2"));
494    assert!(SemVer::parse("1") < SemVer::parse("1.0.1"));
495  }
496
497  #[test]
498  fn semver_sorts_into_a_total_order() {
499    let mut versions = ["1.0.10", "0.9", "1.0.9", "1.0.0", "1.10.0", "1.2"].map(SemVer::parse);
500
501    versions.sort();
502
503    assert_eq!(
504      versions.map(|v| v.to_string()),
505      ["0.9.0", "1.0.0", "1.0.9", "1.0.10", "1.2.0", "1.10.0"]
506    );
507  }
508
509  #[test]
510  fn semver_renders_as_major_minor_patch() {
511    let version = SemVer {
512      major: 5,
513      minor: 4,
514      patch: 2200,
515    };
516
517    assert_eq!(version.to_string(), "5.4.2200");
518    assert_eq!(format!("{version}"), "5.4.2200");
519  }
520
521  #[test]
522  #[cfg(feature = "io")]
523  fn an_unreadable_record_names_its_path() {
524    let dir = tempdir().unwrap();
525
526    std::fs::write(dir.path().join("mods.yml"), "not: [valid").unwrap();
527
528    let message = read(dir.path()).unwrap_err().to_string();
529
530    assert!(
531      message.contains(&dir.path().join("mods.yml").display().to_string()),
532      "a read failure must name the file, so a caller need not add it; got: {message}"
533    );
534  }
535}