Skip to main content

fontoxide_misc/
argparse.rs

1//! The part of Python's `argparse` (CPython 3.13) that the fontTools command
2//! lines use: parsing the arguments as `ArgumentParser.parse_args` does, with
3//! its error messages.
4//!
5//! The arguments are declared as with `add_argument` ([`Argument`]): options
6//! with abbreviable long names and combinable short names, positional
7//! arguments with `nargs`, `type=float`/`type=int` values, mutually exclusive
8//! groups ([`Argument::group`]). [`parse`] follows `_parse_known_args`: the
9//! positional arguments are matched against the pattern of the arguments
10//! between the options, as `argparse` does with regular expressions.
11//!
12//! The help and usage texts are not generated: [`Command`] holds them as
13//! fontTools prints them, and prints them as `argparse` does
14//! (`print_help`, `error`), through [`program_text`].
15
16use std::collections::{BTreeMap, BTreeSet};
17use std::io::Write;
18
19use crate::cli_tools::program_text;
20use crate::py;
21
22/// What an argument does when it is given (`action=`).
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Action {
25	/// `store`: keeps the value.
26	Store,
27	/// `append`: collects the values.
28	Append,
29	/// `store_true` (or `store_false`, `store_const`): no value.
30	StoreTrue,
31	/// `count`.
32	Count,
33	/// `help`: prints the help and exits.
34	Help,
35	/// `version`: prints the version and exits.
36	Version,
37}
38
39/// How many values an argument takes (`nargs=`).
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum Nargs {
42	/// No value (the flags).
43	Zero,
44	/// The default: one value.
45	One,
46	/// `"?"`.
47	Optional,
48	/// `"*"`.
49	ZeroOrMore,
50	/// `"+"`.
51	OneOrMore,
52}
53
54/// The `type` of an argument's values, checked when they are taken.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Ty {
57	/// A string.
58	Str,
59	/// `type=float`.
60	Float,
61	/// `type=int`.
62	Int,
63}
64
65/// An argument (`add_argument`).
66#[derive(Debug, Clone, Copy)]
67pub struct Argument {
68	/// The option strings, in the order they are declared; empty for a
69	/// positional argument.
70	pub strings: &'static [&'static str],
71	/// The name of a positional argument in the messages (its `metavar`, or
72	/// `dest`).
73	pub name: &'static str,
74	/// What it does.
75	pub action: Action,
76	/// How many values it takes.
77	pub nargs: Nargs,
78	/// The type of its values.
79	pub ty: Ty,
80	/// Its mutually exclusive group, if any.
81	pub group: Option<usize>,
82	/// Whether it is required.
83	pub required: bool,
84}
85
86impl Argument {
87	const fn new(strings: &'static [&'static str], action: Action, nargs: Nargs) -> Self {
88		Argument {
89			strings,
90			name: "",
91			action,
92			nargs,
93			ty: Ty::Str,
94			group: None,
95			required: false,
96		}
97	}
98
99	/// `-h/--help`.
100	pub const fn help() -> Self {
101		Self::new(&["-h", "--help"], Action::Help, Nargs::Zero)
102	}
103
104	/// `action="version"`.
105	pub const fn version(strings: &'static [&'static str]) -> Self {
106		Self::new(strings, Action::Version, Nargs::Zero)
107	}
108
109	/// `action="store_true"` (or `store_false`).
110	pub const fn flag(strings: &'static [&'static str]) -> Self {
111		Self::new(strings, Action::StoreTrue, Nargs::Zero)
112	}
113
114	/// `action="count"`.
115	pub const fn count(strings: &'static [&'static str]) -> Self {
116		Self::new(strings, Action::Count, Nargs::Zero)
117	}
118
119	/// An option with one value.
120	pub const fn option(strings: &'static [&'static str]) -> Self {
121		Self::new(strings, Action::Store, Nargs::One)
122	}
123
124	/// `action="append"`: an option with one value, which may be given more
125	/// than once.
126	pub const fn append(strings: &'static [&'static str]) -> Self {
127		Self::new(strings, Action::Append, Nargs::One)
128	}
129
130	/// A positional argument with one value, named `name` in the messages.
131	pub const fn positional(name: &'static str) -> Self {
132		let mut argument = Self::new(&[], Action::Store, Nargs::One);
133		argument.name = name;
134		argument.required = true;
135		argument
136	}
137
138	/// `nargs=`; a positional argument is required unless it takes `"?"` or
139	/// `"*"`.
140	pub const fn nargs(mut self, nargs: Nargs) -> Self {
141		self.nargs = nargs;
142		if self.strings.is_empty() {
143			self.required = !matches!(nargs, Nargs::Optional | Nargs::ZeroOrMore | Nargs::Zero);
144		}
145		self
146	}
147
148	/// `type=`.
149	pub const fn ty(mut self, ty: Ty) -> Self {
150		self.ty = ty;
151		self
152	}
153
154	/// The mutually exclusive group `group`.
155	pub const fn group(mut self, group: usize) -> Self {
156		self.group = Some(group);
157		self
158	}
159
160	/// `required=True`.
161	pub const fn required(mut self) -> Self {
162		self.required = true;
163		self
164	}
165
166	/// The key of the argument in [`Parsed`]: its first long option string,
167	/// or its first option string, or the name of a positional argument.
168	pub fn key(&self) -> &'static str {
169		self.strings
170			.iter()
171			.find(|s| s.starts_with("--"))
172			.or(self.strings.first())
173			.copied()
174			.unwrap_or(self.name)
175	}
176
177	/// `_get_action_name`: the option strings joined with `/`, or the name of
178	/// a positional argument.
179	pub fn display(&self) -> String {
180		if self.strings.is_empty() {
181			self.name.to_owned()
182		} else {
183			self.strings.join("/")
184		}
185	}
186}
187
188/// The values of an argument given on the command line.
189#[derive(Debug, Clone, Default)]
190pub struct Seen {
191	/// How often it was given.
192	pub count: usize,
193	/// The last value of an argument taking one value (`None` for an omitted
194	/// `nargs="?"` value).
195	pub value: Option<String>,
196	/// The last values of an argument taking `nargs="*"` or `"+"`, or all the
197	/// values of an `append` argument.
198	pub values: Vec<String>,
199}
200
201/// The parsed command line, by [`Argument::key`].
202#[derive(Debug, Clone, Default)]
203pub struct Parsed {
204	/// The arguments given.
205	pub seen: BTreeMap<&'static str, Seen>,
206}
207
208impl Parsed {
209	/// Whether the argument was given.
210	pub fn flag(&self, key: &str) -> bool {
211		self.seen.contains_key(key)
212	}
213
214	/// How often the argument was given.
215	pub fn count(&self, key: &str) -> usize {
216		self.seen.get(key).map_or(0, |s| s.count)
217	}
218
219	/// The values of the argument, if it was given.
220	pub fn get(&self, key: &str) -> Option<&Seen> {
221		self.seen.get(key)
222	}
223
224	/// The value of an argument taking one value, if it was given.
225	pub fn str(&self, key: &str) -> Option<&str> {
226		self.seen.get(key).and_then(|s| s.value.as_deref())
227	}
228
229	/// The values of an argument taking `nargs="*"` or `"+"` (empty if it was
230	/// not given).
231	pub fn list(&self, key: &str) -> &[String] {
232		self.seen.get(key).map_or(&[], |s| s.values.as_slice())
233	}
234}
235
236/// `type=float`: the value, or the message of the error for the argument
237/// `display` (see [`Argument::display`]).
238pub fn parse_float(display: &str, value: &str) -> Result<f64, String> {
239	py::parse_float(value).ok_or_else(|| {
240		format!(
241			"argument {display}: invalid float value: {}",
242			py::str_repr(value)
243		)
244	})
245}
246
247/// `type=int`: the value, or the message of the error for the argument
248/// `display` (see [`Argument::display`]).
249pub fn parse_int(display: &str, value: &str) -> Result<i128, String> {
250	py::parse_int(value).ok_or_else(|| {
251		format!(
252			"argument {display}: invalid int value: {}",
253			py::str_repr(value)
254		)
255	})
256}
257
258/// `argparse`'s `_negative_number_matcher`: `^-\d+$|^-\d*\.\d+$`.
259fn is_negative_number(arg: &str) -> bool {
260	let Some(s) = arg.strip_prefix('-') else {
261		return false;
262	};
263	let digits = |s: &str| s.chars().all(|c| c.is_ascii_digit());
264	match s.split_once('.') {
265		None => !s.is_empty() && digits(s),
266		Some((a, b)) => digits(a) && !b.is_empty() && digits(b),
267	}
268}
269
270/// A possible interpretation of an option string (`option_tuple`): the
271/// argument (`None` for an unknown option), the option string, whether it was
272/// separated from an explicit value by `=`, and the explicit value.
273#[derive(Debug, Clone)]
274struct OptionTuple {
275	action: Option<usize>,
276	option_string: String,
277	sep: bool,
278	explicit: Option<String>,
279}
280
281/// The characters of a pattern of argument strings: `A` for an argument, `O`
282/// for an option, `-` for `--`.
283const A: u8 = 1;
284const O: u8 = 2;
285const DASH: u8 = 4;
286
287/// A quantified character class of a `nargs` pattern.
288#[derive(Debug, Clone, Copy)]
289struct Atom {
290	set: u8,
291	min: usize,
292	max: usize,
293}
294
295const fn atom(set: u8, min: usize, max: usize) -> Atom {
296	Atom { set, min, max }
297}
298
299/// `_get_nargs_pattern`, as the atoms of the regular expression.
300fn nargs_pattern(argument: &Argument) -> Vec<Atom> {
301	let dashes = atom(DASH, 0, usize::MAX);
302	if argument.strings.is_empty() {
303		match argument.nargs {
304			Nargs::Zero => vec![dashes],
305			Nargs::One => vec![dashes, atom(A, 1, 1), dashes],
306			Nargs::Optional => vec![dashes, atom(A, 0, 1), dashes],
307			Nargs::ZeroOrMore => vec![dashes, atom(A | DASH, 0, usize::MAX)],
308			Nargs::OneOrMore => vec![dashes, atom(A, 1, 1), atom(A | DASH, 0, usize::MAX)],
309		}
310	} else {
311		match argument.nargs {
312			Nargs::Zero => vec![],
313			Nargs::One => vec![atom(A, 1, 1)],
314			Nargs::Optional => vec![atom(A, 0, 1)],
315			Nargs::ZeroOrMore => vec![atom(A, 0, usize::MAX)],
316			Nargs::OneOrMore => vec![atom(A, 1, usize::MAX)],
317		}
318	}
319}
320
321/// Matches the groups of atoms at the start of `pattern` as Python's `re.match`
322/// does (greedy, backtracking); returns the length of each group.
323fn match_groups(groups: &[Vec<Atom>], pattern: &[u8]) -> Option<Vec<usize>> {
324	let atoms: Vec<(usize, Atom)> = groups
325		.iter()
326		.enumerate()
327		.flat_map(|(g, atoms)| atoms.iter().map(move |a| (g, *a)))
328		.collect();
329	let mut lengths = vec![0; atoms.len()];
330	if !match_atoms(&atoms, 0, pattern, 0, &mut lengths) {
331		return None;
332	}
333	let mut result = vec![0; groups.len()];
334	for ((g, _), len) in atoms.iter().zip(&lengths) {
335		result[*g] += len;
336	}
337	Some(result)
338}
339
340fn match_atoms(
341	atoms: &[(usize, Atom)],
342	index: usize,
343	pattern: &[u8],
344	pos: usize,
345	lengths: &mut [usize],
346) -> bool {
347	let Some((_, atom)) = atoms.get(index) else {
348		return true;
349	};
350	let available = pattern[pos..]
351		.iter()
352		.take_while(|&&c| c & atom.set != 0)
353		.count()
354		.min(atom.max);
355	if available < atom.min {
356		return false;
357	}
358	for len in (atom.min..=available).rev() {
359		lengths[index] = len;
360		if match_atoms(atoms, index + 1, pattern, pos + len, lengths) {
361			return true;
362		}
363	}
364	false
365}
366
367/// The parser state of [`parse`].
368struct State<'a> {
369	arguments: &'a [Argument],
370	parsed: Parsed,
371	seen_actions: BTreeSet<usize>,
372	seen_non_default: BTreeSet<usize>,
373}
374
375/// What [`State::take_action`] asks the parser to do next.
376enum Next {
377	Continue,
378	/// `-h` or `--version` was given: stop parsing.
379	Exit,
380}
381
382impl State<'_> {
383	/// `_get_values`, then the conflict check and the action of `take_action`.
384	fn take_action(&mut self, index: usize, strings: &[String]) -> Result<Next, String> {
385		let argument = &self.arguments[index];
386		self.seen_actions.insert(index);
387		// `_get_values`: the type conversions.
388		let single = strings.len() == 1 && matches!(argument.nargs, Nargs::One | Nargs::Optional);
389		if argument.nargs != Nargs::Zero {
390			for s in strings {
391				match argument.ty {
392					Ty::Str => {}
393					Ty::Float => {
394						parse_float(&argument.display(), s)?;
395					}
396					Ty::Int => {
397						parse_int(&argument.display(), s)?;
398					}
399				}
400			}
401		}
402		if !argument.strings.is_empty() || !strings.is_empty() {
403			self.seen_non_default.insert(index);
404			if let Some(group) = argument.group
405				&& let Some(conflict) = self
406					.arguments
407					.iter()
408					.enumerate()
409					.find(|(i, a)| {
410						*i != index && a.group == Some(group) && self.seen_non_default.contains(i)
411					})
412					.map(|(_, a)| a)
413			{
414				return Err(format!(
415					"argument {}: not allowed with argument {}",
416					argument.display(),
417					conflict.display()
418				));
419			}
420		}
421		let seen = self.parsed.seen.entry(argument.key()).or_default();
422		seen.count += 1;
423		match argument.action {
424			Action::Help | Action::Version => return Ok(Next::Exit),
425			Action::StoreTrue | Action::Count => {}
426			Action::Append => seen.values.extend(strings.iter().cloned()),
427			Action::Store => {
428				if single {
429					seen.value = strings.first().cloned();
430				} else if matches!(argument.nargs, Nargs::One | Nargs::Optional) {
431					seen.value = None;
432				} else {
433					seen.values = strings.to_vec();
434				}
435			}
436		}
437		Ok(Next::Continue)
438	}
439}
440
441/// Parses `args` as `ArgumentParser.parse_args` does, for the declared
442/// `arguments`; `required_groups` are the mutually exclusive groups with
443/// `required=True`. `Err` holds the message of `parser.error`.
444///
445/// Parsing stops at `-h` or a `version` action: the result then has the
446/// argument (see [`Parsed::flag`]), as `argparse` prints and exits there.
447pub fn parse(
448	args: &[&str],
449	arguments: &[Argument],
450	required_groups: &[usize],
451) -> Result<Parsed, String> {
452	// `_option_string_actions`, in the order of the declarations.
453	let table: Vec<(&str, usize)> = arguments
454		.iter()
455		.enumerate()
456		.flat_map(|(i, a)| a.strings.iter().map(move |s| (*s, i)))
457		.collect();
458	let lookup = |s: &str| table.iter().find(|(o, _)| *o == s).map(|(_, i)| *i);
459	let has_negative_number_optionals = table.iter().any(|(o, _)| is_negative_number(o));
460
461	// `_get_option_tuples`.
462	let option_tuples = |arg: &str| -> Vec<OptionTuple> {
463		let mut result = Vec::new();
464		let second = arg.chars().nth(1);
465		if second == Some('-') {
466			let (prefix, sep, explicit) = match arg.split_once('=') {
467				Some((p, e)) => (p, true, Some(e.to_owned())),
468				None => (arg, false, None),
469			};
470			for (o, i) in &table {
471				if o.starts_with(prefix) {
472					result.push(OptionTuple {
473						action: Some(*i),
474						option_string: (*o).to_owned(),
475						sep,
476						explicit: explicit.clone(),
477					});
478				}
479			}
480		} else {
481			let (prefix, sep, explicit) = match arg.split_once('=') {
482				Some((p, e)) => (p, true, Some(e.to_owned())),
483				None => (arg, false, None),
484			};
485			let cut = arg.char_indices().nth(2).map_or(arg.len(), |(i, _)| i);
486			let (short_prefix, short_explicit) = arg.split_at(cut);
487			for (o, i) in &table {
488				if *o == short_prefix {
489					result.push(OptionTuple {
490						action: Some(*i),
491						option_string: (*o).to_owned(),
492						sep: false,
493						explicit: Some(short_explicit.to_owned()),
494					});
495				} else if o.starts_with(prefix) {
496					result.push(OptionTuple {
497						action: Some(*i),
498						option_string: (*o).to_owned(),
499						sep,
500						explicit: explicit.clone(),
501					});
502				}
503			}
504		}
505		result
506	};
507
508	// `_parse_optional`.
509	let parse_optional = |arg: &str| -> Option<Vec<OptionTuple>> {
510		if !arg.starts_with('-') {
511			return None;
512		}
513		if let Some(i) = lookup(arg) {
514			return Some(vec![OptionTuple {
515				action: Some(i),
516				option_string: arg.to_owned(),
517				sep: false,
518				explicit: None,
519			}]);
520		}
521		if arg.chars().count() == 1 {
522			return None;
523		}
524		if let Some((option, explicit)) = arg.split_once('=')
525			&& let Some(i) = lookup(option)
526		{
527			return Some(vec![OptionTuple {
528				action: Some(i),
529				option_string: option.to_owned(),
530				sep: true,
531				explicit: Some(explicit.to_owned()),
532			}]);
533		}
534		let tuples = option_tuples(arg);
535		if !tuples.is_empty() {
536			return Some(tuples);
537		}
538		if is_negative_number(arg) && !has_negative_number_optionals {
539			return None;
540		}
541		if arg.contains(' ') {
542			return None;
543		}
544		Some(vec![OptionTuple {
545			action: None,
546			option_string: arg.to_owned(),
547			sep: false,
548			explicit: None,
549		}])
550	};
551
552	// The pattern of the argument strings, and the options at their indices.
553	let mut pattern: Vec<u8> = Vec::with_capacity(args.len());
554	let mut options: BTreeMap<usize, Vec<OptionTuple>> = BTreeMap::new();
555	let mut iter = args.iter().enumerate();
556	while let Some((i, arg)) = iter.next() {
557		if *arg == "--" {
558			pattern.push(DASH);
559			pattern.extend(iter.by_ref().map(|_| A));
560		} else if let Some(tuples) = parse_optional(arg) {
561			options.insert(i, tuples);
562			pattern.push(O);
563		} else {
564			pattern.push(A);
565		}
566	}
567
568	let mut state = State {
569		arguments,
570		parsed: Parsed::default(),
571		seen_actions: BTreeSet::new(),
572		seen_non_default: BTreeSet::new(),
573	};
574	let mut extras: Vec<String> = Vec::new();
575	let mut positionals: Vec<usize> = arguments
576		.iter()
577		.enumerate()
578		.filter(|(_, a)| a.strings.is_empty())
579		.map(|(i, _)| i)
580		.collect();
581
582	// `_match_argument`.
583	let match_argument = |index: usize, pattern: &[u8]| -> Result<usize, String> {
584		let argument = &arguments[index];
585		match match_groups(&[nargs_pattern(argument)], pattern) {
586			Some(lengths) => Ok(lengths[0]),
587			None => {
588				let message = match argument.nargs {
589					Nargs::Optional => "expected at most one argument",
590					Nargs::OneOrMore => "expected at least one argument",
591					_ => "expected one argument",
592				};
593				Err(format!("argument {}: {message}", argument.display()))
594			}
595		}
596	};
597
598	// `consume_positionals`; `None` when parsing stops.
599	let consume_positionals = |state: &mut State<'_>,
600	                           positionals: &mut Vec<usize>,
601	                           start: usize|
602	 -> Result<Option<usize>, String> {
603		let selected = &pattern[start..];
604		// `_match_arguments_partial`.
605		let mut counts: Vec<usize> = Vec::new();
606		for n in (1..=positionals.len()).rev() {
607			let groups: Vec<Vec<Atom>> = positionals[..n]
608				.iter()
609				.map(|&i| nargs_pattern(&arguments[i]))
610				.collect();
611			if let Some(mut result) = match_groups(&groups, selected) {
612				let end: usize = result.iter().sum();
613				if end < selected.len() && selected[end] == O {
614					while result.last() == Some(&0) {
615						result.pop();
616					}
617				}
618				counts = result;
619				break;
620			}
621		}
622		let mut start = start;
623		for (&index, &count) in positionals.iter().zip(&counts) {
624			let mut strings: Vec<String> = args[start..start + count]
625				.iter()
626				.map(|s| (*s).to_owned())
627				.collect();
628			if pattern[start..start + count].contains(&DASH)
629				&& let Some(at) = strings.iter().position(|s| s == "--")
630			{
631				strings.remove(at);
632			}
633			start += count;
634			if let Next::Exit = state.take_action(index, &strings)? {
635				return Ok(None);
636			}
637		}
638		positionals.drain(..counts.len());
639		Ok(Some(start))
640	};
641
642	let max_option_index = options.keys().next_back().copied();
643	let mut start = 0;
644	while let Some(max) = max_option_index
645		&& start <= max
646	{
647		// Consume any positionals preceding the next option.
648		let next_option = options.range(start..).next().map_or(max + 1, |(i, _)| *i);
649		if start != next_option {
650			let Some(end) = consume_positionals(&mut state, &mut positionals, start)? else {
651				return Ok(state.parsed);
652			};
653			if end > start {
654				start = end;
655				continue;
656			}
657			start = end;
658		}
659		if !options.contains_key(&start) {
660			extras.extend(args[start..next_option].iter().map(|s| (*s).to_owned()));
661			start = next_option;
662		}
663
664		// `consume_optional`.
665		let tuples = &options[&start];
666		if tuples.len() > 1 {
667			let matches: Vec<&str> = tuples.iter().map(|t| t.option_string.as_str()).collect();
668			return Err(format!(
669				"ambiguous option: {} could match {}",
670				args[start],
671				matches.join(", ")
672			));
673		}
674		let OptionTuple {
675			mut action,
676			mut option_string,
677			mut sep,
678			mut explicit,
679		} = tuples[0].clone();
680		let mut action_tuples: Vec<(usize, Vec<String>)> = Vec::new();
681		loop {
682			let Some(index) = action else {
683				extras.push(args[start].to_owned());
684				break;
685			};
686			match explicit.take() {
687				Some(explicit_arg) => {
688					let count = match_argument(index, &[A])?;
689					let mut chars = option_string.chars();
690					chars.next();
691					let single_dash = chars.next() != Some('-');
692					if count == 0 && single_dash && !explicit_arg.is_empty() {
693						if sep || explicit_arg.starts_with('-') {
694							return Err(format!(
695								"argument {}: ignored explicit argument {}",
696								arguments[index].display(),
697								py::str_repr(&explicit_arg)
698							));
699						}
700						action_tuples.push((index, Vec::new()));
701						let mut rest = explicit_arg.chars();
702						let c = rest.next().unwrap_or_default();
703						option_string = format!("-{c}");
704						match lookup(&option_string) {
705							Some(i) => {
706								action = Some(i);
707								let rest = rest.as_str();
708								if rest.is_empty() {
709									sep = false;
710									explicit = None;
711								} else if let Some(r) = rest.strip_prefix('=') {
712									sep = true;
713									explicit = Some(r.to_owned());
714								} else {
715									sep = false;
716									explicit = Some(rest.to_owned());
717								}
718							}
719							None => {
720								extras.push(format!("-{explicit_arg}"));
721								break;
722							}
723						}
724					} else if count == 1 {
725						action_tuples.push((index, vec![explicit_arg]));
726						break;
727					} else {
728						return Err(format!(
729							"argument {}: ignored explicit argument {}",
730							arguments[index].display(),
731							py::str_repr(&explicit_arg)
732						));
733					}
734				}
735				None => {
736					let count = match_argument(index, &pattern[start + 1..])?;
737					let strings = args[start + 1..start + 1 + count]
738						.iter()
739						.map(|s| (*s).to_owned())
740						.collect();
741					action_tuples.push((index, strings));
742					start += count;
743					break;
744				}
745			}
746		}
747		let stop = start + 1;
748		for (index, strings) in action_tuples {
749			if let Next::Exit = state.take_action(index, &strings)? {
750				return Ok(state.parsed);
751			}
752		}
753		start = stop;
754	}
755
756	// Consume any positionals following the last option.
757	let Some(stop) = consume_positionals(&mut state, &mut positionals, start)? else {
758		return Ok(state.parsed);
759	};
760	extras.extend(args[stop..].iter().map(|s| (*s).to_owned()));
761
762	let required: Vec<String> = arguments
763		.iter()
764		.enumerate()
765		.filter(|(i, a)| a.required && !state.seen_actions.contains(i))
766		.map(|(_, a)| a.display())
767		.collect();
768	if !required.is_empty() {
769		return Err(format!(
770			"the following arguments are required: {}",
771			required.join(", ")
772		));
773	}
774	for &group in required_groups {
775		let members: Vec<(usize, &Argument)> = arguments
776			.iter()
777			.enumerate()
778			.filter(|(_, a)| a.group == Some(group))
779			.collect();
780		if !members
781			.iter()
782			.any(|(i, _)| state.seen_non_default.contains(i))
783		{
784			let names: Vec<String> = members.iter().map(|(_, a)| a.display()).collect();
785			return Err(format!(
786				"one of the arguments {} is required",
787				names.join(" ")
788			));
789		}
790	}
791	if !extras.is_empty() {
792		return Err(format!("unrecognized arguments: {}", extras.join(" ")));
793	}
794	Ok(state.parsed)
795}
796
797/// A command line declared with `argparse`: its `prog`, its module (for
798/// [`program_text`]), its help text as `argparse` prints it, and its arguments.
799#[derive(Debug, Clone, Copy)]
800pub struct Command {
801	/// The `prog` of the parser, e.g. `"fonttools ttLib.scaleUpem"`.
802	pub prog: &'static str,
803	/// The module, without `fontTools.`, e.g. `"ttLib.scaleUpem"`.
804	pub module: &'static str,
805	/// `parser.format_help()`; its usage is the text before the first empty
806	/// line.
807	pub help: &'static str,
808	/// The arguments.
809	pub arguments: &'static [Argument],
810	/// The mutually exclusive groups with `required=True`.
811	pub required_groups: &'static [usize],
812}
813
814impl Command {
815	/// `parser.format_usage()`.
816	pub fn usage(&self) -> &'static str {
817		match self.help.find("\n\n") {
818			Some(at) => &self.help[..at + 1],
819			None => self.help,
820		}
821	}
822
823	/// `parser.print_help()`: writes the help to `out`.
824	pub fn print_help(&self, out: &mut dyn Write) -> std::io::Result<()> {
825		out.write_all(program_text(self.help, self.prog, self.module).as_bytes())
826	}
827
828	/// `parser.error(message)`: writes the usage and the message to `err`;
829	/// returns the exit code, 2.
830	pub fn error(&self, err: &mut dyn Write, message: &str) -> std::io::Result<i32> {
831		let text = format!("{}{}: error: {message}\n", self.usage(), self.prog);
832		err.write_all(program_text(&text, self.prog, self.module).as_bytes())?;
833		Ok(2)
834	}
835
836	/// `parser.parse_args(args)`: the parsed arguments, or the exit code when
837	/// the help was printed to `out` (0) or an error to `err` (2).
838	pub fn parse_args(
839		&self,
840		args: &[&str],
841		out: &mut dyn Write,
842		err: &mut dyn Write,
843	) -> std::io::Result<Result<Parsed, i32>> {
844		match parse(args, self.arguments, self.required_groups) {
845			Ok(parsed) if parsed.flag("--help") => {
846				self.print_help(out)?;
847				Ok(Err(0))
848			}
849			Ok(parsed) => Ok(Ok(parsed)),
850			Err(message) => Ok(Err(self.error(err, &message)?)),
851		}
852	}
853}
854
855#[cfg(test)]
856mod tests {
857	use super::*;
858
859	const ARGS: &[Argument] = &[
860		Argument::help(),
861		Argument::count(&["-v", "--verbose"]),
862		Argument::option(&["-e", "--conversion-error"]).ty(Ty::Float),
863		Argument::flag(&["-m", "--mixed"]),
864		Argument::option(&["-o", "--output-file"]).group(0),
865		Argument::option(&["-d", "--output-dir"]).group(0),
866		Argument::positional("INPUT").nargs(Nargs::OneOrMore),
867	];
868
869	fn error(args: &[&str]) -> String {
870		parse(args, ARGS, &[]).err().unwrap_or_default()
871	}
872
873	#[test]
874	fn messages() {
875		assert_eq!(error(&[]), "the following arguments are required: INPUT");
876		assert_eq!(error(&["-vx", "a"]), "unrecognized arguments: -x");
877		assert_eq!(
878			error(&["-ex", "a"]),
879			"argument -e/--conversion-error: invalid float value: 'x'"
880		);
881		assert_eq!(
882			error(&["--mixed=3", "a"]),
883			"argument -m/--mixed: ignored explicit argument '3'"
884		);
885		assert_eq!(
886			error(&["--o=x", "a"]),
887			"ambiguous option: --o=x could match --output-file, --output-dir"
888		);
889		assert_eq!(
890			error(&["a", "-o"]),
891			"argument -o/--output-file: expected one argument"
892		);
893		assert_eq!(
894			error(&["-o", "x", "-d", "y", "a"]),
895			"argument -d/--output-dir: not allowed with argument -o/--output-file"
896		);
897		assert_eq!(error(&["a", "-m", "b"]), "unrecognized arguments: b");
898	}
899
900	#[test]
901	fn values() -> Result<(), String> {
902		let parsed = parse(&["-vv", "-e0.5", "a", "b", "--", "-c"], ARGS, &[])?;
903		assert_eq!(parsed.count("--verbose"), 2);
904		assert_eq!(parsed.str("--conversion-error"), Some("0.5"));
905		assert_eq!(parsed.list("INPUT"), ["a", "b", "-c"]);
906		let parsed = parse(&["--output-f", "x", "-h"], ARGS, &[])?;
907		assert_eq!(parsed.str("--output-file"), Some("x"));
908		assert!(parsed.flag("--help"));
909		Ok(())
910	}
911
912	#[test]
913	fn optional_positionals() -> Result<(), String> {
914		const ARGS: &[Argument] = &[
915			Argument::help(),
916			Argument::flag(&["--keep"]),
917			Argument::positional("INPUT"),
918			Argument::positional("OUTPUT").nargs(Nargs::Optional),
919			Argument::positional("GLYPHS").nargs(Nargs::ZeroOrMore),
920		];
921		let parsed = parse(&["a", "--keep", "b", "c", "d"], ARGS, &[])?;
922		assert_eq!(parsed.str("INPUT"), Some("a"));
923		assert_eq!(parsed.str("OUTPUT"), Some("b"));
924		assert_eq!(parsed.list("GLYPHS"), ["c", "d"]);
925		let parsed = parse(&["a"], ARGS, &[])?;
926		assert_eq!(parsed.str("OUTPUT"), None);
927		assert!(parsed.list("GLYPHS").is_empty());
928		// Python 3.13 leaves `nargs="*"` for after an option, rather than
929		// consuming nothing for it before.
930		const STAR: &[Argument] = &[
931			Argument::help(),
932			Argument::flag(&["-c"]),
933			Argument::positional("font"),
934			Argument::positional("glyphs").nargs(Nargs::ZeroOrMore),
935		];
936		let parsed = parse(&["a", "-c", "g1", "g2"], STAR, &[])?;
937		assert_eq!(parsed.list("glyphs"), ["g1", "g2"]);
938		Ok(())
939	}
940
941	#[test]
942	fn required_groups() {
943		const ARGS: &[Argument] = &[
944			Argument::help(),
945			Argument::option(&["-d", "--designspace"]).group(0),
946			Argument::option(&["-l", "--locations"])
947				.nargs(Nargs::OneOrMore)
948				.group(0),
949		];
950		assert_eq!(
951			parse(&[], ARGS, &[0]).err().unwrap_or_default(),
952			"one of the arguments -d/--designspace -l/--locations is required"
953		);
954		assert_eq!(
955			parse(&["-l"], ARGS, &[0]).err().unwrap_or_default(),
956			"argument -l/--locations: expected at least one argument"
957		);
958		assert!(
959			parse(&["-l", "0,0", "1,0"], ARGS, &[0])
960				.is_ok_and(|p| p.list("--locations").len() == 2)
961		);
962	}
963}