parser.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. // optional arguments must check
  177. TakesValue::Optional(_) => {
  178. if let Some(next_arg) = inputs.peek() {
  179. if is_flag(next_arg) {
  180. result_flags.push((flag, None));
  181. } else {
  182. result_flags.push((flag, Some(inputs.next().unwrap())));
  183. }
  184. } else {
  185. result_flags.push((flag, None));
  186. }
  187. }
  188. }
  189. }
  190. }
  191. // If the string starts with *one* dash then it’s one or more
  192. // short arguments.
  193. else if bytes.starts_with(b"-") && arg != "-" {
  194. let short_arg = bytes_to_os_str(&bytes[1..]);
  195. // If there’s an equals in it, then the argument immediately
  196. // before the equals was the one that has the value, with the
  197. // others (if any) as value-less short ones.
  198. //
  199. // -x=abc => ‘x=abc’
  200. // -abcdx=fgh => ‘a’, ‘b’, ‘c’, ‘d’, ‘x=fgh’
  201. // -x= => error
  202. // -abcdx= => error
  203. //
  204. // There’s no way to give two values in a cluster like this:
  205. // it’s an error if any of the first set of arguments actually
  206. // takes a value.
  207. if let Some((before, after)) = split_on_equals(short_arg) {
  208. let (arg_with_value, other_args) =
  209. os_str_to_bytes(before).split_last().unwrap();
  210. // Process the characters immediately following the dash...
  211. for byte in other_args {
  212. let arg = self.lookup_short(*byte)?;
  213. let flag = Flag::Short(*byte);
  214. match arg.takes_value {
  215. TakesValue::Forbidden | TakesValue::Optional(_) => {
  216. result_flags.push((flag, None));
  217. }
  218. TakesValue::Necessary(values) => {
  219. return Err(ParseError::NeedsValue { flag, values });
  220. }
  221. }
  222. }
  223. // ...then the last one and the value after the equals.
  224. let arg = self.lookup_short(*arg_with_value)?;
  225. let flag = Flag::Short(arg.short.unwrap());
  226. match arg.takes_value {
  227. TakesValue::Necessary(_) | TakesValue::Optional(_) => {
  228. result_flags.push((flag, Some(after)));
  229. }
  230. TakesValue::Forbidden => {
  231. return Err(ParseError::ForbiddenValue { flag });
  232. }
  233. }
  234. }
  235. // If there’s no equals, then every character is parsed as
  236. // its own short argument. However, if any of the arguments
  237. // takes a value, then the *rest* of the string is used as
  238. // its value, and if there’s no rest of the string, then it
  239. // uses the next one in the iterator.
  240. //
  241. // -a => ‘a’
  242. // -abc => ‘a’, ‘b’, ‘c’
  243. // -abxdef => ‘a’, ‘b’, ‘x=def’
  244. // -abx def => ‘a’, ‘b’, ‘x=def’
  245. // -abx => error
  246. //
  247. else {
  248. for (index, byte) in bytes.iter().enumerate().skip(1) {
  249. let arg = self.lookup_short(*byte)?;
  250. let flag = Flag::Short(*byte);
  251. match arg.takes_value {
  252. TakesValue::Forbidden => {
  253. result_flags.push((flag, None));
  254. }
  255. TakesValue::Necessary(values) | TakesValue::Optional(values) => {
  256. if index < bytes.len() - 1 {
  257. let remnants = &bytes[index + 1..];
  258. result_flags.push((flag, Some(bytes_to_os_str(remnants))));
  259. break;
  260. } else if let Some(next_arg) = inputs.next() {
  261. result_flags.push((flag, Some(next_arg)));
  262. } else {
  263. match arg.takes_value {
  264. TakesValue::Forbidden => {
  265. unreachable!()
  266. }
  267. TakesValue::Necessary(_) => {
  268. return Err(ParseError::NeedsValue { flag, values });
  269. }
  270. TakesValue::Optional(_) => {
  271. result_flags.push((flag, None));
  272. }
  273. }
  274. }
  275. }
  276. }
  277. }
  278. }
  279. }
  280. // Otherwise, it’s a free string, usually a file name.
  281. else {
  282. frees.push(arg);
  283. }
  284. }
  285. Ok(Matches {
  286. frees,
  287. flags: MatchedFlags {
  288. flags: result_flags,
  289. strictness,
  290. },
  291. })
  292. }
  293. fn lookup_short(&self, short: ShortArg) -> Result<&Arg, ParseError> {
  294. match self.0.iter().find(|arg| arg.short == Some(short)) {
  295. Some(arg) => Ok(arg),
  296. None => Err(ParseError::UnknownShortArgument { attempt: short }),
  297. }
  298. }
  299. fn lookup_long(&self, long: &OsStr) -> Result<&Arg, ParseError> {
  300. match self.0.iter().find(|arg| arg.long == long) {
  301. Some(arg) => Ok(arg),
  302. None => Err(ParseError::UnknownArgument {
  303. attempt: long.to_os_string(),
  304. }),
  305. }
  306. }
  307. }
  308. fn is_flag(arg: &OsStr) -> bool {
  309. let bytes = os_str_to_bytes(arg);
  310. match bytes {
  311. // The only optional arguments allowed
  312. b"always" | b"auto" | b"automatic" | b"never" => false,
  313. _ => bytes.starts_with(b"-"),
  314. }
  315. }
  316. /// The **matches** are the result of parsing the user’s command-line strings.
  317. #[derive(PartialEq, Eq, Debug)]
  318. pub struct Matches<'args> {
  319. /// The flags that were parsed from the user’s input.
  320. pub flags: MatchedFlags<'args>,
  321. /// All the strings that weren’t matched as arguments, as well as anything
  322. /// after the special “--” string.
  323. pub frees: Vec<&'args OsStr>,
  324. }
  325. #[derive(PartialEq, Eq, Debug)]
  326. pub struct MatchedFlags<'args> {
  327. /// The individual flags from the user’s input, in the order they were
  328. /// originally given.
  329. ///
  330. /// Long and short arguments need to be kept in the same vector because
  331. /// we usually want the one nearest the end to count, and to know this,
  332. /// we need to know where they are in relation to one another.
  333. flags: Vec<(Flag, Option<&'args OsStr>)>,
  334. /// Whether to check for duplicate or redundant arguments.
  335. strictness: Strictness,
  336. }
  337. impl<'a> MatchedFlags<'a> {
  338. /// Whether the given argument was specified.
  339. /// Returns `true` if it was, `false` if it wasn’t, and an error in
  340. /// strict mode if it was specified more than once.
  341. pub fn has(&self, arg: &'static Arg) -> Result<bool, OptionsError> {
  342. self.has_where(|flag| flag.matches(arg))
  343. .map(|flag| flag.is_some())
  344. }
  345. /// Returns the first found argument that satisfies the predicate, or
  346. /// nothing if none is found, or an error in strict mode if multiple
  347. /// argument satisfy the predicate.
  348. ///
  349. /// You’ll have to test the resulting flag to see which argument it was.
  350. pub fn has_where<P>(&self, predicate: P) -> Result<Option<&Flag>, OptionsError>
  351. where
  352. P: Fn(&Flag) -> bool,
  353. {
  354. if self.is_strict() {
  355. let all = self
  356. .flags
  357. .iter()
  358. .filter(|tuple| tuple.1.is_none() && predicate(&tuple.0))
  359. .collect::<Vec<_>>();
  360. if all.len() < 2 {
  361. Ok(all.first().map(|t| &t.0))
  362. } else {
  363. Err(OptionsError::Duplicate(all[0].0, all[1].0))
  364. }
  365. } else {
  366. Ok(self.has_where_any(predicate))
  367. }
  368. }
  369. /// Returns the first found argument that satisfies the predicate, or
  370. /// nothing if none is found, with strict mode having no effect.
  371. ///
  372. /// You’ll have to test the resulting flag to see which argument it was.
  373. pub fn has_where_any<P>(&self, predicate: P) -> Option<&Flag>
  374. where
  375. P: Fn(&Flag) -> bool,
  376. {
  377. self.flags
  378. .iter()
  379. .rev()
  380. .find(|tuple| tuple.1.is_none() && predicate(&tuple.0))
  381. .map(|tuple| &tuple.0)
  382. }
  383. // This code could probably be better.
  384. // Both ‘has’ and ‘get’ immediately begin with a conditional, which makes
  385. // me think the functionality could be moved to inside Strictness.
  386. /// Returns the value of the given argument if it was specified, nothing
  387. /// if it wasn’t, and an error in strict mode if it was specified more
  388. /// than once.
  389. pub fn get(&self, arg: &'static Arg) -> Result<Option<&OsStr>, OptionsError> {
  390. self.get_where(|flag| flag.matches(arg))
  391. }
  392. /// Returns the value of the argument that matches the predicate if it
  393. /// was specified, nothing if it wasn’t, and an error in strict mode if
  394. /// multiple arguments matched the predicate.
  395. ///
  396. /// It’s not possible to tell which flag the value belonged to from this.
  397. pub fn get_where<P>(&self, predicate: P) -> Result<Option<&OsStr>, OptionsError>
  398. where
  399. P: Fn(&Flag) -> bool,
  400. {
  401. if self.is_strict() {
  402. let those = self
  403. .flags
  404. .iter()
  405. .filter(|tuple| tuple.1.is_some() && predicate(&tuple.0))
  406. .collect::<Vec<_>>();
  407. if those.len() < 2 {
  408. Ok(those.first().copied().map(|t| t.1.unwrap()))
  409. } else {
  410. Err(OptionsError::Duplicate(those[0].0, those[1].0))
  411. }
  412. } else {
  413. let found = self
  414. .flags
  415. .iter()
  416. .rev()
  417. .find(|tuple| tuple.1.is_some() && predicate(&tuple.0))
  418. .map(|tuple| tuple.1.unwrap());
  419. Ok(found)
  420. }
  421. }
  422. // It’s annoying that ‘has’ and ‘get’ won’t work when accidentally given
  423. // flags that do/don’t take values, but this should be caught by tests.
  424. /// Counts the number of occurrences of the given argument, even in
  425. /// strict mode.
  426. pub fn count(&self, arg: &Arg) -> usize {
  427. self.flags
  428. .iter()
  429. .filter(|tuple| tuple.0.matches(arg))
  430. .count()
  431. }
  432. /// Checks whether strict mode is on. This is usually done from within
  433. /// ‘has’ and ‘get’, but it’s available in an emergency.
  434. pub fn is_strict(&self) -> bool {
  435. self.strictness == Strictness::ComplainAboutRedundantArguments
  436. }
  437. }
  438. /// A problem with the user’s input that meant it couldn’t be parsed into a
  439. /// coherent list of arguments.
  440. #[derive(PartialEq, Eq, Debug)]
  441. pub enum ParseError {
  442. /// A flag that has to take a value was not given one.
  443. NeedsValue { flag: Flag, values: Option<Values> },
  444. /// A flag that can’t take a value *was* given one.
  445. ForbiddenValue { flag: Flag },
  446. /// A short argument, either alone or in a cluster, was not
  447. /// recognised by the program.
  448. UnknownShortArgument { attempt: ShortArg },
  449. /// A long argument was not recognised by the program.
  450. /// We don’t have a known &str version of the flag, so
  451. /// this may not be valid UTF-8.
  452. UnknownArgument { attempt: OsString },
  453. }
  454. impl fmt::Display for ParseError {
  455. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  456. match self {
  457. Self::NeedsValue { flag, values: None } => write!(f, "Flag {flag} needs a value"),
  458. Self::NeedsValue {
  459. flag,
  460. values: Some(cs),
  461. } => write!(f, "Flag {flag} needs a value ({})", Choices(cs)),
  462. Self::ForbiddenValue { flag } => write!(f, "Flag {flag} cannot take a value"),
  463. Self::UnknownShortArgument { attempt } => {
  464. write!(f, "Unknown argument -{}", *attempt as char)
  465. }
  466. Self::UnknownArgument { attempt } => {
  467. write!(f, "Unknown argument --{}", attempt.to_string_lossy())
  468. }
  469. }
  470. }
  471. }
  472. #[cfg(unix)]
  473. fn os_str_to_bytes(s: &OsStr) -> &[u8] {
  474. use std::os::unix::ffi::OsStrExt;
  475. return s.as_bytes();
  476. }
  477. #[cfg(unix)]
  478. fn bytes_to_os_str(b: &[u8]) -> &OsStr {
  479. use std::os::unix::ffi::OsStrExt;
  480. return OsStr::from_bytes(b);
  481. }
  482. #[cfg(windows)]
  483. fn os_str_to_bytes(s: &OsStr) -> &[u8] {
  484. return s.to_str().unwrap().as_bytes();
  485. }
  486. #[cfg(windows)]
  487. fn bytes_to_os_str(b: &[u8]) -> &OsStr {
  488. use std::str;
  489. return OsStr::new(str::from_utf8(b).unwrap());
  490. }
  491. /// Splits a string on its `=` character, returning the two substrings on
  492. /// either side. Returns `None` if there’s no equals or a string is missing.
  493. fn split_on_equals(input: &OsStr) -> Option<(&OsStr, &OsStr)> {
  494. if let Some(index) = os_str_to_bytes(input).iter().position(|elem| *elem == b'=') {
  495. let (before, after) = os_str_to_bytes(input).split_at(index);
  496. // The after string contains the = that we need to remove.
  497. if !before.is_empty() && after.len() >= 2 {
  498. return Some((bytes_to_os_str(before), bytes_to_os_str(&after[1..])));
  499. }
  500. }
  501. None
  502. }
  503. #[cfg(test)]
  504. mod split_test {
  505. use super::split_on_equals;
  506. use std::ffi::{OsStr, OsString};
  507. macro_rules! test_split {
  508. ($name:ident: $input:expr => None) => {
  509. #[test]
  510. fn $name() {
  511. assert_eq!(split_on_equals(&OsString::from($input)), None);
  512. }
  513. };
  514. ($name:ident: $input:expr => $before:expr, $after:expr) => {
  515. #[test]
  516. fn $name() {
  517. assert_eq!(
  518. split_on_equals(&OsString::from($input)),
  519. Some((OsStr::new($before), OsStr::new($after)))
  520. );
  521. }
  522. };
  523. }
  524. test_split!(empty: "" => None);
  525. test_split!(letter: "a" => None);
  526. test_split!(just: "=" => None);
  527. test_split!(intro: "=bbb" => None);
  528. test_split!(denou: "aaa=" => None);
  529. test_split!(equals: "aaa=bbb" => "aaa", "bbb");
  530. test_split!(sort: "--sort=size" => "--sort", "size");
  531. test_split!(more: "this=that=other" => "this", "that=other");
  532. }
  533. #[cfg(test)]
  534. mod parse_test {
  535. use super::*;
  536. macro_rules! test {
  537. ($name:ident: $inputs:expr => frees: $frees:expr, flags: $flags:expr) => {
  538. #[test]
  539. fn $name() {
  540. let inputs: &[&'static str] = $inputs.as_ref();
  541. let inputs = inputs.iter().map(OsStr::new);
  542. let frees: &[&'static str] = $frees.as_ref();
  543. let frees = frees.iter().map(OsStr::new).collect();
  544. let flags = <[_]>::into_vec(Box::new($flags));
  545. let strictness = Strictness::UseLastArguments; // this isn’t even used
  546. let got = Args(TEST_ARGS).parse(inputs, strictness);
  547. let flags = MatchedFlags { flags, strictness };
  548. let expected = Ok(Matches { frees, flags });
  549. assert_eq!(got, expected);
  550. }
  551. };
  552. ($name:ident: $inputs:expr => error $error:expr) => {
  553. #[test]
  554. fn $name() {
  555. use self::ParseError::*;
  556. let inputs = $inputs.iter().map(OsStr::new);
  557. let strictness = Strictness::UseLastArguments; // this isn’t even used
  558. let got = Args(TEST_ARGS).parse(inputs, strictness);
  559. assert_eq!(got, Err($error));
  560. }
  561. };
  562. }
  563. const SUGGESTIONS: Values = &["example"];
  564. #[rustfmt::skip]
  565. static TEST_ARGS: &[&Arg] = &[
  566. &Arg { short: Some(b'l'), long: "long", takes_value: TakesValue::Forbidden },
  567. &Arg { short: Some(b'v'), long: "verbose", takes_value: TakesValue::Forbidden },
  568. &Arg { short: Some(b'c'), long: "count", takes_value: TakesValue::Necessary(None) },
  569. &Arg { short: Some(b't'), long: "type", takes_value: TakesValue::Necessary(Some(SUGGESTIONS)) }
  570. ];
  571. // Just filenames
  572. test!(empty: [] => frees: [], flags: []);
  573. test!(one_arg: ["exa"] => frees: [ "exa" ], flags: []);
  574. // Dashes and double dashes
  575. test!(one_dash: ["-"] => frees: [ "-" ], flags: []);
  576. test!(two_dashes: ["--"] => frees: [], flags: []);
  577. test!(two_file: ["--", "file"] => frees: [ "file" ], flags: []);
  578. test!(two_arg_l: ["--", "--long"] => frees: [ "--long" ], flags: []);
  579. test!(two_arg_s: ["--", "-l"] => frees: [ "-l" ], flags: []);
  580. // Long args
  581. test!(long: ["--long"] => frees: [], flags: [ (Flag::Long("long"), None) ]);
  582. test!(long_then: ["--long", "4"] => frees: [ "4" ], flags: [ (Flag::Long("long"), None) ]);
  583. test!(long_two: ["--long", "--verbose"] => frees: [], flags: [ (Flag::Long("long"), None), (Flag::Long("verbose"), None) ]);
  584. // Long args with values
  585. test!(bad_equals: ["--long=equals"] => error ForbiddenValue { flag: Flag::Long("long") });
  586. test!(no_arg: ["--count"] => error NeedsValue { flag: Flag::Long("count"), values: None });
  587. test!(arg_equals: ["--count=4"] => frees: [], flags: [ (Flag::Long("count"), Some(OsStr::new("4"))) ]);
  588. test!(arg_then: ["--count", "4"] => frees: [], flags: [ (Flag::Long("count"), Some(OsStr::new("4"))) ]);
  589. // Long args with values and suggestions
  590. test!(no_arg_s: ["--type"] => error NeedsValue { flag: Flag::Long("type"), values: Some(SUGGESTIONS) });
  591. test!(arg_equals_s: ["--type=exa"] => frees: [], flags: [ (Flag::Long("type"), Some(OsStr::new("exa"))) ]);
  592. test!(arg_then_s: ["--type", "exa"] => frees: [], flags: [ (Flag::Long("type"), Some(OsStr::new("exa"))) ]);
  593. // Short args
  594. test!(short: ["-l"] => frees: [], flags: [ (Flag::Short(b'l'), None) ]);
  595. test!(short_then: ["-l", "4"] => frees: [ "4" ], flags: [ (Flag::Short(b'l'), None) ]);
  596. test!(short_two: ["-lv"] => frees: [], flags: [ (Flag::Short(b'l'), None), (Flag::Short(b'v'), None) ]);
  597. test!(mixed: ["-v", "--long"] => frees: [], flags: [ (Flag::Short(b'v'), None), (Flag::Long("long"), None) ]);
  598. // Short args with values
  599. test!(bad_short: ["-l=equals"] => error ForbiddenValue { flag: Flag::Short(b'l') });
  600. test!(short_none: ["-c"] => error NeedsValue { flag: Flag::Short(b'c'), values: None });
  601. test!(short_arg_eq: ["-c=4"] => frees: [], flags: [(Flag::Short(b'c'), Some(OsStr::new("4"))) ]);
  602. test!(short_arg_then: ["-c", "4"] => frees: [], flags: [(Flag::Short(b'c'), Some(OsStr::new("4"))) ]);
  603. test!(short_two_together: ["-lctwo"] => frees: [], flags: [(Flag::Short(b'l'), None), (Flag::Short(b'c'), Some(OsStr::new("two"))) ]);
  604. test!(short_two_equals: ["-lc=two"] => frees: [], flags: [(Flag::Short(b'l'), None), (Flag::Short(b'c'), Some(OsStr::new("two"))) ]);
  605. test!(short_two_next: ["-lc", "two"] => frees: [], flags: [(Flag::Short(b'l'), None), (Flag::Short(b'c'), Some(OsStr::new("two"))) ]);
  606. // Short args with values and suggestions
  607. test!(short_none_s: ["-t"] => error NeedsValue { flag: Flag::Short(b't'), values: Some(SUGGESTIONS) });
  608. test!(short_two_together_s: ["-texa"] => frees: [], flags: [(Flag::Short(b't'), Some(OsStr::new("exa"))) ]);
  609. test!(short_two_equals_s: ["-t=exa"] => frees: [], flags: [(Flag::Short(b't'), Some(OsStr::new("exa"))) ]);
  610. test!(short_two_next_s: ["-t", "exa"] => frees: [], flags: [(Flag::Short(b't'), Some(OsStr::new("exa"))) ]);
  611. // Unknown args
  612. test!(unknown_long: ["--quiet"] => error UnknownArgument { attempt: OsString::from("quiet") });
  613. test!(unknown_long_eq: ["--quiet=shhh"] => error UnknownArgument { attempt: OsString::from("quiet") });
  614. test!(unknown_short: ["-q"] => error UnknownShortArgument { attempt: b'q' });
  615. test!(unknown_short_2nd: ["-lq"] => error UnknownShortArgument { attempt: b'q' });
  616. test!(unknown_short_eq: ["-q=shhh"] => error UnknownShortArgument { attempt: b'q' });
  617. test!(unknown_short_2nd_eq: ["-lq=shhh"] => error UnknownShortArgument { attempt: b'q' });
  618. }
  619. #[cfg(test)]
  620. mod matches_test {
  621. use super::*;
  622. macro_rules! test {
  623. ($name:ident: $input:expr, has $param:expr => $result:expr) => {
  624. #[test]
  625. fn $name() {
  626. let flags = MatchedFlags {
  627. flags: $input.to_vec(),
  628. strictness: Strictness::UseLastArguments,
  629. };
  630. assert_eq!(flags.has(&$param), Ok($result));
  631. }
  632. };
  633. }
  634. static VERBOSE: Arg = Arg {
  635. short: Some(b'v'),
  636. long: "verbose",
  637. takes_value: TakesValue::Forbidden,
  638. };
  639. static COUNT: Arg = Arg {
  640. short: Some(b'c'),
  641. long: "count",
  642. takes_value: TakesValue::Necessary(None),
  643. };
  644. test!(short_never: [], has VERBOSE => false);
  645. test!(short_once: [(Flag::Short(b'v'), None)], has VERBOSE => true);
  646. test!(short_twice: [(Flag::Short(b'v'), None), (Flag::Short(b'v'), None)], has VERBOSE => true);
  647. test!(long_once: [(Flag::Long("verbose"), None)], has VERBOSE => true);
  648. test!(long_twice: [(Flag::Long("verbose"), None), (Flag::Long("verbose"), None)], has VERBOSE => true);
  649. test!(long_mixed: [(Flag::Long("verbose"), None), (Flag::Short(b'v'), None)], has VERBOSE => true);
  650. #[test]
  651. fn only_count() {
  652. let everything = OsString::from("everything");
  653. let flags = MatchedFlags {
  654. flags: vec![(Flag::Short(b'c'), Some(&*everything))],
  655. strictness: Strictness::UseLastArguments,
  656. };
  657. assert_eq!(flags.get(&COUNT), Ok(Some(&*everything)));
  658. }
  659. #[test]
  660. fn rightmost_count() {
  661. let everything = OsString::from("everything");
  662. let nothing = OsString::from("nothing");
  663. let flags = MatchedFlags {
  664. flags: vec![
  665. (Flag::Short(b'c'), Some(&*everything)),
  666. (Flag::Short(b'c'), Some(&*nothing)),
  667. ],
  668. strictness: Strictness::UseLastArguments,
  669. };
  670. assert_eq!(flags.get(&COUNT), Ok(Some(&*nothing)));
  671. }
  672. #[test]
  673. fn no_count() {
  674. let flags = MatchedFlags {
  675. flags: Vec::new(),
  676. strictness: Strictness::UseLastArguments,
  677. };
  678. assert!(!flags.has(&COUNT).unwrap());
  679. }
  680. }