exa.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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]
  19. extern crate lazy_static;
  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. Exa { options, writer, args }
  59. })
  60. }
  61. pub fn run(&mut self) -> IOResult<i32> {
  62. let mut files = Vec::new();
  63. let mut dirs = Vec::new();
  64. let mut exit_status = 0;
  65. // List the current directory by default, like ls.
  66. if self.args.is_empty() {
  67. self.args = vec![ OsStr::new(".") ];
  68. }
  69. for file_path in &self.args {
  70. match File::new(PathBuf::from(file_path), None, None) {
  71. Err(e) => {
  72. exit_status = 2;
  73. writeln!(stderr(), "{:?}: {}", file_path, e)?;
  74. },
  75. Ok(f) => {
  76. if f.is_directory() && !self.options.dir_action.treat_dirs_as_files() {
  77. match f.to_dir(self.options.should_scan_for_git()) {
  78. Ok(d) => dirs.push(d),
  79. Err(e) => writeln!(stderr(), "{:?}: {}", file_path, e)?,
  80. }
  81. }
  82. else {
  83. files.push(f);
  84. }
  85. },
  86. }
  87. }
  88. // We want to print a directory’s name before we list it, *except* in
  89. // the case where it’s the only directory, *except* if there are any
  90. // files to print as well. (It’s a double negative)
  91. let no_files = files.is_empty();
  92. let is_only_dir = dirs.len() == 1 && no_files;
  93. self.options.filter.filter_argument_files(&mut files);
  94. self.print_files(None, files)?;
  95. self.print_dirs(dirs, no_files, is_only_dir, exit_status)
  96. }
  97. fn print_dirs(&mut self, dir_files: Vec<Dir>, mut first: bool, is_only_dir: bool, exit_status: i32) -> IOResult<i32> {
  98. for dir in dir_files {
  99. // Put a gap between directories, or between the list of files and
  100. // the first directory.
  101. if first {
  102. first = false;
  103. }
  104. else {
  105. write!(self.writer, "\n")?;
  106. }
  107. if !is_only_dir {
  108. let mut bits = Vec::new();
  109. escape(dir.path.display().to_string(), &mut bits, Style::default(), Style::default());
  110. writeln!(self.writer, "{}:", ANSIStrings(&bits))?;
  111. }
  112. let mut children = Vec::new();
  113. for file in dir.files(self.options.filter.dot_filter) {
  114. match file {
  115. Ok(file) => children.push(file),
  116. Err((path, e)) => writeln!(stderr(), "[{}: {}]", path.display(), e)?,
  117. }
  118. };
  119. self.options.filter.filter_child_files(&mut children);
  120. self.options.filter.sort_files(&mut children);
  121. if let Some(recurse_opts) = self.options.dir_action.recurse_options() {
  122. let depth = dir.path.components().filter(|&c| c != Component::CurDir).count() + 1;
  123. if !recurse_opts.tree && !recurse_opts.is_too_deep(depth) {
  124. let mut child_dirs = Vec::new();
  125. for child_dir in children.iter().filter(|f| f.is_directory()) {
  126. match child_dir.to_dir(false) {
  127. Ok(d) => child_dirs.push(d),
  128. Err(e) => writeln!(stderr(), "{}: {}", child_dir.path.display(), e)?,
  129. }
  130. }
  131. self.print_files(Some(&dir), children)?;
  132. match self.print_dirs(child_dirs, false, false, exit_status) {
  133. Ok(_) => (),
  134. Err(e) => return Err(e),
  135. }
  136. continue;
  137. }
  138. }
  139. self.print_files(Some(&dir), children)?;
  140. }
  141. Ok(exit_status)
  142. }
  143. /// Prints the list of files using whichever view is selected.
  144. /// For various annoying logistical reasons, each one handles
  145. /// printing differently...
  146. fn print_files(&mut self, dir: Option<&Dir>, files: Vec<File>) -> IOResult<()> {
  147. if !files.is_empty() {
  148. let View { ref mode, ref colours, ref style } = self.options.view;
  149. match *mode {
  150. Mode::Lines => {
  151. lines::Render { files, colours, style }.render(self.writer)
  152. }
  153. Mode::Grid(ref opts) => {
  154. grid::Render { files, colours, style, opts }.render(self.writer)
  155. }
  156. Mode::Details(ref opts) => {
  157. details::Render { dir, files, colours, style, opts, filter: &self.options.filter, recurse: self.options.dir_action.recurse_options() }.render(self.writer)
  158. }
  159. Mode::GridDetails(ref opts) => {
  160. 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)
  161. }
  162. }
  163. }
  164. else {
  165. Ok(())
  166. }
  167. }
  168. }