details.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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. //!
  62. //!
  63. //! ## Extended Attributes and Errors
  64. //!
  65. //! Finally, files' extended attributes and any errors that occur while statting
  66. //! them can also be displayed as their children. It looks like this:
  67. //!
  68. //! ```text
  69. //! .rw-r--r-- 0 ben 3 Sep 13:26 forbidden
  70. //! โ””โ”€โ”€ <Permission denied (os error 13)>
  71. //! .rw-r--r--@ 0 ben 3 Sep 13:26 file_with_xattrs
  72. //! โ”œโ”€โ”€ another_greeting (len 2)
  73. //! โ””โ”€โ”€ greeting (len 5)
  74. //! ```
  75. //!
  76. //! These lines also have `None` cells, and the error string or attribute details
  77. //! are used in place of the filename.
  78. use std::io::{Write, Error as IOError, Result as IOResult};
  79. use std::ops::Add;
  80. use std::path::PathBuf;
  81. use std::string::ToString;
  82. use std::sync::{Arc, Mutex};
  83. use ansi_term::Style;
  84. use datetime::fmt::DateFormat;
  85. use datetime::{LocalDateTime, DatePiece};
  86. use datetime::TimeZone;
  87. use zoneinfo_compiled::{CompiledData, Result as TZResult};
  88. use locale;
  89. use users::{Users, Groups, UsersCache};
  90. use fs::{Dir, File, fields as f};
  91. use fs::feature::xattr::{Attribute, FileAttributes};
  92. use options::{FileFilter, RecurseOptions};
  93. use output::colours::Colours;
  94. use output::column::{Alignment, Column, Columns, SizeFormat};
  95. use output::cell::{TextCell, DisplayWidth};
  96. use output::tree::TreeTrunk;
  97. use super::filename;
  98. /// With the **Details** view, the output gets formatted into columns, with
  99. /// each `Column` object showing some piece of information about the file,
  100. /// such as its size, or its permissions.
  101. ///
  102. /// To do this, the results have to be written to a table, instead of
  103. /// displaying each file immediately. Then, the width of each column can be
  104. /// calculated based on the individual results, and the fields are padded
  105. /// during output.
  106. ///
  107. /// Almost all the heavy lifting is done in a Table object, which handles the
  108. /// columns for each row.
  109. #[derive(PartialEq, Debug, Clone, Default)]
  110. pub struct Details {
  111. /// A Columns object that says which columns should be included in the
  112. /// output in the general case. Directories themselves can pick which
  113. /// columns are *added* to this list, such as the Git column.
  114. pub columns: Option<Columns>,
  115. /// Whether to recurse through directories with a tree view, and if so,
  116. /// which options to use. This field is only relevant here if the `tree`
  117. /// field of the RecurseOptions is `true`.
  118. pub recurse: Option<RecurseOptions>,
  119. /// How to sort and filter the files after getting their details.
  120. pub filter: FileFilter,
  121. /// Whether to show a header line or not.
  122. pub header: bool,
  123. /// Whether to show each file's extended attributes.
  124. pub xattr: bool,
  125. /// The colours to use to display information in the table, including the
  126. /// colour of the tree view symbols.
  127. pub colours: Colours,
  128. /// Whether to show a file type indiccator.
  129. pub classify: bool,
  130. }
  131. /// The **environment** struct contains any data that could change between
  132. /// running instances of exa, depending on the user's computer's configuration.
  133. ///
  134. /// Any environment field should be able to be mocked up for test runs.
  135. pub struct Environment<U: Users+Groups> {
  136. /// The year of the current time. This gets used to determine which date
  137. /// format to use.
  138. current_year: i64,
  139. /// Localisation rules for formatting numbers.
  140. numeric: locale::Numeric,
  141. /// Localisation rules for formatting timestamps.
  142. time: locale::Time,
  143. /// The computer's current time zone. This gets used to determine how to
  144. /// offset files' timestamps.
  145. tz: Option<TimeZone>,
  146. /// Mapping cache of user IDs to usernames.
  147. users: Mutex<U>,
  148. }
  149. impl Default for Environment<UsersCache> {
  150. fn default() -> Self {
  151. let tz = determine_time_zone();
  152. if let Err(ref e) = tz {
  153. println!("Unable to determine time zone: {}", e);
  154. }
  155. Environment {
  156. current_year: LocalDateTime::now().year(),
  157. numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()),
  158. time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()),
  159. tz: tz.ok(),
  160. users: Mutex::new(UsersCache::new()),
  161. }
  162. }
  163. }
  164. fn determine_time_zone() -> TZResult<TimeZone> {
  165. TimeZone::from_file("/etc/localtime")
  166. }
  167. impl Details {
  168. /// Print the details of the given vector of files -- all of which will
  169. /// have been read from the given directory, if present -- to stdout.
  170. pub fn view<W: Write>(&self, dir: Option<&Dir>, files: Vec<File>, w: &mut W) -> IOResult<()> {
  171. // First, transform the Columns object into a vector of columns for
  172. // the current directory.
  173. let columns_for_dir = match self.columns {
  174. Some(cols) => cols.for_dir(dir),
  175. None => Vec::new(),
  176. };
  177. // Then, retrieve various environment variables.
  178. let env = Arc::new(Environment::<UsersCache>::default());
  179. // Build the table to put rows in.
  180. let mut table = Table {
  181. columns: &*columns_for_dir,
  182. opts: self,
  183. env: env,
  184. rows: Vec::new(),
  185. };
  186. // Next, add a header if the user requests it.
  187. if self.header { table.add_header() }
  188. // Then add files to the table and print it out.
  189. self.add_files_to_table(&mut table, files, 0);
  190. for cell in table.print_table() {
  191. writeln!(w, "{}", cell.strings())?;
  192. }
  193. Ok(())
  194. }
  195. /// Adds files to the table, possibly recursively. This is easily
  196. /// parallelisable, and uses a pool of threads.
  197. fn add_files_to_table<'dir, U: Users+Groups+Send>(&self, mut table: &mut Table<U>, src: Vec<File<'dir>>, depth: usize) {
  198. use num_cpus;
  199. use scoped_threadpool::Pool;
  200. use std::sync::{Arc, Mutex};
  201. use fs::feature::xattr;
  202. let mut pool = Pool::new(num_cpus::get() as u32);
  203. let mut file_eggs = Vec::new();
  204. struct Egg<'a> {
  205. cells: Vec<TextCell>,
  206. xattrs: Vec<Attribute>,
  207. errors: Vec<(IOError, Option<PathBuf>)>,
  208. dir: Option<Dir>,
  209. file: File<'a>,
  210. }
  211. impl<'a> AsRef<File<'a>> for Egg<'a> {
  212. fn as_ref(&self) -> &File<'a> {
  213. &self.file
  214. }
  215. }
  216. pool.scoped(|scoped| {
  217. let file_eggs = Arc::new(Mutex::new(&mut file_eggs));
  218. let table = Arc::new(&mut table);
  219. for file in src {
  220. let file_eggs = file_eggs.clone();
  221. let table = table.clone();
  222. scoped.execute(move || {
  223. let mut errors = Vec::new();
  224. let mut xattrs = Vec::new();
  225. if xattr::ENABLED {
  226. match file.path.attributes() {
  227. Ok(xs) => xattrs.extend(xs),
  228. Err(e) => errors.push((e, None)),
  229. };
  230. }
  231. let cells = table.cells_for_file(&file, !xattrs.is_empty());
  232. if !table.opts.xattr {
  233. xattrs.clear();
  234. }
  235. let mut dir = None;
  236. if let Some(r) = self.recurse {
  237. if file.is_directory() && r.tree && !r.is_too_deep(depth) {
  238. if let Ok(d) = file.to_dir(false) {
  239. dir = Some(d);
  240. }
  241. }
  242. };
  243. let egg = Egg {
  244. cells: cells,
  245. xattrs: xattrs,
  246. errors: errors,
  247. dir: dir,
  248. file: file,
  249. };
  250. file_eggs.lock().unwrap().push(egg);
  251. });
  252. }
  253. });
  254. self.filter.sort_files(&mut file_eggs);
  255. let num_eggs = file_eggs.len();
  256. for (index, egg) in file_eggs.into_iter().enumerate() {
  257. let mut files = Vec::new();
  258. let mut errors = egg.errors;
  259. let mut width = DisplayWidth::from_file(&egg.file, self.classify);
  260. if egg.file.dir.is_none() {
  261. if let Some(parent) = egg.file.path.parent() {
  262. width = width + 1 + DisplayWidth::from(parent.to_string_lossy().as_ref());
  263. }
  264. }
  265. let name = TextCell {
  266. contents: filename(&egg.file, &self.colours, true, self.classify),
  267. width: width,
  268. };
  269. let row = Row {
  270. depth: depth,
  271. cells: Some(egg.cells),
  272. name: name,
  273. last: index == num_eggs - 1,
  274. };
  275. table.rows.push(row);
  276. if let Some(ref dir) = egg.dir {
  277. for file_to_add in dir.files() {
  278. match file_to_add {
  279. Ok(f) => files.push(f),
  280. Err((path, e)) => errors.push((e, Some(path)))
  281. }
  282. }
  283. self.filter.filter_child_files(&mut files);
  284. if !files.is_empty() {
  285. for xattr in egg.xattrs {
  286. table.add_xattr(xattr, depth + 1, false);
  287. }
  288. for (error, path) in errors {
  289. table.add_error(&error, depth + 1, false, path);
  290. }
  291. self.add_files_to_table(table, files, depth + 1);
  292. continue;
  293. }
  294. }
  295. let count = egg.xattrs.len();
  296. for (index, xattr) in egg.xattrs.into_iter().enumerate() {
  297. table.add_xattr(xattr, depth + 1, errors.is_empty() && index == count - 1);
  298. }
  299. let count = errors.len();
  300. for (index, (error, path)) in errors.into_iter().enumerate() {
  301. table.add_error(&error, depth + 1, index == count - 1, path);
  302. }
  303. }
  304. }
  305. }
  306. pub struct Row {
  307. /// Vector of cells to display.
  308. ///
  309. /// Most of the rows will be used to display files' metadata, so this will
  310. /// almost always be `Some`, containing a vector of cells. It will only be
  311. /// `None` for a row displaying an attribute or error, neither of which
  312. /// have cells.
  313. cells: Option<Vec<TextCell>>,
  314. /// This file's name, in coloured output. The name is treated separately
  315. /// from the other cells, as it never requires padding.
  316. name: TextCell,
  317. /// How many directories deep into the tree structure this is. Directories
  318. /// on top have depth 0.
  319. depth: usize,
  320. /// Whether this is the last entry in the directory. This flag is used
  321. /// when calculating the tree view.
  322. last: bool,
  323. }
  324. impl Row {
  325. /// Gets the Unicode display width of the indexed column, if present. If
  326. /// not, returns 0.
  327. fn column_width(&self, index: usize) -> usize {
  328. match self.cells {
  329. Some(ref cells) => *cells[index].width,
  330. None => 0,
  331. }
  332. }
  333. }
  334. /// A **Table** object gets built up by the view as it lists files and
  335. /// directories.
  336. pub struct Table<'a, U: Users+Groups+'a> {
  337. pub rows: Vec<Row>,
  338. pub columns: &'a [Column],
  339. pub opts: &'a Details,
  340. pub env: Arc<Environment<U>>,
  341. }
  342. impl<'a, U: Users+Groups+'a> Table<'a, U> {
  343. /// Add a dummy "header" row to the table, which contains the names of all
  344. /// the columns, underlined. This has dummy data for the cases that aren't
  345. /// actually used, such as the depth or list of attributes.
  346. pub fn add_header(&mut self) {
  347. let row = Row {
  348. depth: 0,
  349. cells: Some(self.columns.iter().map(|c| TextCell::paint_str(self.opts.colours.header, c.header())).collect()),
  350. name: TextCell::paint_str(self.opts.colours.header, "Name"),
  351. last: false,
  352. };
  353. self.rows.push(row);
  354. }
  355. fn add_error(&mut self, error: &IOError, depth: usize, last: bool, path: Option<PathBuf>) {
  356. let error_message = match path {
  357. Some(path) => format!("<{}: {}>", path.display(), error),
  358. None => format!("<{}>", error),
  359. };
  360. let row = Row {
  361. depth: depth,
  362. cells: None,
  363. name: TextCell::paint(self.opts.colours.broken_arrow, error_message),
  364. last: last,
  365. };
  366. self.rows.push(row);
  367. }
  368. fn add_xattr(&mut self, xattr: Attribute, depth: usize, last: bool) {
  369. let row = Row {
  370. depth: depth,
  371. cells: None,
  372. name: TextCell::paint(self.opts.colours.perms.attribute, format!("{} (len {})", xattr.name, xattr.size)),
  373. last: last,
  374. };
  375. self.rows.push(row);
  376. }
  377. pub fn filename_cell(&self, file: File, links: bool) -> TextCell {
  378. let mut width = DisplayWidth::from_file(&file, self.opts.classify);
  379. if file.dir.is_none() {
  380. if let Some(parent) = file.path.parent() {
  381. width = width + 1 + DisplayWidth::from(parent.to_string_lossy().as_ref());
  382. }
  383. }
  384. TextCell {
  385. contents: filename(&file, &self.opts.colours, links, self.opts.classify),
  386. width: width,
  387. }
  388. }
  389. pub fn add_file_with_cells(&mut self, cells: Vec<TextCell>, name_cell: TextCell, depth: usize, last: bool) {
  390. let row = Row {
  391. depth: depth,
  392. cells: Some(cells),
  393. name: name_cell,
  394. last: last,
  395. };
  396. self.rows.push(row);
  397. }
  398. /// Use the list of columns to find which cells should be produced for
  399. /// this file, per-column.
  400. pub fn cells_for_file(&self, file: &File, xattrs: bool) -> Vec<TextCell> {
  401. self.columns.iter()
  402. .map(|c| self.display(file, c, xattrs))
  403. .collect()
  404. }
  405. fn display(&self, file: &File, column: &Column, xattrs: bool) -> TextCell {
  406. use output::column::TimeType::*;
  407. match *column {
  408. Column::Permissions => self.render_permissions(file.type_char(), file.permissions(), xattrs),
  409. Column::FileSize(fmt) => self.render_size(file.size(), fmt),
  410. Column::Timestamp(Modified) => self.render_time(file.modified_time()),
  411. Column::Timestamp(Created) => self.render_time(file.created_time()),
  412. Column::Timestamp(Accessed) => self.render_time(file.accessed_time()),
  413. Column::HardLinks => self.render_links(file.links()),
  414. Column::Inode => self.render_inode(file.inode()),
  415. Column::Blocks => self.render_blocks(file.blocks()),
  416. Column::User => self.render_user(file.user()),
  417. Column::Group => self.render_group(file.group()),
  418. Column::GitStatus => self.render_git_status(file.git_status()),
  419. }
  420. }
  421. fn render_permissions(&self, file_type: f::Type, permissions: f::Permissions, xattrs: bool) -> TextCell {
  422. let perms = self.opts.colours.perms;
  423. let types = self.opts.colours.filetypes;
  424. let bit = |bit, chr: &'static str, style: Style| {
  425. if bit { style.paint(chr) } else { self.opts.colours.punctuation.paint("-") }
  426. };
  427. let type_char = match file_type {
  428. f::Type::File => types.normal.paint("."),
  429. f::Type::Directory => types.directory.paint("d"),
  430. f::Type::Pipe => types.pipe.paint("|"),
  431. f::Type::Link => types.symlink.paint("l"),
  432. f::Type::CharDevice => types.device.paint("c"),
  433. f::Type::BlockDevice => types.device.paint("b"),
  434. f::Type::Socket => types.socket.paint("s"),
  435. f::Type::Special => types.special.paint("?"),
  436. };
  437. let x_colour = if file_type.is_regular_file() { perms.user_execute_file }
  438. else { perms.user_execute_other };
  439. let mut chars = vec![
  440. type_char,
  441. bit(permissions.user_read, "r", perms.user_read),
  442. bit(permissions.user_write, "w", perms.user_write),
  443. bit(permissions.user_execute, "x", x_colour),
  444. bit(permissions.group_read, "r", perms.group_read),
  445. bit(permissions.group_write, "w", perms.group_write),
  446. bit(permissions.group_execute, "x", perms.group_execute),
  447. bit(permissions.other_read, "r", perms.other_read),
  448. bit(permissions.other_write, "w", perms.other_write),
  449. bit(permissions.other_execute, "x", perms.other_execute),
  450. ];
  451. if xattrs {
  452. chars.push(perms.attribute.paint("@"));
  453. }
  454. // As these are all ASCII characters, we can guarantee that theyโ€™re
  455. // all going to be one character wide, and donโ€™t need to compute the
  456. // cellโ€™s display width.
  457. let width = DisplayWidth::from(chars.len());
  458. TextCell {
  459. contents: chars.into(),
  460. width: width,
  461. }
  462. }
  463. fn render_links(&self, links: f::Links) -> TextCell {
  464. let style = if links.multiple { self.opts.colours.links.multi_link_file }
  465. else { self.opts.colours.links.normal };
  466. TextCell::paint(style, self.env.numeric.format_int(links.count))
  467. }
  468. fn render_blocks(&self, blocks: f::Blocks) -> TextCell {
  469. match blocks {
  470. f::Blocks::Some(blk) => TextCell::paint(self.opts.colours.blocks, blk.to_string()),
  471. f::Blocks::None => TextCell::blank(self.opts.colours.punctuation),
  472. }
  473. }
  474. fn render_inode(&self, inode: f::Inode) -> TextCell {
  475. TextCell::paint(self.opts.colours.inode, inode.0.to_string())
  476. }
  477. fn render_size(&self, size: f::Size, size_format: SizeFormat) -> TextCell {
  478. use number_prefix::{binary_prefix, decimal_prefix};
  479. use number_prefix::{Prefixed, Standalone, PrefixNames};
  480. let size = match size {
  481. f::Size::Some(s) => s,
  482. f::Size::None => return TextCell::blank(self.opts.colours.punctuation),
  483. };
  484. let result = match size_format {
  485. SizeFormat::DecimalBytes => decimal_prefix(size as f64),
  486. SizeFormat::BinaryBytes => binary_prefix(size as f64),
  487. SizeFormat::JustBytes => {
  488. let string = self.env.numeric.format_int(size);
  489. return TextCell::paint(self.opts.colours.file_size(size), string);
  490. },
  491. };
  492. let (prefix, n) = match result {
  493. Standalone(b) => return TextCell::paint(self.opts.colours.file_size(b as u64), b.to_string()),
  494. Prefixed(p, n) => (p, n)
  495. };
  496. let symbol = prefix.symbol();
  497. let number = if n < 10f64 { self.env.numeric.format_float(n, 1) }
  498. else { self.env.numeric.format_int(n as isize) };
  499. // The numbers and symbols are guaranteed to be written in ASCII, so
  500. // we can skip the display width calculation.
  501. let width = DisplayWidth::from(number.len() + symbol.len());
  502. TextCell {
  503. width: width,
  504. contents: vec![
  505. self.opts.colours.file_size(size).paint(number),
  506. self.opts.colours.size.unit.paint(symbol),
  507. ].into(),
  508. }
  509. }
  510. #[allow(trivial_numeric_casts)]
  511. fn render_time(&self, timestamp: f::Time) -> TextCell {
  512. // TODO(ogham): This method needs some serious de-duping!
  513. // zoned and local times have different types at the moment,
  514. // so it's tricky.
  515. if let Some(ref tz) = self.env.tz {
  516. let date = tz.to_zoned(LocalDateTime::at(timestamp.0 as i64));
  517. let datestamp = if date.year() == self.env.current_year {
  518. DATE_AND_TIME.format(&date, &self.env.time)
  519. }
  520. else {
  521. DATE_AND_YEAR.format(&date, &self.env.time)
  522. };
  523. TextCell::paint(self.opts.colours.date, datestamp)
  524. }
  525. else {
  526. let date = LocalDateTime::at(timestamp.0 as i64);
  527. let datestamp = if date.year() == self.env.current_year {
  528. DATE_AND_TIME.format(&date, &self.env.time)
  529. }
  530. else {
  531. DATE_AND_YEAR.format(&date, &self.env.time)
  532. };
  533. TextCell::paint(self.opts.colours.date, datestamp)
  534. }
  535. }
  536. fn render_git_status(&self, git: f::Git) -> TextCell {
  537. let git_char = |status| match status {
  538. f::GitStatus::NotModified => self.opts.colours.punctuation.paint("-"),
  539. f::GitStatus::New => self.opts.colours.git.new.paint("N"),
  540. f::GitStatus::Modified => self.opts.colours.git.modified.paint("M"),
  541. f::GitStatus::Deleted => self.opts.colours.git.deleted.paint("D"),
  542. f::GitStatus::Renamed => self.opts.colours.git.renamed.paint("R"),
  543. f::GitStatus::TypeChange => self.opts.colours.git.typechange.paint("T"),
  544. };
  545. TextCell {
  546. width: DisplayWidth::from(2),
  547. contents: vec![
  548. git_char(git.staged),
  549. git_char(git.unstaged)
  550. ].into(),
  551. }
  552. }
  553. fn render_user(&self, user: f::User) -> TextCell {
  554. let users = self.env.users.lock().unwrap();
  555. let user_name = match users.get_user_by_uid(user.0) {
  556. Some(user) => user.name().to_owned(),
  557. None => user.0.to_string(),
  558. };
  559. let style = if users.get_current_uid() == user.0 { self.opts.colours.users.user_you }
  560. else { self.opts.colours.users.user_someone_else };
  561. TextCell::paint(style, user_name)
  562. }
  563. fn render_group(&self, group: f::Group) -> TextCell {
  564. use users::os::unix::GroupExt;
  565. let mut style = self.opts.colours.users.group_not_yours;
  566. let users = self.env.users.lock().unwrap();
  567. let group = match users.get_group_by_gid(group.0) {
  568. Some(g) => (*g).clone(),
  569. None => return TextCell::paint(style, group.0.to_string()),
  570. };
  571. let current_uid = users.get_current_uid();
  572. if let Some(current_user) = users.get_user_by_uid(current_uid) {
  573. if current_user.primary_group_id() == group.gid()
  574. || group.members().contains(&current_user.name().to_owned()) {
  575. style = self.opts.colours.users.group_yours;
  576. }
  577. }
  578. TextCell::paint(style, group.name().to_owned())
  579. }
  580. /// Render the table as a vector of Cells, to be displayed on standard output.
  581. pub fn print_table(self) -> Vec<TextCell> {
  582. let mut tree_trunk = TreeTrunk::default();
  583. let mut cells = Vec::new();
  584. // Work out the list of column widths by finding the longest cell for
  585. // each column, then formatting each cell in that column to be the
  586. // width of that one.
  587. let column_widths: Vec<usize> = (0 .. self.columns.len())
  588. .map(|n| self.rows.iter().map(|row| row.column_width(n)).max().unwrap_or(0))
  589. .collect();
  590. let total_width: usize = self.columns.len() + column_widths.iter().fold(0, Add::add);
  591. for row in self.rows {
  592. let mut cell = TextCell::default();
  593. if let Some(cells) = row.cells {
  594. for (n, (this_cell, width)) in cells.into_iter().zip(column_widths.iter()).enumerate() {
  595. let padding = width - *this_cell.width;
  596. match self.columns[n].alignment() {
  597. Alignment::Left => { cell.append(this_cell); cell.add_spaces(padding); }
  598. Alignment::Right => { cell.add_spaces(padding); cell.append(this_cell); }
  599. }
  600. cell.add_spaces(1);
  601. }
  602. }
  603. else {
  604. cell.add_spaces(total_width)
  605. }
  606. let mut filename = TextCell::default();
  607. for tree_part in tree_trunk.new_row(row.depth, row.last) {
  608. filename.push(self.opts.colours.punctuation.paint(tree_part.ascii_art()), 4);
  609. }
  610. // If any tree characters have been printed, then add an extra
  611. // space, which makes the output look much better.
  612. if row.depth != 0 {
  613. filename.add_spaces(1);
  614. }
  615. // Print the name without worrying about padding.
  616. filename.append(row.name);
  617. cell.append(filename);
  618. cells.push(cell);
  619. }
  620. cells
  621. }
  622. }
  623. lazy_static! {
  624. static ref DATE_AND_TIME: DateFormat<'static> =
  625. DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap();
  626. static ref DATE_AND_YEAR: DateFormat<'static> =
  627. DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap();
  628. }
  629. #[cfg(test)]
  630. pub mod test {
  631. pub use super::{Table, Environment, Details};
  632. pub use std::sync::Mutex;
  633. pub use fs::{File, fields as f};
  634. pub use output::column::{Column, Columns};
  635. pub use output::cell::TextCell;
  636. pub use users::{User, Group, uid_t, gid_t};
  637. pub use users::mock::MockUsers;
  638. pub use users::os::unix::{UserExt, GroupExt};
  639. pub use ansi_term::Style;
  640. pub use ansi_term::Colour::*;
  641. impl Default for Environment<MockUsers> {
  642. fn default() -> Self {
  643. use locale;
  644. use users::mock::MockUsers;
  645. use std::sync::Mutex;
  646. Environment {
  647. current_year: 1234,
  648. numeric: locale::Numeric::english(),
  649. time: locale::Time::english(),
  650. tz: None,
  651. users: Mutex::new(MockUsers::with_current_uid(0)),
  652. }
  653. }
  654. }
  655. pub fn new_table<'a>(columns: &'a [Column], details: &'a Details, users: MockUsers) -> Table<'a, MockUsers> {
  656. use std::sync::Arc;
  657. Table {
  658. columns: columns,
  659. opts: details,
  660. env: Arc::new(Environment { users: Mutex::new(users), ..Environment::default() }),
  661. rows: Vec::new(),
  662. }
  663. }
  664. mod users {
  665. #![allow(unused_results)]
  666. use super::*;
  667. #[test]
  668. fn named() {
  669. let columns = Columns::default().for_dir(None);
  670. let mut details = Details::default();
  671. details.colours.users.user_you = Red.bold();
  672. let mut users = MockUsers::with_current_uid(1000);
  673. users.add_user(User::new(1000, "enoch", 100));
  674. let table = new_table(&columns, &details, users);
  675. let user = f::User(1000);
  676. let expected = TextCell::paint_str(Red.bold(), "enoch");
  677. assert_eq!(expected, table.render_user(user))
  678. }
  679. #[test]
  680. fn unnamed() {
  681. let columns = Columns::default().for_dir(None);
  682. let mut details = Details::default();
  683. details.colours.users.user_you = Cyan.bold();
  684. let users = MockUsers::with_current_uid(1000);
  685. let table = new_table(&columns, &details, users);
  686. let user = f::User(1000);
  687. let expected = TextCell::paint_str(Cyan.bold(), "1000");
  688. assert_eq!(expected, table.render_user(user));
  689. }
  690. #[test]
  691. fn different_named() {
  692. let columns = Columns::default().for_dir(None);
  693. let mut details = Details::default();
  694. details.colours.users.user_someone_else = Green.bold();
  695. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  696. table.env.users.lock().unwrap().add_user(User::new(1000, "enoch", 100));
  697. let user = f::User(1000);
  698. let expected = TextCell::paint_str(Green.bold(), "enoch");
  699. assert_eq!(expected, table.render_user(user));
  700. }
  701. #[test]
  702. fn different_unnamed() {
  703. let columns = Columns::default().for_dir(None);
  704. let mut details = Details::default();
  705. details.colours.users.user_someone_else = Red.normal();
  706. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  707. let user = f::User(1000);
  708. let expected = TextCell::paint_str(Red.normal(), "1000");
  709. assert_eq!(expected, table.render_user(user));
  710. }
  711. #[test]
  712. fn overflow() {
  713. let columns = Columns::default().for_dir(None);
  714. let mut details = Details::default();
  715. details.colours.users.user_someone_else = Blue.underline();
  716. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  717. let user = f::User(2_147_483_648);
  718. let expected = TextCell::paint_str(Blue.underline(), "2147483648");
  719. assert_eq!(expected, table.render_user(user));
  720. }
  721. }
  722. mod groups {
  723. #![allow(unused_results)]
  724. use super::*;
  725. #[test]
  726. fn named() {
  727. let columns = Columns::default().for_dir(None);
  728. let mut details = Details::default();
  729. details.colours.users.group_not_yours = Fixed(101).normal();
  730. let mut users = MockUsers::with_current_uid(1000);
  731. users.add_group(Group::new(100, "folk"));
  732. let table = new_table(&columns, &details, users);
  733. let group = f::Group(100);
  734. let expected = TextCell::paint_str(Fixed(101).normal(), "folk");
  735. assert_eq!(expected, table.render_group(group))
  736. }
  737. #[test]
  738. fn unnamed() {
  739. let columns = Columns::default().for_dir(None);
  740. let mut details = Details::default();
  741. details.colours.users.group_not_yours = Fixed(87).normal();
  742. let users = MockUsers::with_current_uid(1000);
  743. let table = new_table(&columns, &details, users);
  744. let group = f::Group(100);
  745. let expected = TextCell::paint_str(Fixed(87).normal(), "100");
  746. assert_eq!(expected, table.render_group(group));
  747. }
  748. #[test]
  749. fn primary() {
  750. let columns = Columns::default().for_dir(None);
  751. let mut details = Details::default();
  752. details.colours.users.group_yours = Fixed(64).normal();
  753. let mut users = MockUsers::with_current_uid(2);
  754. users.add_user(User::new(2, "eve", 100));
  755. users.add_group(Group::new(100, "folk"));
  756. let table = new_table(&columns, &details, users);
  757. let group = f::Group(100);
  758. let expected = TextCell::paint_str(Fixed(64).normal(), "folk");
  759. assert_eq!(expected, table.render_group(group))
  760. }
  761. #[test]
  762. fn secondary() {
  763. let columns = Columns::default().for_dir(None);
  764. let mut details = Details::default();
  765. details.colours.users.group_yours = Fixed(31).normal();
  766. let mut users = MockUsers::with_current_uid(2);
  767. users.add_user(User::new(2, "eve", 666));
  768. let test_group = Group::new(100, "folk").add_member("eve");
  769. users.add_group(test_group);
  770. let table = new_table(&columns, &details, users);
  771. let group = f::Group(100);
  772. let expected = TextCell::paint_str(Fixed(31).normal(), "folk");
  773. assert_eq!(expected, table.render_group(group))
  774. }
  775. #[test]
  776. fn overflow() {
  777. let columns = Columns::default().for_dir(None);
  778. let mut details = Details::default();
  779. details.colours.users.group_not_yours = Blue.underline();
  780. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  781. let group = f::Group(2_147_483_648);
  782. let expected = TextCell::paint_str(Blue.underline(), "2147483648");
  783. assert_eq!(expected, table.render_group(group));
  784. }
  785. }
  786. }