exa.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #![warn(trivial_casts, trivial_numeric_casts)]
  2. #![warn(unused_results)]
  3. extern crate ansi_term;
  4. extern crate datetime;
  5. extern crate glob;
  6. extern crate libc;
  7. extern crate locale;
  8. extern crate natord;
  9. extern crate num_cpus;
  10. extern crate number_prefix;
  11. extern crate scoped_threadpool;
  12. extern crate term_grid;
  13. extern crate unicode_width;
  14. extern crate users;
  15. extern crate zoneinfo_compiled;
  16. extern crate term_size;
  17. #[cfg(feature="git")] extern crate git2;
  18. #[macro_use] extern crate lazy_static;
  19. #[macro_use] extern crate log;
  20. use std::env::var_os;
  21. use std::ffi::{OsStr, OsString};
  22. use std::io::{stderr, Write, Result as IOResult};
  23. use std::path::{Component, PathBuf};
  24. use ansi_term::{ANSIStrings, Style};
  25. use fs::{Dir, File};
  26. use fs::feature::ignore::IgnoreCache;
  27. use fs::feature::git::GitCache;
  28. use options::{Options, Vars};
  29. pub use options::vars;
  30. pub use options::Misfire;
  31. use output::{escape, lines, grid, grid_details, details, View, Mode};
  32. mod fs;
  33. mod info;
  34. mod options;
  35. mod output;
  36. mod style;
  37. /// The main program wrapper.
  38. pub struct Exa<'args, 'w, W: Write + 'w> {
  39. /// List of command-line options, having been successfully parsed.
  40. pub options: Options,
  41. /// The output handle that we write to. When running the program normally,
  42. /// this will be `std::io::Stdout`, but it can accept any struct that’s
  43. /// `Write` so we can write into, say, a vector for testing.
  44. pub writer: &'w mut W,
  45. /// List of the free command-line arguments that should correspond to file
  46. /// names (anything that isn’t an option).
  47. pub args: Vec<&'args OsStr>,
  48. /// A global Git cache, if the option was passed in.
  49. /// This has to last the lifetime of the program, because the user might
  50. /// want to list several directories in the same repository.
  51. pub git: Option<GitCache>,
  52. /// A cache of git-ignored files.
  53. /// This lasts the lifetime of the program too, for the same reason.
  54. pub ignore: Option<IgnoreCache>,
  55. }
  56. /// The “real” environment variables type.
  57. /// Instead of just calling `var_os` from within the options module,
  58. /// the method of looking up environment variables has to be passed in.
  59. struct LiveVars;
  60. impl Vars for LiveVars {
  61. fn get(&self, name: &'static str) -> Option<OsString> {
  62. var_os(name)
  63. }
  64. }
  65. /// Create a Git cache populated with the arguments that are going to be
  66. /// listed before they’re actually listed, if the options demand it.
  67. fn git_options(options: &Options, args: &[&OsStr]) -> Option<GitCache> {
  68. if options.should_scan_for_git() {
  69. Some(args.iter().map(PathBuf::from).collect())
  70. }
  71. else {
  72. None
  73. }
  74. }
  75. fn ignore_cache(options: &Options) -> Option<IgnoreCache> {
  76. use fs::filter::GitIgnore;
  77. match options.filter.git_ignore {
  78. GitIgnore::CheckAndIgnore => Some(IgnoreCache::new()),
  79. GitIgnore::Off => None,
  80. }
  81. }
  82. impl<'args, 'w, W: Write + 'w> Exa<'args, 'w, W> {
  83. pub fn from_args<I>(args: I, writer: &'w mut W) -> Result<Exa<'args, 'w, W>, Misfire>
  84. where I: Iterator<Item=&'args OsString> {
  85. Options::parse(args, &LiveVars).map(move |(options, mut args)| {
  86. debug!("Dir action from arguments: {:#?}", options.dir_action);
  87. debug!("Filter from arguments: {:#?}", options.filter);
  88. debug!("View from arguments: {:#?}", options.view.mode);
  89. // List the current directory by default, like ls.
  90. // This has to be done here, otherwise git_options won’t see it.
  91. if args.is_empty() {
  92. args = vec![ OsStr::new(".") ];
  93. }
  94. let git = git_options(&options, &args);
  95. let ignore = ignore_cache(&options);
  96. Exa { options, writer, args, git, ignore }
  97. })
  98. }
  99. pub fn run(&mut self) -> IOResult<i32> {
  100. let mut files = Vec::new();
  101. let mut dirs = Vec::new();
  102. let mut exit_status = 0;
  103. for file_path in &self.args {
  104. match File::from_args(PathBuf::from(file_path), None, None) {
  105. Err(e) => {
  106. exit_status = 2;
  107. writeln!(stderr(), "{:?}: {}", file_path, e)?;
  108. },
  109. Ok(f) => {
  110. if f.points_to_directory() && !self.options.dir_action.treat_dirs_as_files() {
  111. match f.to_dir() {
  112. Ok(d) => dirs.push(d),
  113. Err(e) => writeln!(stderr(), "{:?}: {}", file_path, e)?,
  114. }
  115. }
  116. else {
  117. files.push(f);
  118. }
  119. },
  120. }
  121. }
  122. // We want to print a directory’s name before we list it, *except* in
  123. // the case where it’s the only directory, *except* if there are any
  124. // files to print as well. (It’s a double negative)
  125. let no_files = files.is_empty();
  126. let is_only_dir = dirs.len() == 1 && no_files;
  127. self.options.filter.filter_argument_files(&mut files);
  128. self.print_files(None, files)?;
  129. self.print_dirs(dirs, no_files, is_only_dir, exit_status)
  130. }
  131. fn print_dirs(&mut self, dir_files: Vec<Dir>, mut first: bool, is_only_dir: bool, exit_status: i32) -> IOResult<i32> {
  132. for dir in dir_files {
  133. // Put a gap between directories, or between the list of files and
  134. // the first directory.
  135. if first {
  136. first = false;
  137. }
  138. else {
  139. writeln!(self.writer)?;
  140. }
  141. if !is_only_dir {
  142. let mut bits = Vec::new();
  143. escape(dir.path.display().to_string(), &mut bits, Style::default(), Style::default());
  144. writeln!(self.writer, "{}:", ANSIStrings(&bits))?;
  145. }
  146. let mut children = Vec::new();
  147. for file in dir.files(self.options.filter.dot_filter, self.ignore.as_ref()) {
  148. match file {
  149. Ok(file) => children.push(file),
  150. Err((path, e)) => writeln!(stderr(), "[{}: {}]", path.display(), e)?,
  151. }
  152. };
  153. self.options.filter.filter_child_files(&mut children);
  154. self.options.filter.sort_files(&mut children);
  155. if let Some(recurse_opts) = self.options.dir_action.recurse_options() {
  156. let depth = dir.path.components().filter(|&c| c != Component::CurDir).count() + 1;
  157. if !recurse_opts.tree && !recurse_opts.is_too_deep(depth) {
  158. let mut child_dirs = Vec::new();
  159. for child_dir in children.iter().filter(|f| f.is_directory() && !f.is_all_all) {
  160. match child_dir.to_dir() {
  161. Ok(d) => child_dirs.push(d),
  162. Err(e) => writeln!(stderr(), "{}: {}", child_dir.path.display(), e)?,
  163. }
  164. }
  165. self.print_files(Some(&dir), children)?;
  166. match self.print_dirs(child_dirs, false, false, exit_status) {
  167. Ok(_) => (),
  168. Err(e) => return Err(e),
  169. }
  170. continue;
  171. }
  172. }
  173. self.print_files(Some(&dir), children)?;
  174. }
  175. Ok(exit_status)
  176. }
  177. /// Prints the list of files using whichever view is selected.
  178. /// For various annoying logistical reasons, each one handles
  179. /// printing differently...
  180. fn print_files(&mut self, dir: Option<&Dir>, files: Vec<File>) -> IOResult<()> {
  181. if !files.is_empty() {
  182. let View { ref mode, ref colours, ref style } = self.options.view;
  183. match *mode {
  184. Mode::Lines(ref opts) => {
  185. let r = lines::Render { files, colours, style, opts };
  186. r.render(self.writer)
  187. }
  188. Mode::Grid(ref opts) => {
  189. let r = grid::Render { files, colours, style, opts };
  190. r.render(self.writer)
  191. }
  192. Mode::Details(ref opts) => {
  193. let filter = &self.options.filter;
  194. let recurse = self.options.dir_action.recurse_options();
  195. let r = details::Render { dir, files, colours, style, opts, filter, recurse };
  196. r.render(self.git.as_ref(), self.ignore.as_ref(), self.writer)
  197. }
  198. Mode::GridDetails(ref opts) => {
  199. let grid = &opts.grid;
  200. let filter = &self.options.filter;
  201. let details = &opts.details;
  202. let row_threshold = opts.row_threshold;
  203. let r = grid_details::Render { dir, files, colours, style, grid, details, filter, row_threshold };
  204. r.render(self.git.as_ref(), self.writer)
  205. }
  206. }
  207. }
  208. else {
  209. Ok(())
  210. }
  211. }
  212. }