foch 0.0.2

EU4 mod analysis and merge toolkit
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
pub mod dependency;
pub mod descriptor;
mod error;
pub mod steam;

pub use error::{ParseError, ParseErrorKind};

use crate::game::eu4::Eu4;
use crate::model::GamePath;
use descriptor::{LauncherDescriptor, load_launcher_descriptor};
use relative_path::RelativePath;
use serde::Deserialize;
use std::path::{Path, PathBuf};
use steam::WorkshopInstallIdentity;

/// In-memory representation of an EU4 playset.
///
/// The on-disk format is the launcher's `dlc_load.json` plus the `mod/`
/// directory of `.mod` descriptors next to it; this struct is the parsed
/// projection used everywhere downstream. It is **not** itself a serializable
/// JSON shape — the launcher owns the canonical format and `foch` consumes it
/// via [`Playset::from_dlc_load`].
#[derive(Debug, Clone, Default)]
pub struct Playset {
	pub game: Eu4,
	pub name: String,
	pub mods: Vec<PlaysetEntry>,
}

#[derive(Debug, Clone, Default)]
pub struct PlaysetEntry {
	pub id: Option<String>,
	pub display_name: Option<String>,
	pub enabled: bool,
	pub position: Option<usize>,
	pub steam_id: Option<String>,
	pub workshop_identity: Option<WorkshopInstallIdentity>,
	pub root_path: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
struct DlcLoad {
	#[serde(default)]
	enabled_mods: Vec<String>,
	#[serde(default)]
	#[allow(dead_code)] // surfaced for completeness; foch ignores DLC selection.
	disabled_dlcs: Vec<String>,
}

impl Playset {
	/// Parse the launcher's `dlc_load.json` plus the sibling `mod/` directory
	/// of `.mod` descriptors into an in-memory [`Playset`].
	///
	/// Conventions:
	/// - `dlc_load.json`'s `enabled_mods` is an ordered list of paths like
	///   `mod/ugc_<steamId>.mod` (positions = array index = precedence). The
	///   launcher writes them relative to the Paradox data directory in `/`
	///   syntax on every host; an entry in any other form, or one that leaves
	///   the data directory, is a format error.
	/// - Each referenced descriptor is read for its `name` (→ display_name)
	///   and `remote_file_id` (→ steam_id, falling back to the filename's
	///   numeric tail when the descriptor omits it).
	/// - EU4 is the only supported game, so the parsed playset carries the
	///   concrete [`Eu4`] identity.
	pub fn from_dlc_load(path: &Path) -> Result<Self, ParseError> {
		Self::from_dlc_load_impl(path, None)
	}

	/// Like [`Playset::from_dlc_load`], but an unreadable or invalid launcher
	/// descriptor is an error. A descriptor that does not exist is not: the
	/// game skips such an entry, so it is kept with its filename identity and
	/// reported, by playset position, for the caller to omit.
	pub(crate) fn from_dlc_load_with_required_descriptors(
		path: &Path,
	) -> Result<(Self, Vec<MissingLauncherDescriptor>), ParseError> {
		let mut missing = Vec::new();
		let playset = Self::from_dlc_load_impl(path, Some(&mut missing))?;
		Ok((playset, missing))
	}

	fn from_dlc_load_impl(
		path: &Path,
		mut required: Option<&mut Vec<MissingLauncherDescriptor>>,
	) -> Result<Self, ParseError> {
		let bytes = std::fs::read(path).map_err(|err| ParseError::io(path.to_path_buf(), err))?;
		let dlc: DlcLoad = serde_json::from_slice(&bytes)
			.map_err(|err| ParseError::format(path.to_path_buf(), err.to_string()))?;
		let parent = path
			.parent()
			.ok_or_else(|| {
				ParseError::format(
					path.to_path_buf(),
					"dlc_load.json must live inside a paradox game data directory".to_string(),
				)
			})?
			.to_path_buf();
		let game = Eu4;
		let mut mods = Vec::with_capacity(dlc.enabled_mods.len());
		for (position, rel) in dlc.enabled_mods.iter().enumerate() {
			let rel = parse_enabled_mod_entry(path, rel)?;
			let entry = match required.as_deref_mut() {
				Some(missing) => read_dlc_load_entry_required(&parent, position, rel, missing)?,
				None => read_dlc_load_entry(&parent, position, rel)?,
			};
			mods.push(entry);
		}
		let name = match path.file_stem().and_then(|s| s.to_str()) {
			Some(stem) if !stem.is_empty() => format!("{stem} (active)"),
			_ => "active".to_string(),
		};
		Ok(Playset { game, name, mods })
	}
}

/// Reads an `enabled_mods` entry. The launcher writes each entry relative to
/// the Paradox data directory in `/` syntax on every host. That syntax has the
/// constraints a [`GamePath`] validates (relative, no `.` or `..`, no host path
/// structure), so the same validator is reused and the entry cannot leave the
/// data directory. The entry stays a [`RelativePath`], though: it names a
/// launcher file under the data directory, not a file in the game's namespace.
/// A separator the syntax does not declare, such as `\`, is rejected rather
/// than guessed at.
fn parse_enabled_mod_entry<'a>(
	dlc_load: &Path,
	rel: &'a str,
) -> Result<&'a RelativePath, ParseError> {
	GamePath::new(rel)
		.map(GamePath::as_relative_path)
		.map_err(|error| {
			ParseError::format(
				dlc_load.to_path_buf(),
				format!(
					"enabled mod descriptor path `{rel}` must be normalized and relative: {}",
					error.kind
				),
			)
		})
}

/// The descriptor file an `enabled_mods` entry names under the data
/// directory, joined one name at a time.
fn enabled_mod_descriptor_path(paradox_data_dir: &Path, rel: &RelativePath) -> PathBuf {
	rel.iter()
		.fold(paradox_data_dir.to_path_buf(), |path, name| path.join(name))
}

/// Reads an entry whose descriptor may be absent: only a missing file falls
/// back to the filename's steam id. A descriptor that exists but cannot be
/// opened as a regular file, read, or parsed is an error naming that file,
/// since guessing past it could resolve a different mod.
fn read_dlc_load_entry(
	paradox_data_dir: &Path,
	position: usize,
	rel: &RelativePath,
) -> Result<PlaysetEntry, ParseError> {
	let path = enabled_mod_descriptor_path(paradox_data_dir, rel);
	let descriptor = match std::fs::symlink_metadata(&path) {
		Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
		Err(err) => return Err(ParseError::io(path, err)),
		Ok(_) => Some(load_launcher_descriptor(&path)?),
	};
	playset_entry_from_descriptor(&path, position, rel, descriptor)
}

/// An enabled playset entry whose launcher descriptor does not exist.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct MissingLauncherDescriptor {
	/// Zero-based index into `enabled_mods`.
	pub position: usize,
	pub path: PathBuf,
}

fn read_dlc_load_entry_required(
	paradox_data_dir: &Path,
	position: usize,
	rel: &RelativePath,
	missing: &mut Vec<MissingLauncherDescriptor>,
) -> Result<PlaysetEntry, ParseError> {
	let path = enabled_mod_descriptor_path(paradox_data_dir, rel);
	// Only absence is tolerated; anything else at the path, including a
	// symlink, goes through the strict loader and its errors.
	if let Err(error) = std::fs::symlink_metadata(&path)
		&& error.kind() == std::io::ErrorKind::NotFound
	{
		missing.push(MissingLauncherDescriptor {
			position,
			path: path.clone(),
		});
		return playset_entry_from_descriptor(&path, position, rel, None);
	}
	let descriptor = load_launcher_descriptor(&path)?;
	playset_entry_from_descriptor(&path, position, rel, Some(descriptor))
}

fn playset_entry_from_descriptor(
	descriptor_path: &Path,
	position: usize,
	rel: &RelativePath,
	descriptor: Option<LauncherDescriptor>,
) -> Result<PlaysetEntry, ParseError> {
	let remote_file_id = descriptor
		.as_ref()
		.and_then(|d| d.remote_file_id.clone())
		.filter(|id| !id.trim().is_empty());
	if let Some(id) = remote_file_id.as_deref()
		&& single_path_component(id).is_none()
	{
		return Err(ParseError::format(
			descriptor_path.to_path_buf(),
			format!("remote_file_id `{id}` must be a single plain path component"),
		));
	}
	let steam_id = remote_file_id.or_else(|| extract_steam_id_from_descriptor_path(rel));
	let display_name = descriptor
		.as_ref()
		.and_then(|d| (!d.name.trim().is_empty()).then(|| d.name.clone()))
		.or_else(|| steam_id.as_ref().map(|id| format!("ugc_{id}")));
	Ok(PlaysetEntry {
		id: None,
		display_name,
		enabled: true,
		position: Some(position),
		steam_id,
		workshop_identity: None,
		root_path: None,
	})
}

/// Returns `text` when it is exactly one ordinary path component on every
/// host: not empty, not `.` or `..`, no `/` or `\` separator, no `:` (a
/// Windows drive or stream prefix, judged the same on every host), and no
/// NUL. Mod ids and names are joined onto search roots only through this
/// check, so they can never name a directory outside the root they are
/// joined to.
pub(crate) fn single_path_component(text: &str) -> Option<&str> {
	if text.is_empty() || text.contains(['/', '\\', ':', '\0']) {
		return None;
	}
	let mut components = Path::new(text).components();
	match (components.next(), components.next()) {
		(Some(std::path::Component::Normal(name)), None) if name == text => Some(text),
		_ => None,
	}
}

fn extract_steam_id_from_descriptor_path(rel: &RelativePath) -> Option<String> {
	// Convention: dlc_load lists mods as `mod/ugc_<numeric steam id>.mod`;
	// strip the prefix/suffix and validate the inner segment.
	let filename = rel.file_stem()?;
	let stripped = filename.strip_prefix("ugc_")?;
	if stripped.chars().all(|c| c.is_ascii_digit()) && !stripped.is_empty() {
		Some(stripped.to_string())
	} else {
		None
	}
}

/// Default location of a launcher `dlc_load.json` for a paradox data
/// directory configured via `Config::paradox_data_path`.
pub fn default_dlc_load_path(paradox_data_dir: &Path) -> PathBuf {
	paradox_data_dir.join("dlc_load.json")
}

#[cfg(test)]
mod tests {
	use super::*;
	use std::fs;
	use tempfile::TempDir;

	fn write_dlc_load(dir: &Path, mods: &[(&str, &str)]) {
		fs::create_dir_all(dir.join("mod")).unwrap();
		let entries: Vec<String> = mods
			.iter()
			.map(|(steam_id, _)| format!("mod/ugc_{steam_id}.mod"))
			.collect();
		let payload =
			serde_json::json!({ "enabled_mods": entries, "disabled_dlcs": Vec::<String>::new() });
		fs::write(
			dir.join("dlc_load.json"),
			serde_json::to_string_pretty(&payload).unwrap(),
		)
		.unwrap();
		for (steam_id, name) in mods {
			let body = format!(
				"name=\"{name}\"\npath=\"/tmp/mod_{steam_id}\"\nremote_file_id=\"{steam_id}\"\n"
			);
			fs::write(dir.join("mod").join(format!("ugc_{steam_id}.mod")), body).unwrap();
		}
	}

	#[test]
	fn parses_dlc_load_with_descriptors() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(&game_dir).unwrap();
		write_dlc_load(
			&game_dir,
			&[("2164202838", "Europa Expanded"), ("1999055990", "汉化")],
		);

		let playlist = Playset::from_dlc_load(&game_dir.join("dlc_load.json")).unwrap();
		assert_eq!(playlist.game, Eu4);
		assert_eq!(playlist.mods.len(), 2);
		assert_eq!(playlist.mods[0].steam_id.as_deref(), Some("2164202838"));
		assert_eq!(
			playlist.mods[0].display_name.as_deref(),
			Some("Europa Expanded")
		);
		assert_eq!(playlist.mods[0].position, Some(0));
		assert!(playlist.mods[0].enabled);
		assert_eq!(playlist.mods[1].steam_id.as_deref(), Some("1999055990"));
		assert_eq!(playlist.mods[1].display_name.as_deref(), Some("汉化"));
		assert_eq!(playlist.mods[1].position, Some(1));
	}

	#[test]
	fn falls_back_to_filename_when_descriptor_missing() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(&game_dir).unwrap();
		fs::write(
			game_dir.join("dlc_load.json"),
			r#"{"enabled_mods":["mod/ugc_999.mod"],"disabled_dlcs":[]}"#,
		)
		.unwrap();

		let playlist = Playset::from_dlc_load(&game_dir.join("dlc_load.json")).unwrap();
		assert_eq!(playlist.mods.len(), 1);
		assert_eq!(playlist.mods[0].steam_id.as_deref(), Some("999"));
		assert_eq!(playlist.mods[0].display_name.as_deref(), Some("ugc_999"));
		// Current-input inspection keeps the entry and reports the absence so
		// the caller can omit it, as the game does.
		let (strict, missing) =
			Playset::from_dlc_load_with_required_descriptors(&game_dir.join("dlc_load.json"))
				.expect("a missing descriptor does not fail the playset");
		assert_eq!(strict.mods[0].steam_id.as_deref(), Some("999"));
		assert_eq!(missing.len(), 1);
		assert_eq!(missing[0].position, 0);
		assert!(missing[0].path.ends_with("mod/ugc_999.mod"));
	}

	/// Only a missing descriptor falls back to the filename. One that exists
	/// but is not a regular file, or does not parse, names its own path
	/// instead of surfacing later as an unresolved `<missing-steam-id>`.
	#[test]
	fn an_unreadable_or_unparseable_descriptor_is_reported_with_its_path() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(game_dir.join("mod").join("ugc_1.mod")).unwrap();
		fs::write(game_dir.join("mod").join("ugc_2.mod"), "name = { a = ").unwrap();
		for (id, expected_kind) in [("1", ParseErrorKind::Io), ("2", ParseErrorKind::Format)] {
			let dlc_load = game_dir.join("dlc_load.json");
			fs::write(
				&dlc_load,
				format!(r#"{{"enabled_mods":["mod/ugc_{id}.mod"],"disabled_dlcs":[]}}"#),
			)
			.unwrap();
			let error = Playset::from_dlc_load(&dlc_load).expect_err(id);
			assert_eq!(error.kind, expected_kind, "{error}");
			assert!(error.path.ends_with(format!("mod/ugc_{id}.mod")), "{error}");
		}
	}

	#[test]
	fn a_remote_file_id_that_is_not_one_path_component_is_rejected() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		write_dlc_load(&game_dir, &[("1001", "Named")]);
		let dlc_load = game_dir.join("dlc_load.json");
		let launcher_copy = game_dir.join("mod").join("ugc_1001.mod");
		for bad in ["..", "../../x", "a/b", "/abs"] {
			fs::write(
				&launcher_copy,
				format!("name=\"Named\"\nremote_file_id=\"{bad}\"\n"),
			)
			.unwrap();
			for result in [
				Playset::from_dlc_load(&dlc_load),
				Playset::from_dlc_load_with_required_descriptors(&dlc_load)
					.map(|(playset, _missing)| playset),
			] {
				let error = result.expect_err(bad);
				assert_eq!(error.kind, ParseErrorKind::Format, "{error}");
				assert!(error.path.ends_with("mod/ugc_1001.mod"), "{error}");
			}
		}
	}

	#[test]
	fn single_path_component_accepts_only_one_plain_name() {
		for good in ["1001", "My Mod", "汉化", "mod.v2"] {
			assert_eq!(single_path_component(good), Some(good));
		}
		for bad in [
			"", ".", "..", "a/b", r"a\b", "/abs", "a/", "./a", "a\0b", r"C:\x", "C:",
		] {
			assert_eq!(single_path_component(bad), None, "{bad:?}");
		}
	}

	/// The launcher's copy of a descriptor is read for the mod's name and id
	/// only. A `replace_path` the mod's own descriptor would reject leaves both
	/// readers with the name the launcher wrote, not a file-name fallback or an
	/// unreadable playset.
	#[test]
	fn a_launcher_descriptor_replace_path_does_not_affect_the_playset_entry() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		write_dlc_load(&game_dir, &[("1001", "Named")]);
		let launcher_copy = game_dir.join("mod").join("ugc_1001.mod");
		let mut body = fs::read_to_string(&launcher_copy).unwrap();
		body.push_str("replace_path=\"common/../events\"\n");
		fs::write(&launcher_copy, body).unwrap();

		let dlc_load = game_dir.join("dlc_load.json");
		for playset in [
			Playset::from_dlc_load(&dlc_load).unwrap(),
			Playset::from_dlc_load_with_required_descriptors(&dlc_load)
				.unwrap()
				.0,
		] {
			assert_eq!(playset.mods[0].display_name.as_deref(), Some("Named"));
			assert_eq!(playset.mods[0].steam_id.as_deref(), Some("1001"));
		}
	}

	#[test]
	fn strict_loader_rejects_descriptor_path_escape() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(&game_dir).unwrap();
		fs::write(
			temp.path().join("outside.mod"),
			"name=\"Outside\"\nremote_file_id=\"999\"\n",
		)
		.unwrap();
		fs::write(
			game_dir.join("dlc_load.json"),
			r#"{"enabled_mods":["../outside.mod"],"disabled_dlcs":[]}"#,
		)
		.unwrap();

		let error =
			Playset::from_dlc_load_with_required_descriptors(&game_dir.join("dlc_load.json"))
				.expect_err("strict loader must reject paths escaping the game data directory");
		assert!(
			error
				.to_string()
				.contains("must be normalized and relative")
		);
	}

	#[test]
	fn both_loaders_reject_entries_outside_the_launcher_slash_syntax() {
		let temp = TempDir::new().unwrap();
		let game_dir = temp.path().join("Europa Universalis IV");
		fs::create_dir_all(game_dir.join("mod")).unwrap();
		fs::write(
			temp.path().join("outside.mod"),
			"name=\"Outside\"\nremote_file_id=\"999\"\n",
		)
		.unwrap();
		// On a Unix host `mod\ugc_999.mod` is one file name, so reading it
		// with host syntax would silently look for a different file than the
		// launcher meant; the declared `/` syntax rejects it instead.
		fs::write(
			game_dir.join("mod").join("ugc_999.mod"),
			"name=\"Inside\"\nremote_file_id=\"999\"\n",
		)
		.unwrap();
		let dlc_load = game_dir.join("dlc_load.json");
		for entry in [
			"../outside.mod",
			"/mod/ugc_999.mod",
			r"mod\ugc_999.mod",
			"mod//ugc_999.mod",
			"./mod/ugc_999.mod",
			"",
		] {
			fs::write(
				&dlc_load,
				serde_json::json!({ "enabled_mods": [entry], "disabled_dlcs": [] }).to_string(),
			)
			.unwrap();
			for error in [
				Playset::from_dlc_load(&dlc_load).expect_err(entry),
				Playset::from_dlc_load_with_required_descriptors(&dlc_load).expect_err(entry),
			] {
				assert_eq!(error.kind, ParseErrorKind::Format, "{entry}");
				assert_eq!(error.path, dlc_load, "{entry}");
				assert!(
					error
						.message
						.contains(&format!("`{entry}` must be normalized and relative")),
					"{entry}: {error}"
				);
				assert!(
					!error.message.contains("game path"),
					"a launcher entry is not a game path: {error}"
				);
			}
		}
	}

	#[test]
	fn unknown_paradox_data_dir_defaults_to_eu4() {
		let temp = TempDir::new().unwrap();
		let path = temp.path().join("dlc_load.json");
		fs::write(&path, r#"{"enabled_mods":[],"disabled_dlcs":[]}"#).unwrap();
		let playlist = Playset::from_dlc_load(&path).unwrap();
		assert_eq!(playlist.game, Eu4);
	}
}