main.rs 12 KB

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