parser.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. //! A general parser for command-line options.
  2. //!
  3. //! exa uses its own hand-rolled parser for command-line options. It supports
  4. //! the following syntax:
  5. //!
  6. //! - Long options: `--inode`, `--grid`
  7. //! - Long options with values: `--sort size`, `--level=4`
  8. //! - Short options: `-i`, `-G`
  9. //! - Short options with values: `-ssize`, `-L=4`
  10. //!
  11. //! These values can be mixed and matched: `exa -lssize --grid`. If you’ve used
  12. //! other command-line programs, then hopefully it’ll work much like them.
  13. //!
  14. //! Because exa already has its own files for the help text, shell completions,
  15. //! man page, and readme, so it can get away with having the options parser do
  16. //! very little: all it really needs to do is parse a slice of strings.
  17. //!
  18. //!
  19. //! ## UTF-8 and `OsStr`
  20. //!
  21. //! The parser uses `OsStr` as its string type. This is necessary for exa to
  22. //! list files that have invalid UTF-8 in their names: by treating file paths
  23. //! as bytes with no encoding, a file can be specified on the command-line and
  24. //! be looked up without having to be encoded into a `str` first.
  25. //!
  26. //! It also avoids the overhead of checking for invalid UTF-8 when parsing
  27. //! command-line options, as all the options and their values (such as
  28. //! `--sort size`) are guaranteed to just be 8-bit ASCII.
  29. use std::ffi::{OsStr, OsString};
  30. use std::fmt;
  31. use crate::options::error::{Choices, OptionsError};
  32. /// A **short argument** is a single ASCII character.
  33. pub type ShortArg = u8;
  34. /// A **long argument** is a string. This can be a UTF-8 string, even though
  35. /// the arguments will all be unchecked `OsString` values, because we don’t
  36. /// actually store the user’s input after it’s been matched to a flag, we just
  37. /// store which flag it was.
  38. pub type LongArg = &'static str;
  39. /// A **list of values** that an option can have, to be displayed when the
  40. /// user enters an invalid one or skips it.
  41. ///
  42. /// This is literally just help text, and won’t be used to validate a value to
  43. /// see if it’s correct.
  44. pub type Values = &'static [&'static str];
  45. /// A **flag** is either of the two argument types, because they have to
  46. /// be in the same array together.
  47. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  48. pub enum Flag {
  49. Short(ShortArg),
  50. Long(LongArg),
  51. }
  52. impl Flag {
  53. pub fn matches(&self, arg: &Arg) -> bool {
  54. match self {
  55. Self::Short(short) => arg.short == Some(*short),
  56. Self::Long(long) => arg.long == *long,
  57. }
  58. }
  59. }
  60. impl fmt::Display for Flag {
  61. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
  62. match self {
  63. Self::Short(short) => write!(f, "-{}", *short as char),
  64. Self::Long(long) => write!(f, "--{long}"),
  65. }
  66. }
  67. }
  68. /// Whether redundant arguments should be considered a problem.
  69. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  70. pub enum Strictness {
  71. /// Throw an error when an argument doesn’t do anything, either because
  72. /// it requires another argument to be specified, or because two conflict.
  73. ComplainAboutRedundantArguments,
  74. /// Search the arguments list back-to-front, giving ones specified later
  75. /// in the list priority over earlier ones.
  76. UseLastArguments,
  77. }
  78. /// Whether a flag takes a value. This is applicable to both long and short
  79. /// arguments.
  80. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  81. pub enum TakesValue {
  82. /// This flag has to be followed by a value.
  83. /// If there’s a fixed set of possible values, they can be printed out
  84. /// with the error text.
  85. Necessary(Option<Values>),
  86. /// This flag will throw an error if there’s a value after it.
  87. Forbidden,
  88. /// This flag may be followed by a value to override its defaults
  89. Optional(Option<Values>),
  90. }
  91. /// An **argument** can be matched by one of the user’s input strings.
  92. #[derive(PartialEq, Eq, Debug, Copy, Clone)]
  93. pub struct Arg {
  94. /// The short argument that matches it, if any.
  95. pub short: Option<ShortArg>,
  96. /// The long argument that matches it. This is non-optional; all flags
  97. /// should at least have a descriptive long name.
  98. pub long: LongArg,
  99. /// Whether this flag takes a value or not.
  100. pub takes_value: TakesValue,
  101. }
  102. impl fmt::Display for Arg {
  103. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
  104. write!(f, "--{}", self.long)?;
  105. if let Some(short) = self.short {
  106. write!(f, " (-{})", short as char)?;
  107. }
  108. Ok(())
  109. }
  110. }
  111. /// Literally just several args.
  112. #[derive(PartialEq, Eq, Debug)]
  113. pub struct Args(pub &'static [&'static Arg]);
  114. impl Args {
  115. /// Iterates over the given list of command-line arguments and parses
  116. /// them into a list of matched flags and free strings.
  117. pub fn parse<'args, I>(
  118. &self,
  119. inputs: I,
  120. strictness: Strictness,
  121. ) -> Result<Matches<'args>, ParseError>
  122. where
  123. I: IntoIterator<Item = &'args OsStr>,
  124. {
  125. let mut parsing = true;
  126. // The results that get built up.
  127. let mut result_flags = Vec::new();
  128. let mut frees: Vec<&OsStr> = Vec::new();
  129. // Iterate over the inputs with “while let” because we need to advance
  130. // the iterator manually whenever an argument that takes a value
  131. // doesn’t have one in its string so it needs the next one.
  132. let mut inputs = inputs.into_iter().peekable();
  133. while let Some(arg) = inputs.next() {
  134. let bytes = os_str_to_bytes(arg);
  135. // Stop parsing if one of the arguments is the literal string “--”.
  136. // This allows a file named “--arg” to be specified by passing in
  137. // the pair “-- --arg”, without it getting matched as a flag that
  138. // doesn’t exist.
  139. if !parsing {
  140. frees.push(arg);
  141. } else if arg == "--" {
  142. parsing = false;
  143. }
  144. // If the string starts with *two* dashes then it’s a long argument.
  145. else if bytes.starts_with(b"--") {
  146. let long_arg_name = bytes_to_os_str(&bytes[2..]);
  147. // If there’s an equals in it, then the string before the
  148. // equals will be the flag’s name, and the string after it
  149. // will be its value.
  150. if let Some((before, after)) = split_on_equals(long_arg_name) {
  151. let arg = self.lookup_long(before)?;
  152. let flag = Flag::Long(arg.long);
  153. match arg.takes_value {
  154. TakesValue::Necessary(_) | TakesValue::Optional(_) => {
  155. result_flags.push((flag, Some(after)));
  156. }
  157. TakesValue::Forbidden => return Err(ParseError::ForbiddenValue { flag }),
  158. }
  159. }
  160. // If there’s no equals, then the entire string (apart from
  161. // the dashes) is the argument name.
  162. else {
  163. let arg = self.lookup_long(long_arg_name)?;
  164. let flag = Flag::Long(arg.long);
  165. match arg.takes_value {
  166. TakesValue::Forbidden => {
  167. result_flags.push((flag, None));
  168. }
  169. TakesValue::Necessary(values) => {
  170. if let Some(next_arg) = inputs.next() {
  171. result_flags.push((flag, Some(next_arg)));
  172. } else {
  173. return Err(ParseError::NeedsValue { flag, values });
  174. }
  175. }
  176. TakesValue::Optional(_) => match inputs.peek() {
  177. Some(next_arg) if is_optional_arg(next_arg) => {
  178. result_flags.push((flag, Some(inputs.next().unwrap())));
  179. }
  180. _ => result_flags.push((flag, None)),
  181. },
  182. }
  183. }
  184. }
  185. // If the string starts with *one* dash then it’s one or more
  186. // short arguments.
  187. else if bytes.starts_with(b"-") && arg != "-" {
  188. let short_arg = bytes_to_os_str(&bytes[1..]);
  189. // If there’s an equals in it, then the argument immediately
  190. // before the equals was the one that has the value, with the
  191. // others (if any) as value-less short ones.
  192. //
  193. // -x=abc => ‘x=abc’
  194. // -abcdx=fgh => ‘a’, ‘b’, ‘c’, ‘d’, ‘x=fgh’
  195. // -x= => error
  196. // -abcdx= => error
  197. //
  198. // There’s no way to give two values in a cluster like this:
  199. // it’s an error if any of the first set of arguments actually
  200. // takes a value.
  201. if let Some((before, after)) = split_on_equals(short_arg) {
  202. let (arg_with_value, other_args) =
  203. os_str_to_bytes(before).split_last().unwrap();
  204. // Process the characters immediately following the dash...
  205. for byte in other_args {
  206. let arg = self.lookup_short(*byte)?;
  207. let flag = Flag::Short(*byte);
  208. match arg.takes_value {
  209. TakesValue::Forbidden | TakesValue::Optional(_) => {
  210. result_flags.push((flag, None));
  211. }
  212. TakesValue::Necessary(values) => {
  213. return Err(ParseError::NeedsValue { flag, values });
  214. }
  215. }
  216. }
  217. // ...then the last one and the value after the equals.
  218. let arg = self.lookup_short(*arg_with_value)?;
  219. let flag = Flag::Short(arg.short.unwrap());
  220. match arg.takes_value {
  221. TakesValue::Necessary(_) | TakesValue::Optional(_) => {
  222. result_flags.push((flag, Some(after)));
  223. }
  224. TakesValue::Forbidden => {
  225. return Err(ParseError::ForbiddenValue { flag });
  226. }
  227. }
  228. }
  229. // If there’s no equals, then every character is parsed as
  230. // its own short argument. However, if any of the arguments
  231. // takes a value, then the *rest* of the string is used as
  232. // its value, and if there’s no rest of the string, then it
  233. // uses the next one in the iterator.
  234. //
  235. // -a => ‘a’
  236. // -abc => ‘a’, ‘b’, ‘c’
  237. // -abxdef => ‘a’, ‘b’, ‘x=def’
  238. // -abx def => ‘a’, ‘b’, ‘x=def’
  239. // -abx => error
  240. //
  241. else {
  242. for (index, byte) in bytes.iter().enumerate().skip(1) {
  243. let arg = self.lookup_short(*byte)?;
  244. let flag = Flag::Short(*byte);
  245. match arg.takes_value {
  246. TakesValue::Forbidden => {
  247. result_flags.push((flag, None));
  248. }
  249. TakesValue::Necessary(values) | TakesValue::Optional(values) => {
  250. if index < bytes.len() - 1 {
  251. let remnants = &bytes[index + 1..];
  252. result_flags.push((flag, Some(bytes_to_os_str(remnants))));
  253. break;
  254. } else if let Some(next_arg) = inputs.next() {
  255. result_flags.push((flag, Some(next_arg)));
  256. } else {
  257. match arg.takes_value {
  258. TakesValue::Forbidden => {
  259. unreachable!()
  260. }
  261. TakesValue::Necessary(_) => {
  262. return Err(ParseError::NeedsValue { flag, values });
  263. }
  264. TakesValue::Optional(_) => {
  265. result_flags.push((flag, None));
  266. }
  267. }
  268. }
  269. }
  270. }
  271. }
  272. }
  273. }
  274. // Otherwise, it’s a free string, usually a file name.
  275. else {
  276. frees.push(arg);
  277. }
  278. }
  279. Ok(Matches {
  280. frees,
  281. flags: MatchedFlags {
  282. flags: result_flags,
  283. strictness,
  284. },
  285. })
  286. }
  287. fn lookup_short(&self, short: ShortArg) -> Result<&Arg, ParseError> {
  288. match self.0.iter().find(|arg| arg.short == Some(short)) {
  289. Some(arg) => Ok(arg),
  290. None => Err(ParseError::UnknownShortArgument { attempt: short }),
  291. }
  292. }
  293. fn lookup_long(&self, long: &OsStr) -> Result<&Arg, ParseError> {
  294. match self.0.iter().find(|arg| arg.long == long) {
  295. Some(arg) => Ok(arg),
  296. None => Err(ParseError::UnknownArgument {
  297. attempt: long.to_os_string(),
  298. }),
  299. }
  300. }
  301. }
  302. fn is_optional_arg(arg: &OsStr) -> bool {
  303. let bytes = os_str_to_bytes(arg);
  304. match bytes {
  305. // The only optional arguments allowed
  306. b"always" | b"auto" | b"automatic" | b"never" => true,
  307. _ => false,
  308. }
  309. }
  310. /// The **matches** are the result of parsing the user’s command-line strings.
  311. #[derive(PartialEq, Eq, Debug)]
  312. pub struct Matches<'args> {
  313. /// The flags that were parsed from the user’s input.
  314. pub flags: MatchedFlags<'args>,
  315. /// All the strings that weren’t matched as arguments, as well as anything
  316. /// after the special “--” string.
  317. pub frees: Vec<&'args OsStr>,
  318. }
  319. #[derive(PartialEq, Eq, Debug)]
  320. pub struct MatchedFlags<'args> {
  321. /// The individual flags from the user’s input, in the order they were
  322. /// originally given.
  323. ///
  324. /// Long and short arguments need to be kept in the same vector because
  325. /// we usually want the one nearest the end to count, and to know this,
  326. /// we need to know where they are in relation to one another.
  327. flags: Vec<(Flag, Option<&'args OsStr>)>,
  328. /// Whether to check for duplicate or redundant arguments.
  329. strictness: Strictness,
  330. }
  331. impl<'a> MatchedFlags<'a> {
  332. /// Whether the given argument was specified.
  333. /// Returns `true` if it was, `false` if it wasn’t, and an error in
  334. /// strict mode if it was specified more than once.
  335. pub fn has(&self, arg: &'static Arg) -> Result<bool, OptionsError> {
  336. self.has_where(|flag| flag.matches(arg))
  337. .map(|flag| flag.is_some())
  338. }
  339. /// Returns the first found argument that satisfies the predicate, or
  340. /// nothing if none is found, or an error in strict mode if multiple
  341. /// argument satisfy the predicate.
  342. ///
  343. /// You’ll have to test the resulting flag to see which argument it was.
  344. pub fn has_where<P>(&self, predicate: P) -> Result<Option<&Flag>, OptionsError>
  345. where
  346. P: Fn(&Flag) -> bool,
  347. {
  348. if self.is_strict() {
  349. let all = self
  350. .flags
  351. .iter()
  352. .filter(|tuple| tuple.1.is_none() && predicate(&tuple.0))
  353. .collect::<Vec<_>>();
  354. if all.len() < 2 {
  355. Ok(all.first().map(|t| &t.0))
  356. } else {
  357. Err(OptionsError::Duplicate(all[0].0, all[1].0))
  358. }
  359. } else {
  360. Ok(self.has_where_any(predicate))
  361. }
  362. }
  363. /// Returns the first found argument that satisfies the predicate, or
  364. /// nothing if none is found, with strict mode having no effect.
  365. ///
  366. /// You’ll have to test the resulting flag to see which argument it was.
  367. pub fn has_where_any<P>(&self, predicate: P) -> Option<&Flag>
  368. where
  369. P: Fn(&Flag) -> bool,
  370. {
  371. self.flags
  372. .iter()
  373. .rev()
  374. .find(|tuple| tuple.1.is_none() && predicate(&tuple.0))
  375. .map(|tuple| &tuple.0)
  376. }
  377. // This code could probably be better.
  378. // Both ‘has’ and ‘get’ immediately begin with a conditional, which makes
  379. // me think the functionality could be moved to inside Strictness.
  380. /// Returns the value of the given argument if it was specified, nothing
  381. /// if it wasn’t, and an error in strict mode if it was specified more
  382. /// than once.
  383. pub fn get(&self, arg: &'static Arg) -> Result<Option<&OsStr>, OptionsError> {
  384. self.get_where(|flag| flag.matches(arg))
  385. }
  386. /// Returns the value of the argument that matches the predicate if it
  387. /// was specified, nothing if it wasn’t, and an error in strict mode if
  388. /// multiple arguments matched the predicate.
  389. ///
  390. /// It’s not possible to tell which flag the value belonged to from this.
  391. pub fn get_where<P>(&self, predicate: P) -> Result<Option<&OsStr>, OptionsError>
  392. where
  393. P: Fn(&Flag) -> bool,
  394. {
  395. if self.is_strict() {
  396. let those = self
  397. .flags
  398. .iter()
  399. .filter(|tuple| tuple.1.is_some() && predicate(&tuple.0))
  400. .collect::<Vec<_>>();
  401. if those.len() < 2 {
  402. Ok(those.first().copied().map(|t| t.1.unwrap()))
  403. } else {
  404. Err(OptionsError::Duplicate(those[0].0, those[1].0))
  405. }
  406. } else {
  407. let found = self
  408. .flags
  409. .iter()
  410. .rev()
  411. .find(|tuple| tuple.1.is_some() && predicate(&tuple.0))
  412. .map(|tuple| tuple.1.unwrap());
  413. Ok(found)
  414. }
  415. }
  416. // It’s annoying that ‘has’ and ‘get’ won’t work when accidentally given
  417. // flags that do/don’t take values, but this should be caught by tests.
  418. /// Counts the number of occurrences of the given argument, even in
  419. /// strict mode.
  420. pub fn count(&self, arg: &Arg) -> usize {
  421. self.flags
  422. .iter()
  423. .filter(|tuple| tuple.0.matches(arg))
  424. .count()
  425. }
  426. /// Checks whether strict mode is on. This is usually done from within
  427. /// ‘has’ and ‘get’, but it’s available in an emergency.
  428. pub fn is_strict(&self) -> bool {
  429. self.strictness == Strictness::ComplainAboutRedundantArguments
  430. }
  431. }
  432. /// A problem with the user’s input that meant it couldn’t be parsed into a
  433. /// coherent list of arguments.
  434. #[derive(PartialEq, Eq, Debug)]
  435. pub enum ParseError {
  436. /// A flag that has to take a value was not given one.
  437. NeedsValue { flag: Flag, values: Option<Values> },
  438. /// A flag that can’t take a value *was* given one.
  439. ForbiddenValue { flag: Flag },
  440. /// A short argument, either alone or in a cluster, was not
  441. /// recognised by the program.
  442. UnknownShortArgument { attempt: ShortArg },
  443. /// A long argument was not recognised by the program.
  444. /// We don’t have a known &str version of the flag, so
  445. /// this may not be valid UTF-8.
  446. UnknownArgument { attempt: OsString },
  447. }
  448. impl fmt::Display for ParseError {
  449. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  450. match self {
  451. Self::NeedsValue { flag, values: None } => write!(f, "Flag {flag} needs a value"),
  452. Self::NeedsValue {
  453. flag,
  454. values: Some(cs),
  455. } => write!(f, "Flag {flag} needs a value ({})", Choices(cs)),
  456. Self::ForbiddenValue { flag } => write!(f, "Flag {flag} cannot take a value"),
  457. Self::UnknownShortArgument { attempt } => {
  458. write!(f, "Unknown argument -{}", *attempt as char)
  459. }
  460. Self::UnknownArgument { attempt } => {
  461. write!(f, "Unknown argument --{}", attempt.to_string_lossy())
  462. }
  463. }
  464. }
  465. }
  466. #[cfg(unix)]
  467. fn os_str_to_bytes(s: &OsStr) -> &[u8] {
  468. use std::os::unix::ffi::OsStrExt;
  469. return s.as_bytes();
  470. }
  471. #[cfg(unix)]
  472. fn bytes_to_os_str(b: &[u8]) -> &OsStr {
  473. use std::os::unix::ffi::OsStrExt;
  474. return OsStr::from_bytes(b);
  475. }
  476. #[cfg(windows)]
  477. fn os_str_to_bytes(s: &OsStr) -> &[u8] {
  478. return s.to_str().unwrap().as_bytes();
  479. }
  480. #[cfg(windows)]
  481. fn bytes_to_os_str(b: &[u8]) -> &OsStr {
  482. use std::str;
  483. return OsStr::new(str::from_utf8(b).unwrap());
  484. }
  485. /// Splits a string on its `=` character, returning the two substrings on
  486. /// either side. Returns `None` if there’s no equals or a string is missing.
  487. fn split_on_equals(input: &OsStr) -> Option<(&OsStr, &OsStr)> {
  488. if let Some(index) = os_str_to_bytes(input).iter().position(|elem| *elem == b'=') {
  489. let (before, after) = os_str_to_bytes(input).split_at(index);
  490. // The after string contains the = that we need to remove.
  491. if !before.is_empty() && after.len() >= 2 {
  492. return Some((bytes_to_os_str(before), bytes_to_os_str(&after[1..])));
  493. }
  494. }
  495. None
  496. }
  497. #[cfg(test)]
  498. mod split_test {
  499. use super::split_on_equals;
  500. use std::ffi::{OsStr, OsString};
  501. macro_rules! test_split {
  502. ($name:ident: $input:expr => None) => {
  503. #[test]
  504. fn $name() {
  505. assert_eq!(split_on_equals(&OsString::from($input)), None);
  506. }
  507. };
  508. ($name:ident: $input:expr => $before:expr, $after:expr) => {
  509. #[test]
  510. fn $name() {
  511. assert_eq!(
  512. split_on_equals(&OsString::from($input)),
  513. Some((OsStr::new($before), OsStr::new($after)))
  514. );
  515. }
  516. };
  517. }
  518. test_split!(empty: "" => None);
  519. test_split!(letter: "a" => None);
  520. test_split!(just: "=" => None);
  521. test_split!(intro: "=bbb" => None);
  522. test_split!(denou: "aaa=" => None);
  523. test_split!(equals: "aaa=bbb" => "aaa", "bbb");
  524. test_split!(sort: "--sort=size" => "--sort", "size");
  525. test_split!(more: "this=that=other" => "this", "that=other");
  526. }
  527. #[cfg(test)]
  528. mod parse_test {
  529. use super::*;
  530. macro_rules! test {
  531. ($name:ident: $inputs:expr => frees: $frees:expr, flags: $flags:expr) => {
  532. #[test]
  533. fn $name() {
  534. let inputs: &[&'static str] = $inputs.as_ref();
  535. let inputs = inputs.iter().map(OsStr::new);
  536. let frees: &[&'static str] = $frees.as_ref();
  537. let frees = frees.iter().map(OsStr::new).collect();
  538. let flags = <[_]>::into_vec(Box::new($flags));
  539. let strictness = Strictness::UseLastArguments; // this isn’t even used
  540. let got = Args(TEST_ARGS).parse(inputs, strictness);
  541. let flags = MatchedFlags { flags, strictness };
  542. let expected = Ok(Matches { frees, flags });
  543. assert_eq!(got, expected);
  544. }
  545. };
  546. ($name:ident: $inputs:expr => error $error:expr) => {
  547. #[test]
  548. fn $name() {
  549. use self::ParseError::*;
  550. let inputs = $inputs.iter().map(OsStr::new);
  551. let strictness = Strictness::UseLastArguments; // this isn’t even used
  552. let got = Args(TEST_ARGS).parse(inputs, strictness);
  553. assert_eq!(got, Err($error));
  554. }
  555. };
  556. }
  557. const SUGGESTIONS: Values = &["example"];
  558. #[rustfmt::skip]
  559. static TEST_ARGS: &[&Arg] = &[
  560. &Arg { short: Some(b'l'), long: "long", takes_value: TakesValue::Forbidden },
  561. &Arg { short: Some(b'v'), long: "verbose", takes_value: TakesValue::Forbidden },
  562. &Arg { short: Some(b'c'), long: "count", takes_value: TakesValue::Necessary(None) },
  563. &Arg { short: Some(b't'), long: "type", takes_value: TakesValue::Necessary(Some(SUGGESTIONS)) }
  564. ];
  565. // Just filenames
  566. test!(empty: [] => frees: [], flags: []);
  567. test!(one_arg: ["exa"] => frees: [ "exa" ], flags: []);
  568. // Dashes and double dashes
  569. test!(one_dash: ["-"] => frees: [ "-" ], flags: []);
  570. test!(two_dashes: ["--"] => frees: [], flags: []);
  571. test!(two_file: ["--", "file"] => frees: [ "file" ], flags: []);
  572. test!(two_arg_l: ["--", "--long"] => frees: [ "--long" ], flags: []);
  573. test!(two_arg_s: ["--", "-l"] => frees: [ "-l" ], flags: []);
  574. // Long args
  575. test!(long: ["--long"] => frees: [], flags: [ (Flag::Long("long"), None) ]);
  576. test!(long_then: ["--long", "4"] => frees: [ "4" ], flags: [ (Flag::Long("long"), None) ]);
  577. test!(long_two: ["--long", "--verbose"] => frees: [], flags: [ (Flag::Long("long"), None), (Flag::Long("verbose"), None) ]);
  578. // Long args with values
  579. test!(bad_equals: ["--long=equals"] => error ForbiddenValue { flag: Flag::Long("long") });
  580. test!(no_arg: ["--count"] => error NeedsValue { flag: Flag::Long("count"), values: None });
  581. test!(arg_equals: ["--count=4"] => frees: [], flags: [ (Flag::Long("count"), Some(OsStr::new("4"))) ]);
  582. test!(arg_then: ["--count", "4"] => frees: [], flags: [ (Flag::Long("count"), Some(OsStr::new("4"))) ]);
  583. // Long args with values and suggestions
  584. test!(no_arg_s: ["--type"] => error NeedsValue { flag: Flag::Long("type"), values: Some(SUGGESTIONS) });
  585. test!(arg_equals_s: ["--type=exa"] => frees: [], flags: [ (Flag::Long("type"), Some(OsStr::new("exa"))) ]);
  586. test!(arg_then_s: ["--type", "exa"] => frees: [], flags: [ (Flag::Long("type"), Some(OsStr::new("exa"))) ]);
  587. // Short args
  588. test!(short: ["-l"] => frees: [], flags: [ (Flag::Short(b'l'), None) ]);
  589. test!(short_then: ["-l", "4"] => frees: [ "4" ], flags: [ (Flag::Short(b'l'), None) ]);
  590. test!(short_two: ["-lv"] => frees: [], flags: [ (Flag::Short(b'l'), None), (Flag::Short(b'v'), None) ]);
  591. test!(mixed: ["-v", "--long"] => frees: [], flags: [ (Flag::Short(b'v'), None), (Flag::Long("long"), None) ]);
  592. // Short args with values
  593. test!(bad_short: ["-l=equals"] => error ForbiddenValue { flag: Flag::Short(b'l') });
  594. test!(short_none: ["-c"] => error NeedsValue { flag: Flag::Short(b'c'), values: None });
  595. test!(short_arg_eq: ["-c=4"] => frees: [], flags: [(Flag::Short(b'c'), Some(OsStr::new("4"))) ]);
  596. test!(short_arg_then: ["-c", "4"] => frees: [], flags: [(Flag::Short(b'c'), Some(OsStr::new("4"))) ]);
  597. test!(short_two_together: ["-lctwo"] => frees: [], flags: [(Flag::Short(b'l'), None), (Flag::Short(b'c'), Some(OsStr::new("two"))) ]);
  598. test!(short_two_equals: ["-lc=two"] => frees: [], flags: [(Flag::Short(b'l'), None), (Flag::Short(b'c'), Some(OsStr::new("two"))) ]);
  599. test!(short_two_next: ["-lc", "two"] => frees: [], flags: [(Flag::Short(b'l'), None), (Flag::Short(b'c'), Some(OsStr::new("two"))) ]);
  600. // Short args with values and suggestions
  601. test!(short_none_s: ["-t"] => error NeedsValue { flag: Flag::Short(b't'), values: Some(SUGGESTIONS) });
  602. test!(short_two_together_s: ["-texa"] => frees: [], flags: [(Flag::Short(b't'), Some(OsStr::new("exa"))) ]);
  603. test!(short_two_equals_s: ["-t=exa"] => frees: [], flags: [(Flag::Short(b't'), Some(OsStr::new("exa"))) ]);
  604. test!(short_two_next_s: ["-t", "exa"] => frees: [], flags: [(Flag::Short(b't'), Some(OsStr::new("exa"))) ]);
  605. // Unknown args
  606. test!(unknown_long: ["--quiet"] => error UnknownArgument { attempt: OsString::from("quiet") });
  607. test!(unknown_long_eq: ["--quiet=shhh"] => error UnknownArgument { attempt: OsString::from("quiet") });
  608. test!(unknown_short: ["-q"] => error UnknownShortArgument { attempt: b'q' });
  609. test!(unknown_short_2nd: ["-lq"] => error UnknownShortArgument { attempt: b'q' });
  610. test!(unknown_short_eq: ["-q=shhh"] => error UnknownShortArgument { attempt: b'q' });
  611. test!(unknown_short_2nd_eq: ["-lq=shhh"] => error UnknownShortArgument { attempt: b'q' });
  612. }
  613. #[cfg(test)]
  614. mod matches_test {
  615. use super::*;
  616. macro_rules! test {
  617. ($name:ident: $input:expr, has $param:expr => $result:expr) => {
  618. #[test]
  619. fn $name() {
  620. let flags = MatchedFlags {
  621. flags: $input.to_vec(),
  622. strictness: Strictness::UseLastArguments,
  623. };
  624. assert_eq!(flags.has(&$param), Ok($result));
  625. }
  626. };
  627. }
  628. static VERBOSE: Arg = Arg {
  629. short: Some(b'v'),
  630. long: "verbose",
  631. takes_value: TakesValue::Forbidden,
  632. };
  633. static COUNT: Arg = Arg {
  634. short: Some(b'c'),
  635. long: "count",
  636. takes_value: TakesValue::Necessary(None),
  637. };
  638. test!(short_never: [], has VERBOSE => false);
  639. test!(short_once: [(Flag::Short(b'v'), None)], has VERBOSE => true);
  640. test!(short_twice: [(Flag::Short(b'v'), None), (Flag::Short(b'v'), None)], has VERBOSE => true);
  641. test!(long_once: [(Flag::Long("verbose"), None)], has VERBOSE => true);
  642. test!(long_twice: [(Flag::Long("verbose"), None), (Flag::Long("verbose"), None)], has VERBOSE => true);
  643. test!(long_mixed: [(Flag::Long("verbose"), None), (Flag::Short(b'v'), None)], has VERBOSE => true);
  644. #[test]
  645. fn only_count() {
  646. let everything = OsString::from("everything");
  647. let flags = MatchedFlags {
  648. flags: vec![(Flag::Short(b'c'), Some(&*everything))],
  649. strictness: Strictness::UseLastArguments,
  650. };
  651. assert_eq!(flags.get(&COUNT), Ok(Some(&*everything)));
  652. }
  653. #[test]
  654. fn rightmost_count() {
  655. let everything = OsString::from("everything");
  656. let nothing = OsString::from("nothing");
  657. let flags = MatchedFlags {
  658. flags: vec![
  659. (Flag::Short(b'c'), Some(&*everything)),
  660. (Flag::Short(b'c'), Some(&*nothing)),
  661. ],
  662. strictness: Strictness::UseLastArguments,
  663. };
  664. assert_eq!(flags.get(&COUNT), Ok(Some(&*nothing)));
  665. }
  666. #[test]
  667. fn no_count() {
  668. let flags = MatchedFlags {
  669. flags: Vec::new(),
  670. strictness: Strictness::UseLastArguments,
  671. };
  672. assert!(!flags.has(&COUNT).unwrap());
  673. }
  674. }