1use std::path::{Path, PathBuf};
5
6pub fn file_exists(path: impl AsRef<Path>) -> bool {
8 path.as_ref().is_file()
9}
10
11pub 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
34pub fn iso_local_time(timestamp: f64) -> String {
36 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 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
76pub 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
93pub 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 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
158fn 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 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}