Skip to main content

fontoxide_diff/
utils.rs

1//! Port of `fontTools.diff.utils`, and of the parts of Python's `shutil` that
2//! `fontTools.diff` uses.
3
4use std::path::{Path, PathBuf};
5
6/// `file_exists`: whether the path is an existing file (`os.path.isfile`).
7pub fn file_exists(path: impl AsRef<Path>) -> bool {
8	path.as_ref().is_file()
9}
10
11/// `get_file_modtime`: the modification time of the file in ISO format, in the
12/// local time zone, e.g. `2024-01-31T12:34:56.789012+08:00`.
13///
14/// As Python does, the time is the float `st_mtime` rounded to microseconds
15/// (half to even), and the offset of the local time zone is that of the system
16/// (or of the `TZ` environment variable).
17pub fn get_file_modtime(path: impl AsRef<Path>) -> std::io::Result<String> {
18	let modified = std::fs::metadata(path)?.modified()?;
19	let (sec, nsec) = match modified.duration_since(std::time::UNIX_EPOCH) {
20		Ok(d) => (d.as_secs() as i64, i64::from(d.subsec_nanos())),
21		Err(e) => {
22			let d = e.duration();
23			let (s, n) = (d.as_secs() as i64, i64::from(d.subsec_nanos()));
24			if n == 0 {
25				(-s, 0)
26			} else {
27				(-s - 1, 1_000_000_000 - n)
28			}
29		}
30	};
31	Ok(iso_local_time(sec as f64 + nsec as f64 * 1e-9))
32}
33
34/// `datetime.fromtimestamp(timestamp, timezone.utc).astimezone().isoformat()`.
35pub fn iso_local_time(timestamp: f64) -> String {
36	// `_PyTime_ObjectToTimeval(..., _PyTime_ROUND_HALF_EVEN)`.
37	let mut seconds = timestamp.trunc();
38	let mut micros = ((timestamp - seconds) * 1e6).round_ties_even();
39	if micros >= 1e6 {
40		micros -= 1e6;
41		seconds += 1.0;
42	} else if micros < 0.0 {
43		micros += 1e6;
44		seconds -= 1.0;
45	}
46	let Ok(ts) = jiff::Timestamp::new(seconds as i64, micros as i32 * 1000) else {
47		return String::new();
48	};
49	// LENIENT(L53): the offset comes from the time zone database (jiff), with the
50	// historical rules; Python on Windows asks the C runtime, which applies
51	// the current daylight saving rules to all dates.
52	let offset = jiff::tz::TimeZone::system().to_offset(ts);
53	let dt = offset.to_datetime(ts);
54	let mut text = format!(
55		"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
56		dt.year(),
57		dt.month(),
58		dt.day(),
59		dt.hour(),
60		dt.minute(),
61		dt.second()
62	);
63	if micros != 0.0 {
64		text.push_str(&format!(".{:06}", micros as i64));
65	}
66	let total = offset.seconds();
67	let sign = if total < 0 { '-' } else { '+' };
68	let total = total.unsigned_abs();
69	text.push_str(&format!("{sign}{:02}:{:02}", total / 3600, total / 60 % 60));
70	if !total.is_multiple_of(60) {
71		text.push_str(&format!(":{:02}", total % 60));
72	}
73	text
74}
75
76/// `get_tables_argument_list`: the table tags given on the command line,
77/// padded with spaces to four characters, or `None` if none were given.
78pub fn get_tables_argument_list(table_list: Option<&[String]>) -> Option<Vec<String>> {
79	table_list.map(|tables| {
80		tables
81			.iter()
82			.map(|t| {
83				let mut t = t.clone();
84				for _ in t.chars().count()..4 {
85					t.push(' ');
86				}
87				t
88			})
89			.collect()
90	})
91}
92
93/// `shutil.which(cmd)`: the path of an executable, looked up in `PATH` if
94/// `cmd` has no directory; on Windows, with the extensions of `PATHEXT`, and
95/// in the current directory first.
96pub fn which(cmd: &str) -> Option<PathBuf> {
97	let windows = cfg!(windows);
98	let separators: &[char] = if windows { &['/', '\\'] } else { &['/'] };
99	let (dirname, cmd) = match cmd.rfind(separators) {
100		Some(at) => (Some(&cmd[..=at]), &cmd[at + 1..]),
101		None => (None, cmd),
102	};
103	let dirs: Vec<PathBuf> = match dirname {
104		Some(dir) => vec![PathBuf::from(dir)],
105		None => {
106			let path = std::env::var_os("PATH")?;
107			if path.is_empty() {
108				return None;
109			}
110			let mut dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
111			// `_win_path_needs_curdir` (`NeedCurrentDirectoryForExePath`).
112			if windows && std::env::var_os("NoDefaultCurrentDirectoryInExePath").is_none() {
113				dirs.insert(0, PathBuf::from("."));
114			}
115			dirs
116		}
117	};
118	let files: Vec<String> = if windows {
119		let pathext = std::env::var("PATHEXT")
120			.ok()
121			.filter(|p| !p.is_empty())
122			.unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC".into());
123		let pathext: Vec<&str> = pathext
124			.split(';')
125			.filter(|e| !e.is_empty())
126			.map(|e| e.trim_end_matches('.'))
127			.collect();
128		let mut files: Vec<String> = pathext.iter().map(|e| format!("{cmd}{e}")).collect();
129		let upper = cmd.to_uppercase();
130		if pathext.iter().any(|e| upper.ends_with(&e.to_uppercase())) {
131			files.insert(0, cmd.to_owned());
132		}
133		files
134	} else {
135		vec![cmd.to_owned()]
136	};
137	let mut seen = Vec::new();
138	for dir in dirs {
139		let norm = if windows {
140			dir.to_string_lossy().to_lowercase().replace('/', "\\")
141		} else {
142			dir.to_string_lossy().into_owned()
143		};
144		if seen.contains(&norm) {
145			continue;
146		}
147		seen.push(norm);
148		for file in &files {
149			let name = dir.join(file);
150			if is_executable(&name) {
151				return Some(name);
152			}
153		}
154	}
155	None
156}
157
158/// `_access_check(fn, os.F_OK | os.X_OK)`.
159fn is_executable(path: &Path) -> bool {
160	let Ok(metadata) = std::fs::metadata(path) else {
161		return false;
162	};
163	if metadata.is_dir() {
164		return false;
165	}
166	#[cfg(unix)]
167	{
168		use std::os::unix::fs::PermissionsExt;
169		metadata.permissions().mode() & 0o111 != 0
170	}
171	#[cfg(not(unix))]
172	{
173		true
174	}
175}
176
177#[cfg(test)]
178mod tests {
179	use super::*;
180
181	#[test]
182	fn tables_argument_list() {
183		assert_eq!(get_tables_argument_list(None), None);
184		let tables = ["cvt".to_owned(), "head".to_owned(), "GlyphOrder".to_owned()];
185		assert_eq!(
186			get_tables_argument_list(Some(&tables)),
187			Some(vec![
188				"cvt ".to_owned(),
189				"head".to_owned(),
190				"GlyphOrder".to_owned()
191			])
192		);
193	}
194
195	#[test]
196	fn iso_times() {
197		// The offset depends on the time zone of the system: check the rest.
198		let text = iso_local_time(1_700_000_000.123_456_7);
199		assert!(text.contains(".123457"), "{text}");
200		let text = iso_local_time(1_700_000_000.0);
201		assert_eq!(text.len(), "2023-11-14T22:13:20+00:00".len(), "{text}");
202	}
203}