details.rs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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, TextCellContents, DisplayWidth};
  96. use output::tree::TreeTrunk;
  97. use output::file_name::{FileName, LinkStyle, Classify};
  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: Classify,
  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 row = Row {
  260. depth: depth,
  261. cells: Some(egg.cells),
  262. name: FileName::new(&egg.file, LinkStyle::FullLinkPaths, self.classify, &self.colours).paint().promote(),
  263. last: index == num_eggs - 1,
  264. };
  265. table.rows.push(row);
  266. if let Some(ref dir) = egg.dir {
  267. for file_to_add in dir.files() {
  268. match file_to_add {
  269. Ok(f) => files.push(f),
  270. Err((path, e)) => errors.push((e, Some(path)))
  271. }
  272. }
  273. self.filter.filter_child_files(&mut files);
  274. if !files.is_empty() {
  275. for xattr in egg.xattrs {
  276. table.add_xattr(xattr, depth + 1, false);
  277. }
  278. for (error, path) in errors {
  279. table.add_error(&error, depth + 1, false, path);
  280. }
  281. self.add_files_to_table(table, files, depth + 1);
  282. continue;
  283. }
  284. }
  285. let count = egg.xattrs.len();
  286. for (index, xattr) in egg.xattrs.into_iter().enumerate() {
  287. table.add_xattr(xattr, depth + 1, errors.is_empty() && index == count - 1);
  288. }
  289. let count = errors.len();
  290. for (index, (error, path)) in errors.into_iter().enumerate() {
  291. table.add_error(&error, depth + 1, index == count - 1, path);
  292. }
  293. }
  294. }
  295. }
  296. pub struct Row {
  297. /// Vector of cells to display.
  298. ///
  299. /// Most of the rows will be used to display files' metadata, so this will
  300. /// almost always be `Some`, containing a vector of cells. It will only be
  301. /// `None` for a row displaying an attribute or error, neither of which
  302. /// have cells.
  303. cells: Option<Vec<TextCell>>,
  304. /// This file's name, in coloured output. The name is treated separately
  305. /// from the other cells, as it never requires padding.
  306. name: TextCell,
  307. /// How many directories deep into the tree structure this is. Directories
  308. /// on top have depth 0.
  309. depth: usize,
  310. /// Whether this is the last entry in the directory. This flag is used
  311. /// when calculating the tree view.
  312. last: bool,
  313. }
  314. impl Row {
  315. /// Gets the Unicode display width of the indexed column, if present. If
  316. /// not, returns 0.
  317. fn column_width(&self, index: usize) -> usize {
  318. match self.cells {
  319. Some(ref cells) => *cells[index].width,
  320. None => 0,
  321. }
  322. }
  323. }
  324. /// A **Table** object gets built up by the view as it lists files and
  325. /// directories.
  326. pub struct Table<'a, U: Users+Groups+'a> {
  327. pub rows: Vec<Row>,
  328. pub columns: &'a [Column],
  329. pub opts: &'a Details,
  330. pub env: Arc<Environment<U>>,
  331. }
  332. impl<'a, U: Users+Groups+'a> Table<'a, U> {
  333. /// Add a dummy "header" row to the table, which contains the names of all
  334. /// the columns, underlined. This has dummy data for the cases that aren't
  335. /// actually used, such as the depth or list of attributes.
  336. pub fn add_header(&mut self) {
  337. let row = Row {
  338. depth: 0,
  339. cells: Some(self.columns.iter().map(|c| TextCell::paint_str(self.opts.colours.header, c.header())).collect()),
  340. name: TextCell::paint_str(self.opts.colours.header, "Name"),
  341. last: false,
  342. };
  343. self.rows.push(row);
  344. }
  345. fn add_error(&mut self, error: &IOError, depth: usize, last: bool, path: Option<PathBuf>) {
  346. let error_message = match path {
  347. Some(path) => format!("<{}: {}>", path.display(), error),
  348. None => format!("<{}>", error),
  349. };
  350. let row = Row {
  351. depth: depth,
  352. cells: None,
  353. name: TextCell::paint(self.opts.colours.broken_arrow, error_message),
  354. last: last,
  355. };
  356. self.rows.push(row);
  357. }
  358. fn add_xattr(&mut self, xattr: Attribute, depth: usize, last: bool) {
  359. let row = Row {
  360. depth: depth,
  361. cells: None,
  362. name: TextCell::paint(self.opts.colours.perms.attribute, format!("{} (len {})", xattr.name, xattr.size)),
  363. last: last,
  364. };
  365. self.rows.push(row);
  366. }
  367. pub fn filename(&self, file: File, links: LinkStyle) -> TextCellContents {
  368. FileName::new(&file, links, self.opts.classify, &self.opts.colours).paint()
  369. }
  370. pub fn add_file_with_cells(&mut self, cells: Vec<TextCell>, name_cell: TextCell, depth: usize, last: bool) {
  371. let row = Row {
  372. depth: depth,
  373. cells: Some(cells),
  374. name: name_cell,
  375. last: last,
  376. };
  377. self.rows.push(row);
  378. }
  379. /// Use the list of columns to find which cells should be produced for
  380. /// this file, per-column.
  381. pub fn cells_for_file(&self, file: &File, xattrs: bool) -> Vec<TextCell> {
  382. self.columns.iter()
  383. .map(|c| self.display(file, c, xattrs))
  384. .collect()
  385. }
  386. fn display(&self, file: &File, column: &Column, xattrs: bool) -> TextCell {
  387. use output::column::TimeType::*;
  388. match *column {
  389. Column::Permissions => self.render_permissions(file.type_char(), file.permissions(), xattrs),
  390. Column::FileSize(fmt) => self.render_size(file.size(), fmt),
  391. Column::Timestamp(Modified) => self.render_time(file.modified_time()),
  392. Column::Timestamp(Created) => self.render_time(file.created_time()),
  393. Column::Timestamp(Accessed) => self.render_time(file.accessed_time()),
  394. Column::HardLinks => self.render_links(file.links()),
  395. Column::Inode => self.render_inode(file.inode()),
  396. Column::Blocks => self.render_blocks(file.blocks()),
  397. Column::User => self.render_user(file.user()),
  398. Column::Group => self.render_group(file.group()),
  399. Column::GitStatus => self.render_git_status(file.git_status()),
  400. }
  401. }
  402. fn render_permissions(&self, file_type: f::Type, permissions: f::Permissions, xattrs: bool) -> TextCell {
  403. let perms = self.opts.colours.perms;
  404. let types = self.opts.colours.filetypes;
  405. let bit = |bit, chr: &'static str, style: Style| {
  406. if bit { style.paint(chr) } else { self.opts.colours.punctuation.paint("-") }
  407. };
  408. let type_char = match file_type {
  409. f::Type::File => types.normal.paint("."),
  410. f::Type::Directory => types.directory.paint("d"),
  411. f::Type::Pipe => types.pipe.paint("|"),
  412. f::Type::Link => types.symlink.paint("l"),
  413. f::Type::CharDevice => types.device.paint("c"),
  414. f::Type::BlockDevice => types.device.paint("b"),
  415. f::Type::Socket => types.socket.paint("s"),
  416. f::Type::Special => types.special.paint("?"),
  417. };
  418. let x_colour = if file_type.is_regular_file() { perms.user_execute_file }
  419. else { perms.user_execute_other };
  420. let mut chars = vec![
  421. type_char,
  422. bit(permissions.user_read, "r", perms.user_read),
  423. bit(permissions.user_write, "w", perms.user_write),
  424. bit(permissions.user_execute, "x", x_colour),
  425. bit(permissions.group_read, "r", perms.group_read),
  426. bit(permissions.group_write, "w", perms.group_write),
  427. bit(permissions.group_execute, "x", perms.group_execute),
  428. bit(permissions.other_read, "r", perms.other_read),
  429. bit(permissions.other_write, "w", perms.other_write),
  430. bit(permissions.other_execute, "x", perms.other_execute),
  431. ];
  432. if xattrs {
  433. chars.push(perms.attribute.paint("@"));
  434. }
  435. // As these are all ASCII characters, we can guarantee that theyโ€™re
  436. // all going to be one character wide, and donโ€™t need to compute the
  437. // cellโ€™s display width.
  438. let width = DisplayWidth::from(chars.len());
  439. TextCell {
  440. contents: chars.into(),
  441. width: width,
  442. }
  443. }
  444. fn render_links(&self, links: f::Links) -> TextCell {
  445. let style = if links.multiple { self.opts.colours.links.multi_link_file }
  446. else { self.opts.colours.links.normal };
  447. TextCell::paint(style, self.env.numeric.format_int(links.count))
  448. }
  449. fn render_blocks(&self, blocks: f::Blocks) -> TextCell {
  450. match blocks {
  451. f::Blocks::Some(blk) => TextCell::paint(self.opts.colours.blocks, blk.to_string()),
  452. f::Blocks::None => TextCell::blank(self.opts.colours.punctuation),
  453. }
  454. }
  455. fn render_inode(&self, inode: f::Inode) -> TextCell {
  456. TextCell::paint(self.opts.colours.inode, inode.0.to_string())
  457. }
  458. fn render_size(&self, size: f::Size, size_format: SizeFormat) -> TextCell {
  459. use number_prefix::{binary_prefix, decimal_prefix};
  460. use number_prefix::{Prefixed, Standalone, PrefixNames};
  461. let size = match size {
  462. f::Size::Some(s) => s,
  463. f::Size::None => return TextCell::blank(self.opts.colours.punctuation),
  464. };
  465. let result = match size_format {
  466. SizeFormat::DecimalBytes => decimal_prefix(size as f64),
  467. SizeFormat::BinaryBytes => binary_prefix(size as f64),
  468. SizeFormat::JustBytes => {
  469. let string = self.env.numeric.format_int(size);
  470. return TextCell::paint(self.opts.colours.file_size(size), string);
  471. },
  472. };
  473. let (prefix, n) = match result {
  474. Standalone(b) => return TextCell::paint(self.opts.colours.file_size(b as u64), b.to_string()),
  475. Prefixed(p, n) => (p, n)
  476. };
  477. let symbol = prefix.symbol();
  478. let number = if n < 10f64 { self.env.numeric.format_float(n, 1) }
  479. else { self.env.numeric.format_int(n as isize) };
  480. // The numbers and symbols are guaranteed to be written in ASCII, so
  481. // we can skip the display width calculation.
  482. let width = DisplayWidth::from(number.len() + symbol.len());
  483. TextCell {
  484. width: width,
  485. contents: vec![
  486. self.opts.colours.file_size(size).paint(number),
  487. self.opts.colours.size.unit.paint(symbol),
  488. ].into(),
  489. }
  490. }
  491. #[allow(trivial_numeric_casts)]
  492. fn render_time(&self, timestamp: f::Time) -> TextCell {
  493. // TODO(ogham): This method needs some serious de-duping!
  494. // zoned and local times have different types at the moment,
  495. // so it's tricky.
  496. if let Some(ref tz) = self.env.tz {
  497. let date = tz.to_zoned(LocalDateTime::at(timestamp.0 as i64));
  498. let datestamp = if date.year() == self.env.current_year {
  499. DATE_AND_TIME.format(&date, &self.env.time)
  500. }
  501. else {
  502. DATE_AND_YEAR.format(&date, &self.env.time)
  503. };
  504. TextCell::paint(self.opts.colours.date, datestamp)
  505. }
  506. else {
  507. let date = LocalDateTime::at(timestamp.0 as i64);
  508. let datestamp = if date.year() == self.env.current_year {
  509. DATE_AND_TIME.format(&date, &self.env.time)
  510. }
  511. else {
  512. DATE_AND_YEAR.format(&date, &self.env.time)
  513. };
  514. TextCell::paint(self.opts.colours.date, datestamp)
  515. }
  516. }
  517. fn render_git_status(&self, git: f::Git) -> TextCell {
  518. let git_char = |status| match status {
  519. f::GitStatus::NotModified => self.opts.colours.punctuation.paint("-"),
  520. f::GitStatus::New => self.opts.colours.git.new.paint("N"),
  521. f::GitStatus::Modified => self.opts.colours.git.modified.paint("M"),
  522. f::GitStatus::Deleted => self.opts.colours.git.deleted.paint("D"),
  523. f::GitStatus::Renamed => self.opts.colours.git.renamed.paint("R"),
  524. f::GitStatus::TypeChange => self.opts.colours.git.typechange.paint("T"),
  525. };
  526. TextCell {
  527. width: DisplayWidth::from(2),
  528. contents: vec![
  529. git_char(git.staged),
  530. git_char(git.unstaged)
  531. ].into(),
  532. }
  533. }
  534. fn render_user(&self, user: f::User) -> TextCell {
  535. let users = self.env.users.lock().unwrap();
  536. let user_name = match users.get_user_by_uid(user.0) {
  537. Some(user) => user.name().to_owned(),
  538. None => user.0.to_string(),
  539. };
  540. let style = if users.get_current_uid() == user.0 { self.opts.colours.users.user_you }
  541. else { self.opts.colours.users.user_someone_else };
  542. TextCell::paint(style, user_name)
  543. }
  544. fn render_group(&self, group: f::Group) -> TextCell {
  545. use users::os::unix::GroupExt;
  546. let mut style = self.opts.colours.users.group_not_yours;
  547. let users = self.env.users.lock().unwrap();
  548. let group = match users.get_group_by_gid(group.0) {
  549. Some(g) => (*g).clone(),
  550. None => return TextCell::paint(style, group.0.to_string()),
  551. };
  552. let current_uid = users.get_current_uid();
  553. if let Some(current_user) = users.get_user_by_uid(current_uid) {
  554. if current_user.primary_group_id() == group.gid()
  555. || group.members().contains(&current_user.name().to_owned()) {
  556. style = self.opts.colours.users.group_yours;
  557. }
  558. }
  559. TextCell::paint(style, group.name().to_owned())
  560. }
  561. /// Render the table as a vector of Cells, to be displayed on standard output.
  562. pub fn print_table(self) -> Vec<TextCell> {
  563. let mut tree_trunk = TreeTrunk::default();
  564. let mut cells = Vec::new();
  565. // Work out the list of column widths by finding the longest cell for
  566. // each column, then formatting each cell in that column to be the
  567. // width of that one.
  568. let column_widths: Vec<usize> = (0 .. self.columns.len())
  569. .map(|n| self.rows.iter().map(|row| row.column_width(n)).max().unwrap_or(0))
  570. .collect();
  571. let total_width: usize = self.columns.len() + column_widths.iter().fold(0, Add::add);
  572. for row in self.rows {
  573. let mut cell = TextCell::default();
  574. if let Some(cells) = row.cells {
  575. for (n, (this_cell, width)) in cells.into_iter().zip(column_widths.iter()).enumerate() {
  576. let padding = width - *this_cell.width;
  577. match self.columns[n].alignment() {
  578. Alignment::Left => { cell.append(this_cell); cell.add_spaces(padding); }
  579. Alignment::Right => { cell.add_spaces(padding); cell.append(this_cell); }
  580. }
  581. cell.add_spaces(1);
  582. }
  583. }
  584. else {
  585. cell.add_spaces(total_width)
  586. }
  587. let mut filename = TextCell::default();
  588. for tree_part in tree_trunk.new_row(row.depth, row.last) {
  589. filename.push(self.opts.colours.punctuation.paint(tree_part.ascii_art()), 4);
  590. }
  591. // If any tree characters have been printed, then add an extra
  592. // space, which makes the output look much better.
  593. if row.depth != 0 {
  594. filename.add_spaces(1);
  595. }
  596. // Print the name without worrying about padding.
  597. filename.append(row.name);
  598. cell.append(filename);
  599. cells.push(cell);
  600. }
  601. cells
  602. }
  603. }
  604. lazy_static! {
  605. static ref DATE_AND_TIME: DateFormat<'static> =
  606. DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap();
  607. static ref DATE_AND_YEAR: DateFormat<'static> =
  608. DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap();
  609. }
  610. #[cfg(test)]
  611. pub mod test {
  612. pub use super::{Table, Environment, Details};
  613. pub use std::sync::Mutex;
  614. pub use fs::{File, fields as f};
  615. pub use output::column::{Column, Columns};
  616. pub use output::cell::TextCell;
  617. pub use users::{User, Group, uid_t, gid_t};
  618. pub use users::mock::MockUsers;
  619. pub use users::os::unix::{UserExt, GroupExt};
  620. pub use ansi_term::Style;
  621. pub use ansi_term::Colour::*;
  622. impl Default for Environment<MockUsers> {
  623. fn default() -> Self {
  624. use locale;
  625. use users::mock::MockUsers;
  626. use std::sync::Mutex;
  627. Environment {
  628. current_year: 1234,
  629. numeric: locale::Numeric::english(),
  630. time: locale::Time::english(),
  631. tz: None,
  632. users: Mutex::new(MockUsers::with_current_uid(0)),
  633. }
  634. }
  635. }
  636. pub fn new_table<'a>(columns: &'a [Column], details: &'a Details, users: MockUsers) -> Table<'a, MockUsers> {
  637. use std::sync::Arc;
  638. Table {
  639. columns: columns,
  640. opts: details,
  641. env: Arc::new(Environment { users: Mutex::new(users), ..Environment::default() }),
  642. rows: Vec::new(),
  643. }
  644. }
  645. mod users {
  646. #![allow(unused_results)]
  647. use super::*;
  648. #[test]
  649. fn named() {
  650. let columns = Columns::default().for_dir(None);
  651. let mut details = Details::default();
  652. details.colours.users.user_you = Red.bold();
  653. let mut users = MockUsers::with_current_uid(1000);
  654. users.add_user(User::new(1000, "enoch", 100));
  655. let table = new_table(&columns, &details, users);
  656. let user = f::User(1000);
  657. let expected = TextCell::paint_str(Red.bold(), "enoch");
  658. assert_eq!(expected, table.render_user(user))
  659. }
  660. #[test]
  661. fn unnamed() {
  662. let columns = Columns::default().for_dir(None);
  663. let mut details = Details::default();
  664. details.colours.users.user_you = Cyan.bold();
  665. let users = MockUsers::with_current_uid(1000);
  666. let table = new_table(&columns, &details, users);
  667. let user = f::User(1000);
  668. let expected = TextCell::paint_str(Cyan.bold(), "1000");
  669. assert_eq!(expected, table.render_user(user));
  670. }
  671. #[test]
  672. fn different_named() {
  673. let columns = Columns::default().for_dir(None);
  674. let mut details = Details::default();
  675. details.colours.users.user_someone_else = Green.bold();
  676. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  677. table.env.users.lock().unwrap().add_user(User::new(1000, "enoch", 100));
  678. let user = f::User(1000);
  679. let expected = TextCell::paint_str(Green.bold(), "enoch");
  680. assert_eq!(expected, table.render_user(user));
  681. }
  682. #[test]
  683. fn different_unnamed() {
  684. let columns = Columns::default().for_dir(None);
  685. let mut details = Details::default();
  686. details.colours.users.user_someone_else = Red.normal();
  687. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  688. let user = f::User(1000);
  689. let expected = TextCell::paint_str(Red.normal(), "1000");
  690. assert_eq!(expected, table.render_user(user));
  691. }
  692. #[test]
  693. fn overflow() {
  694. let columns = Columns::default().for_dir(None);
  695. let mut details = Details::default();
  696. details.colours.users.user_someone_else = Blue.underline();
  697. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  698. let user = f::User(2_147_483_648);
  699. let expected = TextCell::paint_str(Blue.underline(), "2147483648");
  700. assert_eq!(expected, table.render_user(user));
  701. }
  702. }
  703. mod groups {
  704. #![allow(unused_results)]
  705. use super::*;
  706. #[test]
  707. fn named() {
  708. let columns = Columns::default().for_dir(None);
  709. let mut details = Details::default();
  710. details.colours.users.group_not_yours = Fixed(101).normal();
  711. let mut users = MockUsers::with_current_uid(1000);
  712. users.add_group(Group::new(100, "folk"));
  713. let table = new_table(&columns, &details, users);
  714. let group = f::Group(100);
  715. let expected = TextCell::paint_str(Fixed(101).normal(), "folk");
  716. assert_eq!(expected, table.render_group(group))
  717. }
  718. #[test]
  719. fn unnamed() {
  720. let columns = Columns::default().for_dir(None);
  721. let mut details = Details::default();
  722. details.colours.users.group_not_yours = Fixed(87).normal();
  723. let users = MockUsers::with_current_uid(1000);
  724. let table = new_table(&columns, &details, users);
  725. let group = f::Group(100);
  726. let expected = TextCell::paint_str(Fixed(87).normal(), "100");
  727. assert_eq!(expected, table.render_group(group));
  728. }
  729. #[test]
  730. fn primary() {
  731. let columns = Columns::default().for_dir(None);
  732. let mut details = Details::default();
  733. details.colours.users.group_yours = Fixed(64).normal();
  734. let mut users = MockUsers::with_current_uid(2);
  735. users.add_user(User::new(2, "eve", 100));
  736. users.add_group(Group::new(100, "folk"));
  737. let table = new_table(&columns, &details, users);
  738. let group = f::Group(100);
  739. let expected = TextCell::paint_str(Fixed(64).normal(), "folk");
  740. assert_eq!(expected, table.render_group(group))
  741. }
  742. #[test]
  743. fn secondary() {
  744. let columns = Columns::default().for_dir(None);
  745. let mut details = Details::default();
  746. details.colours.users.group_yours = Fixed(31).normal();
  747. let mut users = MockUsers::with_current_uid(2);
  748. users.add_user(User::new(2, "eve", 666));
  749. let test_group = Group::new(100, "folk").add_member("eve");
  750. users.add_group(test_group);
  751. let table = new_table(&columns, &details, users);
  752. let group = f::Group(100);
  753. let expected = TextCell::paint_str(Fixed(31).normal(), "folk");
  754. assert_eq!(expected, table.render_group(group))
  755. }
  756. #[test]
  757. fn overflow() {
  758. let columns = Columns::default().for_dir(None);
  759. let mut details = Details::default();
  760. details.colours.users.group_not_yours = Blue.underline();
  761. let table = new_table(&columns, &details, MockUsers::with_current_uid(0));
  762. let group = f::Group(2_147_483_648);
  763. let expected = TextCell::paint_str(Blue.underline(), "2147483648");
  764. assert_eq!(expected, table.render_group(group));
  765. }
  766. }
  767. }