Skip to main content

fontoxide_diff/
lib.rs

1//! Port of `fontTools.diff`: comparing two fonts table by table, as a unified
2//! diff of their TTX dumps, or as a summary of which tables are present and
3//! binary identical.
4//!
5//! | fontoxide-diff | fontTools                 |
6//! |----------------|---------------------------|
7//! | [`summarize`], [`get_binary_exclude_tables`], [`main`], [`run`], [`pipe_output`] | `fontTools.diff` (`__init__`, `__main__`) |
8//! | [`color`]      | `fontTools.diff.color`    |
9//! | [`diff`]       | `fontTools.diff.diff`     |
10//! | [`utils`]      | `fontTools.diff.utils`    |
11//! | [`difflib`]    | Python's `difflib` (`SequenceMatcher`, `unified_diff`) |
12//!
13//! The diff tool, the pager and the modification times use the operating
14//! system; the TTX dumps are made in memory (and saved to a temporary directory
15//! only for an external diff tool).
16
17#![forbid(unsafe_code)]
18
19pub mod color;
20pub mod diff;
21pub mod difflib;
22pub mod utils;
23
24use std::collections::BTreeSet;
25use std::io::{IsTerminal, Write};
26use std::path::PathBuf;
27
28use fontoxide_misc::argparse::{Argument, Command, Nargs, Ty};
29use fontoxide_ttlib::Font;
30
31pub use diff::{DiffOptions, run_external_diff, u_diff};
32
33/// The errors of `fontTools.diff`.
34#[derive(Debug, thiserror::Error)]
35pub enum DiffError {
36	/// An error reading or dumping a font.
37	#[error(transparent)]
38	Ttlib(#[from] fontoxide_ttlib::Error),
39	/// A file could not be read or written, or a program run.
40	#[error(transparent)]
41	Io(#[from] std::io::Error),
42	/// What the external diff tool wrote to standard error (`IOError(err)`).
43	#[error("{0}")]
44	External(String),
45	/// Another error.
46	#[error("{0}")]
47	Message(String),
48}
49
50/// The result type of this crate.
51pub type Result<T, E = DiffError> = std::result::Result<T, E>;
52
53/// `_iter_filtered_table_tags`: the tags not excluded, and included if there
54/// is a list of tables to include.
55fn filtered_table_tags<'a>(
56	tags: impl IntoIterator<Item = &'a String>,
57	include_tables: Option<&[String]>,
58	exclude_tables: Option<&[String]>,
59) -> Vec<&'a String> {
60	tags.into_iter()
61		.filter(|tag| {
62			!exclude_tables.is_some_and(|t| !t.is_empty() && t.contains(tag))
63				&& !include_tables.is_some_and(|t| !t.is_empty() && !t.contains(tag))
64		})
65		.collect()
66}
67
68/// The tables of the two fonts, as `TTFont(file, lazy=True, fontNumber=...)`
69/// has them: the fonts, and their tags.
70fn read_tables(
71	file1: &str,
72	file2: &str,
73	font_number_1: i64,
74	font_number_2: i64,
75) -> Result<[(Font, BTreeSet<String>); 2]> {
76	let font1 = diff::open_font(file1, font_number_1)?;
77	let font2 = diff::open_font(file2, font_number_2)?;
78	let tags = |font: &Font| -> BTreeSet<String> {
79		font.reader()
80			.map(|r| r.tags().map(|t| t.to_string()).collect())
81			.unwrap_or_default()
82	};
83	let (tags1, tags2) = (tags(&font1), tags(&font2));
84	Ok([(font1, tags1), (font2, tags2)])
85}
86
87/// The data of a table (`font.reader[tag]`).
88fn table_data(font: &Font, tag: &str) -> Result<Vec<u8>> {
89	let reader = font
90		.reader()
91		.ok_or_else(|| DiffError::Message(format!("KeyError: '{tag}'")))?;
92	let tag = fontoxide_misc::py::latin1_encode(tag)
93		.and_then(|b| <[u8; 4]>::try_from(b).ok())
94		.map(|b| fontoxide_ttlib::Tag::new(&b))
95		.ok_or_else(|| DiffError::Message(format!("KeyError: '{tag}'")))?;
96	Ok(reader.table_data(tag)?.to_vec())
97}
98
99/// `summarize`: which tables are only in one of the fonts, and which of those
100/// in both are binary identical. Returns whether the fonts are identical, and
101/// the report.
102pub fn summarize(
103	file1: &str,
104	file2: &str,
105	include_tables: Option<&[String]>,
106	exclude_tables: Option<&[String]>,
107	font_number_1: i64,
108	font_number_2: i64,
109) -> Result<(bool, String)> {
110	let [(font1, tags1), (font2, tags2)] = read_tables(file1, file2, font_number_1, font_number_2)?;
111	let all: BTreeSet<&String> = tags1.union(&tags2).collect();
112	let all_tags = filtered_table_tags(all, include_tables, exclude_tables);
113
114	let only1: Vec<&String> = all_tags
115		.iter()
116		.copied()
117		.filter(|t| tags1.contains(*t) && !tags2.contains(*t))
118		.collect();
119	let only2: Vec<&String> = all_tags
120		.iter()
121		.copied()
122		.filter(|t| tags2.contains(*t) && !tags1.contains(*t))
123		.collect();
124	let both: Vec<&String> = all_tags
125		.iter()
126		.copied()
127		.filter(|t| tags1.contains(*t) && tags2.contains(*t))
128		.collect();
129
130	let mut identical = true;
131	let mut lines = String::new();
132	lines.push_str("Binary table summary:\n");
133	lines.push_str(&format!("  file1: {file1}\n"));
134	lines.push_str(&format!("  file2: {file2}\n"));
135
136	if !only1.is_empty() {
137		identical = false;
138		lines.push_str(&format!("\nTables only in file1 ({}):\n", only1.len()));
139		for tag in only1 {
140			lines.push_str(&format!(
141				"- {tag} ({} bytes)\n",
142				table_data(&font1, tag)?.len()
143			));
144		}
145	}
146	if !only2.is_empty() {
147		identical = false;
148		lines.push_str(&format!("\nTables only in file2 ({}):\n", only2.len()));
149		for tag in only2 {
150			lines.push_str(&format!(
151				"+ {tag} ({} bytes)\n",
152				table_data(&font2, tag)?.len()
153			));
154		}
155	}
156
157	lines.push_str(&format!("\nTables in both ({}):\n", both.len()));
158	for tag in both {
159		let data1 = table_data(&font1, tag)?;
160		let data2 = table_data(&font2, tag)?;
161		if data1 == data2 {
162			lines.push_str(&format!("  {tag}: SAME ({} bytes)\n", data1.len()));
163		} else {
164			identical = false;
165			lines.push_str(&format!(
166				"* {tag}: DIFF ({} vs {} bytes)\n",
167				data1.len(),
168				data2.len()
169			));
170		}
171	}
172
173	lines.push_str(if identical {
174		"\nResult: SAME\n"
175	} else {
176		"\nResult: DIFFERENT\n"
177	});
178	Ok((identical, lines))
179}
180
181/// `get_binary_exclude_tables`: the tables (filtered as in [`summarize`]) that
182/// are in both fonts and binary identical.
183pub fn get_binary_exclude_tables(
184	file1: &str,
185	file2: &str,
186	include_tables: Option<&[String]>,
187	exclude_tables: Option<&[String]>,
188	font_number_1: i64,
189	font_number_2: i64,
190) -> Result<BTreeSet<String>> {
191	let [(font1, tags1), (font2, tags2)] = read_tables(file1, file2, font_number_1, font_number_2)?;
192	let all: BTreeSet<&String> = tags1.union(&tags2).collect();
193	let mut out = BTreeSet::new();
194	for tag in filtered_table_tags(all, include_tables, exclude_tables) {
195		if tags1.contains(tag)
196			&& tags2.contains(tag)
197			&& table_data(&font1, tag)? == table_data(&font2, tag)?
198		{
199			out.insert(tag.clone());
200		}
201	}
202	Ok(out)
203}
204
205/// `pipe_output`: writes the output to standard output, through a pager
206/// (`$PAGER`, or `less -R`) if standard output is a terminal.
207pub fn pipe_output(output: &str) -> Result<()> {
208	if output.is_empty() {
209		return Ok(());
210	}
211	let stdout = std::io::stdout();
212	if !stdout.is_terminal() {
213		stdout.lock().write_all(output.as_bytes())?;
214		return Ok(());
215	}
216	let pager = std::env::var_os("PAGER")
217		.filter(|p| !p.is_empty())
218		.map(PathBuf::from)
219		.or_else(|| utils::which("less"));
220	let Some(pager) = pager else {
221		stdout.lock().write_all(output.as_bytes())?;
222		return Ok(());
223	};
224	let mut command = std::process::Command::new(&pager);
225	if pager
226		.file_name()
227		.is_some_and(|n| n.to_string_lossy().contains("less"))
228	{
229		command.arg("-R");
230	}
231	let mut child = command.stdin(std::process::Stdio::piped()).spawn()?;
232	if let Some(mut stdin) = child.stdin.take() {
233		// The pager may quit before reading everything: not an error.
234		match stdin.write_all(output.as_bytes()) {
235			Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
236			r => r?,
237		}
238	}
239	child.wait()?;
240	Ok(())
241}
242
243const HELP: &str = "\
244usage: fonttools diff [-h] [-l] [-U LINES] [-t INCLUDE [INCLUDE ...]]
245                      [-x EXCLUDE [EXCLUDE ...]] [--diff DIFF]
246                      [--diff-arg DIFF_ARG] [--color {auto,never,always}]
247                      [--y1 NUMBER] [--y2 NUMBER] [-a] [-b] [-q]
248                      FILE1 FILE2
249
250An OpenType table diff tool for fonts.
251
252positional arguments:
253  FILE1                 Font file path 1
254  FILE2                 Font file path 2
255
256options:
257  -h, --help            show this help message and exit
258  -l, --summary         Report table presence and binary equality only
259  -U, --lines LINES     Number of context lines for unified diff (default: 3)
260  -t, --include INCLUDE [INCLUDE ...]
261                        Font tables to include. Multiple options are allowed.
262  -x, --exclude EXCLUDE [EXCLUDE ...]
263                        Font tables to exclude. Multiple options are allowed.
264  --diff DIFF           Run external diff tool command (default: diff)
265  --diff-arg DIFF_ARG   External diff tool arguments (default: -u)
266  --color {auto,never,always}
267                        Whether to colorize output (default: auto)
268  --y1 NUMBER           Select font number for TrueType Collection (.ttc/.otc)
269                        FILE1, starting from 0
270  --y2 NUMBER           Select font number for TrueType Collection (.ttc/.otc)
271                        FILE2, starting from 0
272  -a, --always          Compare tables even if binary identical
273  -b, --binary          Compare tables only if binaries differ (default)
274  -q, --quiet           Suppress all output
275";
276
277const ARGUMENTS: &[Argument] = &[
278	Argument::help(),
279	Argument::flag(&["-l", "--summary"]),
280	Argument::option(&["-U", "--lines"]).ty(Ty::Int),
281	Argument::option(&["-t", "--include"]).nargs(Nargs::OneOrMore),
282	Argument::option(&["-x", "--exclude"]).nargs(Nargs::OneOrMore),
283	Argument::option(&["--diff"]),
284	Argument::option(&["--diff-arg"]),
285	Argument::option(&["--color"]),
286	Argument::option(&["--y1"]).ty(Ty::Int),
287	Argument::option(&["--y2"]).ty(Ty::Int),
288	Argument::flag(&["-a", "--always"]),
289	Argument::flag(&["-b", "--binary"]),
290	Argument::flag(&["-q", "--quiet"]),
291	Argument::positional("FILE1"),
292	Argument::positional("FILE2"),
293];
294
295/// The command line of `fonttools diff`.
296pub const COMMAND: Command = Command {
297	prog: "fonttools diff",
298	module: "diff",
299	help: HELP,
300	arguments: ARGUMENTS,
301	required_groups: &[],
302};
303
304/// The choices of `--color`.
305const COLORS: [&str; 3] = ["auto", "never", "always"];
306
307/// `main`: compares two fonts (see [`run`]), writing the diff to standard
308/// output (through a pager if it is a terminal) and the errors to standard
309/// error. Returns the exit code: 0 if the fonts are the same, 1 if they differ,
310/// 2 on errors.
311pub fn main(args: &[&str]) -> Result<i32> {
312	run_with(args, &mut std::io::stdout(), &mut std::io::stderr(), true)
313}
314
315/// `run(argv)`: compares two fonts, writing the diff (or the summary, or the
316/// help) to `out` and the errors to `err`. Returns the exit code: 0 if the
317/// fonts are the same, 1 if they differ, 2 on errors.
318pub fn run(args: &[&str], out: &mut dyn Write, err: &mut dyn Write) -> Result<i32> {
319	run_with(args, out, err, false)
320}
321
322/// [`run`]; with `pager`, the diff is written with [`pipe_output`] instead.
323fn run_with(args: &[&str], out: &mut dyn Write, err: &mut dyn Write, pager: bool) -> Result<i32> {
324	let parsed = match COMMAND.parse_args(args, out, err)? {
325		Ok(parsed) => parsed,
326		Err(code) => return Ok(code),
327	};
328	let color = parsed.str("--color").unwrap_or("auto");
329	// LENIENT(L52): `argparse` checks the choices while parsing, so an invalid
330	// choice is reported before the errors found after it (such as missing
331	// files); here it is checked afterwards.
332	if !COLORS.contains(&color) {
333		let message = format!(
334			"argument --color: invalid choice: {} (choose from 'auto', 'never', 'always')",
335			fontoxide_misc::py::str_repr(color)
336		);
337		return Ok(COMMAND.error(err, &message)?);
338	}
339	let int = |key: &str, default: i128| -> i128 {
340		parsed
341			.str(key)
342			.and_then(fontoxide_misc::py::parse_int)
343			.unwrap_or(default)
344	};
345	let lines = int("--lines", 3);
346	let y1 = int("--y1", -1).clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
347	let y2 = int("--y2", -1).clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
348	let quiet = parsed.flag("--quiet");
349	let always = parsed.flag("--always");
350	let file1 = parsed.str("FILE1").unwrap_or_default();
351	let file2 = parsed.str("FILE2").unwrap_or_default();
352
353	// Incompatible argument validations.
354	if always && parsed.flag("--binary") {
355		if !quiet {
356			err.write_all(
357				b"[*] Error: --always and --binary are mutually exclusive options. \
358				  Please use ONLY one of these options in your command.\n",
359			)?;
360		}
361		return Ok(2);
362	}
363	let binary = !always;
364
365	// File path argument validations.
366	for file in [file1, file2] {
367		if !utils::file_exists(file) {
368			if !quiet {
369				writeln!(err, "[*] ERROR: The file path '{file}' can not be found.")?;
370			}
371			return Ok(2);
372		}
373	}
374
375	let tables = |key: &str| parsed.get(key).map(|s| s.values.clone());
376	let mut include_list = utils::get_tables_argument_list(tables("--include").as_deref());
377	let mut exclude_list = utils::get_tables_argument_list(tables("--exclude").as_deref());
378
379	if parsed.flag("--summary") {
380		return match summarize(
381			file1,
382			file2,
383			include_list.as_deref(),
384			exclude_list.as_deref(),
385			y1,
386			y2,
387		) {
388			Ok((identical, output)) => {
389				if !quiet {
390					out.write_all(output.as_bytes())?;
391				}
392				Ok(if identical { 0 } else { 1 })
393			}
394			Err(e) => {
395				if !quiet {
396					writeln!(err, "[*] ERROR: {e}")?;
397				}
398				Ok(2)
399			}
400		};
401	}
402
403	if binary {
404		// UPSTREAM-BUG(B74): not caught, unlike the same errors with `--summary`: they
405		// are a traceback (e.g. a collection without `--y1`), returned as errors.
406		let excluded_binary_tables = get_binary_exclude_tables(
407			file1,
408			file2,
409			include_list.as_deref(),
410			exclude_list.as_deref(),
411			y1,
412			y2,
413		)?;
414		// UPSTREAM-BUG(B73): if all the included tables are binary identical, the
415		// list becomes empty, and an empty list of tables dumps all of them.
416		match &mut include_list {
417			Some(include) => include.retain(|t| !excluded_binary_tables.contains(t)),
418			None => exclude_list
419				.get_or_insert_with(Vec::new)
420				.extend(excluded_binary_tables),
421		}
422	}
423
424	// UPSTREAM-BUG(B72): `sys.stdout.isatty` is not called, so `auto` always
425	// colors the output, even when it is not a terminal.
426	let color_output = color == "always" || color == "auto";
427
428	let diff_option = parsed.str("--diff");
429	let diff_tool: Option<PathBuf> = match diff_option {
430		None => utils::which("diff"),
431		Some("") => None,
432		Some(tool) => match utils::which(tool) {
433			Some(path) => Some(path),
434			None => {
435				if !quiet {
436					writeln!(
437						err,
438						"[*] ERROR: The external diff tool executable '{tool}' was not found."
439					)?;
440				}
441				return Ok(2);
442			}
443		},
444	};
445
446	let options = DiffOptions {
447		include_tables: include_list,
448		exclude_tables: exclude_list,
449		font_number_a: y1,
450		font_number_b: y2,
451		use_multiprocess: true,
452	};
453	let result = match &diff_tool {
454		Some(tool) => {
455			let diff_args: Vec<String> = match parsed.str("--diff-arg") {
456				Some(args) => args.split_whitespace().map(str::to_owned).collect(),
457				None => {
458					let mut args = vec![if lines == 3 {
459						"-u".to_owned()
460					} else {
461						format!("-u{lines}")
462					}];
463					if is_gnu_diff(tool) {
464						args.push(r"-F^\s\s<".to_owned());
465					}
466					args
467				}
468			};
469			run_external_diff(tool, &diff_args, file1, file2, &options)
470		}
471		None => u_diff(file1, file2, lines, &options),
472	};
473	match result {
474		Ok(lines) => {
475			let output: String = if color_output {
476				lines
477					.iter()
478					.map(|l| color::color_unified_diff_line(l))
479					.collect()
480			} else {
481				lines.concat()
482			};
483			if !quiet {
484				if pager {
485					out.flush()?;
486					pipe_output(&output)?;
487				} else {
488					out.write_all(output.as_bytes())?;
489				}
490			}
491			Ok(if output.is_empty() { 0 } else { 1 })
492		}
493		Err(e) => {
494			if !quiet {
495				writeln!(err, "[*] ERROR: {e}")?;
496			}
497			Ok(2)
498		}
499	}
500}
501
502/// `_is_gnu_diff`: whether the diff tool is GNU diff (says so in the output
503/// of `--version`).
504fn is_gnu_diff(diff_tool: &std::path::Path) -> bool {
505	match std::process::Command::new(diff_tool)
506		.arg("--version")
507		.stdin(std::process::Stdio::null())
508		.output()
509	{
510		Ok(output) => {
511			String::from_utf8_lossy(&output.stdout).contains("GNU diffutils")
512				|| String::from_utf8_lossy(&output.stderr).contains("GNU diffutils")
513		}
514		Err(_) => false,
515	}
516}