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)]
97#[serde(rename_all = "camelCase")]
98#[non_exhaustive]
99pub struct ProfileMod {
100 pub manifest_version: u32,
102 pub name: String,
104 pub author_name: String,
106 pub website_url: String,
108 pub display_name: String,
110 pub description: String,
113 pub game_version: String,
115 pub network_mode: String,
117 pub package_type: String,
119 pub install_mode: String,
121 pub installed_at_time: u64,
123 pub loaders: Vec<String>,
125 pub dependencies: Vec<String>,
127 pub incompatibilities: Vec<String>,
129 pub optional_dependencies: Vec<String>,
131 pub version_number: SemVer,
133 pub enabled: bool,
135 #[serde(skip)]
137 pub icon: String,
138 pub online_source: bool,
140 #[serde(default)]
150 pub trusted_package: bool,
151}
152
153#[cfg(feature = "io")]
155const MODS_YML: &str = "mods.yml";
156
157#[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#[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
195pub fn find<'a>(mods: &'a [ProfileMod], full_name: &str) -> Option<&'a ProfileMod> {
197 mods.iter().find(|m| m.name == full_name)
198}
199
200pub 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#[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 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 #[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 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 #[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 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}