wt_blk 0.3.1

Parser and unpacker for the BLK file format
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
use std::{
	ffi::OsStr,
	fmt::{Debug, Formatter},
	io::{Cursor, Write},
	mem,
	ops::{Deref, Not},
	path::{Path, PathBuf},
	str::FromStr,
	sync::Arc,
};

use color_eyre::{
	eyre::{eyre, Context, ContextCompat},
	Help,
	Report,
};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use regex::Regex;
use wt_version::Version;
use zip::{write::SimpleFileOptions, CompressionMethod, ZipWriter};
use zstd::dict::DecoderDictionary;

use crate::{
	blk,
	blk::{name_map::NameMap, util::maybe_blk},
	vromf::{
		binary_container::decode_bin_vromf,
		header::Metadata,
		inner_container::decode_inner_vromf,
		File,
	},
};
use crate::blk::blk_type::BlkFormatting;

// TODO: Check if this leaks, or if the FFI drops the contents appropriately
// TODO: Implement https://docs.rs/zstd/latest/zstd/dict/struct.DecoderDictionary.html#method.new once it is no longer experimental
#[derive()]
struct DictWrapper(DecoderDictionary<'static>);

impl Debug for DictWrapper {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		write!(f, "DecoderDictionary {{...}}")
	}
}

impl<'a> Deref for DictWrapper {
	type Target = DecoderDictionary<'static>;

	fn deref(&self) -> &Self::Target {
		&self.0
	}
}

/// Unpacks vromf image into all internal files, optionally formatting binary BLK files
#[derive(Debug, Clone)]
pub struct VromfUnpacker {
	files:    Vec<File>,
	dict:     Option<Arc<DictWrapper>>,
	nm:       Option<Arc<NameMap>>,
	metadata: Metadata,
}

/// Defines plaintext format should be exported to
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum BlkOutputFormat {
	Json,
	BlkText,
	BlkCompact,
}

impl BlkOutputFormat {
	pub fn map_to_formatter(self) -> BlkFormatting {
		match self {
			BlkOutputFormat::Json | BlkOutputFormat::BlkText => {BlkFormatting::standard()},
			BlkOutputFormat::BlkCompact => {BlkFormatting::compact()},
		}
	}
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum ZipFormat {
	Uncompressed,
	Compressed(u8),
}

#[derive(Debug, Clone)]
pub enum FileFilter {
	All,
	OneFolder {
		remove_base: bool,
		prefix:      Arc<PathBuf>,
	},
	FullPathRegex {
		rex: Arc<Regex>,
	},
}

impl FileFilter {
	pub fn accept(&self, file: &File) -> bool {
		match self {
			FileFilter::All => true,
			FileFilter::OneFolder { prefix, .. } => file.path().starts_with(prefix.as_ref()),
			FileFilter::FullPathRegex { rex } => rex.is_match(&file.path().to_string_lossy()),
		}
	}

	pub fn base_path_start(&self) -> usize {
		match self {
			FileFilter::OneFolder { prefix, .. } => prefix.to_string_lossy().len(),
			_ => 0,
		}
	}

	pub fn from_regexstr(re: &str) -> Result<Self, Report> {
		Ok(Self::FullPathRegex {
			rex: Arc::new(Regex::new(re).context(format!("Invalid regex: {}", re))?),
		})
	}

	pub const fn all() -> Self {
		Self::All
	}

	pub fn one_folder(prefix: Arc<PathBuf>, remove_base: bool) -> Self {
		Self::OneFolder {
			remove_base,
			prefix,
		}
	}
}

impl VromfUnpacker {
	pub fn from_file(file: &File, validate: bool) -> Result<Self, Report> {
		let (decoded, metadata) = decode_bin_vromf(file.buf(), validate)?;
		let inner = decode_inner_vromf(&decoded, validate)?;

		let nm = inner
			.iter()
			.find(|elem| elem.path().file_name() == Some(OsStr::new("nm")))
			.map(|elem| NameMap::from_encoded_file(&elem.buf()))
			.transpose()?
			.map(|elem| Arc::new(elem));

		let dict = inner
			.iter()
			.find(|elem| elem.path().extension() == Some(OsStr::new("dict")))
			.map(|elem| Arc::new(DictWrapper(DecoderDictionary::copy(&elem.buf()))));

		Ok(Self {
			files: inner,
			dict,
			nm,
			metadata,
		})
	}

	pub fn unpack_all(
		mut self,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
	) -> Result<Vec<File>, Report> {
		// Important: We own self here, so "destroying" the files vector isn't an issue
		// Due to partial moving rules this is necessary
		let files = mem::replace(&mut self.files, vec![]);
		files
			.into_par_iter()
			.panic_fuse()
			.map(|file| self.unpack_file(file, unpack_blk_into, apply_overrides, FileFilter::All))
			.collect::<Result<Vec<File>, Report>>()
	}

	/// Skips the buffering step and directly writes the file to disk, using a provided writer
	pub fn unpack_all_with_writer<W: Write>(
		mut self,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
		writer: impl FnOnce(&mut File) -> Result<W, Report> + Sync + Send + Copy,
		// Runs unpacking in the global rayon threadpool if true, otherwise its single threaded
		// false increases global throughput when executed from a threadpool,
		// but slower when individual calls are performed
		threaded: bool,
	) -> Result<(), Report> {
		// Important: We own self here, so "destroying" the files vector isn't an issue
		// Due to partial moving rules this is necessary
		let files = mem::replace(&mut self.files, vec![]);

		// TODO: Figure out some way to deduplicate this
		// ParIter and Iter are obv. incompatible so this might need macro magic of sorts
		if threaded {
			files
				.into_par_iter()
				.panic_fuse()
				.map(|mut file| {
					let mut w = writer(&mut file)?;
					self.unpack_file_with_writer(
						&mut file,
						unpack_blk_into,
						apply_overrides,
						&mut w,
						FileFilter::All,
					)?;
					Ok(())
				})
				.collect::<Result<(), Report>>()
		} else {
			files
				.into_iter()
				.map(|mut file| {
					let mut w = writer(&mut file)?;
					self.unpack_file_with_writer(
						&mut file,
						unpack_blk_into,
						apply_overrides,
						&mut w,
						FileFilter::All,
					)?;
					Ok(())
				})
				.collect::<Result<(), Report>>()
		}
	}

	pub fn unpack_subfolder_to_zip(
		&self,
		zip_format: ZipFormat,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
		// Runs unpacking in the global rayon threadpool if true, otherwise its single threaded
		// false increases global throughput when executed from a threadpool,
		// but slower when individual calls are performed
		threaded: bool,
		filter: FileFilter,
	) -> Result<Vec<u8>, Report> {
		// TODO: Figure out some way to deduplicate this
		// ParIter and Iter are obv. incompatible so this might need macro magic of sorts
		let files = &self.files;
		let unpacked = if threaded {
			files
				.into_par_iter()
				.panic_fuse()
				.cloned()
				.map(|file| {
					self.unpack_file(file, unpack_blk_into, apply_overrides, filter.clone())
				})
				.collect::<Result<Vec<File>, Report>>()?
		} else {
			files
				.iter()
				.cloned()
				.map(|file| {
					self.unpack_file(file, unpack_blk_into, apply_overrides, filter.clone())
				})
				.collect::<Result<Vec<File>, Report>>()?
		};

		let mut buf = Cursor::new(Vec::with_capacity(4096));
		let mut writer = ZipWriter::new(&mut buf);

		let (compression_level, compression_method) = match zip_format {
			ZipFormat::Uncompressed => (None, CompressionMethod::STORE),
			ZipFormat::Compressed(level) => (Some(level as i64), CompressionMethod::DEFLATE),
		};

		for f in unpacked.into_iter() {
			writer.start_file(
				&f.path().to_string_lossy()[filter.base_path_start()..],
				SimpleFileOptions::default()
					.compression_level(compression_level)
					.compression_method(compression_method),
			)?;
			writer.write_all(f.buf())?;
		}

		let buf = mem::replace(writer.finish()?, Default::default());
		Ok(buf.into_inner())
	}

	pub fn unpack_all_to_zip(
		&self,
		zip_format: ZipFormat,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
		// Runs unpacking in the global rayon threadpool if true, otherwise its single threaded
		threaded: bool,
	) -> Result<Vec<u8>, Report> {
		self.unpack_subfolder_to_zip(
			zip_format,
			unpack_blk_into,
			apply_overrides,
			threaded,
			FileFilter::All,
		)
	}

	pub fn unpack_one(
		&self,
		path_name: &Path,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
		file_filter: FileFilter,
	) -> Result<File, Report> {
		let file = self
			.files
			.iter()
			.find(|e| e.path() == path_name)
			.context(format!(
				"File {} was not found in VROMF",
				path_name.to_string_lossy()
			))
			.suggestion("Validate file-name and ensure it was typed correctly")?
			.to_owned();
		self.unpack_file(file, unpack_blk_into, apply_overrides, file_filter)
	}

	pub fn unpack_file(
		&self,
		mut file: File,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
		filter: FileFilter,
	) -> Result<File, Report> {
		let mut buf = Cursor::new(Vec::with_capacity(4096));
		self.unpack_file_with_writer(
			&mut file,
			unpack_blk_into,
			apply_overrides,
			&mut buf,
			filter,
		)?;
		*file.buf_mut() = buf.into_inner();
		Ok(file)
	}

	/// This is where the unpacking actually occurs
	pub fn unpack_file_with_writer(
		&self,
		file: &mut File,
		unpack_blk_into: Option<BlkOutputFormat>,
		apply_overrides: bool,
		mut writer: impl Write,
		filter: FileFilter,
	) -> Result<(), Report> {
		if filter.accept(file).not() {
			return Ok(());
		}
		match () {
			_ if maybe_blk(&file) => {
				if let Some(format) = unpack_blk_into {
					let mut parsed = blk::unpack_blk(file.buf_mut(), self.dict(), self.nm.clone())
						.context(format!("unpacking {}", file.path().to_string_lossy()))?;

					match format {
						BlkOutputFormat::BlkText | BlkOutputFormat::BlkCompact => {
							if apply_overrides {
								parsed.apply_overrides(false);
							}
							writer.write_all(parsed.as_blk_text(format.map_to_formatter())?.as_bytes())?;
						},
						BlkOutputFormat::Json => {
							parsed.merge_fields()?;
							if apply_overrides {
								parsed.apply_overrides(true);
							}
							parsed.as_serde_json_streaming(&mut writer)?;
						},
					}
				} else {
					// Default to the raw file
					writer.write_all(file.buf())?;
				}
			},
			// Default to the raw file
			_ => {
				writer.write_all(file.buf())?;
			},
		}
		writer.flush()?;
		Ok(())
	}

	pub fn query_versions(&self) -> Result<Vec<Version>, Report> {
		let mut versions = vec![];
		if let Some(meta) = self.metadata.version {
			versions.push(meta);
		};

		if let Ok((_, version_file)) = self
			.unpack_one(Path::new("version"), None, false, FileFilter::All)
			.map(|e| e.split())
		{
			let s = String::from_utf8(version_file)?;
			versions.push(
				Version::from_str(&s).map_err(|_| eyre!("Invalid version file contents: {s}"))?,
			);
		}

		Ok(versions)
	}

	pub fn latest_version(&self) -> Result<Option<Version>, Report> {
		let mut versions = self.query_versions()?;
		versions.sort_unstable();
		Ok(versions.last().map(|e| e.to_owned()))
	}

	pub fn list_files(&self) {
		for f in &self.files {
			println!("{}", f.path().to_string_lossy());
		}
	}

	pub fn dict(&self) -> Option<&DecoderDictionary<'_>> {
		self.dict.as_deref().map(Deref::deref)
	}

	pub fn nm(&self) -> Option<Arc<NameMap>> {
		self.nm.clone()
	}
}