1use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicUsize, Ordering};
7
8use fontoxide_ttlib::{Font, ReadOptions, TableKey, Tag, TtxOptions};
9
10use crate::difflib::unified_diff;
11use crate::utils::get_file_modtime;
12use crate::{DiffError, Result};
13
14#[derive(Debug, Clone, Default)]
17pub struct DiffOptions {
18 pub include_tables: Option<Vec<String>>,
20 pub exclude_tables: Option<Vec<String>>,
22 pub font_number_a: i64,
25 pub font_number_b: i64,
28 pub use_multiprocess: bool,
30}
31
32impl DiffOptions {
33 pub fn new() -> Self {
35 DiffOptions {
36 font_number_a: -1,
37 font_number_b: -1,
38 use_multiprocess: true,
39 ..Default::default()
40 }
41 }
42}
43
44pub(crate) fn open_font(path: &str, font_number: i64) -> Result<Font> {
46 let options = ReadOptions {
47 font_number: usize::try_from(font_number).ok(),
48 ..Default::default()
49 };
50 Ok(Font::read(std::fs::read(path)?, options)?)
51}
52
53fn table_key(name: &str) -> Option<TableKey> {
56 if name == "GlyphOrder" {
57 return Some(TableKey::GlyphOrder);
58 }
59 let bytes = fontoxide_misc::py::latin1_encode(name)?;
60 let bytes: [u8; 4] = bytes.try_into().ok()?;
61 Some(TableKey::Table(Tag::new(&bytes)))
62}
63
64fn ttx_dump(font: &mut Font, options: &DiffOptions) -> Result<String> {
67 let keys = |names: &Option<Vec<String>>| -> Vec<TableKey> {
68 names
69 .iter()
70 .flatten()
71 .filter_map(|n| table_key(n))
72 .collect()
73 };
74 let mut tables = keys(&options.include_tables);
75 if tables.is_empty()
76 && options
77 .include_tables
78 .as_ref()
79 .is_some_and(|t| !t.is_empty())
80 {
81 let tags = font.tags();
84 let absent = (0..=u32::MAX)
85 .map(|n| Tag::new(&n.to_be_bytes()))
86 .find(|t| !tags.contains(t))
87 .ok_or_else(|| DiffError::Message("no absent tag".into()))?;
88 tables.push(TableKey::Table(absent));
89 }
90 Ok(font.to_ttx(&TtxOptions {
91 tables,
92 skip_tables: keys(&options.exclude_tables),
93 ..Default::default()
94 })?)
95}
96
97fn load_and_dump(path: &str, font_number: i64, options: &DiffOptions) -> Result<String> {
99 ttx_dump(&mut open_font(path, font_number)?, options)
100}
101
102fn dump_fonts(
105 filepath_a: &str,
106 filepath_b: &str,
107 options: &DiffOptions,
108) -> Result<(String, String)> {
109 drop(open_font(filepath_a, options.font_number_a)?);
112 drop(open_font(filepath_b, options.font_number_b)?);
113 let parallel =
114 options.use_multiprocess && std::thread::available_parallelism().is_ok_and(|n| n.get() > 1);
115 if parallel {
116 let (left, right) = std::thread::scope(|scope| {
117 let left = scope.spawn(|| load_and_dump(filepath_a, options.font_number_a, options));
118 let right = load_and_dump(filepath_b, options.font_number_b, options);
119 let left = left
120 .join()
121 .unwrap_or_else(|_| Err(DiffError::Message("the TTX dump panicked".into())));
122 (left, right)
123 });
124 Ok((left?, right?))
125 } else {
126 let left = load_and_dump(filepath_a, options.font_number_a, options)?;
127 let right = load_and_dump(filepath_b, options.font_number_b, options)?;
128 Ok((left, right))
129 }
130}
131
132fn readlines(text: &str) -> Vec<String> {
139 let mut lines = Vec::new();
140 let mut current = String::new();
141 let mut chars = text.chars().peekable();
142 while let Some(c) = chars.next() {
143 match c {
144 '\r' => {
145 if chars.peek() == Some(&'\n') {
146 chars.next();
147 }
148 current.push('\n');
149 lines.push(std::mem::take(&mut current));
150 }
151 '\n' => {
152 current.push('\n');
153 lines.push(std::mem::take(&mut current));
154 }
155 c => current.push(c),
156 }
157 }
158 if !current.is_empty() {
159 lines.push(current);
160 }
161 lines
162}
163
164pub fn u_diff(
169 filepath_a: &str,
170 filepath_b: &str,
171 context_lines: i128,
172 options: &DiffOptions,
173) -> Result<Vec<String>> {
174 let (left, right) = dump_fonts(filepath_a, filepath_b, options)?;
175 let fromlines = readlines(&left);
176 let tolines = readlines(&right);
177 let fromdate = get_file_modtime(filepath_a)?;
178 let todate = get_file_modtime(filepath_b)?;
179 let a: Vec<&str> = fromlines.iter().map(String::as_str).collect();
180 let b: Vec<&str> = tolines.iter().map(String::as_str).collect();
181 Ok(unified_diff(
182 &a,
183 &b,
184 filepath_a,
185 filepath_b,
186 &fromdate,
187 &todate,
188 context_lines,
189 "\n",
190 ))
191}
192
193struct TemporaryDirectory(PathBuf);
195
196impl TemporaryDirectory {
197 fn new() -> Result<Self> {
198 static COUNTER: AtomicUsize = AtomicUsize::new(0);
199 let nanos = std::time::SystemTime::now()
200 .duration_since(std::time::UNIX_EPOCH)
201 .map_or(0, |d| d.subsec_nanos());
202 for _ in 0..100 {
203 let name = format!(
204 "tmp{:x}{:x}{:x}",
205 std::process::id(),
206 nanos,
207 COUNTER.fetch_add(1, Ordering::Relaxed)
208 );
209 let dir = std::env::temp_dir().join(name);
210 match std::fs::create_dir(&dir) {
211 Ok(()) => return Ok(TemporaryDirectory(dir)),
212 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
213 Err(e) => return Err(e.into()),
214 }
215 }
216 Err(DiffError::Message(
217 "No usable temporary directory name found".into(),
218 ))
219 }
220
221 fn path(&self) -> &Path {
222 &self.0
223 }
224}
225
226impl Drop for TemporaryDirectory {
227 fn drop(&mut self) {
228 let _ = std::fs::remove_dir_all(&self.0);
229 }
230}
231
232pub fn run_external_diff(
237 diff_tool: &Path,
238 diff_args: &[String],
239 filepath_a: &str,
240 filepath_b: &str,
241 options: &DiffOptions,
242) -> Result<Vec<String>> {
243 let tmp = TemporaryDirectory::new()?;
244 let (left, right) = dump_fonts(filepath_a, filepath_b, options)?;
245 let left_ttxpath = tmp.path().join("left.ttx");
246 let right_ttxpath = tmp.path().join("right.ttx");
247 std::fs::write(&left_ttxpath, left)?;
248 std::fs::write(&right_ttxpath, right)?;
249 let output = std::process::Command::new(diff_tool)
250 .args(diff_args)
251 .arg(&left_ttxpath)
252 .arg(&right_ttxpath)
253 .stdin(std::process::Stdio::null())
254 .output()?;
255 let decode = |data: Vec<u8>| {
257 String::from_utf8(data).map_err(|e| {
258 DiffError::Message(format!(
259 "'utf-8' codec can't decode byte 0x{:02x} in position {}: invalid start byte",
260 e.as_bytes()[e.utf8_error().valid_up_to()],
261 e.utf8_error().valid_up_to()
262 ))
263 })
264 };
265 let lines = readlines(&decode(output.stdout)?);
266 let err = readlines(&decode(output.stderr)?).concat();
267 if !err.is_empty() {
268 return Err(DiffError::External(err));
269 }
270 Ok(lines)
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 #[test]
278 fn universal_newlines() {
279 assert_eq!(readlines("a\r\nb\rc\nd"), ["a\n", "b\n", "c\n", "d"]);
280 assert!(readlines("").is_empty());
281 }
282
283 #[test]
284 fn table_keys() {
285 assert_eq!(table_key("GlyphOrder"), Some(TableKey::GlyphOrder));
286 assert_eq!(table_key("cvt "), Some(TableKey::Table(Tag::new(b"cvt "))));
287 assert_eq!(table_key("toolong"), None);
288 assert_eq!(table_key("中文中文"), None);
289 }
290}