exa.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 options::{Options, Vars};
  27. pub use options::Misfire;
  28. use output::{escape, lines, grid, grid_details, details, View, Mode};
  29. mod fs;
  30. mod info;
  31. mod options;
  32. mod output;
  33. /// The main program wrapper.
  34. pub struct Exa<'args, 'w, W: Write + 'w> {
  35. /// List of command-line options, having been successfully parsed.
  36. pub options: Options,
  37. /// The output handle that we write to. When running the program normally,
  38. /// this will be `std::io::Stdout`, but it can accept any struct that’s
  39. /// `Write` so we can write into, say, a vector for testing.
  40. pub writer: &'w mut W,
  41. /// List of the free command-line arguments that should correspond to file
  42. /// names (anything that isn’t an option).
  43. pub args: Vec<&'args OsStr>,
  44. }
  45. /// The “real” environment variables type.
  46. /// Instead of just calling `var_os` from within the options module,
  47. /// the method of looking up environment variables has to be passed in.
  48. struct LiveVars;
  49. impl Vars for LiveVars {
  50. fn get(&self, name: &'static str) -> Option<OsString> {
  51. var_os(name)
  52. }
  53. }
  54. impl<'args, 'w, W: Write + 'w> Exa<'args, 'w, W> {
  55. pub fn new<I>(args: I, writer: &'w mut W) -> Result<Exa<'args, 'w, W>, Misfire>
  56. where I: Iterator<Item=&'args OsString> {
  57. Options::parse(args, &LiveVars).map(move |(options, args)| {
  58. debug!("Dir action from arguments: {:#?}", options.dir_action);
  59. debug!("Filter from arguments: {:#?}", options.filter);
  60. debug!("View from arguments: {:#?}", options.view.mode);
  61. Exa { options, writer, args }
  62. })
  63. }
  64. pub fn run(&mut self) -> IOResult<i32> {
  65. let mut files = Vec::new();
  66. let mut dirs = Vec::new();
  67. let mut exit_status = 0;
  68. // List the current directory by default, like ls.
  69. if self.args.is_empty() {
  70. self.args = vec![ OsStr::new(".") ];
  71. }
  72. for file_path in &self.args {
  73. match File::new(PathBuf::from(file_path), None, None) {
  74. Err(e) => {
  75. exit_status = 2;
  76. writeln!(stderr(), "{:?}: {}", file_path, e)?;
  77. },
  78. Ok(f) => {
  79. if f.is_directory() && !self.options.dir_action.treat_dirs_as_files() {
  80. match f.to_dir(self.options.should_scan_for_git()) {
  81. Ok(d) => dirs.push(d),
  82. Err(e) => writeln!(stderr(), "{:?}: {}", file_path, e)?,
  83. }
  84. }
  85. else {
  86. files.push(f);
  87. }
  88. },
  89. }
  90. }
  91. // We want to print a directory’s name before we list it, *except* in
  92. // the case where it’s the only directory, *except* if there are any
  93. // files to print as well. (It’s a double negative)
  94. let no_files = files.is_empty();
  95. let is_only_dir = dirs.len() == 1 && no_files;
  96. self.options.filter.filter_argument_files(&mut files);
  97. self.print_files(None, files)?;
  98. self.print_dirs(dirs, no_files, is_only_dir, exit_status)
  99. }
  100. fn print_dirs(&mut self, dir_files: Vec<Dir>, mut first: bool, is_only_dir: bool, exit_status: i32) -> IOResult<i32> {
  101. for dir in dir_files {
  102. // Put a gap between directories, or between the list of files and
  103. // the first directory.
  104. if first {
  105. first = false;
  106. }
  107. else {
  108. write!(self.writer, "\n")?;
  109. }
  110. if !is_only_dir {
  111. let mut bits = Vec::new();
  112. escape(dir.path.display().to_string(), &mut bits, Style::default(), Style::default());
  113. writeln!(self.writer, "{}:", ANSIStrings(&bits))?;
  114. }
  115. let mut children = Vec::new();
  116. for file in dir.files(self.options.filter.dot_filter) {
  117. match file {
  118. Ok(file) => children.push(file),
  119. Err((path, e)) => writeln!(stderr(), "[{}: {}]", path.display(), e)?,
  120. }
  121. };
  122. self.options.filter.filter_child_files(&mut children);
  123. self.options.filter.sort_files(&mut children);
  124. if let Some(recurse_opts) = self.options.dir_action.recurse_options() {
  125. let depth = dir.path.components().filter(|&c| c != Component::CurDir).count() + 1;
  126. if !recurse_opts.tree && !recurse_opts.is_too_deep(depth) {
  127. let mut child_dirs = Vec::new();
  128. for child_dir in children.iter().filter(|f| f.is_directory()) {
  129. match child_dir.to_dir(false) {
  130. Ok(d) => child_dirs.push(d),
  131. Err(e) => writeln!(stderr(), "{}: {}", child_dir.path.display(), e)?,
  132. }
  133. }
  134. self.print_files(Some(&dir), children)?;
  135. match self.print_dirs(child_dirs, false, false, exit_status) {
  136. Ok(_) => (),
  137. Err(e) => return Err(e),
  138. }
  139. continue;
  140. }
  141. }
  142. self.print_files(Some(&dir), children)?;
  143. }
  144. Ok(exit_status)
  145. }
  146. /// Prints the list of files using whichever view is selected.
  147. /// For various annoying logistical reasons, each one handles
  148. /// printing differently...
  149. fn print_files(&mut self, dir: Option<&Dir>, files: Vec<File>) -> IOResult<()> {
  150. if !files.is_empty() {
  151. let View { ref mode, ref colours, ref style } = self.options.view;
  152. match *mode {
  153. Mode::Lines => {
  154. lines::Render { files, colours, style }.render(self.writer)
  155. }
  156. Mode::Grid(ref opts) => {
  157. grid::Render { files, colours, style, opts }.render(self.writer)
  158. }
  159. Mode::Details(ref opts) => {
  160. details::Render { dir, files, colours, style, opts, filter: &self.options.filter, recurse: self.options.dir_action.recurse_options() }.render(self.writer)
  161. }
  162. Mode::GridDetails(ref opts) => {
  163. grid_details::Render { dir, files, colours, style, grid: &opts.grid, details: &opts.details, filter: &self.options.filter, row_threshold: opts.row_threshold }.render(self.writer)
  164. }
  165. }
  166. }
  167. else {
  168. Ok(())
  169. }
  170. }
  171. }