mod.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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::{details, grid_details, Mode, View};
  74. use crate::theme::Options as ThemeOptions;
  75. mod dir_action;
  76. mod file_name;
  77. mod filter;
  78. #[rustfmt::skip] // this module becomes unreadable with rustfmt
  79. mod flags;
  80. mod theme;
  81. mod view;
  82. mod error;
  83. pub use self::error::{NumberSource, OptionsError};
  84. mod help;
  85. use self::help::HelpString;
  86. mod parser;
  87. use self::parser::MatchedFlags;
  88. pub mod vars;
  89. pub use self::vars::Vars;
  90. mod version;
  91. use self::version::VersionString;
  92. /// These **options** represent a parsed, error-checked versions of the
  93. /// user’s command-line options.
  94. #[derive(Debug)]
  95. pub struct Options {
  96. /// The action to perform when encountering a directory rather than a
  97. /// regular file.
  98. pub dir_action: DirAction,
  99. /// How to sort and filter files before outputting them.
  100. pub filter: FileFilter,
  101. /// The user’s preference of view to use (lines, grid, details, or
  102. /// grid-details) along with the options on how to render file names.
  103. /// If the view requires the terminal to have a width, and there is no
  104. /// width, then the view will be downgraded.
  105. pub view: View,
  106. /// The options to make up the styles of the UI and file names.
  107. pub theme: ThemeOptions,
  108. }
  109. impl Options {
  110. /// Parse the given iterator of command-line strings into an Options
  111. /// struct and a list of free filenames, using the environment variables
  112. /// for extra options.
  113. #[allow(unused_results)]
  114. pub fn parse<'args, I, V>(args: I, vars: &V) -> OptionsResult<'args>
  115. where
  116. I: IntoIterator<Item = &'args OsStr>,
  117. V: Vars,
  118. {
  119. use crate::options::parser::{Matches, Strictness};
  120. #[rustfmt::skip]
  121. let strictness = match vars.get_with_fallback(vars::EZA_STRICT, vars::EXA_STRICT) {
  122. None => Strictness::UseLastArguments,
  123. Some(ref t) if t.is_empty() => Strictness::UseLastArguments,
  124. Some(_) => Strictness::ComplainAboutRedundantArguments,
  125. };
  126. let Matches { flags, frees } = match flags::ALL_ARGS.parse(args, strictness) {
  127. Ok(m) => m,
  128. Err(pe) => return OptionsResult::InvalidOptions(OptionsError::Parse(pe)),
  129. };
  130. if let Some(help) = HelpString::deduce(&flags) {
  131. return OptionsResult::Help(help);
  132. }
  133. if let Some(version) = VersionString::deduce(&flags) {
  134. return OptionsResult::Version(version);
  135. }
  136. match Self::deduce(&flags, vars) {
  137. Ok(options) => OptionsResult::Ok(options, frees),
  138. Err(oe) => OptionsResult::InvalidOptions(oe),
  139. }
  140. }
  141. /// Whether the View specified in this set of options includes a Git
  142. /// status column. It’s only worth trying to discover a repository if the
  143. /// results will end up being displayed.
  144. pub fn should_scan_for_git(&self) -> bool {
  145. if self.filter.git_ignore == GitIgnore::CheckAndIgnore {
  146. return true;
  147. }
  148. match self.view.mode {
  149. Mode::Details(details::Options {
  150. table: Some(ref table),
  151. ..
  152. })
  153. | Mode::GridDetails(grid_details::Options {
  154. details:
  155. details::Options {
  156. table: Some(ref table),
  157. ..
  158. },
  159. ..
  160. }) => table.columns.git,
  161. _ => false,
  162. }
  163. }
  164. /// Determines the complete set of options based on the given command-line
  165. /// arguments, after they’ve been parsed.
  166. fn deduce<V: Vars>(matches: &MatchedFlags<'_>, vars: &V) -> Result<Self, OptionsError> {
  167. if cfg!(not(feature = "git"))
  168. && matches
  169. .has_where_any(|f| f.matches(&flags::GIT) || f.matches(&flags::GIT_IGNORE))
  170. .is_some()
  171. {
  172. return Err(OptionsError::Unsupported(String::from(
  173. "Options --git and --git-ignore can't be used because `git` feature was disabled in this build of exa"
  174. )));
  175. }
  176. let view = View::deduce(matches, vars)?;
  177. let dir_action = DirAction::deduce(matches, matches!(view.mode, Mode::Details(_)))?;
  178. let filter = FileFilter::deduce(matches)?;
  179. let theme = ThemeOptions::deduce(matches, vars)?;
  180. Ok(Self {
  181. dir_action,
  182. filter,
  183. view,
  184. theme,
  185. })
  186. }
  187. }
  188. /// The result of the `Options::parse` function.
  189. ///
  190. /// NOTE: We disallow the `large_enum_variant` lint here, because we're not
  191. /// overly concerned about variant fragmentation. We can do this because we are
  192. /// reasonably sure that the error variant will be rare, and only on faulty
  193. /// program execution and thus boxing the large variant will be a waste of
  194. /// resources, but should we come to use it more, we should reconsider.
  195. ///
  196. /// See <https://github.com/eza-community/eza/pull/437#issuecomment-1738470254>
  197. #[allow(clippy::large_enum_variant)]
  198. #[derive(Debug)]
  199. pub enum OptionsResult<'args> {
  200. /// The options were parsed successfully.
  201. Ok(Options, Vec<&'args OsStr>),
  202. /// There was an error parsing the arguments.
  203. InvalidOptions(OptionsError),
  204. /// One of the arguments was `--help`, so display help.
  205. Help(HelpString),
  206. /// One of the arguments was `--version`, so display the version number.
  207. Version(VersionString),
  208. }
  209. #[cfg(test)]
  210. pub mod test {
  211. use crate::options::parser::{Arg, MatchedFlags};
  212. use std::ffi::OsStr;
  213. #[derive(PartialEq, Eq, Debug)]
  214. pub enum Strictnesses {
  215. Last,
  216. Complain,
  217. Both,
  218. }
  219. /// This function gets used by the other testing modules.
  220. /// It can run with one or both strictness values: if told to run with
  221. /// both, then both should resolve to the same result.
  222. ///
  223. /// It returns a vector with one or two elements in.
  224. /// These elements can then be tested with `assert_eq` or what have you.
  225. pub fn parse_for_test<T, F>(
  226. inputs: &[&str],
  227. args: &'static [&'static Arg],
  228. strictnesses: Strictnesses,
  229. get: F,
  230. ) -> Vec<T>
  231. where
  232. F: Fn(&MatchedFlags<'_>) -> T,
  233. {
  234. use self::Strictnesses::*;
  235. use crate::options::parser::{Args, Strictness};
  236. let bits = inputs.iter().map(OsStr::new).collect::<Vec<_>>();
  237. let mut result = Vec::new();
  238. if strictnesses == Last || strictnesses == Both {
  239. let results = Args(args).parse(bits.clone(), Strictness::UseLastArguments);
  240. result.push(get(&results.unwrap().flags));
  241. }
  242. if strictnesses == Complain || strictnesses == Both {
  243. let results = Args(args).parse(bits, Strictness::ComplainAboutRedundantArguments);
  244. result.push(get(&results.unwrap().flags));
  245. }
  246. result
  247. }
  248. }