fontoxide_misc/
cli_tools.rs1use std::borrow::Cow;
8use std::cell::Cell;
9
10const SEPARATORS: &[char] = if cfg!(windows) { &['/', '\\'] } else { &['/'] };
11
12fn split(path: &str) -> (&str, &str) {
14 let Some(at) = path.rfind(SEPARATORS) else {
15 return ("", path);
16 };
17 let (head, tail) = path.split_at(at + 1);
18 let stripped = head.trim_end_matches(SEPARATORS);
19 (if stripped.is_empty() { head } else { stripped }, tail)
20}
21
22fn splitext(name: &str) -> (&str, &str) {
24 let leading = name.len() - name.trim_start_matches('.').len();
25 match name[leading..].rfind('.') {
26 Some(at) => name.split_at(leading + at),
27 None => (name, ""),
28 }
29}
30
31fn join(dir: &str, name: &str) -> String {
33 if dir.is_empty() || dir.ends_with(SEPARATORS) {
34 format!("{dir}{name}")
35 } else {
36 format!("{dir}{}{name}", SEPARATORS[SEPARATORS.len() - 1])
37 }
38}
39
40fn strip_number(name: &str) -> &str {
42 if let Some(at) = name.rfind('#') {
43 let digits = &name[at + 1..];
44 if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) {
45 return &name[..at];
46 }
47 }
48 name
49}
50
51pub fn make_output_file_name(
56 input: &str,
57 output_dir: Option<&str>,
58 extension: Option<&str>,
59 over_write: bool,
60 suffix: &str,
61) -> String {
62 let (dir, file) = split(input);
63 let (name, input_extension) = splitext(file);
64 let dir = output_dir.filter(|d| !d.is_empty()).unwrap_or(dir);
65 let name = strip_number(name);
66 let extension = extension.unwrap_or(input_extension);
67 let mut output = join(dir, &format!("{name}{suffix}{extension}"));
68 if !over_write {
69 let mut n = 1;
70 while std::path::Path::new(&output).exists() {
71 output = join(dir, &format!("{name}{suffix}#{n}{extension}"));
72 n += 1;
73 }
74 }
75 output
76}
77
78thread_local! {
79 static PROGRAM_NAME: Cell<Option<&'static str>> = const { Cell::new(None) };
80}
81
82pub fn program_name() -> Option<&'static str> {
85 PROGRAM_NAME.with(Cell::get)
86}
87
88pub fn with_program_name<R>(name: &'static str, f: impl FnOnce() -> R) -> R {
92 struct Restore(Option<&'static str>);
93 impl Drop for Restore {
94 fn drop(&mut self) {
95 PROGRAM_NAME.with(|p| p.set(self.0));
96 }
97 }
98 let _restore = Restore(PROGRAM_NAME.with(|p| p.replace(Some(name))));
99 f()
100}
101
102pub fn program_text<'a>(text: &'a str, prog: &str, module: &str) -> Cow<'a, str> {
114 let Some(name) = program_name() else {
115 return Cow::Borrowed(text);
116 };
117 let new = format!("{name} {module}");
118 if new == prog {
119 return Cow::Borrowed(text);
120 }
121 let everywhere = prog.starts_with("fonttools ");
122 let delta = new.chars().count() as isize - prog.chars().count() as isize;
123 let usage_prefix = format!("usage: {prog}");
124 let mut out = String::with_capacity(text.len() + 64);
125 let mut in_usage = false;
126 for line in text.split_inclusive('\n') {
127 if in_usage && line.starts_with(' ') && !line.trim().is_empty() {
128 out.push_str(&reindent(line, delta));
129 continue;
130 }
131 in_usage = false;
132 if everywhere {
133 if line.starts_with(&usage_prefix) && is_word_end(&line[usage_prefix.len()..]) {
134 in_usage = true;
135 }
136 out.push_str(&replace_words(line, prog, &new));
137 } else if let Some(rest) = line.strip_prefix(&usage_prefix)
138 && is_word_end(rest)
139 {
140 in_usage = true;
141 out.push_str("usage: ");
142 out.push_str(&new);
143 out.push_str(rest);
144 } else if let Some(rest) = line.strip_prefix(prog)
145 && rest.starts_with(": error:")
146 {
147 out.push_str(&new);
148 out.push_str(rest);
149 } else {
150 out.push_str(line);
151 }
152 }
153 Cow::Owned(out)
154}
155
156fn is_word_end(rest: &str) -> bool {
158 !rest
159 .chars()
160 .next()
161 .is_some_and(|c| c.is_alphanumeric() || matches!(c, '.' | '_' | '-'))
162}
163
164fn replace_words(line: &str, old: &str, new: &str) -> String {
166 let mut out = String::with_capacity(line.len());
167 let mut rest = line;
168 while let Some(at) = rest.find(old) {
169 let before = rest[..at].chars().next_back();
170 let starts_word =
171 !before.is_some_and(|c| c.is_alphanumeric() || matches!(c, '.' | '_' | '/'));
172 let after = &rest[at + old.len()..];
173 out.push_str(&rest[..at]);
174 out.push_str(if starts_word && is_word_end(after) {
175 new
176 } else {
177 old
178 });
179 rest = after;
180 }
181 out.push_str(rest);
182 out
183}
184
185fn reindent(line: &str, delta: isize) -> Cow<'_, str> {
188 if delta > 0 {
189 Cow::Owned(format!("{}{line}", " ".repeat(delta.unsigned_abs())))
190 } else {
191 let spaces = line.len() - line.trim_start_matches(' ').len();
192 let remove = delta.unsigned_abs().min(spaces.saturating_sub(1));
193 Cow::Borrowed(&line[remove..])
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn output_file_names() {
203 let name =
204 |input, extension, suffix| make_output_file_name(input, None, extension, true, suffix);
205 assert_eq!(name("font.ttf", None, ""), "font.ttf");
206 assert_eq!(
207 name("font.ttf", Some(".woff"), ".subset"),
208 "font.subset.woff"
209 );
210 assert_eq!(
211 name("a/font.otf", None, ".subset"),
212 join("a", "font.subset.otf")
213 );
214 assert_eq!(name("font#12.ttf", None, ""), "font.ttf");
215 assert_eq!(name("font#x.ttf", None, ""), "font#x.ttf");
216 assert_eq!(name(".hidden", None, "-s"), ".hidden-s");
217 assert_eq!(name("a.b.c", None, "-s"), "a.b-s.c");
218 assert_eq!(
219 make_output_file_name("a/font.ttf", Some("out"), None, true, ""),
220 join("out", "font.ttf")
221 );
222 }
223
224 #[test]
225 fn program_texts() {
226 let text = "usage: fonttools subset font [-h]\n\
227 Try fonttools subset --help; see github.com/fonttools/fonttools.\n\
228 $ fonttools subsetter fonttools subset\n";
229 assert!(matches!(
231 program_text(text, "fonttools subset", "subset"),
232 Cow::Borrowed(t) if t == text
233 ));
234 with_program_name("fontoxide", || {
235 assert_eq!(
236 program_text(text, "fonttools subset", "subset"),
237 "usage: fontoxide subset font [-h]\n\
238 Try fontoxide subset --help; see github.com/fonttools/fonttools.\n\
239 $ fonttools subsetter fontoxide subset\n"
240 );
241 let text = "usage: cu2qu [-h] [-i |\n -j [N]]\n\n INPUT cu2qu input\n\
243 cu2qu: error: oops";
244 assert_eq!(
245 program_text(text, "cu2qu", "cu2qu"),
246 "usage: fontoxide cu2qu [-h] [-i |\n -j [N]]\n\n INPUT cu2qu input\n\
247 fontoxide cu2qu: error: oops"
248 );
249 with_program_name("other", || assert_eq!(program_name(), Some("other")));
251 assert_eq!(program_name(), Some("fontoxide"));
252 });
253 assert_eq!(program_name(), None);
254 }
255}