main.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #![warn(deprecated_in_future)]
  2. #![warn(future_incompatible)]
  3. #![warn(nonstandard_style)]
  4. #![warn(rust_2018_compatibility)]
  5. #![warn(rust_2018_idioms)]
  6. #![warn(trivial_casts, trivial_numeric_casts)]
  7. #![warn(unused)]
  8. #![warn(clippy::all, clippy::pedantic)]
  9. #![allow(clippy::cast_precision_loss)]
  10. #![allow(clippy::cast_possible_truncation)]
  11. #![allow(clippy::cast_possible_wrap)]
  12. #![allow(clippy::cast_sign_loss)]
  13. #![allow(clippy::enum_glob_use)]
  14. #![allow(clippy::map_unwrap_or)]
  15. #![allow(clippy::match_same_arms)]
  16. #![allow(clippy::module_name_repetitions)]
  17. #![allow(clippy::non_ascii_literal)]
  18. #![allow(clippy::option_if_let_else)]
  19. #![allow(clippy::too_many_lines)]
  20. #![allow(clippy::unused_self)]
  21. #![allow(clippy::upper_case_acronyms)]
  22. #![allow(clippy::wildcard_imports)]
  23. use std::env;
  24. use std::ffi::{OsStr, OsString};
  25. use std::io::{self, Write, ErrorKind};
  26. use std::path::{Component, PathBuf};
  27. use ansi_term::{ANSIStrings, Style};
  28. use log::*;
  29. use crate::fs::{Dir, File};
  30. use crate::fs::feature::git::GitCache;
  31. use crate::fs::filter::GitIgnore;
  32. use crate::options::{Options, Vars, vars, OptionsResult};
  33. use crate::output::{escape, lines, grid, grid_details, details, View, Mode};
  34. use crate::theme::Theme;
  35. mod fs;
  36. mod info;
  37. mod logger;
  38. mod options;
  39. mod output;
  40. mod theme;
  41. fn main() {
  42. use std::process::exit;
  43. #[cfg(unix)]
  44. unsafe {
  45. libc::signal(libc::SIGPIPE, libc::SIG_DFL);
  46. }
  47. logger::configure(env::var_os(vars::EXA_DEBUG));
  48. #[cfg(windows)]
  49. if let Err(e) = ansi_term::enable_ansi_support() {
  50. warn!("Failed to enable ANSI support: {}", e);
  51. }
  52. let args: Vec<_> = env::args_os().skip(1).collect();
  53. match Options::parse(args.iter().map(std::convert::AsRef::as_ref), &LiveVars) {
  54. OptionsResult::Ok(options, mut input_paths) => {
  55. // List the current directory by default.
  56. // (This has to be done here, otherwise git_options won’t see it.)
  57. if input_paths.is_empty() {
  58. input_paths = vec![ OsStr::new(".") ];
  59. }
  60. let git = git_options(&options, &input_paths);
  61. let writer = io::stdout();
  62. let console_width = options.view.width.actual_terminal_width();
  63. let theme = options.theme.to_theme(console_width.is_some());
  64. let exa = Exa { options, writer, input_paths, theme, console_width, git };
  65. match exa.run() {
  66. Ok(exit_status) => {
  67. exit(exit_status);
  68. }
  69. Err(e) if e.kind() == ErrorKind::BrokenPipe => {
  70. warn!("Broken pipe error: {}", e);
  71. exit(exits::SUCCESS);
  72. }
  73. Err(e) => {
  74. eprintln!("{}", e);
  75. exit(exits::RUNTIME_ERROR);
  76. }
  77. }
  78. }
  79. OptionsResult::Help(help_text) => {
  80. print!("{}", help_text);
  81. }
  82. OptionsResult::Version(version_str) => {
  83. print!("{}", version_str);
  84. }
  85. OptionsResult::InvalidOptions(error) => {
  86. eprintln!("exa: {}", error);
  87. if let Some(s) = error.suggestion() {
  88. eprintln!("{}", s);
  89. }
  90. exit(exits::OPTIONS_ERROR);
  91. }
  92. }
  93. }
  94. /// The main program wrapper.
  95. pub struct Exa<'args> {
  96. /// List of command-line options, having been successfully parsed.
  97. pub options: Options,
  98. /// The output handle that we write to.
  99. pub writer: io::Stdout,
  100. /// List of the free command-line arguments that should correspond to file
  101. /// names (anything that isn’t an option).
  102. pub input_paths: Vec<&'args OsStr>,
  103. /// The theme that has been configured from the command-line options and
  104. /// environment variables. If colours are disabled, this is a theme with
  105. /// every style set to the default.
  106. pub theme: Theme,
  107. /// The detected width of the console. This is used to determine which
  108. /// view to use.
  109. pub console_width: Option<usize>,
  110. /// A global Git cache, if the option was passed in.
  111. /// This has to last the lifetime of the program, because the user might
  112. /// want to list several directories in the same repository.
  113. pub git: Option<GitCache>,
  114. }
  115. /// The “real” environment variables type.
  116. /// Instead of just calling `var_os` from within the options module,
  117. /// the method of looking up environment variables has to be passed in.
  118. struct LiveVars;
  119. impl Vars for LiveVars {
  120. fn get(&self, name: &'static str) -> Option<OsString> {
  121. env::var_os(name)
  122. }
  123. }
  124. /// Create a Git cache populated with the arguments that are going to be
  125. /// listed before they’re actually listed, if the options demand it.
  126. fn git_options(options: &Options, args: &[&OsStr]) -> Option<GitCache> {
  127. if options.should_scan_for_git() {
  128. Some(args.iter().map(PathBuf::from).collect())
  129. }
  130. else {
  131. None
  132. }
  133. }
  134. impl<'args> Exa<'args> {
  135. /// # Errors
  136. ///
  137. /// Will return `Err` if printing to stderr fails.
  138. pub fn run(mut self) -> io::Result<i32> {
  139. debug!("Running with options: {:#?}", self.options);
  140. let mut files = Vec::new();
  141. let mut dirs = Vec::new();
  142. let mut exit_status = 0;
  143. for file_path in &self.input_paths {
  144. match File::from_args(PathBuf::from(file_path), None, None) {
  145. Err(e) => {
  146. exit_status = 2;
  147. writeln!(io::stderr(), "{:?}: {}", file_path, e)?;
  148. }
  149. Ok(f) => {
  150. if f.points_to_directory() && ! self.options.dir_action.treat_dirs_as_files() {
  151. match f.to_dir() {
  152. Ok(d) => dirs.push(d),
  153. Err(e) => writeln!(io::stderr(), "{:?}: {}", file_path, e)?,
  154. }
  155. }
  156. else {
  157. files.push(f);
  158. }
  159. }
  160. }
  161. }
  162. // We want to print a directory’s name before we list it, *except* in
  163. // the case where it’s the only directory, *except* if there are any
  164. // files to print as well. (It’s a double negative)
  165. let no_files = files.is_empty();
  166. let is_only_dir = dirs.len() == 1 && no_files;
  167. self.options.filter.filter_argument_files(&mut files);
  168. self.print_files(None, files)?;
  169. self.print_dirs(dirs, no_files, is_only_dir, exit_status)
  170. }
  171. fn print_dirs(&mut self, dir_files: Vec<Dir>, mut first: bool, is_only_dir: bool, exit_status: i32) -> io::Result<i32> {
  172. for dir in dir_files {
  173. // Put a gap between directories, or between the list of files and
  174. // the first directory.
  175. if first {
  176. first = false;
  177. }
  178. else {
  179. writeln!(&mut self.writer)?;
  180. }
  181. if ! is_only_dir {
  182. let mut bits = Vec::new();
  183. escape(dir.path.display().to_string(), &mut bits, Style::default(), Style::default());
  184. writeln!(&mut self.writer, "{}:", ANSIStrings(&bits))?;
  185. }
  186. let mut children = Vec::new();
  187. let git_ignore = self.options.filter.git_ignore == GitIgnore::CheckAndIgnore;
  188. for file in dir.files(self.options.filter.dot_filter, self.git.as_ref(), git_ignore) {
  189. match file {
  190. Ok(file) => children.push(file),
  191. Err((path, e)) => writeln!(io::stderr(), "[{}: {}]", path.display(), e)?,
  192. }
  193. };
  194. self.options.filter.filter_child_files(&mut children);
  195. self.options.filter.sort_files(&mut children);
  196. if let Some(recurse_opts) = self.options.dir_action.recurse_options() {
  197. let depth = dir.path.components().filter(|&c| c != Component::CurDir).count() + 1;
  198. if ! recurse_opts.tree && ! recurse_opts.is_too_deep(depth) {
  199. let mut child_dirs = Vec::new();
  200. for child_dir in children.iter().filter(|f| f.is_directory() && ! f.is_all_all) {
  201. match child_dir.to_dir() {
  202. Ok(d) => child_dirs.push(d),
  203. Err(e) => writeln!(io::stderr(), "{}: {}", child_dir.path.display(), e)?,
  204. }
  205. }
  206. self.print_files(Some(&dir), children)?;
  207. match self.print_dirs(child_dirs, false, false, exit_status) {
  208. Ok(_) => (),
  209. Err(e) => return Err(e),
  210. }
  211. continue;
  212. }
  213. }
  214. self.print_files(Some(&dir), children)?;
  215. }
  216. Ok(exit_status)
  217. }
  218. /// Prints the list of files using whichever view is selected.
  219. fn print_files(&mut self, dir: Option<&Dir>, files: Vec<File<'_>>) -> io::Result<()> {
  220. if files.is_empty() {
  221. return Ok(());
  222. }
  223. let theme = &self.theme;
  224. let View { ref mode, ref file_style, .. } = self.options.view;
  225. match (mode, self.console_width) {
  226. (Mode::Grid(ref opts), Some(console_width)) => {
  227. let filter = &self.options.filter;
  228. let r = grid::Render { files, theme, file_style, opts, console_width, filter };
  229. r.render(&mut self.writer)
  230. }
  231. (Mode::Grid(_), None) |
  232. (Mode::Lines, _) => {
  233. let filter = &self.options.filter;
  234. let r = lines::Render { files, theme, file_style, filter };
  235. r.render(&mut self.writer)
  236. }
  237. (Mode::Details(ref opts), _) => {
  238. let filter = &self.options.filter;
  239. let recurse = self.options.dir_action.recurse_options();
  240. let git_ignoring = self.options.filter.git_ignore == GitIgnore::CheckAndIgnore;
  241. let git = self.git.as_ref();
  242. let r = details::Render { dir, files, theme, file_style, opts, recurse, filter, git_ignoring, git };
  243. r.render(&mut self.writer)
  244. }
  245. (Mode::GridDetails(ref opts), Some(console_width)) => {
  246. let grid = &opts.grid;
  247. let details = &opts.details;
  248. let row_threshold = opts.row_threshold;
  249. let filter = &self.options.filter;
  250. let git_ignoring = self.options.filter.git_ignore == GitIgnore::CheckAndIgnore;
  251. let git = self.git.as_ref();
  252. let r = grid_details::Render { dir, files, theme, file_style, grid, details, filter, row_threshold, git_ignoring, git, console_width };
  253. r.render(&mut self.writer)
  254. }
  255. (Mode::GridDetails(ref opts), None) => {
  256. let opts = &opts.to_details_options();
  257. let filter = &self.options.filter;
  258. let recurse = self.options.dir_action.recurse_options();
  259. let git_ignoring = self.options.filter.git_ignore == GitIgnore::CheckAndIgnore;
  260. let git = self.git.as_ref();
  261. let r = details::Render { dir, files, theme, file_style, opts, recurse, filter, git_ignoring, git };
  262. r.render(&mut self.writer)
  263. }
  264. }
  265. }
  266. }
  267. mod exits {
  268. /// Exit code for when exa runs OK.
  269. pub const SUCCESS: i32 = 0;
  270. /// Exit code for when there was at least one I/O error during execution.
  271. pub const RUNTIME_ERROR: i32 = 1;
  272. /// Exit code for when the command-line options are invalid.
  273. pub const OPTIONS_ERROR: i32 = 3;
  274. }