details.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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::{self, Write};
  62. use std::mem::MaybeUninit;
  63. use std::path::PathBuf;
  64. use std::vec::IntoIter as VecIntoIter;
  65. use ansi_term::Style;
  66. use scoped_threadpool::Pool;
  67. use crate::fs::{Dir, File};
  68. use crate::fs::dir_action::RecurseOptions;
  69. use crate::fs::feature::git::GitCache;
  70. use crate::fs::feature::xattr::Attribute;
  71. use crate::fs::fields::SecurityContextType;
  72. use crate::fs::filter::FileFilter;
  73. use crate::output::cell::TextCell;
  74. use crate::output::file_name::Options as FileStyle;
  75. use crate::output::table::{Table, Options as TableOptions, Row as TableRow};
  76. use crate::output::tree::{TreeTrunk, TreeParams, TreeDepth};
  77. use crate::theme::Theme;
  78. /// With the **Details** view, the output gets formatted into columns, with
  79. /// each `Column` object showing some piece of information about the file,
  80. /// such as its size, or its permissions.
  81. ///
  82. /// To do this, the results have to be written to a table, instead of
  83. /// displaying each file immediately. Then, the width of each column can be
  84. /// calculated based on the individual results, and the fields are padded
  85. /// during output.
  86. ///
  87. /// Almost all the heavy lifting is done in a Table object, which handles the
  88. /// columns for each row.
  89. #[derive(PartialEq, Eq, Debug)]
  90. pub struct Options {
  91. /// Options specific to drawing a table.
  92. ///
  93. /// Directories themselves can pick which columns are *added* to this
  94. /// list, such as the Git column.
  95. pub table: Option<TableOptions>,
  96. /// Whether to show a header line or not.
  97. pub header: bool,
  98. /// Whether to show each fileโ€™s extended attributes.
  99. pub xattr: bool,
  100. /// Whether to show each file's security attribute.
  101. pub secattr: bool,
  102. }
  103. pub struct Render<'a> {
  104. pub dir: Option<&'a Dir>,
  105. pub files: Vec<File<'a>>,
  106. pub theme: &'a Theme,
  107. pub file_style: &'a FileStyle,
  108. pub opts: &'a Options,
  109. /// Whether to recurse through directories with a tree view, and if so,
  110. /// which options to use. This field is only relevant here if the `tree`
  111. /// field of the RecurseOptions is `true`.
  112. pub recurse: Option<RecurseOptions>,
  113. /// How to sort and filter the files after getting their details.
  114. pub filter: &'a FileFilter,
  115. /// Whether we are skipping Git-ignored files.
  116. pub git_ignoring: bool,
  117. pub git: Option<&'a GitCache>,
  118. }
  119. struct Egg<'a> {
  120. table_row: Option<TableRow>,
  121. xattrs: &'a [Attribute],
  122. errors: Vec<(io::Error, Option<PathBuf>)>,
  123. dir: Option<Dir>,
  124. file: &'a File<'a>,
  125. }
  126. impl<'a> AsRef<File<'a>> for Egg<'a> {
  127. fn as_ref(&self) -> &File<'a> {
  128. self.file
  129. }
  130. }
  131. impl<'a> Render<'a> {
  132. pub fn render<W: Write>(mut self, w: &mut W) -> io::Result<()> {
  133. let n_cpus = match num_cpus::get() as u32 {
  134. 0 => 1,
  135. n => n,
  136. };
  137. let mut pool = Pool::new(n_cpus);
  138. let mut rows = Vec::new();
  139. if let Some(ref table) = self.opts.table {
  140. match (self.git, self.dir) {
  141. (Some(g), Some(d)) => if ! g.has_anything_for(&d.path) { self.git = None },
  142. (Some(g), None) => if ! self.files.iter().any(|f| g.has_anything_for(&f.path)) { self.git = None },
  143. (None, _) => {/* Keep Git how it is */},
  144. }
  145. let mut table = Table::new(table, self.git, self.theme);
  146. if self.opts.header {
  147. let header = table.header_row();
  148. table.add_widths(&header);
  149. rows.push(self.render_header(header));
  150. }
  151. // This is weird, but I canโ€™t find a way around it:
  152. // https://internals.rust-lang.org/t/should-option-mut-t-implement-copy/3715/6
  153. let mut table = Some(table);
  154. self.add_files_to_table(&mut pool, &mut table, &mut rows, &self.files, TreeDepth::root());
  155. for row in self.iterate_with_table(table.unwrap(), rows) {
  156. writeln!(w, "{}", row.strings())?
  157. }
  158. }
  159. else {
  160. self.add_files_to_table(&mut pool, &mut None, &mut rows, &self.files, TreeDepth::root());
  161. for row in self.iterate(rows) {
  162. writeln!(w, "{}", row.strings())?
  163. }
  164. }
  165. Ok(())
  166. }
  167. /// Whether to show the extended attribute hint
  168. pub fn show_xattr_hint(&self, file: &File<'_>) -> bool {
  169. // Do not show the hint '@' if the only extended attribute is the security
  170. // attribute and the security attribute column is active.
  171. let xattr_count = file.extended_attributes.len();
  172. let selinux_ctx_shown = self.opts.secattr && match file.security_context().context {
  173. SecurityContextType::SELinux(_) => true,
  174. SecurityContextType::None => false,
  175. };
  176. xattr_count > 1 || (xattr_count == 1 && !selinux_ctx_shown)
  177. }
  178. /// Adds files to the table, possibly recursively. This is easily
  179. /// parallelisable, and uses a pool of threads.
  180. fn add_files_to_table<'dir>(&self, pool: &mut Pool, table: &mut Option<Table<'a>>, rows: &mut Vec<Row>, src: &[File<'dir>], depth: TreeDepth) {
  181. use std::sync::{Arc, Mutex};
  182. use crate::fs::feature::xattr;
  183. let mut file_eggs = (0..src.len()).map(|_| MaybeUninit::uninit()).collect::<Vec<_>>();
  184. pool.scoped(|scoped| {
  185. let file_eggs = Arc::new(Mutex::new(&mut file_eggs));
  186. let table = table.as_ref();
  187. for (idx, file) in src.iter().enumerate() {
  188. let file_eggs = Arc::clone(&file_eggs);
  189. scoped.execute(move || {
  190. let mut errors = Vec::new();
  191. // There are three โ€œlevelsโ€ of extended attribute support:
  192. //
  193. // 1. If weโ€™re compiling without that feature, then
  194. // exa pretends all files have no attributes.
  195. // 2. If the feature is enabled and the --extended flag
  196. // has been specified, then display an @ in the
  197. // permissions column for files with attributes, the
  198. // names of all attributes and their values, and any
  199. // errors encountered when getting them.
  200. // 3. If the --extended flag *hasnโ€™t* been specified, then
  201. // display the @, but donโ€™t display anything else.
  202. //
  203. // For a while, exa took a stricter approach to (3):
  204. // if an error occurred while checking a fileโ€™s xattrs to
  205. // see if it should display the @, exa would display that
  206. // error even though the attributes werenโ€™t actually being
  207. // shown! This was confusing, as users were being shown
  208. // errors for something they didnโ€™t explicitly ask for,
  209. // and just cluttered up the output. So now errors arenโ€™t
  210. // printed unless the user passes --extended to signify
  211. // that they want to see them.
  212. let xattrs: &[Attribute] = if xattr::ENABLED && self.opts.xattr {
  213. &file.extended_attributes
  214. } else {
  215. &[]
  216. };
  217. let table_row = table.as_ref()
  218. .map(|t| t.row_for_file(file, self.show_xattr_hint(file)));
  219. let mut dir = None;
  220. if let Some(r) = self.recurse {
  221. if file.is_directory() && r.tree && ! r.is_too_deep(depth.0) {
  222. match file.to_dir() {
  223. Ok(d) => {
  224. dir = Some(d);
  225. }
  226. Err(e) => {
  227. errors.push((e, None));
  228. }
  229. }
  230. }
  231. };
  232. let egg = Egg { table_row, xattrs, errors, dir, file };
  233. unsafe { std::ptr::write(file_eggs.lock().unwrap()[idx].as_mut_ptr(), egg) }
  234. });
  235. }
  236. });
  237. // this is safe because all entries have been initialized above
  238. let mut file_eggs = unsafe { std::mem::transmute::<_, Vec<Egg<'_>>>(file_eggs) };
  239. self.filter.sort_files(&mut file_eggs);
  240. for (tree_params, egg) in depth.iterate_over(file_eggs.into_iter()) {
  241. let mut files = Vec::new();
  242. let mut errors = egg.errors;
  243. if let (Some(ref mut t), Some(row)) = (table.as_mut(), egg.table_row.as_ref()) {
  244. t.add_widths(row);
  245. }
  246. let file_name = self.file_style.for_file(egg.file, self.theme)
  247. .with_link_paths()
  248. .paint()
  249. .promote();
  250. let row = Row {
  251. tree: tree_params,
  252. cells: egg.table_row,
  253. name: file_name,
  254. };
  255. rows.push(row);
  256. if let Some(ref dir) = egg.dir {
  257. for file_to_add in dir.files(self.filter.dot_filter, self.git, self.git_ignoring) {
  258. match file_to_add {
  259. Ok(f) => {
  260. files.push(f);
  261. }
  262. Err((path, e)) => {
  263. errors.push((e, Some(path)));
  264. }
  265. }
  266. }
  267. self.filter.filter_child_files(&mut files);
  268. if ! files.is_empty() {
  269. for xattr in egg.xattrs {
  270. rows.push(self.render_xattr(xattr, TreeParams::new(depth.deeper(), false)));
  271. }
  272. for (error, path) in errors {
  273. rows.push(self.render_error(&error, TreeParams::new(depth.deeper(), false), path));
  274. }
  275. self.add_files_to_table(pool, table, rows, &files, depth.deeper());
  276. continue;
  277. }
  278. }
  279. let count = egg.xattrs.len();
  280. for (index, xattr) in egg.xattrs.into_iter().enumerate() {
  281. let params = TreeParams::new(depth.deeper(), errors.is_empty() && index == count - 1);
  282. let r = self.render_xattr(xattr, params);
  283. rows.push(r);
  284. }
  285. let count = errors.len();
  286. for (index, (error, path)) in errors.into_iter().enumerate() {
  287. let params = TreeParams::new(depth.deeper(), index == count - 1);
  288. let r = self.render_error(&error, params, path);
  289. rows.push(r);
  290. }
  291. }
  292. }
  293. pub fn render_header(&self, header: TableRow) -> Row {
  294. Row {
  295. tree: TreeParams::new(TreeDepth::root(), false),
  296. cells: Some(header),
  297. name: TextCell::paint_str(self.theme.ui.header, "Name"),
  298. }
  299. }
  300. fn render_error(&self, error: &io::Error, tree: TreeParams, path: Option<PathBuf>) -> Row {
  301. use crate::output::file_name::Colours;
  302. let error_message = if let Some(path) = path {
  303. format!("<{}: {}>", path.display(), error)
  304. } else {
  305. format!("<{}>", error)
  306. };
  307. // TODO: broken_symlink() doesnโ€™t quite seem like the right name for
  308. // the style thatโ€™s being used here. Maybe split it in two?
  309. let name = TextCell::paint(self.theme.broken_symlink(), error_message);
  310. Row { cells: None, name, tree }
  311. }
  312. fn render_xattr(&self, xattr: &Attribute, tree: TreeParams) -> Row {
  313. let name = TextCell::paint(self.theme.ui.perms.attribute, format!("{}=\"{}\"", xattr.name, xattr.value));
  314. Row { cells: None, name, tree }
  315. }
  316. pub fn render_file(&self, cells: TableRow, name: TextCell, tree: TreeParams) -> Row {
  317. Row { cells: Some(cells), name, tree }
  318. }
  319. pub fn iterate_with_table(&'a self, table: Table<'a>, rows: Vec<Row>) -> TableIter<'a> {
  320. TableIter {
  321. tree_trunk: TreeTrunk::default(),
  322. total_width: table.widths().total(),
  323. table,
  324. inner: rows.into_iter(),
  325. tree_style: self.theme.ui.punctuation,
  326. }
  327. }
  328. pub fn iterate(&'a self, rows: Vec<Row>) -> Iter {
  329. Iter {
  330. tree_trunk: TreeTrunk::default(),
  331. inner: rows.into_iter(),
  332. tree_style: self.theme.ui.punctuation,
  333. }
  334. }
  335. }
  336. pub struct Row {
  337. /// Vector of cells to display.
  338. ///
  339. /// Most of the rows will be used to display filesโ€™ metadata, so this will
  340. /// almost always be `Some`, containing a vector of cells. It will only be
  341. /// `None` for a row displaying an attribute or error, neither of which
  342. /// have cells.
  343. pub cells: Option<TableRow>,
  344. /// This fileโ€™s name, in coloured output. The name is treated separately
  345. /// from the other cells, as it never requires padding.
  346. pub name: TextCell,
  347. /// Information used to determine which symbols to display in a tree.
  348. pub tree: TreeParams,
  349. }
  350. pub struct TableIter<'a> {
  351. inner: VecIntoIter<Row>,
  352. table: Table<'a>,
  353. total_width: usize,
  354. tree_style: Style,
  355. tree_trunk: TreeTrunk,
  356. }
  357. impl<'a> Iterator for TableIter<'a> {
  358. type Item = TextCell;
  359. fn next(&mut self) -> Option<Self::Item> {
  360. self.inner.next().map(|row| {
  361. let mut cell =
  362. if let Some(cells) = row.cells {
  363. self.table.render(cells)
  364. }
  365. else {
  366. let mut cell = TextCell::default();
  367. cell.add_spaces(self.total_width);
  368. cell
  369. };
  370. for tree_part in self.tree_trunk.new_row(row.tree) {
  371. cell.push(self.tree_style.paint(tree_part.ascii_art()), 4);
  372. }
  373. // If any tree characters have been printed, then add an extra
  374. // space, which makes the output look much better.
  375. if ! row.tree.is_at_root() {
  376. cell.add_spaces(1);
  377. }
  378. cell.append(row.name);
  379. cell
  380. })
  381. }
  382. }
  383. pub struct Iter {
  384. tree_trunk: TreeTrunk,
  385. tree_style: Style,
  386. inner: VecIntoIter<Row>,
  387. }
  388. impl Iterator for Iter {
  389. type Item = TextCell;
  390. fn next(&mut self) -> Option<Self::Item> {
  391. self.inner.next().map(|row| {
  392. let mut cell = TextCell::default();
  393. for tree_part in self.tree_trunk.new_row(row.tree) {
  394. cell.push(self.tree_style.paint(tree_part.ascii_art()), 4);
  395. }
  396. // If any tree characters have been printed, then add an extra
  397. // space, which makes the output look much better.
  398. if ! row.tree.is_at_root() {
  399. cell.add_spaces(1);
  400. }
  401. cell.append(row.name);
  402. cell
  403. })
  404. }
  405. }