mod.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //! Parsing command-line strings into exa options.
  2. //!
  3. //! This module imports exa’s configuration types, such as `View` (the details
  4. //! of displaying multiple files) and `DirAction` (what to do when encountering
  5. //! a directory), and implements `deduce` methods on them so they can be
  6. //! configured using command-line options.
  7. //!
  8. //!
  9. //! ## Useless and overridden options
  10. //!
  11. //! Let’s say exa was invoked with just one argument: `exa --inode`. The
  12. //! `--inode` option is used in the details view, where it adds the inode
  13. //! column to the output. But because the details view is *only* activated with
  14. //! the `--long` argument, adding `--inode` without it would not have any
  15. //! effect.
  16. //!
  17. //! For a long time, exa’s philosophy was that the user should be warned
  18. //! whenever they could be mistaken like this. If you tell exa to display the
  19. //! inode, and it *doesn’t* display the inode, isn’t that more annoying than
  20. //! having it throw an error back at you?
  21. //!
  22. //! However, this doesn’t take into account *configuration*. Say a user wants
  23. //! to configure exa so that it lists inodes in the details view, but otherwise
  24. //! functions normally. A common way to do this for command-line programs is to
  25. //! define a shell alias that specifies the details they want to use every
  26. //! time. For the inode column, the alias would be:
  27. //!
  28. //! `alias exa="exa --inode"`
  29. //!
  30. //! Using this alias means that although the inode column will be shown in the
  31. //! details view, you’re now *only* allowed to use the details view, as any
  32. //! other view type will result in an error. Oops!
  33. //!
  34. //! Another example is when an option is specified twice, such as `exa
  35. //! --sort=Name --sort=size`. Did the user change their mind about sorting, and
  36. //! accidentally specify the option twice?
  37. //!
  38. //! Again, exa rejected this case, throwing an error back to the user instead
  39. //! of trying to guess how they want their output sorted. And again, this
  40. //! doesn’t take into account aliases being used to set defaults. A user who
  41. //! wants their files to be sorted case-insensitively may configure their shell
  42. //! with the following:
  43. //!
  44. //! `alias exa="exa --sort=Name"`
  45. //!
  46. //! Just like the earlier example, the user now can’t use any other sort order,
  47. //! because exa refuses to guess which one they meant. It’s *more* annoying to
  48. //! have to go back and edit the command than if there were no error.
  49. //!
  50. //! Fortunately, there’s a heuristic for telling which options came from an
  51. //! alias and which came from the actual command-line: aliased options are
  52. //! nearer the beginning of the options array, and command-line options are
  53. //! nearer the end. This means that after the options have been parsed, exa
  54. //! needs to traverse them *backwards* to find the last-most-specified one.
  55. //!
  56. //! For example, invoking exa with `exa --sort=size` when that alias is present
  57. //! would result in a full command-line of:
  58. //!
  59. //! `exa --sort=Name --sort=size`
  60. //!
  61. //! `--sort=size` should override `--sort=Name` because it’s closer to the end
  62. //! of the arguments array. In fact, because there’s no way to tell where the
  63. //! arguments came from — it’s just a heuristic — this will still work even
  64. //! if no aliases are being used!
  65. //!
  66. //! Finally, this isn’t just useful when options could override each other.
  67. //! Creating an alias `exal="exa --long --inode --header"` then invoking `exal
  68. //! --grid --long` shouldn’t complain about `--long` being given twice when
  69. //! it’s clear what the user wants.
  70. use std::ffi::OsStr;
  71. use crate::fs::dir_action::DirAction;
  72. use crate::fs::filter::{FileFilter, GitIgnore};
  73. use crate::output::{View, Mode, details, grid_details};
  74. use crate::theme::Options as ThemeOptions;
  75. mod dir_action;
  76. mod file_name;
  77. mod filter;
  78. mod flags;
  79. mod theme;
  80. mod view;
  81. mod error;
  82. pub use self::error::{OptionsError, NumberSource};
  83. mod help;
  84. use self::help::HelpString;
  85. mod parser;
  86. use self::parser::MatchedFlags;
  87. pub mod vars;
  88. pub use self::vars::Vars;
  89. mod version;
  90. use self::version::VersionString;
  91. /// These **options** represent a parsed, error-checked versions of the
  92. /// user’s command-line options.
  93. #[derive(Debug)]
  94. pub struct Options {
  95. /// The action to perform when encountering a directory rather than a
  96. /// regular file.
  97. pub dir_action: DirAction,
  98. /// How to sort and filter files before outputting them.
  99. pub filter: FileFilter,
  100. /// The user’s preference of view to use (lines, grid, details, or
  101. /// grid-details) along with the options on how to render file names.
  102. /// If the view requires the terminal to have a width, and there is no
  103. /// width, then the view will be downgraded.
  104. pub view: View,
  105. /// The options to make up the styles of the UI and file names.
  106. pub theme: ThemeOptions,
  107. }
  108. impl Options {
  109. /// Parse the given iterator of command-line strings into an Options
  110. /// struct and a list of free filenames, using the environment variables
  111. /// for extra options.
  112. #[allow(unused_results)]
  113. pub fn parse<'args, I, V>(args: I, vars: &V) -> OptionsResult<'args>
  114. where I: IntoIterator<Item = &'args OsStr>,
  115. V: Vars,
  116. {
  117. use crate::options::parser::{Matches, Strictness};
  118. let strictness = match vars.get(vars::EXA_STRICT) {
  119. None => Strictness::UseLastArguments,
  120. Some(ref t) if t.is_empty() => Strictness::UseLastArguments,
  121. Some(_) => Strictness::ComplainAboutRedundantArguments,
  122. };
  123. let Matches { flags, frees } = match flags::ALL_ARGS.parse(args, strictness) {
  124. Ok(m) => m,
  125. Err(pe) => return OptionsResult::InvalidOptions(OptionsError::Parse(pe)),
  126. };
  127. if let Some(help) = HelpString::deduce(&flags) {
  128. return OptionsResult::Help(help);
  129. }
  130. if let Some(version) = VersionString::deduce(&flags) {
  131. return OptionsResult::Version(version);
  132. }
  133. match Self::deduce(&flags, vars) {
  134. Ok(options) => OptionsResult::Ok(options, frees),
  135. Err(oe) => OptionsResult::InvalidOptions(oe),
  136. }
  137. }
  138. /// Whether the View specified in this set of options includes a Git
  139. /// status column. It’s only worth trying to discover a repository if the
  140. /// results will end up being displayed.
  141. pub fn should_scan_for_git(&self) -> bool {
  142. if self.filter.git_ignore == GitIgnore::CheckAndIgnore {
  143. return true;
  144. }
  145. match self.view.mode {
  146. Mode::Details(details::Options { table: Some(ref table), .. }) |
  147. Mode::GridDetails(grid_details::Options { details: details::Options { table: Some(ref table), .. }, .. }) => table.columns.git,
  148. _ => false,
  149. }
  150. }
  151. /// Determines the complete set of options based on the given command-line
  152. /// arguments, after they’ve been parsed.
  153. fn deduce<V: Vars>(matches: &MatchedFlags<'_>, vars: &V) -> Result<Self, OptionsError> {
  154. if cfg!(not(feature = "git")) &&
  155. matches.has_where_any(|f| f.matches(&flags::GIT) || f.matches(&flags::GIT_IGNORE)).is_some() {
  156. return Err(OptionsError::Unsupported(String::from(
  157. "Options --git and --git-ignore can't be used because `git` feature was disabled in this build of exa"
  158. )));
  159. }
  160. let view = View::deduce(matches, vars)?;
  161. let dir_action = DirAction::deduce(matches, matches!(view.mode, Mode::Details(_)))?;
  162. let filter = FileFilter::deduce(matches)?;
  163. let theme = ThemeOptions::deduce(matches, vars)?;
  164. Ok(Self { dir_action, filter, view, theme })
  165. }
  166. }
  167. /// The result of the `Options::getopts` function.
  168. #[derive(Debug)]
  169. pub enum OptionsResult<'args> {
  170. /// The options were parsed successfully.
  171. Ok(Options, Vec<&'args OsStr>),
  172. /// There was an error parsing the arguments.
  173. InvalidOptions(OptionsError),
  174. /// One of the arguments was `--help`, so display help.
  175. Help(HelpString),
  176. /// One of the arguments was `--version`, so display the version number.
  177. Version(VersionString),
  178. }
  179. #[cfg(test)]
  180. pub mod test {
  181. use crate::options::parser::{Arg, MatchedFlags};
  182. use std::ffi::OsStr;
  183. #[derive(PartialEq, Eq, Debug)]
  184. pub enum Strictnesses {
  185. Last,
  186. Complain,
  187. Both,
  188. }
  189. /// This function gets used by the other testing modules.
  190. /// It can run with one or both strictness values: if told to run with
  191. /// both, then both should resolve to the same result.
  192. ///
  193. /// It returns a vector with one or two elements in.
  194. /// These elements can then be tested with `assert_eq` or what have you.
  195. pub fn parse_for_test<T, F>(inputs: &[&str], args: &'static [&'static Arg], strictnesses: Strictnesses, get: F) -> Vec<T>
  196. where F: Fn(&MatchedFlags<'_>) -> T
  197. {
  198. use self::Strictnesses::*;
  199. use crate::options::parser::{Args, Strictness};
  200. let bits = inputs.iter().map(OsStr::new).collect::<Vec<_>>();
  201. let mut result = Vec::new();
  202. if strictnesses == Last || strictnesses == Both {
  203. let results = Args(args).parse(bits.clone(), Strictness::UseLastArguments);
  204. result.push(get(&results.unwrap().flags));
  205. }
  206. if strictnesses == Complain || strictnesses == Both {
  207. let results = Args(args).parse(bits, Strictness::ComplainAboutRedundantArguments);
  208. result.push(get(&results.unwrap().flags));
  209. }
  210. result
  211. }
  212. }