details.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. //! The **Details** output view displays each file as a row in a table.
  2. //!
  3. //! It's used in the following situations:
  4. //!
  5. //! - Most commonly, when using the `--long` command-line argument to display the
  6. //! details of each file, which requires using a table view to hold all the data;
  7. //! - When using the `--tree` argument, which uses the same table view to display
  8. //! each file on its own line, with the table providing the tree characters;
  9. //! - When using both the `--long` and `--grid` arguments, which constructs a
  10. //! series of tables to fit all the data on the screen.
  11. //!
  12. //! You will probably recognise it from the `ls --long` command. It looks like
  13. //! this:
  14. //!
  15. //! ```text
  16. //! .rw-r--r-- 9.6k ben 29 Jun 16:16 Cargo.lock
  17. //! .rw-r--r-- 547 ben 23 Jun 10:54 Cargo.toml
  18. //! .rw-r--r-- 1.1k ben 23 Nov 2014 LICENCE
  19. //! .rw-r--r-- 2.5k ben 21 May 14:38 README.md
  20. //! .rw-r--r-- 382k ben 8 Jun 21:00 screenshot.png
  21. //! drwxr-xr-x - ben 29 Jun 14:50 src
  22. //! drwxr-xr-x - ben 28 Jun 19:53 target
  23. //! ```
  24. //!
  25. //! The table is constructed by creating a `Table` value, which produces a `Row`
  26. //! value for each file. These rows can contain a vector of `Cell`s, or they can
  27. //! contain depth information for the tree view, or both. These are described
  28. //! below.
  29. //!
  30. //!
  31. //! ## Constructing Detail Views
  32. //!
  33. //! When using the `--long` command-line argument, the details of each file are
  34. //! displayed next to its name.
  35. //!
  36. //! The table holds a vector of all the column types. For each file and column, a
  37. //! `Cell` value containing the ANSI-coloured text and Unicode width of each cell
  38. //! is generated, with the row and column determined by indexing into both arrays.
  39. //!
  40. //! The column types vector does not actually include the filename. This is
  41. //! because the filename is always the rightmost field, and as such, it does not
  42. //! need to have its width queried or be padded with spaces.
  43. //!
  44. //! To illustrate the above:
  45. //!
  46. //! ```text
  47. //! โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  48. //! โ”‚ columns: [ Permissions, Size, User, Date(Modified) ] โ”‚
  49. //! โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
  50. //! โ”‚ rows: cells: filename: โ”‚
  51. //! โ”‚ row 1: [ ".rw-r--r--", "9.6k", "ben", "29 Jun 16:16" ] Cargo.lock โ”‚
  52. //! โ”‚ row 2: [ ".rw-r--r--", "547", "ben", "23 Jun 10:54" ] Cargo.toml โ”‚
  53. //! โ”‚ row 3: [ "drwxr-xr-x", "-", "ben", "29 Jun 14:50" ] src โ”‚
  54. //! โ”‚ row 4: [ "drwxr-xr-x", "-", "ben", "28 Jun 19:53" ] target โ”‚
  55. //! โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  56. //! ```
  57. //!
  58. //! Each column in the table needs to be resized to fit its widest argument. This
  59. //! means that we must wait until every row has been added to the table before it
  60. //! can be displayed, in order to make sure that every column is wide enough.
  61. use std::io::{Write, Error as IOError, Result as IOResult};
  62. use std::path::PathBuf;
  63. use std::vec::IntoIter as VecIntoIter;
  64. use fs::{Dir, File};
  65. use fs::feature::xattr::{Attribute, FileAttributes};
  66. use options::{FileFilter, RecurseOptions};
  67. use output::colours::Colours;
  68. use output::cell::TextCell;
  69. use output::tree::{TreeTrunk, TreeParams, TreeDepth};
  70. use output::file_name::{FileName, LinkStyle, Classify};
  71. use output::table::{Table, Options as TableOptions, Row as TableRow};
  72. /// With the **Details** view, the output gets formatted into columns, with
  73. /// each `Column` object showing some piece of information about the file,
  74. /// such as its size, or its permissions.
  75. ///
  76. /// To do this, the results have to be written to a table, instead of
  77. /// displaying each file immediately. Then, the width of each column can be
  78. /// calculated based on the individual results, and the fields are padded
  79. /// during output.
  80. ///
  81. /// Almost all the heavy lifting is done in a Table object, which handles the
  82. /// columns for each row.
  83. #[derive(Debug)]
  84. pub struct Options {
  85. /// Options specific to drawing a table.
  86. ///
  87. /// Directories themselves can pick which columns are *added* to this
  88. /// list, such as the Git column.
  89. pub table: Option<TableOptions>,
  90. /// Whether to show a header line or not.
  91. pub header: bool,
  92. /// Whether to show each file's extended attributes.
  93. pub xattr: bool,
  94. }
  95. pub struct Render<'a> {
  96. pub dir: Option<&'a Dir>,
  97. pub files: Vec<File<'a>>,
  98. pub colours: &'a Colours,
  99. pub classify: Classify,
  100. pub opts: &'a Options,
  101. /// Whether to recurse through directories with a tree view, and if so,
  102. /// which options to use. This field is only relevant here if the `tree`
  103. /// field of the RecurseOptions is `true`.
  104. pub recurse: Option<RecurseOptions>,
  105. /// How to sort and filter the files after getting their details.
  106. pub filter: &'a FileFilter,
  107. }
  108. struct Egg<'a> {
  109. table_row: Option<TableRow>,
  110. xattrs: Vec<Attribute>,
  111. errors: Vec<(IOError, Option<PathBuf>)>,
  112. dir: Option<Dir>,
  113. file: &'a File<'a>,
  114. }
  115. impl<'a> AsRef<File<'a>> for Egg<'a> {
  116. fn as_ref(&self) -> &File<'a> {
  117. self.file
  118. }
  119. }
  120. impl<'a> Render<'a> {
  121. pub fn render<W: Write>(self, w: &mut W) -> IOResult<()> {
  122. let mut rows = Vec::new();
  123. if let Some(ref table) = self.opts.table {
  124. let mut table = Table::new(&table, self.dir, &self.colours);
  125. if self.opts.header {
  126. let header = table.header_row();
  127. table.add_widths(&header);
  128. rows.push(self.render_header(header));
  129. }
  130. // This is weird, but I can't find a way around it:
  131. // https://internals.rust-lang.org/t/should-option-mut-t-implement-copy/3715/6
  132. let mut table = Some(table);
  133. self.add_files_to_table(&mut table, &mut rows, &self.files, TreeDepth::root());
  134. for row in self.iterate_with_table(table.unwrap(), rows) {
  135. writeln!(w, "{}", row.strings())?
  136. }
  137. }
  138. else {
  139. self.add_files_to_table(&mut None, &mut rows, &self.files, TreeDepth::root());
  140. for row in self.iterate(rows) {
  141. writeln!(w, "{}", row.strings())?
  142. }
  143. }
  144. Ok(())
  145. }
  146. /// Adds files to the table, possibly recursively. This is easily
  147. /// parallelisable, and uses a pool of threads.
  148. fn add_files_to_table<'dir>(&self, table: &mut Option<Table<'a>>, rows: &mut Vec<Row>, src: &Vec<File<'dir>>, depth: TreeDepth) {
  149. use num_cpus;
  150. use scoped_threadpool::Pool;
  151. use std::sync::{Arc, Mutex};
  152. use fs::feature::xattr;
  153. let mut pool = Pool::new(num_cpus::get() as u32);
  154. let mut file_eggs = Vec::new();
  155. pool.scoped(|scoped| {
  156. let file_eggs = Arc::new(Mutex::new(&mut file_eggs));
  157. let table = table.as_ref();
  158. for file in src {
  159. let file_eggs = file_eggs.clone();
  160. scoped.execute(move || {
  161. let mut errors = Vec::new();
  162. let mut xattrs = Vec::new();
  163. if xattr::ENABLED {
  164. match file.path.attributes() {
  165. Ok(xs) => xattrs.extend(xs),
  166. Err(e) => errors.push((e, None)),
  167. };
  168. }
  169. let table_row = table.as_ref().map(|t| t.row_for_file(&file, !xattrs.is_empty()));
  170. if !self.opts.xattr {
  171. xattrs.clear();
  172. }
  173. let mut dir = None;
  174. if let Some(r) = self.recurse {
  175. if file.is_directory() && r.tree && !r.is_too_deep(depth.0) {
  176. match file.to_dir(false) {
  177. Ok(d) => { dir = Some(d); },
  178. Err(e) => { errors.push((e, None)) },
  179. }
  180. }
  181. };
  182. let egg = Egg { table_row, xattrs, errors, dir, file };
  183. file_eggs.lock().unwrap().push(egg);
  184. });
  185. }
  186. });
  187. self.filter.sort_files(&mut file_eggs);
  188. for (tree_params, egg) in depth.iterate_over(file_eggs.into_iter()) {
  189. let mut files = Vec::new();
  190. let mut errors = egg.errors;
  191. if let (Some(ref mut t), Some(ref row)) = (table.as_mut(), egg.table_row.as_ref()) {
  192. t.add_widths(row);
  193. }
  194. let row = Row {
  195. tree: tree_params,
  196. cells: egg.table_row,
  197. name: FileName::new(&egg.file, LinkStyle::FullLinkPaths, self.classify, self.colours).paint().promote(),
  198. };
  199. rows.push(row);
  200. if let Some(ref dir) = egg.dir {
  201. for file_to_add in dir.files(self.filter.dot_filter) {
  202. match file_to_add {
  203. Ok(f) => files.push(f),
  204. Err((path, e)) => errors.push((e, Some(path)))
  205. }
  206. }
  207. self.filter.filter_child_files(&mut files);
  208. if !files.is_empty() {
  209. for xattr in egg.xattrs {
  210. rows.push(self.render_xattr(xattr, TreeParams::new(depth.deeper(), false)));
  211. }
  212. for (error, path) in errors {
  213. rows.push(self.render_error(&error, TreeParams::new(depth.deeper(), false), path));
  214. }
  215. self.add_files_to_table(table, rows, &files, depth.deeper());
  216. continue;
  217. }
  218. }
  219. let count = egg.xattrs.len();
  220. for (index, xattr) in egg.xattrs.into_iter().enumerate() {
  221. rows.push(self.render_xattr(xattr, TreeParams::new(depth.deeper(), errors.is_empty() && index == count - 1)));
  222. }
  223. let count = errors.len();
  224. for (index, (error, path)) in errors.into_iter().enumerate() {
  225. rows.push(self.render_error(&error, TreeParams::new(depth.deeper(), index == count - 1), path));
  226. }
  227. }
  228. }
  229. pub fn render_header(&self, header: TableRow) -> Row {
  230. Row {
  231. tree: TreeParams::new(TreeDepth::root(), false),
  232. cells: Some(header),
  233. name: TextCell::paint_str(self.colours.header, "Name"),
  234. }
  235. }
  236. fn render_error(&self, error: &IOError, tree: TreeParams, path: Option<PathBuf>) -> Row {
  237. let error_message = match path {
  238. Some(path) => format!("<{}: {}>", path.display(), error),
  239. None => format!("<{}>", error),
  240. };
  241. let name = TextCell::paint(self.colours.broken_arrow, error_message);
  242. Row { cells: None, name, tree }
  243. }
  244. fn render_xattr(&self, xattr: Attribute, tree: TreeParams) -> Row {
  245. let name = TextCell::paint(self.colours.perms.attribute, format!("{} (len {})", xattr.name, xattr.size));
  246. Row { cells: None, name, tree }
  247. }
  248. pub fn render_file(&self, cells: TableRow, name: TextCell, tree: TreeParams) -> Row {
  249. Row { cells: Some(cells), name, tree }
  250. }
  251. pub fn iterate_with_table(&'a self, table: Table<'a>, rows: Vec<Row>) -> TableIter<'a> {
  252. TableIter {
  253. tree_trunk: TreeTrunk::default(),
  254. total_width: table.widths().total(),
  255. table: table,
  256. inner: rows.into_iter(),
  257. colours: self.colours,
  258. }
  259. }
  260. pub fn iterate(&'a self, rows: Vec<Row>) -> Iter<'a> {
  261. Iter {
  262. tree_trunk: TreeTrunk::default(),
  263. inner: rows.into_iter(),
  264. colours: self.colours,
  265. }
  266. }
  267. }
  268. pub struct Row {
  269. /// Vector of cells to display.
  270. ///
  271. /// Most of the rows will be used to display files' metadata, so this will
  272. /// almost always be `Some`, containing a vector of cells. It will only be
  273. /// `None` for a row displaying an attribute or error, neither of which
  274. /// have cells.
  275. pub cells: Option<TableRow>,
  276. /// This file's name, in coloured output. The name is treated separately
  277. /// from the other cells, as it never requires padding.
  278. pub name: TextCell,
  279. /// Information used to determine which symbols to display in a tree.
  280. pub tree: TreeParams,
  281. }
  282. pub struct TableIter<'a> {
  283. table: Table<'a>,
  284. tree_trunk: TreeTrunk,
  285. total_width: usize,
  286. colours: &'a Colours,
  287. inner: VecIntoIter<Row>,
  288. }
  289. impl<'a> Iterator for TableIter<'a> {
  290. type Item = TextCell;
  291. fn next(&mut self) -> Option<Self::Item> {
  292. self.inner.next().map(|row| {
  293. let mut cell =
  294. if let Some(cells) = row.cells {
  295. self.table.render(cells)
  296. }
  297. else {
  298. let mut cell = TextCell::default();
  299. cell.add_spaces(self.total_width);
  300. cell
  301. };
  302. for tree_part in self.tree_trunk.new_row(row.tree) {
  303. cell.push(self.colours.punctuation.paint(tree_part.ascii_art()), 4);
  304. }
  305. // If any tree characters have been printed, then add an extra
  306. // space, which makes the output look much better.
  307. if !row.tree.is_at_root() {
  308. cell.add_spaces(1);
  309. }
  310. cell.append(row.name);
  311. cell
  312. })
  313. }
  314. }
  315. pub struct Iter<'a> {
  316. tree_trunk: TreeTrunk,
  317. colours: &'a Colours,
  318. inner: VecIntoIter<Row>,
  319. }
  320. impl<'a> Iterator for Iter<'a> {
  321. type Item = TextCell;
  322. fn next(&mut self) -> Option<Self::Item> {
  323. self.inner.next().map(|row| {
  324. let mut cell = TextCell::default();
  325. for tree_part in self.tree_trunk.new_row(row.tree) {
  326. cell.push(self.colours.punctuation.paint(tree_part.ascii_art()), 4);
  327. }
  328. // If any tree characters have been printed, then add an extra
  329. // space, which makes the output look much better.
  330. if !row.tree.is_at_root() {
  331. cell.add_spaces(1);
  332. }
  333. cell.append(row.name);
  334. cell
  335. })
  336. }
  337. }