main.rs 11 KB

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