details.rs 34 KB

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