thunderstore_engine/profile/
modlist.rs1#![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#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
34pub struct SemVer {
35 pub major: u32,
37 pub minor: u32,
39 pub patch: u32,
42}
43
44impl SemVer {
45 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
82fn 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#[derive(Debug, Clone, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102#[non_exhaustive]
103pub struct ProfileMod {
104 #[serde(default)]
106 pub manifest_version: u32,
107 pub name: String,
109 #[serde(default)]
111 pub author_name: String,
112 #[serde(default)]
114 pub website_url: String,
115 #[serde(default)]
117 pub display_name: String,
118 #[serde(default)]
121 pub description: String,
122 #[serde(default)]
124 pub game_version: String,
125 #[serde(default)]
127 pub network_mode: String,
128 #[serde(default)]
130 pub package_type: String,
131 #[serde(default)]
133 pub install_mode: String,
134 #[serde(default)]
136 pub installed_at_time: u64,
137 #[serde(default)]
139 pub loaders: Vec<String>,
140 #[serde(default)]
142 pub dependencies: Vec<String>,
143 #[serde(default)]
145 pub incompatibilities: Vec<String>,
146 #[serde(default)]
148 pub optional_dependencies: Vec<String>,
149 pub version_number: SemVer,
151 #[serde(default)]
153 pub enabled: bool,
154 #[serde(skip)]
156 pub icon: String,
157 #[serde(default)]
159 pub online_source: bool,
160 #[serde(default)]
170 pub trusted_package: bool,
171}
172
173#[cfg(feature = "io")]
175const MODS_YML: &str = "mods.yml";
176
177#[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#[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
215pub fn find<'a>(mods: &'a [ProfileMod], full_name: &str) -> Option<&'a ProfileMod> {
217 mods.iter().find(|m| m.name == full_name)
218}
219
220pub 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#[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 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 #[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 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 #[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 assert!(!mods[0].trusted_package);
483 }
484
485 #[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}