details.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. use colours::Colours;
  2. use column::{Alignment, Column, Cell};
  3. use feature::Attribute;
  4. use dir::Dir;
  5. use file::{Blocks, File, Git, GitStatus, Group, Inode, Links, Permissions, Size, Time, Type, User};
  6. use options::{Columns, FileFilter, RecurseOptions, SizeFormat};
  7. use users::{OSUsers, Users};
  8. use super::filename;
  9. use ansi_term::{ANSIString, ANSIStrings, Style};
  10. use ansi_term::Style::Plain;
  11. use ansi_term::Colour::Fixed;
  12. use locale;
  13. use number_prefix::{binary_prefix, decimal_prefix, Prefixed, Standalone, PrefixNames};
  14. use datetime::local::{LocalDateTime, DatePiece};
  15. use datetime::format::{DateFormat};
  16. /// With the **Details** view, the output gets formatted into columns, with
  17. /// each `Column` object showing some piece of information about the file,
  18. /// such as its size, or its permissions.
  19. ///
  20. /// To do this, the results have to be written to a table, instead of
  21. /// displaying each file immediately. Then, the width of each column can be
  22. /// calculated based on the individual results, and the fields are padded
  23. /// during output.
  24. ///
  25. /// Almost all the heavy lifting is done in a Table object, which handles the
  26. /// columns for each row.
  27. #[derive(PartialEq, Debug, Copy, Clone)]
  28. pub struct Details {
  29. /// A Columns object that says which columns should be included in the
  30. /// output in the general case. Directories themselves can pick which
  31. /// columns are *added* to this list, such as the Git column.
  32. pub columns: Columns,
  33. /// Whether to recurse through directories with a tree view, and if so,
  34. /// which options to use. This field is only relevant here if the `tree`
  35. /// field of the RecurseOptions is `true`.
  36. pub recurse: Option<(RecurseOptions, FileFilter)>,
  37. /// Whether to show a header line or not.
  38. pub header: bool,
  39. /// Whether to show each file's extended attributes.
  40. pub xattr: bool,
  41. pub colours: Colours,
  42. }
  43. impl Details {
  44. pub fn view(&self, dir: Option<&Dir>, files: &[File]) {
  45. // First, transform the Columns object into a vector of columns for
  46. // the current directory.
  47. let mut table = Table::with_options(self.colours, self.columns.for_dir(dir), self.columns.size_format);
  48. if self.header { table.add_header() }
  49. // Then add files to the table and print it out.
  50. self.add_files_to_table(&mut table, files, 0);
  51. table.print_table(self.xattr, self.recurse.is_some());
  52. }
  53. /// Adds files to the table - recursively, if the `recurse` option
  54. /// is present.
  55. fn add_files_to_table(&self, table: &mut Table, src: &[File], depth: usize) {
  56. for (index, file) in src.iter().enumerate() {
  57. table.add_file(file, depth, index == src.len() - 1);
  58. // There are two types of recursion that exa supports: a tree
  59. // view, which is dealt with here, and multiple listings, which is
  60. // dealt with in the main module. So only actually recurse if we
  61. // are in tree mode - the other case will be dealt with elsewhere.
  62. if let Some((r, filter)) = self.recurse {
  63. if r.tree == false || r.is_too_deep(depth) {
  64. continue;
  65. }
  66. // Use the filter to remove unwanted files *before* expanding
  67. // them, so we don't examine any directories that wouldn't
  68. // have their contents listed anyway.
  69. if let Some(ref dir) = file.this {
  70. let mut files = dir.files(true);
  71. filter.transform_files(&mut files);
  72. self.add_files_to_table(table, &files, depth + 1);
  73. }
  74. }
  75. }
  76. }
  77. }
  78. struct Row {
  79. /// Vector of cells to display.
  80. cells: Vec<Cell>,
  81. /// This file's name, in coloured output. The name is treated separately
  82. /// from the other cells, as it never requires padding.
  83. name: String,
  84. /// How many directories deep into the tree structure this is. Directories
  85. /// on top have depth 0.
  86. depth: usize,
  87. /// Vector of this file's extended attributes, if that feature is active.
  88. attrs: Vec<Attribute>,
  89. /// Whether this is the last entry in the directory. This flag is used
  90. /// when calculating the tree view.
  91. last: bool,
  92. /// Whether this file is a directory and has any children. Also used when
  93. /// calculating the tree view.
  94. children: bool,
  95. }
  96. /// A **Table** object gets built up by the view as it lists files and
  97. /// directories.
  98. struct Table {
  99. columns: Vec<Column>,
  100. rows: Vec<Row>,
  101. local: Locals,
  102. colours: Colours,
  103. }
  104. impl Table {
  105. /// Create a new, empty Table object, setting the caching fields to their
  106. /// empty states.
  107. fn with_options(colours: Colours, columns: Vec<Column>, size: SizeFormat) -> Table {
  108. Table {
  109. columns: columns,
  110. local: Locals {
  111. time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()),
  112. numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()),
  113. users: OSUsers::empty_cache(),
  114. current_year: LocalDateTime::now().year(),
  115. size_format: size,
  116. },
  117. rows: Vec::new(),
  118. colours: colours,
  119. }
  120. }
  121. /// Add a dummy "header" row to the table, which contains the names of all
  122. /// the columns, underlined. This has dummy data for the cases that aren't
  123. /// actually used, such as the depth or list of attributes.
  124. fn add_header(&mut self) {
  125. let row = Row {
  126. depth: 0,
  127. cells: self.columns.iter().map(|c| Cell::paint(self.colours.header, c.header())).collect(),
  128. name: self.colours.header.paint("Name").to_string(),
  129. last: false,
  130. attrs: Vec::new(),
  131. children: false,
  132. };
  133. self.rows.push(row);
  134. }
  135. /// Use the list of columns to find which cells should be produced for
  136. /// this file, per-column.
  137. fn cells_for_file(&mut self, file: &File) -> Vec<Cell> {
  138. self.columns.clone().iter()
  139. .map(|c| self.display(file, c))
  140. .collect()
  141. }
  142. fn display(&mut self, file: &File, column: &Column) -> Cell {
  143. match *column {
  144. Column::Permissions => file.permissions().render(&self.colours, &mut self.local),
  145. Column::FileSize(f) => file.size().render(&self.colours, &mut self.local),
  146. Column::Timestamp(t, y) => file.timestamp(t).render(&self.colours, &mut self.local),
  147. Column::HardLinks => file.links().render(&self.colours, &mut self.local),
  148. Column::Inode => file.inode().render(&self.colours, &mut self.local),
  149. Column::Blocks => file.blocks().render(&self.colours, &mut self.local),
  150. Column::User => file.user().render(&self.colours, &mut self.local),
  151. Column::Group => file.group().render(&self.colours, &mut self.local),
  152. Column::GitStatus => file.git_status().render(&self.colours, &mut self.local),
  153. }
  154. }
  155. /// Get the cells for the given file, and add the result to the table.
  156. fn add_file(&mut self, file: &File, depth: usize, last: bool) {
  157. let row = Row {
  158. depth: depth,
  159. cells: self.cells_for_file(file),
  160. name: filename(file, &self.colours),
  161. last: last,
  162. attrs: file.xattrs.clone(),
  163. children: file.this.is_some(),
  164. };
  165. self.rows.push(row)
  166. }
  167. /// Print the table to standard output, consuming it in the process.
  168. fn print_table(self, xattr: bool, show_children: bool) {
  169. let mut stack = Vec::new();
  170. // Work out the list of column widths by finding the longest cell for
  171. // each column, then formatting each cell in that column to be the
  172. // width of that one.
  173. let column_widths: Vec<usize> = (0 .. self.columns.len())
  174. .map(|n| self.rows.iter().map(|row| row.cells[n].length).max().unwrap_or(0))
  175. .collect();
  176. for row in self.rows.into_iter() {
  177. for (n, width) in column_widths.iter().enumerate() {
  178. let padding = width - row.cells[n].length;
  179. print!("{} ", self.columns[n].alignment().pad_string(&row.cells[n].text, padding));
  180. }
  181. // A stack tracks which tree characters should be printed. It's
  182. // necessary to maintain information about the previously-printed
  183. // lines, as the output will change based on whether the
  184. // *previous* entry was the last in its directory.
  185. if show_children {
  186. stack.resize(row.depth + 1, TreePart::Edge);
  187. stack[row.depth] = if row.last { TreePart::Corner } else { TreePart::Edge };
  188. for i in 1 .. row.depth + 1 {
  189. print!("{}", self.colours.punctuation.paint(stack[i].ascii_art()));
  190. }
  191. if row.children {
  192. stack[row.depth] = if row.last { TreePart::Blank } else { TreePart::Line };
  193. }
  194. // If any tree characters have been printed, then add an extra
  195. // space, which makes the output look much better.
  196. if row.depth != 0 {
  197. print!(" ");
  198. }
  199. }
  200. // Print the name without worrying about padding.
  201. print!("{}\n", row.name);
  202. if xattr {
  203. let width = row.attrs.iter().map(|a| a.name().len()).max().unwrap_or(0);
  204. for attr in row.attrs.iter() {
  205. let name = attr.name();
  206. println!("{}\t{}",
  207. Alignment::Left.pad_string(name, width - name.len()),
  208. attr.size()
  209. )
  210. }
  211. }
  212. }
  213. }
  214. }
  215. #[derive(PartialEq, Debug, Clone)]
  216. enum TreePart {
  217. /// Rightmost column, *not* the last in the directory.
  218. Edge,
  219. /// Not the rightmost column, and the directory has not finished yet.
  220. Line,
  221. /// Rightmost column, and the last in the directory.
  222. Corner,
  223. /// Not the rightmost column, and the directory *has* finished.
  224. Blank,
  225. }
  226. impl TreePart {
  227. fn ascii_art(&self) -> &'static str {
  228. match *self {
  229. TreePart::Edge => "├──",
  230. TreePart::Line => "│ ",
  231. TreePart::Corner => "└──",
  232. TreePart::Blank => " ",
  233. }
  234. }
  235. }
  236. pub trait Render {
  237. fn render(self, colours: &Colours, local: &mut Locals) -> Cell;
  238. }
  239. impl Render for Permissions {
  240. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  241. let c = colours.perms;
  242. let bit = |bit, chr: &'static str, style: Style| {
  243. if bit { style.paint(chr) } else { colours.punctuation.paint("-") }
  244. };
  245. let file_type = match self.file_type {
  246. Type::File => colours.filetypes.normal.paint("."),
  247. Type::Directory => colours.filetypes.directory.paint("d"),
  248. Type::Pipe => colours.filetypes.special.paint("|"),
  249. Type::Link => colours.filetypes.symlink.paint("l"),
  250. Type::Special => colours.filetypes.special.paint("?"),
  251. };
  252. let x_colour = if let Type::File = self.file_type { c.user_execute_file }
  253. else { c.user_execute_other};
  254. let string = ANSIStrings( &[
  255. file_type,
  256. bit(self.user_read, "r", c.user_read),
  257. bit(self.user_write, "w", c.user_write),
  258. bit(self.user_execute, "x", x_colour),
  259. bit(self.group_read, "r", c.group_read),
  260. bit(self.group_write, "w", c.group_write),
  261. bit(self.group_execute, "x", c.group_execute),
  262. bit(self.other_read, "r", c.other_read),
  263. bit(self.other_write, "w", c.other_write),
  264. bit(self.other_execute, "x", c.other_execute),
  265. if self.attribute { c.attribute.paint("@") } else { Plain.paint(" ") },
  266. ]).to_string();
  267. Cell {
  268. text: string,
  269. length: 11,
  270. }
  271. }
  272. }
  273. impl Render for Links {
  274. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  275. let style = if self.multiple { colours.links.multi_link_file }
  276. else { colours.links.normal };
  277. Cell::paint(style, &local.numeric.format_int(self.count))
  278. }
  279. }
  280. impl Render for Blocks {
  281. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  282. match self {
  283. Blocks::Some(blocks) => Cell::paint(colours.blocks, &blocks.to_string()),
  284. Blocks::None => Cell::paint(colours.punctuation, "-"),
  285. }
  286. }
  287. }
  288. impl Render for Inode {
  289. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  290. Cell::paint(colours.inode, &self.0.to_string())
  291. }
  292. }
  293. impl Render for Size {
  294. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  295. if let Size::Some(offset) = self {
  296. let result = match local.size_format {
  297. SizeFormat::DecimalBytes => decimal_prefix(offset as f64),
  298. SizeFormat::BinaryBytes => binary_prefix(offset as f64),
  299. SizeFormat::JustBytes => return Cell::paint(colours.size.numbers, &local.numeric.format_int(offset)),
  300. };
  301. match result {
  302. Standalone(bytes) => Cell::paint(colours.size.numbers, &*bytes.to_string()),
  303. Prefixed(prefix, n) => {
  304. let number = if n < 10f64 { local.numeric.format_float(n, 1) } else { local.numeric.format_int(n as isize) };
  305. let symbol = prefix.symbol();
  306. Cell {
  307. text: ANSIStrings( &[ colours.size.numbers.paint(&number[..]), colours.size.unit.paint(symbol) ]).to_string(),
  308. length: number.len() + symbol.len(),
  309. }
  310. }
  311. }
  312. }
  313. else {
  314. Cell::paint(colours.punctuation, "-")
  315. }
  316. }
  317. }
  318. impl Render for Time {
  319. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  320. let date = LocalDateTime::at(self.0);
  321. let format = if date.year() == local.current_year {
  322. DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap()
  323. }
  324. else {
  325. DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
  326. };
  327. Cell::paint(colours.date, &format.format(date, &local.time))
  328. }
  329. }
  330. impl Render for Git {
  331. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  332. let render_char = |chr| {
  333. match chr {
  334. GitStatus::NotModified => colours.punctuation.paint("-"),
  335. GitStatus::New => colours.git.renamed.paint("N"),
  336. GitStatus::Modified => colours.git.renamed.paint("M"),
  337. GitStatus::Deleted => colours.git.renamed.paint("D"),
  338. GitStatus::Renamed => colours.git.renamed.paint("R"),
  339. GitStatus::TypeChange => colours.git.renamed.paint("T"),
  340. }
  341. };
  342. Cell {
  343. text: ANSIStrings(&[ render_char(self.staged), render_char(self.unstaged) ]).to_string(),
  344. length: 2,
  345. }
  346. }
  347. }
  348. impl Render for User {
  349. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  350. let user_name = match local.users.get_user_by_uid(self.0) {
  351. Some(user) => user.name,
  352. None => self.0.to_string(),
  353. };
  354. let style = if local.users.get_current_uid() == self.0 { colours.users.user_you }
  355. else { colours.users.user_someone_else };
  356. Cell::paint(style, &*user_name)
  357. }
  358. }
  359. impl Render for Group {
  360. fn render(self, colours: &Colours, local: &mut Locals) -> Cell {
  361. let mut style = colours.users.group_not_yours;
  362. let group_name = match local.users.get_group_by_gid(self.0) {
  363. Some(group) => {
  364. let current_uid = local.users.get_current_uid();
  365. if let Some(current_user) = local.users.get_user_by_uid(current_uid) {
  366. if current_user.primary_group == group.gid || group.members.contains(&current_user.name) {
  367. style = colours.users.group_yours;
  368. }
  369. }
  370. group.name
  371. },
  372. None => self.0.to_string(),
  373. };
  374. Cell::paint(style, &*group_name)
  375. }
  376. }
  377. pub struct Locals {
  378. pub time: locale::Time,
  379. pub numeric: locale::Numeric,
  380. pub users: OSUsers,
  381. pub size_format: SizeFormat,
  382. pub current_year: i64,
  383. }