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	let tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
313	run_with(
314		args,
315		&mut std::io::stdout(),
316		&mut std::io::stderr(),
317		true,
318		tty,
319	)
320}
321
322/// `run(argv)`: compares two fonts, writing the diff (or the summary, or the
323/// help) to `out` and the errors to `err`. Returns the exit code: 0 if the
324/// fonts are the same, 1 if they differ, 2 on errors. `out` is not a terminal,
325/// so `--color auto` does not color the diff.
326pub fn run(args: &[&str], out: &mut dyn Write, err: &mut dyn Write) -> Result<i32> {
327	run_with(args, out, err, false, false)
328}
329
330/// [`run`]; with `pager`, the diff is written with [`pipe_output`] instead.
331/// `tty` is `sys.stdout.isatty()`, for `--color auto`.
332fn run_with(
333	args: &[&str],
334	out: &mut dyn Write,
335	err: &mut dyn Write,
336	pager: bool,
337	tty: bool,
338) -> Result<i32> {
339	let parsed = match COMMAND.parse_args(args, out, err)? {
340		Ok(parsed) => parsed,
341		Err(code) => return Ok(code),
342	};
343	let color = parsed.str("--color").unwrap_or("auto");
344	// LENIENT(L52): `argparse` checks the choices while parsing, so an invalid
345	// choice is reported before the errors found after it (such as missing
346	// files); here it is checked afterwards.
347	if !COLORS.contains(&color) {
348		let message = format!(
349			"argument --color: invalid choice: {} (choose from 'auto', 'never', 'always')",
350			fontoxide_misc::py::str_repr(color)
351		);
352		return Ok(COMMAND.error(err, &message)?);
353	}
354	let int = |key: &str, default: i128| -> i128 {
355		parsed
356			.str(key)
357			.and_then(fontoxide_misc::py::parse_int)
358			.unwrap_or(default)
359	};
360	let lines = int("--lines", 3);
361	let y1 = int("--y1", -1).clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
362	let y2 = int("--y2", -1).clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
363	let quiet = parsed.flag("--quiet");
364	let always = parsed.flag("--always");
365	let file1 = parsed.str("FILE1").unwrap_or_default();
366	let file2 = parsed.str("FILE2").unwrap_or_default();
367
368	// Incompatible argument validations.
369	if always && parsed.flag("--binary") {
370		if !quiet {
371			err.write_all(
372				b"[*] Error: --always and --binary are mutually exclusive options. \
373				  Please use ONLY one of these options in your command.\n",
374			)?;
375		}
376		return Ok(2);
377	}
378	let binary = !always;
379
380	// File path argument validations.
381	for file in [file1, file2] {
382		if !utils::file_exists(file) {
383			if !quiet {
384				writeln!(err, "[*] ERROR: The file path '{file}' can not be found.")?;
385			}
386			return Ok(2);
387		}
388	}
389
390	let tables = |key: &str| parsed.get(key).map(|s| s.values.clone());
391	let mut include_list = utils::get_tables_argument_list(tables("--include").as_deref());
392	let mut exclude_list = utils::get_tables_argument_list(tables("--exclude").as_deref());
393
394	if parsed.flag("--summary") {
395		return match summarize(
396			file1,
397			file2,
398			include_list.as_deref(),
399			exclude_list.as_deref(),
400			y1,
401			y2,
402		) {
403			Ok((identical, output)) => {
404				if !quiet {
405					out.write_all(output.as_bytes())?;
406				}
407				Ok(if identical { 0 } else { 1 })
408			}
409			Err(e) => {
410				if !quiet {
411					writeln!(err, "[*] ERROR: {e}")?;
412				}
413				Ok(2)
414			}
415		};
416	}
417
418	if binary {
419		let excluded_binary_tables = match get_binary_exclude_tables(
420			file1,
421			file2,
422			include_list.as_deref(),
423			exclude_list.as_deref(),
424			y1,
425			y2,
426		) {
427			Ok(tables) => tables,
428			Err(e) => {
429				if !quiet {
430					writeln!(err, "[*] ERROR: {e}")?;
431				}
432				return Ok(2);
433			}
434		};
435		match &mut include_list {
436			Some(include) => {
437				include.retain(|t| !excluded_binary_tables.contains(t));
438				if include.is_empty() {
439					// All the included tables are binary identical. Don't pass
440					// an empty list on, as that would mean all the tables.
441					return Ok(0);
442				}
443			}
444			None => exclude_list
445				.get_or_insert_with(Vec::new)
446				.extend(excluded_binary_tables),
447		}
448	}
449
450	let color_output = color == "always" || (color == "auto" && tty);
451
452	let diff_option = parsed.str("--diff");
453	let diff_tool: Option<PathBuf> = match diff_option {
454		None => utils::which("diff"),
455		Some("") => None,
456		Some(tool) => match utils::which(tool) {
457			Some(path) => Some(path),
458			None => {
459				if !quiet {
460					writeln!(
461						err,
462						"[*] ERROR: The external diff tool executable '{tool}' was not found."
463					)?;
464				}
465				return Ok(2);
466			}
467		},
468	};
469
470	let options = DiffOptions {
471		include_tables: include_list,
472		exclude_tables: exclude_list,
473		font_number_a: y1,
474		font_number_b: y2,
475		use_multiprocess: true,
476	};
477	let result = match &diff_tool {
478		Some(tool) => {
479			let diff_args: Vec<String> = match parsed.str("--diff-arg") {
480				Some(args) => args.split_whitespace().map(str::to_owned).collect(),
481				None => {
482					let mut args = vec![if lines == 3 {
483						"-u".to_owned()
484					} else {
485						format!("-u{lines}")
486					}];
487					if is_gnu_diff(tool) {
488						args.push(r"-F^\s\s<".to_owned());
489					}
490					args
491				}
492			};
493			run_external_diff(tool, &diff_args, file1, file2, &options)
494		}
495		None => u_diff(file1, file2, lines, &options),
496	};
497	match result {
498		Ok(lines) => {
499			let output: String = if color_output {
500				lines
501					.iter()
502					.map(|l| color::color_unified_diff_line(l))
503					.collect()
504			} else {
505				lines.concat()
506			};
507			if !quiet {
508				if pager {
509					out.flush()?;
510					pipe_output(&output)?;
511				} else {
512					out.write_all(output.as_bytes())?;
513				}
514			}
515			Ok(if output.is_empty() { 0 } else { 1 })
516		}
517		Err(e) => {
518			if !quiet {
519				writeln!(err, "[*] ERROR: {e}")?;
520			}
521			Ok(2)
522		}
523	}
524}
525
526/// `_is_gnu_diff`: whether the diff tool is GNU diff (says so in the output
527/// of `--version`).
528fn is_gnu_diff(diff_tool: &std::path::Path) -> bool {
529	match std::process::Command::new(diff_tool)
530		.arg("--version")
531		.stdin(std::process::Stdio::null())
532		.output()
533	{
534		Ok(output) => {
535			String::from_utf8_lossy(&output.stdout).contains("GNU diffutils")
536				|| String::from_utf8_lossy(&output.stderr).contains("GNU diffutils")
537		}
538		Err(_) => false,
539	}
540}