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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
use crate::model::{GamePath, GamePathBuf, GamePathError};
use crate::playset::{ParseError, ParseErrorKind};
use encoding_rs::WINDOWS_1252;
use jomini::JominiDeserialize;
use jomini::text::{ObjectReader, TextTape};
use serde::de::Error as _;
use std::borrow::Cow;
use std::ffi::OsStr;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Component, Path, PathBuf, Prefix};
use typed_path::{Utf8WindowsComponent, Utf8WindowsPath};

/// A `descriptor.mod` as the launcher writes it.
#[derive(Debug, Clone, Default)]
pub struct ModDescriptor {
	pub name: String,
	/// The mod's directory. The launcher writes `path` for the host it runs
	/// on, so the value is the text between its quotes exactly as written,
	/// read with host syntax only: escape sequences are not interpreted,
	/// nothing is trimmed, and a separator the host does not use stays part of
	/// a name rather than being guessed into a directory boundary. A Windows
	/// launcher's `C:\Users\x\mod` names that directory on Windows and a
	/// single relative name elsewhere. As with `replace_path`, a value cannot
	/// end in `\`, because the reader takes `\"` as an escaped quote and keeps
	/// reading. [`descriptor_path_text`] writes it.
	pub path: Option<PathBuf>,
	pub tags: Vec<String>,
	pub dependencies: Vec<String>,
	/// The directories this mod replaces, read with [`parse_replace_path`].
	pub replace_path: Vec<GamePathBuf>,
	pub version: Option<String>,
	pub remote_file_id: Option<String>,
	pub supported_version: Option<String>,
}

/// A launcher's copy of a mod's descriptor (`mod/ugc_<id>.mod` beside
/// `dlc_load.json`), read for what locates and names the mod. The mod's
/// `replace_path` is read from its own `descriptor.mod` only, so the copy's
/// value is never interpreted and cannot make the copy unreadable.
#[derive(Debug, Clone, Default)]
pub struct LauncherDescriptor {
	pub name: String,
	/// The mod's directory, read as [`ModDescriptor::path`] is.
	pub path: Option<PathBuf>,
	pub version: Option<String>,
	pub remote_file_id: Option<String>,
}

/// Every descriptor field except `path` and `replace_path`, decoded the way
/// jomini decodes text.
#[derive(JominiDeserialize)]
struct TextFields {
	#[jomini(default)]
	name: String,
	#[jomini(default)]
	tags: Vec<String>,
	#[jomini(default)]
	dependencies: Vec<String>,
	version: Option<String>,
	remote_file_id: Option<String>,
	supported_version: Option<String>,
}

/// The descriptor fields before any value is interpreted. `path` and each
/// `replace_path` value hold the bytes between their quotes, decoded but
/// otherwise as written (see [`ModDescriptor::path`] and
/// [`parse_replace_path`]).
struct RawModDescriptor {
	fields: TextFields,
	path: Option<String>,
	replace_path: Vec<String>,
}

impl TryFrom<RawModDescriptor> for ModDescriptor {
	type Error = InvalidReplacePath;

	fn try_from(raw: RawModDescriptor) -> Result<Self, InvalidReplacePath> {
		let replace_path = raw
			.replace_path
			.into_iter()
			.map(|value| {
				parse_replace_path(&value).map_err(|reason| InvalidReplacePath { value, reason })
			})
			.collect::<Result<_, _>>()?;
		let fields = raw.fields;
		Ok(Self {
			name: fields.name,
			path: raw.path.map(PathBuf::from),
			tags: fields.tags,
			dependencies: fields.dependencies,
			replace_path,
			version: fields.version,
			remote_file_id: fields.remote_file_id,
			supported_version: fields.supported_version,
		})
	}
}

impl From<RawModDescriptor> for LauncherDescriptor {
	fn from(raw: RawModDescriptor) -> Self {
		let fields = raw.fields;
		Self {
			name: fields.name,
			path: raw.path.map(PathBuf::from),
			version: fields.version,
			remote_file_id: fields.remote_file_id,
		}
	}
}

/// Why a `replace_path` value names no directory under the game root.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReplacePathError {
	/// A drive, UNC or device prefix names a location outside the game root.
	Prefix,
	/// A `..` component would leave the directory the value names.
	ParentComponent,
	/// Nothing is left once separators and `.` components are dropped.
	Empty,
	/// A component is not a name a game path can hold.
	Name(GamePathError),
}

impl fmt::Display for ReplacePathError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Prefix => f.write_str("it has a drive, UNC or device prefix"),
			Self::ParentComponent => f.write_str("it has a `..` component"),
			Self::Empty => f.write_str("it names no directory"),
			Self::Name(error) => write!(f, "{error}"),
		}
	}
}

/// A `replace_path` value that [`parse_replace_path`] rejects.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InvalidReplacePath {
	/// The value as written in the descriptor.
	pub value: String,
	pub reason: ReplacePathError,
}

impl fmt::Display for InvalidReplacePath {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(
			f,
			"replace_path {:?} is not a directory under the game root: {}",
			self.value, self.reason
		)
	}
}

impl std::error::Error for InvalidReplacePath {}

/// Reads a `replace_path` value as the directory it names under the game
/// root.
///
/// The value is the text between its quotes exactly as written: escape
/// sequences are not interpreted, and nothing is trimmed. Descriptors are
/// written for the Windows game, so it is read in Windows path syntax: `/` and
/// every `\` both separate components. The value is always relative to the
/// game root, so a leading root separator, trailing or repeated separators and
/// `.` components add nothing. A drive, UNC or device prefix, a `..`
/// component, a value with no component left, or a component that is not a
/// valid game path name is an error. Whitespace is part of a name, as it is in
/// an inventory path, and case is kept as written.
///
/// Two consequences of the descriptor format: a value cannot end in `\`,
/// because the reader takes `\"` as an escaped quote and keeps reading, and
/// `\"` inside a value is a separator followed by a name starting with `"`.
pub fn parse_replace_path(value: &str) -> Result<GamePathBuf, ReplacePathError> {
	let mut directory: Option<GamePathBuf> = None;
	for component in Utf8WindowsPath::new(value).components() {
		match component {
			Utf8WindowsComponent::Prefix(_) => return Err(ReplacePathError::Prefix),
			Utf8WindowsComponent::RootDir | Utf8WindowsComponent::CurDir => {}
			Utf8WindowsComponent::ParentDir => return Err(ReplacePathError::ParentComponent),
			Utf8WindowsComponent::Normal(name) => {
				let name = GamePathBuf::parse(name).map_err(ReplacePathError::Name)?;
				directory = Some(match directory {
					Some(parent) => parent.join(&name),
					None => name,
				});
			}
		}
	}
	directory.ok_or(ReplacePathError::Empty)
}

/// Why descriptor bytes do not give a [`ModDescriptor`].
#[derive(Debug)]
pub(crate) enum DescriptorParseError {
	Syntax(jomini::Error),
	ReplacePath(InvalidReplacePath),
}

impl fmt::Display for DescriptorParseError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::Syntax(error) => write!(f, "{error}"),
			Self::ReplacePath(error) => write!(f, "{error}"),
		}
	}
}

/// Reads a mod's own descriptor. A `replace_path` value that names no
/// directory under the game root is reported with
/// [`ParseErrorKind::InvalidReplacePath`], so a caller can tell it from a
/// descriptor that does not parse at all.
pub fn load_descriptor(path: &Path) -> Result<ModDescriptor, ParseError> {
	parse_descriptor_bytes(&read_descriptor_file(path)?).map_err(|error| match error {
		DescriptorParseError::Syntax(error) => {
			ParseError::format(path.to_path_buf(), error.to_string())
		}
		DescriptorParseError::ReplacePath(error) => ParseError {
			kind: ParseErrorKind::InvalidReplacePath,
			path: path.to_path_buf(),
			message: error.to_string(),
		},
	})
}

/// Reads a launcher's copy of a descriptor; see [`LauncherDescriptor`].
pub fn load_launcher_descriptor(path: &Path) -> Result<LauncherDescriptor, ParseError> {
	parse_raw_descriptor_bytes(&read_descriptor_file(path)?)
		.map(LauncherDescriptor::from)
		.map_err(|error| ParseError::format(path.to_path_buf(), error.to_string()))
}

fn read_descriptor_file(path: &Path) -> Result<Vec<u8>, ParseError> {
	let mut file = open_regular_descriptor_no_follow(path)
		.map_err(|err| ParseError::io(path.to_path_buf(), err))?;
	let mut data = Vec::new();
	file.read_to_end(&mut data)
		.map_err(|err| ParseError::io(path.to_path_buf(), err))?;
	Ok(data)
}

fn open_regular_descriptor_no_follow(path: &Path) -> io::Result<File> {
	let metadata = fs::symlink_metadata(path)?;
	if !metadata.file_type().is_file() {
		return Err(io::Error::new(
			io::ErrorKind::InvalidInput,
			format!(
				"descriptor must be a regular file, not a symlink: {}",
				path.display()
			),
		));
	}
	#[cfg(unix)]
	let file = {
		use rustix::fs::{Mode, OFlags, open};
		let descriptor = open(
			path,
			OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
			Mode::empty(),
		)
		.map_err(io::Error::from)?;
		File::from(descriptor)
	};
	#[cfg(not(unix))]
	let file = File::open(path)?;
	if !file.metadata()?.file_type().is_file() {
		return Err(io::Error::new(
			io::ErrorKind::InvalidInput,
			format!("descriptor must be a regular file: {}", path.display()),
		));
	}
	Ok(file)
}

/// Parse `descriptor.mod` bytes into a [`ModDescriptor`], reading each
/// `replace_path` with [`parse_replace_path`].
pub(crate) fn parse_descriptor_bytes(data: &[u8]) -> Result<ModDescriptor, DescriptorParseError> {
	let raw = parse_raw_descriptor_bytes(data).map_err(DescriptorParseError::Syntax)?;
	ModDescriptor::try_from(raw).map_err(DescriptorParseError::ReplacePath)
}

/// Parse `descriptor.mod` bytes, sniffing UTF-8 vs. windows-1252.
///
/// Workshop descriptors come in both encodings: most are ASCII or
/// windows-1252, but a non-trivial slice (notably Chinese-authored mods such
/// as workshop id `2411504869 欧陆拓展-未知领域`) ship as UTF-8, sometimes
/// with a BOM. Decoding those as windows-1252 produces mojibake and breaks
/// dep-string identity matching in [`crate::playset::dependency`].
///
/// Strategy:
/// 1. UTF-8 BOM (`EF BB BF`) → strip and decode as UTF-8.
/// 2. Try UTF-8 first. If it succeeds, prefer it (windows-1252 is a
///    superset of ASCII, so any valid UTF-8 we'd misinterpret as
///    windows-1252 would otherwise mojibake silently).
/// 3. Fall back to windows-1252.
///
/// jomini's text decoding drops every `\` and trims trailing whitespace, so
/// the path fields, `path` and `replace_path`, are decoded from the raw bytes
/// between their quotes instead, in the same encoding as the rest of the file.
fn parse_raw_descriptor_bytes(data: &[u8]) -> Result<RawModDescriptor, jomini::Error> {
	const UTF8_BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
	let payload = data.strip_prefix(UTF8_BOM).unwrap_or(data);
	let tape = TextTape::from_slice(payload)?;

	if std::str::from_utf8(payload).is_ok()
		&& let Ok(parsed) = read_raw_descriptor(&tape.utf8_reader(), |bytes| {
			std::str::from_utf8(bytes)
				.map(Cow::Borrowed)
				.map_err(jomini::Error::custom)
		}) {
		return Ok(parsed);
	}
	read_raw_descriptor(&tape.windows1252_reader(), |bytes| {
		Ok(WINDOWS_1252.decode_without_bom_handling(bytes).0)
	})
}

fn read_raw_descriptor<'data, E>(
	reader: &ObjectReader<'data, '_, E>,
	decode: impl Fn(&'data [u8]) -> Result<Cow<'data, str>, jomini::Error>,
) -> Result<RawModDescriptor, jomini::Error>
where
	E: jomini::Encoding + Clone,
{
	let fields: TextFields = reader.deserialize()?;
	let raw_values = |name: &str| {
		reader
			.fields()
			.filter(|(key, _, _)| key.read_str() == name)
			.map(|(_, _, value)| Ok(decode(value.read_scalar()?.as_bytes())?.into_owned()))
			.collect::<Result<Vec<String>, jomini::Error>>()
	};
	let mut path = raw_values("path")?;
	if path.len() > 1 {
		return Err(jomini::Error::duplicate_field("path"));
	}
	Ok(RawModDescriptor {
		fields,
		path: path.pop(),
		replace_path: raw_values("replace_path")?,
	})
}

/// Why a host directory has no descriptor `path` text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UnwritableDescriptorPath {
	/// A name is not valid UTF-8.
	NotUtf8,
	/// A name holds a `\`, which a Windows launcher reads as a separator and
	/// which, ending the value, escapes its closing quote.
	Backslash,
	/// A name holds a `"`, which would end the value.
	Quote,
	/// A name holds a line break, which would end the line: a value could be
	/// read differently by another launcher, and a comment would end early.
	LineBreak,
	/// A device or verbatim prefix names no directory the launcher reads.
	DevicePrefix,
}

impl fmt::Display for UnwritableDescriptorPath {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.write_str(match self {
			Self::NotUtf8 => "the path is not valid UTF-8",
			Self::Backslash => "a descriptor path cannot hold a `\\` inside a name",
			Self::Quote => "a descriptor path cannot hold a `\"`",
			Self::LineBreak => "a descriptor path cannot hold a line break",
			Self::DevicePrefix => "a device or verbatim prefix has no descriptor spelling",
		})
	}
}

/// The descriptor `path` text naming the host directory `path`, written
/// verbatim between the value's quotes.
///
/// The reader takes the bytes between the quotes as a host path with no
/// escape interpreted (see [`ModDescriptor::path`]), so the text is built
/// from the path's components with `/` between them. On Windows `/` is read
/// as the same separator as `\`, and a verbatim (`\\?\`) drive or UNC prefix
/// is written as the plain one. Elsewhere `\` is an ordinary name character,
/// but a Windows launcher splits on it and one before the closing quote
/// escapes that quote. A name that is not UTF-8, a name holding `\`, `"` or a
/// line break,
/// and a device or other verbatim prefix are errors, never a text naming some
/// other directory.
pub fn descriptor_path_text(path: &Path) -> Result<String, UnwritableDescriptorPath> {
	let text = slash_path_text(path)?;
	if text.contains('"') {
		return Err(UnwritableDescriptorPath::Quote);
	}
	Ok(text)
}

/// `path` spelled as [`descriptor_path_text`] spells it, with its components
/// joined by `/`, but keeping a `"`: for text that is not a `path` value,
/// such as the source playset comment of a generated descriptor. A name that
/// is not UTF-8 or holds `\`, and a device or other verbatim prefix, are
/// errors.
pub(crate) fn slash_path_text(path: &Path) -> Result<String, UnwritableDescriptorPath> {
	let mut text = String::new();
	let mut after_name = false;
	for component in path.components() {
		let name: &str = match component {
			Component::Prefix(prefix) => {
				match prefix.kind() {
					Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => {
						text.push(char::from(drive));
						text.push(':');
						after_name = false;
					}
					Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
						text.push_str("//");
						text.push_str(descriptor_name(server)?);
						text.push('/');
						text.push_str(descriptor_name(share)?);
						after_name = true;
					}
					Prefix::Verbatim(_) | Prefix::DeviceNS(_) => {
						return Err(UnwritableDescriptorPath::DevicePrefix);
					}
				}
				continue;
			}
			Component::RootDir => {
				text.push('/');
				after_name = false;
				continue;
			}
			Component::CurDir => ".",
			Component::ParentDir => "..",
			Component::Normal(name) => descriptor_name(name)?,
		};
		if after_name {
			text.push('/');
		}
		text.push_str(name);
		after_name = true;
	}
	Ok(text)
}

fn descriptor_name(name: &OsStr) -> Result<&str, UnwritableDescriptorPath> {
	let name = name.to_str().ok_or(UnwritableDescriptorPath::NotUtf8)?;
	if name.contains(['\n', '\r']) {
		return Err(UnwritableDescriptorPath::LineBreak);
	}
	if name.contains('\\') {
		return Err(UnwritableDescriptorPath::Backslash);
	}
	Ok(name)
}

/// The `replace_path` text naming `directory`, written verbatim between the
/// value's quotes. The reader takes those bytes with no escape interpreted
/// (see [`parse_replace_path`]), and a game path holds no `\`, so its own
/// text reads back as the same directory. Only a `"`, which would end the
/// value, has no spelling.
pub fn replace_path_text(directory: &GamePath) -> Result<&str, UnwritableDescriptorPath> {
	let text = directory.as_str();
	if text.contains('"') {
		return Err(UnwritableDescriptorPath::Quote);
	}
	Ok(text)
}

/// `text` made safe for the rest of a `#` comment line: every control
/// character, line breaks included, is written as its Rust escape (`\n`,
/// `\u{85}`). A line break would end the comment and let the remaining text
/// be read as descriptor fields.
pub fn descriptor_comment_text(text: &str) -> String {
	let mut escaped = String::with_capacity(text.len());
	for character in text.chars() {
		if character.is_control() {
			escaped.extend(character.escape_default());
		} else {
			escaped.push(character);
		}
	}
	escaped
}

/// A value quoted for a descriptor: `"` and `\` are escaped, so the value
/// cannot end the quotes early. Only for the text fields jomini decodes, such
/// as `name` and `remote_file_id`: jomini turns `\"` back into `"` but drops
/// every `\`. `path` and `replace_path` are read without escapes, so their
/// text comes from [`descriptor_path_text`] and [`replace_path_text`] and is
/// written as it is.
pub fn escape_descriptor_value(value: &str) -> String {
	value.replace('\\', "\\\\").replace('"', "\\\"")
}

#[cfg(test)]
mod tests {
	use super::{
		DescriptorParseError, ModDescriptor, ReplacePathError, UnwritableDescriptorPath,
		descriptor_comment_text, descriptor_path_text, escape_descriptor_value, load_descriptor,
		load_launcher_descriptor, parse_descriptor_bytes, parse_replace_path, replace_path_text,
		slash_path_text,
	};
	use crate::model::{GamePath, GamePathErrorKind};
	use crate::playset::ParseErrorKind;
	use std::fs;
	use std::path::{Path, PathBuf};

	fn parse(input: &str) -> ModDescriptor {
		parse_descriptor_bytes(input.as_bytes()).expect("failed to parse synthetic descriptor")
	}

	fn replace_texts(descriptor: &ModDescriptor) -> Vec<&str> {
		descriptor
			.replace_path
			.iter()
			.map(|path| path.as_str())
			.collect()
	}

	/// Descriptor `replace_path` text is read in the Windows syntax the
	/// launcher writes: either separator splits components, and a root
	/// separator, repeated or trailing separators and `.` add nothing.
	#[test]
	fn replace_path_is_read_as_a_directory_under_the_game_root() {
		for text in [
			"common/ideas",
			r"common\ideas",
			"/common/ideas/",
			r"\common\ideas\",
			"./common/ideas",
			"common/./ideas",
			"common//ideas",
		] {
			assert_eq!(
				parse_replace_path(text).expect(text).as_str(),
				"common/ideas",
				"{text}"
			);
		}
		// Names are kept as written: no case folding and no trimming.
		assert_eq!(
			parse_replace_path("Common/Ideas")
				.expect("mixed case")
				.as_str(),
			"Common/Ideas"
		);
		assert_eq!(
			parse_replace_path(" common/ideas")
				.expect("leading space")
				.as_str(),
			" common/ideas"
		);
	}

	#[test]
	fn replace_path_that_names_no_directory_under_the_game_root_is_an_error() {
		for (text, expected) in [
			(r"C:\x", ReplacePathError::Prefix),
			("C:/x", ReplacePathError::Prefix),
			(r"\\server\share\x", ReplacePathError::Prefix),
			(r"..\x", ReplacePathError::ParentComponent),
			("common/../x", ReplacePathError::ParentComponent),
			("", ReplacePathError::Empty),
			("/", ReplacePathError::Empty),
			(".", ReplacePathError::Empty),
		] {
			assert_eq!(parse_replace_path(text), Err(expected), "{text:?}");
		}
		let Err(ReplacePathError::Name(error)) = parse_replace_path("common/a:b") else {
			panic!("a `:` inside a name is not a game path name");
		};
		assert_eq!(
			error.kind,
			GamePathErrorKind::ReservedCharacter {
				component: "a:b".to_string(),
				character: ':',
			}
		);
	}

	/// A descriptor whose `replace_path` names no directory is reported as
	/// such, with the value, instead of as a descriptor that does not parse.
	#[test]
	fn an_invalid_replace_path_is_its_own_descriptor_error() {
		let DescriptorParseError::ReplacePath(invalid) =
			parse_descriptor_bytes(b"name=\"Bad\"\nreplace_path=\"common/../events\"\n")
				.expect_err("`..` leaves the game root")
		else {
			panic!("expected a replace_path error");
		};
		assert_eq!(invalid.value, "common/../events");
		assert_eq!(invalid.reason, ReplacePathError::ParentComponent);

		let root = tempfile::tempdir().expect("fixture root");
		let path = root.path().join("descriptor.mod");
		fs::write(&path, "name=\"Bad\"\nreplace_path=\"C:/events\"\n").expect("write");
		let error = load_descriptor(&path).expect_err("a drive prefix leaves the game root");
		assert_eq!(error.kind, ParseErrorKind::InvalidReplacePath);
		assert_eq!(error.path, path);
		assert!(error.message.contains(r#""C:/events""#), "{error}");
		assert!(error.message.contains("drive"), "{error}");
	}

	/// The Windows syntax is what a real descriptor delivers: `replace_path`
	/// is read from the bytes between its quotes, where jomini's text decoding
	/// would drop every `\` (`common\ideas` became `commonideas`) and trim
	/// trailing whitespace.
	#[test]
	fn replace_path_is_read_from_the_bytes_the_descriptor_holds() {
		for (value, expected) in [
			(r#""common\ideas""#, "common/ideas"),
			(r#""common\\ideas""#, "common/ideas"),
			(r#""\common\ideas""#, "common/ideas"),
			(r"common\ideas", "common/ideas"),
			(r#""common/ideas ""#, "common/ideas "),
		] {
			let descriptor =
				parse_descriptor_bytes(format!("name=\"x\"\nreplace_path={value}\n").as_bytes())
					.expect(value);
			assert_eq!(replace_texts(&descriptor), vec![expected], "{value}");
		}

		// A windows-1252 descriptor reads its values the same way.
		let descriptor =
			parse_descriptor_bytes(b"name=\"Caf\xe9\"\nreplace_path=\"common\\ideas\"\n")
				.expect("windows-1252 descriptor");
		assert_eq!(descriptor.name, "Café");
		assert_eq!(replace_texts(&descriptor), vec!["common/ideas"]);
	}

	#[test]
	fn replace_path_bytes_that_leave_the_game_root_are_an_error() {
		for (value, expected) in [
			(r"..\x", ReplacePathError::ParentComponent),
			(r"\\server\share\x", ReplacePathError::Prefix),
			(r"C:\x", ReplacePathError::Prefix),
		] {
			let DescriptorParseError::ReplacePath(invalid) = parse_descriptor_bytes(
				format!("name=\"x\"\nreplace_path=\"{value}\"\n").as_bytes(),
			)
			.expect_err(value) else {
				panic!("expected a replace_path error for {value}");
			};
			assert_eq!(invalid.value, value);
			assert_eq!(invalid.reason, expected, "{value}");
		}
	}

	/// A launcher's copy of a descriptor is read for its name, `path`, id and
	/// version; its `replace_path` is not interpreted, so a value the mod's own
	/// descriptor would reject cannot make the copy unreadable.
	#[test]
	fn a_launcher_descriptor_is_read_without_its_replace_path() {
		let root = tempfile::tempdir().expect("fixture root");
		let path = root.path().join("ugc_1001.mod");
		fs::write(
			&path,
			"name=\"Named\"\npath=\"/mods/named\"\nversion=\"2.0\"\n\
			 remote_file_id=\"1001\"\nreplace_path=\"common/../events\"\n",
		)
		.expect("write launcher descriptor");

		let descriptor = load_launcher_descriptor(&path).expect("launcher descriptor");
		assert_eq!(descriptor.name, "Named");
		assert_eq!(descriptor.path.as_deref(), Some(Path::new("/mods/named")));
		assert_eq!(descriptor.version.as_deref(), Some("2.0"));
		assert_eq!(descriptor.remote_file_id.as_deref(), Some("1001"));
		assert_eq!(
			load_descriptor(&path)
				.expect_err("the mod's own reading")
				.kind,
			ParseErrorKind::InvalidReplacePath
		);
	}

	/// A descriptor `path` names a host directory exactly: its text is
	/// written verbatim between the quotes, and reading the descriptor back
	/// yields that directory.
	#[test]
	fn descriptor_path_text_names_the_directory_exactly() {
		let temp = tempfile::tempdir().expect("temp dir");
		let directory = temp.path().join("merged output Ölände 欧陆 (1)");
		let text = descriptor_path_text(&directory).expect("a UTF-8 directory has text");
		let descriptor = temp.path().join("descriptor.mod");
		fs::write(&descriptor, format!("name=\"x\"\npath=\"{text}\"\n")).expect("write descriptor");

		let read_back = load_launcher_descriptor(&descriptor)
			.expect("read descriptor")
			.path
			.expect("descriptor path");
		assert_eq!(read_back, directory);
	}

	/// `path` is read without escapes, so a `"` has no spelling: `\"` would be
	/// read back as both characters. A directory holding one is refused, while
	/// text that is not a `path` value keeps the same `/`-joined spelling.
	#[test]
	fn a_directory_holding_a_quote_has_no_descriptor_path() {
		let quoted = Path::new("merged").join("out \"put\"");
		assert_eq!(
			descriptor_path_text(&quoted),
			Err(UnwritableDescriptorPath::Quote)
		);
		assert_eq!(
			slash_path_text(&quoted).as_deref(),
			Ok("merged/out \"put\"")
		);
	}

	/// `replace_path` is read from the bytes between its quotes, so a game
	/// path's own text is its spelling and reads back as the same directory.
	/// A `"` would end the value, so a directory holding one is refused.
	#[test]
	fn replace_path_text_reads_back_as_its_directory() {
		for text in [
			"common/ideas",
			"history/countries",
			"common/a b",
			"gfx/欧陆",
		] {
			let directory = GamePath::new(text).expect("valid game path");
			let value = replace_path_text(directory).expect("a directory without a quote");
			assert_eq!(value, text);
			let descriptor = parse(&format!("name=\"x\"\nreplace_path=\"{value}\"\n"));
			assert_eq!(replace_texts(&descriptor), vec![text]);
		}
		assert_eq!(
			replace_path_text(GamePath::new("common/a\"b").expect("valid game path")),
			Err(UnwritableDescriptorPath::Quote)
		);
	}

	/// A name holding `\` is refused because a Windows launcher splits on it,
	/// and a name that is not UTF-8 has no text at all. Off Windows either can
	/// be part of a directory name, so such a directory is refused instead of
	/// being written as some other one.
	/// A line break would end a `path` value's line or a comment early, so a
	/// directory holding one has no descriptor text; comment text escapes it.
	#[test]
	fn a_line_break_has_no_descriptor_path_text_and_is_escaped_in_comments() {
		for name in ["out\nput", "out\rput"] {
			let path = Path::new("/merged").join(name);
			assert_eq!(
				descriptor_path_text(&path),
				Err(UnwritableDescriptorPath::LineBreak)
			);
			assert_eq!(
				slash_path_text(&path),
				Err(UnwritableDescriptorPath::LineBreak)
			);
		}
		assert_eq!(
			descriptor_comment_text("a\nb=\"c\"\r\n\u{85}d"),
			r#"a\nb="c"\r\n\u{85}d"#
		);
	}

	#[cfg(unix)]
	#[test]
	fn a_directory_a_descriptor_cannot_name_is_an_error() {
		use std::ffi::OsStr;
		use std::os::unix::ffi::OsStrExt;

		let backslash = Path::new("/merged").join(r"out\put");
		let non_utf8 = Path::new("/merged").join(OsStr::from_bytes(b"out\xffput"));
		assert_eq!(
			descriptor_path_text(&backslash),
			Err(UnwritableDescriptorPath::Backslash)
		);
		assert_eq!(
			descriptor_path_text(&non_utf8),
			Err(UnwritableDescriptorPath::NotUtf8)
		);
		assert_eq!(
			descriptor_path_text(Path::new("/merged/a:/b")).as_deref(),
			Ok("/merged/a:/b")
		);
	}

	fn descriptor_path_of(bytes: &[u8]) -> PathBuf {
		parse_descriptor_bytes(bytes)
			.expect("descriptor")
			.path
			.expect("descriptor path")
	}

	/// The launcher writes `path` in its host's syntax, and it is read from
	/// the bytes between its quotes: jomini's text decoding would drop every
	/// `\` (a Windows launcher's `C:\Users\x` became `C:Usersx`) and trim
	/// trailing whitespace.
	#[test]
	fn descriptor_path_is_the_text_between_its_quotes() {
		for (value, expected) in [
			// The current launcher, on macOS and Linux.
			(
				r#""/Users/x/Library/Application Support/Steam/steamapps/workshop/content/236850/1001""#,
				"/Users/x/Library/Application Support/Steam/steamapps/workshop/content/236850/1001",
			),
			// Forward slashes, as the launcher writes them on Windows.
			(
				r#""C:/Users/x/Documents/Paradox Interactive/Europa Universalis IV/mod/named""#,
				"C:/Users/x/Documents/Paradox Interactive/Europa Universalis IV/mod/named",
			),
			// A Windows launcher's backslashes are kept as written.
			(
				r#""C:\Users\x\Documents\Paradox Interactive\Europa Universalis IV\mod\named""#,
				r"C:\Users\x\Documents\Paradox Interactive\Europa Universalis IV\mod\named",
			),
			// Nothing is trimmed, and no escape sequence is interpreted.
			(r#""/mods/named ""#, "/mods/named "),
			(r#""/mods/a\"b""#, r#"/mods/a\"b"#),
			(r#""/mods/欧陆""#, "/mods/欧陆"),
			("/mods/unquoted", "/mods/unquoted"),
		] {
			let path = descriptor_path_of(format!("name=\"x\"\npath={value}\n").as_bytes());
			assert_eq!(path.as_os_str(), expected, "{value}");
		}

		// A windows-1252 descriptor decodes `path` in the same encoding as its
		// other values.
		let descriptor = parse_descriptor_bytes(b"name=\"Caf\xe9\"\npath=\"/mods/Caf\xe9\"\n")
			.expect("windows-1252 descriptor");
		assert_eq!(descriptor.name, "Café");
		assert_eq!(descriptor.path.as_deref(), Some(Path::new("/mods/Café")));
	}

	/// A `path` cannot end in `\`: the tokenizer reads `\"` as an escaped
	/// quote, so the value runs on to the next quote in the file and the last
	/// one opens a value that never closes. Whether the value is followed by
	/// other fields or is the last line, such a descriptor is a syntax error,
	/// never a path read from the wrong bytes: a launcher copy that does not
	/// parse gives no mod directory.
	#[test]
	fn a_descriptor_path_ending_in_a_backslash_does_not_parse() {
		for bytes in [
			&b"name=\"x\"\npath=\"C:\\mods\\x\\\"\nsupported_version=\"1.37.*\"\n"[..],
			&b"path=\"C:\\mods\\x\\\"\nname=\"x\"\nremote_file_id=\"1001\"\n"[..],
			&b"name=\"x\"\npath=\"C:\\mods\\x\\\"\n"[..],
		] {
			let result = parse_descriptor_bytes(bytes);
			assert!(
				matches!(result, Err(DescriptorParseError::Syntax(_))),
				"{:?}: {result:?}",
				String::from_utf8_lossy(bytes)
			);
		}
	}

	/// A Windows launcher's backslash path is read with host syntax only: a
	/// separator the host does not use stays part of a name.
	#[test]
	fn a_backslash_descriptor_path_resolves_only_on_windows() {
		let path = descriptor_path_of(br#"path="C:\mods\named""#);
		#[cfg(unix)]
		assert_eq!(
			path.components().collect::<Vec<_>>(),
			vec![std::path::Component::Normal(std::ffi::OsStr::new(
				r"C:\mods\named"
			))],
			"one relative name on Unix"
		);
		#[cfg(windows)]
		assert_eq!(path, Path::new("C:/").join("mods").join("named"));
	}

	/// `name` is decoded by jomini, which reads an escaped quote back.
	#[test]
	fn an_escaped_name_reads_back() {
		let name = "The \"Great\" Merge";
		let descriptor = parse(&format!("name=\"{}\"\n", escape_descriptor_value(name)));
		assert_eq!(descriptor.name, name);
	}

	#[test]
	fn a_repeated_or_structured_descriptor_path_does_not_parse() {
		for bytes in [
			&b"path=\"/mods/a\"\npath=\"/mods/b\"\n"[..],
			&b"path={ \"/mods/a\" }\n"[..],
		] {
			assert!(matches!(
				parse_descriptor_bytes(bytes),
				Err(DescriptorParseError::Syntax(_))
			));
		}
	}

	/// Windows spells a verbatim drive or UNC directory with a `\\?\` prefix
	/// the launcher does not read; the descriptor names the plain directory.
	#[cfg(windows)]
	#[test]
	fn a_windows_directory_is_written_with_its_plain_prefix() {
		for (path, text) in [
			(r"D:\mods\merged", "D:/mods/merged"),
			(r"\\?\D:\mods\merged", "D:/mods/merged"),
			(r"\\server\share\merged", "//server/share/merged"),
			(r"\\?\UNC\server\share\merged", "//server/share/merged"),
		] {
			assert_eq!(descriptor_path_text(Path::new(path)).as_deref(), Ok(text));
		}
		assert_eq!(
			descriptor_path_text(Path::new(r"\\.\pipe\merged")),
			Err(UnwritableDescriptorPath::DevicePrefix)
		);
	}

	#[test]
	fn parses_descriptor_from_corpus() {
		let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
		let test_file = manifest_dir
			.join("tests")
			.join("fixtures")
			.join("defines")
			.join("descriptor.mod");

		let descriptor = load_descriptor(&test_file).expect("failed to parse descriptor");
		assert_eq!(descriptor.name, "defines");
		assert_eq!(descriptor.version.as_deref(), Some("0.0.1"));
		assert_eq!(descriptor.remote_file_id.as_deref(), Some("2887527268"));
	}

	#[cfg(unix)]
	#[test]
	fn rejects_descriptor_symlinks_without_reading_the_target() {
		use std::os::unix::fs::symlink;

		let root = tempfile::tempdir().expect("fixture root");
		let target = root.path().join("outside.mod");
		let descriptor = root.path().join("descriptor.mod");
		fs::write(&target, "name=\"outside\"\n").expect("write target");
		symlink(&target, &descriptor).expect("link descriptor");

		let error = load_descriptor(&descriptor).expect_err("descriptor symlink must fail closed");
		assert!(error.to_string().contains("regular file"));
	}

	#[test]
	fn parses_vanilla_style_descriptor() {
		let descriptor = parse(
			r#"
			name="Vanilla-ish Mod"
			version="1.0"
			tags={
				"Gameplay"
				"Balance"
			}
			supported_version="1.37.*"
			"#,
		);
		assert_eq!(descriptor.name, "Vanilla-ish Mod");
		assert_eq!(descriptor.version.as_deref(), Some("1.0"));
		assert_eq!(descriptor.tags, vec!["Gameplay", "Balance"]);
		assert_eq!(descriptor.supported_version.as_deref(), Some("1.37.*"));
		assert!(descriptor.dependencies.is_empty());
		assert!(descriptor.replace_path.is_empty());
		assert!(descriptor.path.is_none());
		assert!(descriptor.remote_file_id.is_none());
	}

	#[test]
	fn parses_multiple_dependencies() {
		let descriptor = parse(
			r#"
			name="With Deps"
			dependencies={
				"Extended Timeline"
				"Banner Flags"
				"Missions Expanded"
			}
			"#,
		);
		assert_eq!(
			descriptor.dependencies,
			vec!["Extended Timeline", "Banner Flags", "Missions Expanded"]
		);
	}

	#[test]
	fn parses_single_replace_path() {
		let descriptor = parse(
			r#"
			name="One Replace"
			replace_path="common/missions"
			"#,
		);
		assert_eq!(replace_texts(&descriptor), vec!["common/missions"]);
	}

	#[test]
	fn parses_multiple_replace_path_lines() {
		let descriptor = parse(
			r#"
			name="Multi Replace"
			replace_path="common/missions"
			replace_path="common/disasters"
			replace_path="events"
			"#,
		);
		assert_eq!(
			replace_texts(&descriptor),
			vec!["common/missions", "common/disasters", "events"]
		);
	}

	#[test]
	fn parses_utf8_descriptor_with_chinese_name() {
		// Pure UTF-8 (no BOM): name contains Chinese characters that would
		// mojibake under windows-1252.
		let raw = "name=\"欧陆拓展-未知领域\"\nversion=\"1.0\"\n".as_bytes();
		let descriptor =
			parse_descriptor_bytes(raw).expect("failed to parse UTF-8 descriptor without BOM");
		assert_eq!(descriptor.name, "欧陆拓展-未知领域");
		assert_eq!(descriptor.version.as_deref(), Some("1.0"));
	}

	#[test]
	fn parses_utf8_descriptor_with_bom() {
		let mut raw: Vec<u8> = vec![0xEF, 0xBB, 0xBF];
		raw.extend_from_slice("name=\"欧陆拓展-未知领域\"\n".as_bytes());
		let descriptor =
			parse_descriptor_bytes(&raw).expect("failed to parse UTF-8 descriptor with BOM");
		assert_eq!(descriptor.name, "欧陆拓展-未知领域");
	}

	#[test]
	fn parses_windows1252_descriptor_with_high_bytes() {
		// `é` = 0xE9 in windows-1252; not valid UTF-8 on its own, so the
		// sniffer must fall back to windows-1252.
		let raw: Vec<u8> = b"name=\"Caf\xe9 Mod\"\nversion=\"1.0\"\n".to_vec();
		let descriptor = parse_descriptor_bytes(&raw).expect("failed to parse windows-1252");
		assert_eq!(descriptor.name, "Café Mod");
	}

	#[test]
	fn missing_optional_fields_fall_back_to_defaults() {
		let descriptor = parse(r#"name="Bare Minimum""#);
		assert_eq!(descriptor.name, "Bare Minimum");
		assert!(descriptor.version.is_none());
		assert!(descriptor.supported_version.is_none());
		assert!(descriptor.tags.is_empty());
		assert!(descriptor.dependencies.is_empty());
		assert!(descriptor.replace_path.is_empty());
	}

	#[test]
	fn parses_mixed_real_world_descriptor() {
		let descriptor = parse(
			r#"
			name="Holy Roman Empire Expanded"
			dependencies={
				"Extended Timeline"
				"Banner Flags"
			}
			tags={
				"Historical"
				"Gameplay"
			}
			picture="thumbnail.png"
			supported_version="v1.37.*"
			remote_file_id="1352521684"
			replace_path="common/missions"
			replace_path="history/countries"
			"#,
		);
		assert_eq!(descriptor.name, "Holy Roman Empire Expanded");
		assert_eq!(
			descriptor.dependencies,
			vec!["Extended Timeline", "Banner Flags"]
		);
		assert_eq!(descriptor.tags, vec!["Historical", "Gameplay"]);
		assert_eq!(descriptor.supported_version.as_deref(), Some("v1.37.*"));
		assert_eq!(descriptor.remote_file_id.as_deref(), Some("1352521684"));
		assert_eq!(
			replace_texts(&descriptor),
			vec!["common/missions", "history/countries"]
		);
	}
}