details.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. use std::error::Error;
  2. use std::io;
  3. use std::iter::repeat;
  4. use std::path::Path;
  5. use std::string::ToString;
  6. use colours::Colours;
  7. use column::{Alignment, Column, Cell};
  8. use dir::Dir;
  9. use feature::Attribute;
  10. use file::fields as f;
  11. use file::File;
  12. use options::{Columns, FileFilter, RecurseOptions, SizeFormat};
  13. use ansi_term::{ANSIString, ANSIStrings, Style};
  14. use datetime::local::{LocalDateTime, DatePiece};
  15. use datetime::format::{DateFormat};
  16. use datetime::zoned::{VariableOffset, TimeZone};
  17. use locale;
  18. use number_prefix::{binary_prefix, decimal_prefix, Prefixed, Standalone, PrefixNames};
  19. use users::{OSUsers, Users};
  20. use users::mock::MockUsers;
  21. use super::filename;
  22. /// With the **Details** view, the output gets formatted into columns, with
  23. /// each `Column` object showing some piece of information about the file,
  24. /// such as its size, or its permissions.
  25. ///
  26. /// To do this, the results have to be written to a table, instead of
  27. /// displaying each file immediately. Then, the width of each column can be
  28. /// calculated based on the individual results, and the fields are padded
  29. /// during output.
  30. ///
  31. /// Almost all the heavy lifting is done in a Table object, which handles the
  32. /// columns for each row.
  33. #[derive(PartialEq, Debug, Copy, Clone, Default)]
  34. pub struct Details {
  35. /// A Columns object that says which columns should be included in the
  36. /// output in the general case. Directories themselves can pick which
  37. /// columns are *added* to this list, such as the Git column.
  38. pub columns: Option<Columns>,
  39. /// Whether to recurse through directories with a tree view, and if so,
  40. /// which options to use. This field is only relevant here if the `tree`
  41. /// field of the RecurseOptions is `true`.
  42. pub recurse: Option<(RecurseOptions, FileFilter)>,
  43. /// Whether to show a header line or not.
  44. pub header: bool,
  45. /// Whether to show each file's extended attributes.
  46. pub xattr: bool,
  47. /// The colours to use to display information in the table, including the
  48. /// colour of the tree view symbols.
  49. pub colours: Colours,
  50. }
  51. impl Details {
  52. pub fn view(&self, dir: Option<&Dir>, files: &[File]) {
  53. // First, transform the Columns object into a vector of columns for
  54. // the current directory.
  55. let columns_for_dir = match self.columns {
  56. Some(cols) => cols.for_dir(dir),
  57. None => Vec::new(),
  58. };
  59. let mut table = Table::with_options(self.colours, columns_for_dir);
  60. if self.header { table.add_header() }
  61. // Then add files to the table and print it out.
  62. self.add_files_to_table(&mut table, files, 0);
  63. for cell in table.print_table(self.xattr, self.recurse.is_some()) {
  64. println!("{}", cell.text);
  65. }
  66. }
  67. /// Adds files to the table - recursively, if the `recurse` option
  68. /// is present.
  69. fn add_files_to_table<U: Users>(&self, table: &mut Table<U>, src: &[File], depth: usize) {
  70. for (index, file) in src.iter().enumerate() {
  71. table.add_file(file, depth, index == src.len() - 1, true);
  72. // There are two types of recursion that exa supports: a tree
  73. // view, which is dealt with here, and multiple listings, which is
  74. // dealt with in the main module. So only actually recurse if we
  75. // are in tree mode - the other case will be dealt with elsewhere.
  76. if let Some((r, filter)) = self.recurse {
  77. if r.tree == false || r.is_too_deep(depth) {
  78. continue;
  79. }
  80. // Use the filter to remove unwanted files *before* expanding
  81. // them, so we don't examine any directories that wouldn't
  82. // have their contents listed anyway.
  83. match file.this {
  84. Some(Ok(ref dir)) => {
  85. let mut files = Vec::new();
  86. for file_to_add in dir.files(true) {
  87. match file_to_add {
  88. Ok(f) => files.push(f),
  89. Err((path, e)) => table.add_error(&e, depth + 1, false, Some(&*path)),
  90. }
  91. }
  92. filter.transform_files(&mut files);
  93. self.add_files_to_table(table, &files, depth + 1);
  94. },
  95. Some(Err(ref e)) => {
  96. table.add_error(e, depth + 1, true, None);
  97. },
  98. None => {},
  99. }
  100. }
  101. }
  102. }
  103. }
  104. struct Row {
  105. /// Vector of cells to display.
  106. ///
  107. /// Most of the rows will be files that have had their metadata
  108. /// successfully queried and displayed in these cells, so this will almost
  109. /// always be `Some`. It will be `None` for a row that's only displaying
  110. /// an attribute or an error.
  111. cells: Option<Vec<Cell>>,
  112. // Did You Know?
  113. // A Vec<Cell> and an Option<Vec<Cell>> actually have the same byte size!
  114. /// This file's name, in coloured output. The name is treated separately
  115. /// from the other cells, as it never requires padding.
  116. name: Cell,
  117. /// How many directories deep into the tree structure this is. Directories
  118. /// on top have depth 0.
  119. depth: usize,
  120. /// Vector of this file's extended attributes, if that feature is active.
  121. attrs: Vec<Attribute>,
  122. /// Whether this is the last entry in the directory. This flag is used
  123. /// when calculating the tree view.
  124. last: bool,
  125. /// Whether this file is a directory and has any children. Also used when
  126. /// calculating the tree view.
  127. children: bool,
  128. }
  129. impl Row {
  130. /// Gets the 'width' of the indexed column, if present. If not, returns 0.
  131. fn column_width(&self, index: usize) -> usize {
  132. match self.cells {
  133. Some(ref cells) => cells[index].length,
  134. None => 0,
  135. }
  136. }
  137. }
  138. /// A **Table** object gets built up by the view as it lists files and
  139. /// directories.
  140. pub struct Table<U> {
  141. columns: Vec<Column>,
  142. rows: Vec<Row>,
  143. time: locale::Time,
  144. numeric: locale::Numeric,
  145. tz: VariableOffset,
  146. users: U,
  147. colours: Colours,
  148. current_year: i64,
  149. }
  150. impl Default for Table<MockUsers> {
  151. fn default() -> Table<MockUsers> {
  152. Table {
  153. columns: Columns::default().for_dir(None),
  154. rows: Vec::new(),
  155. time: locale::Time::english(),
  156. numeric: locale::Numeric::english(),
  157. tz: VariableOffset::localtime().unwrap(),
  158. users: MockUsers::with_current_uid(0),
  159. colours: Colours::default(),
  160. current_year: 1234,
  161. }
  162. }
  163. }
  164. impl Table<OSUsers> {
  165. /// Create a new, empty Table object, setting the caching fields to their
  166. /// empty states.
  167. pub fn with_options(colours: Colours, columns: Vec<Column>) -> Table<OSUsers> {
  168. Table {
  169. columns: columns,
  170. rows: Vec::new(),
  171. time: locale::Time::load_user_locale().unwrap_or_else(|_| locale::Time::english()),
  172. numeric: locale::Numeric::load_user_locale().unwrap_or_else(|_| locale::Numeric::english()),
  173. tz: VariableOffset::localtime().unwrap(),
  174. users: OSUsers::empty_cache(),
  175. colours: colours,
  176. current_year: LocalDateTime::now().year(),
  177. }
  178. }
  179. }
  180. impl<U> Table<U> where U: Users {
  181. /// Add a dummy "header" row to the table, which contains the names of all
  182. /// the columns, underlined. This has dummy data for the cases that aren't
  183. /// actually used, such as the depth or list of attributes.
  184. pub fn add_header(&mut self) {
  185. let row = Row {
  186. depth: 0,
  187. cells: Some(self.columns.iter().map(|c| Cell::paint(self.colours.header, c.header())).collect()),
  188. name: Cell::paint(self.colours.header, "Name"),
  189. last: false,
  190. attrs: Vec::new(),
  191. children: false,
  192. };
  193. self.rows.push(row);
  194. }
  195. pub fn add_error(&mut self, error: &io::Error, depth: usize, last: bool, path: Option<&Path>) {
  196. let error_message = match path {
  197. Some(path) => format!("<{}: {}>", path.display(), error),
  198. None => format!("<{}>", error),
  199. };
  200. let row = Row {
  201. depth: depth,
  202. cells: None,
  203. name: Cell::paint(self.colours.broken_arrow, &error_message),
  204. last: last,
  205. attrs: Vec::new(),
  206. children: false,
  207. };
  208. self.rows.push(row);
  209. }
  210. /// Get the cells for the given file, and add the result to the table.
  211. pub fn add_file(&mut self, file: &File, depth: usize, last: bool, links: bool) {
  212. let cells = self.cells_for_file(file);
  213. self.add_file_with_cells(cells, file, depth, last, links)
  214. }
  215. pub fn add_file_with_cells(&mut self, cells: Vec<Cell>, file: &File, depth: usize, last: bool, links: bool) {
  216. let row = Row {
  217. depth: depth,
  218. cells: Some(cells),
  219. name: Cell { text: filename(file, &self.colours, links), length: file.file_name_width() },
  220. last: last,
  221. attrs: file.xattrs.clone(),
  222. children: file.this.is_some(),
  223. };
  224. self.rows.push(row);
  225. }
  226. /// Use the list of columns to find which cells should be produced for
  227. /// this file, per-column.
  228. pub fn cells_for_file(&mut self, file: &File) -> Vec<Cell> {
  229. self.columns.clone().iter()
  230. .map(|c| self.display(file, c))
  231. .collect()
  232. }
  233. fn display(&mut self, file: &File, column: &Column) -> Cell {
  234. match *column {
  235. Column::Permissions => self.render_permissions(file.permissions()),
  236. Column::FileSize(fmt) => self.render_size(file.size(), fmt),
  237. Column::Timestamp(t) => self.render_time(file.timestamp(t)),
  238. Column::HardLinks => self.render_links(file.links()),
  239. Column::Inode => self.render_inode(file.inode()),
  240. Column::Blocks => self.render_blocks(file.blocks()),
  241. Column::User => self.render_user(file.user()),
  242. Column::Group => self.render_group(file.group()),
  243. Column::GitStatus => self.render_git_status(file.git_status()),
  244. }
  245. }
  246. fn render_permissions(&self, permissions: f::Permissions) -> Cell {
  247. let c = self.colours.perms;
  248. let bit = |bit, chr: &'static str, style: Style| {
  249. if bit { style.paint(chr) } else { self.colours.punctuation.paint("-") }
  250. };
  251. let file_type = match permissions.file_type {
  252. f::Type::File => self.colours.filetypes.normal.paint("."),
  253. f::Type::Directory => self.colours.filetypes.directory.paint("d"),
  254. f::Type::Pipe => self.colours.filetypes.special.paint("|"),
  255. f::Type::Link => self.colours.filetypes.symlink.paint("l"),
  256. f::Type::Special => self.colours.filetypes.special.paint("?"),
  257. };
  258. let x_colour = if let f::Type::File = permissions.file_type { c.user_execute_file }
  259. else { c.user_execute_other };
  260. let mut columns = vec![
  261. file_type,
  262. bit(permissions.user_read, "r", c.user_read),
  263. bit(permissions.user_write, "w", c.user_write),
  264. bit(permissions.user_execute, "x", x_colour),
  265. bit(permissions.group_read, "r", c.group_read),
  266. bit(permissions.group_write, "w", c.group_write),
  267. bit(permissions.group_execute, "x", c.group_execute),
  268. bit(permissions.other_read, "r", c.other_read),
  269. bit(permissions.other_write, "w", c.other_write),
  270. bit(permissions.other_execute, "x", c.other_execute),
  271. ];
  272. if permissions.attribute {
  273. columns.push(c.attribute.paint("@"));
  274. }
  275. Cell {
  276. text: ANSIStrings(&columns).to_string(),
  277. length: columns.len(),
  278. }
  279. }
  280. fn render_links(&self, links: f::Links) -> Cell {
  281. let style = if links.multiple { self.colours.links.multi_link_file }
  282. else { self.colours.links.normal };
  283. Cell::paint(style, &self.numeric.format_int(links.count))
  284. }
  285. fn render_blocks(&self, blocks: f::Blocks) -> Cell {
  286. match blocks {
  287. f::Blocks::Some(blocks) => Cell::paint(self.colours.blocks, &blocks.to_string()),
  288. f::Blocks::None => Cell::paint(self.colours.punctuation, "-"),
  289. }
  290. }
  291. fn render_inode(&self, inode: f::Inode) -> Cell {
  292. Cell::paint(self.colours.inode, &inode.0.to_string())
  293. }
  294. fn render_size(&self, size: f::Size, size_format: SizeFormat) -> Cell {
  295. if let f::Size::Some(offset) = size {
  296. let result = match size_format {
  297. SizeFormat::DecimalBytes => decimal_prefix(offset as f64),
  298. SizeFormat::BinaryBytes => binary_prefix(offset as f64),
  299. SizeFormat::JustBytes => return Cell::paint(self.colours.size.numbers, &self.numeric.format_int(offset)),
  300. };
  301. match result {
  302. Standalone(bytes) => Cell::paint(self.colours.size.numbers, &*bytes.to_string()),
  303. Prefixed(prefix, n) => {
  304. let number = if n < 10f64 { self.numeric.format_float(n, 1) } else { self.numeric.format_int(n as isize) };
  305. let symbol = prefix.symbol();
  306. Cell {
  307. text: ANSIStrings( &[ self.colours.size.numbers.paint(&number[..]), self.colours.size.unit.paint(symbol) ]).to_string(),
  308. length: number.len() + symbol.len(),
  309. }
  310. }
  311. }
  312. }
  313. else {
  314. Cell::paint(self.colours.punctuation, "-")
  315. }
  316. }
  317. fn render_time(&self, timestamp: f::Time) -> Cell {
  318. let date = self.tz.at(LocalDateTime::at(timestamp.0));
  319. let format = if date.year() == self.current_year {
  320. DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap()
  321. }
  322. else {
  323. DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
  324. };
  325. Cell::paint(self.colours.date, &format.format(&date, &self.time))
  326. }
  327. fn render_git_status(&self, git: f::Git) -> Cell {
  328. Cell {
  329. text: ANSIStrings(&[ self.render_git_char(git.staged),
  330. self.render_git_char(git.unstaged) ]).to_string(),
  331. length: 2,
  332. }
  333. }
  334. fn render_git_char(&self, status: f::GitStatus) -> ANSIString {
  335. match status {
  336. f::GitStatus::NotModified => self.colours.punctuation.paint("-"),
  337. f::GitStatus::New => self.colours.git.new.paint("N"),
  338. f::GitStatus::Modified => self.colours.git.modified.paint("M"),
  339. f::GitStatus::Deleted => self.colours.git.deleted.paint("D"),
  340. f::GitStatus::Renamed => self.colours.git.renamed.paint("R"),
  341. f::GitStatus::TypeChange => self.colours.git.typechange.paint("T"),
  342. }
  343. }
  344. fn render_user(&mut self, user: f::User) -> Cell {
  345. let user_name = match self.users.get_user_by_uid(user.0) {
  346. Some(user) => user.name,
  347. None => user.0.to_string(),
  348. };
  349. let style = if self.users.get_current_uid() == user.0 { self.colours.users.user_you }
  350. else { self.colours.users.user_someone_else };
  351. Cell::paint(style, &*user_name)
  352. }
  353. fn render_group(&mut self, group: f::Group) -> Cell {
  354. let mut style = self.colours.users.group_not_yours;
  355. let group_name = match self.users.get_group_by_gid(group.0) {
  356. Some(group) => {
  357. let current_uid = self.users.get_current_uid();
  358. if let Some(current_user) = self.users.get_user_by_uid(current_uid) {
  359. if current_user.primary_group == group.gid || group.members.contains(&current_user.name) {
  360. style = self.colours.users.group_yours;
  361. }
  362. }
  363. group.name
  364. },
  365. None => group.0.to_string(),
  366. };
  367. Cell::paint(style, &*group_name)
  368. }
  369. /// Render the table as a vector of Cells, to be displayed on standard output.
  370. pub fn print_table(&self, xattr: bool, show_children: bool) -> Vec<Cell> {
  371. let mut stack = Vec::new();
  372. let mut cells = Vec::new();
  373. // Work out the list of column widths by finding the longest cell for
  374. // each column, then formatting each cell in that column to be the
  375. // width of that one.
  376. let column_widths: Vec<usize> = (0 .. self.columns.len())
  377. .map(|n| self.rows.iter().map(|row| row.column_width(n)).max().unwrap_or(0))
  378. .collect();
  379. let total_width: usize = self.columns.len() + column_widths.iter().sum::<usize>();
  380. for row in self.rows.iter() {
  381. let mut cell = Cell::empty();
  382. if let Some(ref cells) = row.cells {
  383. for (n, width) in column_widths.iter().enumerate() {
  384. match self.columns[n].alignment() {
  385. Alignment::Left => { cell.append(&cells[n]); cell.add_spaces(width - cells[n].length); }
  386. Alignment::Right => { cell.add_spaces(width - cells[n].length); cell.append(&cells[n]); }
  387. }
  388. cell.add_spaces(1);
  389. }
  390. }
  391. else {
  392. cell.add_spaces(total_width)
  393. }
  394. let mut filename = String::new();
  395. let mut filename_length = 0;
  396. // A stack tracks which tree characters should be printed. It's
  397. // necessary to maintain information about the previously-printed
  398. // lines, as the output will change based on whether the
  399. // *previous* entry was the last in its directory.
  400. if show_children {
  401. stack.resize(row.depth + 1, TreePart::Edge);
  402. stack[row.depth] = if row.last { TreePart::Corner } else { TreePart::Edge };
  403. for i in 1 .. row.depth + 1 {
  404. filename.push_str(&*self.colours.punctuation.paint(stack[i].ascii_art()).to_string());
  405. filename_length += 4;
  406. }
  407. if row.children {
  408. stack[row.depth] = if row.last { TreePart::Blank } else { TreePart::Line };
  409. }
  410. // If any tree characters have been printed, then add an extra
  411. // space, which makes the output look much better.
  412. if row.depth != 0 {
  413. filename.push(' ');
  414. filename_length += 1;
  415. }
  416. }
  417. // Print the name without worrying about padding.
  418. filename.push_str(&*row.name.text);
  419. filename_length += row.name.length;
  420. if xattr {
  421. let width = row.attrs.iter().map(|a| a.name().len()).max().unwrap_or(0);
  422. for attr in row.attrs.iter() {
  423. let name = attr.name();
  424. let spaces: String = repeat(" ").take(width - name.len()).collect();
  425. filename.push_str(&*format!("\n{}{} {}", name, spaces, attr.size()))
  426. }
  427. }
  428. cell.append(&Cell { text: filename, length: filename_length });
  429. cells.push(cell);
  430. }
  431. cells
  432. }
  433. }
  434. #[derive(PartialEq, Debug, Clone)]
  435. enum TreePart {
  436. /// Rightmost column, *not* the last in the directory.
  437. Edge,
  438. /// Not the rightmost column, and the directory has not finished yet.
  439. Line,
  440. /// Rightmost column, and the last in the directory.
  441. Corner,
  442. /// Not the rightmost column, and the directory *has* finished.
  443. Blank,
  444. }
  445. impl TreePart {
  446. fn ascii_art(&self) -> &'static str {
  447. match *self {
  448. TreePart::Edge => "├──",
  449. TreePart::Line => "│ ",
  450. TreePart::Corner => "└──",
  451. TreePart::Blank => " ",
  452. }
  453. }
  454. }
  455. #[cfg(test)]
  456. pub mod test {
  457. pub use super::Table;
  458. pub use file::File;
  459. pub use file::fields as f;
  460. pub use column::{Cell, Column};
  461. pub use users::{User, Group, uid_t, gid_t};
  462. pub use users::mock::MockUsers;
  463. pub use ansi_term::Style;
  464. pub use ansi_term::Colour::*;
  465. pub fn newser(uid: uid_t, name: &str, group: gid_t) -> User {
  466. User {
  467. uid: uid,
  468. name: name.to_string(),
  469. primary_group: group,
  470. home_dir: String::new(),
  471. shell: String::new(),
  472. }
  473. }
  474. // These tests create a new, default Table object, then fill in the
  475. // expected style in a certain way. This means we can check that the
  476. // right style is being used, as otherwise, it would just be plain.
  477. //
  478. // Doing things with fields is way easier than having to fake the entire
  479. // Metadata struct, which is what I was doing before!
  480. mod users {
  481. use super::*;
  482. #[test]
  483. fn named() {
  484. let mut table = Table::default();
  485. table.colours.users.user_you = Red.bold();
  486. let mut users = MockUsers::with_current_uid(1000);
  487. users.add_user(newser(1000, "enoch", 100));
  488. table.users = users;
  489. let user = f::User(1000);
  490. let expected = Cell::paint(Red.bold(), "enoch");
  491. assert_eq!(expected, table.render_user(user))
  492. }
  493. #[test]
  494. fn unnamed() {
  495. let mut table = Table::default();
  496. table.colours.users.user_you = Cyan.bold();
  497. let users = MockUsers::with_current_uid(1000);
  498. table.users = users;
  499. let user = f::User(1000);
  500. let expected = Cell::paint(Cyan.bold(), "1000");
  501. assert_eq!(expected, table.render_user(user));
  502. }
  503. #[test]
  504. fn different_named() {
  505. let mut table = Table::default();
  506. table.colours.users.user_someone_else = Green.bold();
  507. table.users.add_user(newser(1000, "enoch", 100));
  508. let user = f::User(1000);
  509. let expected = Cell::paint(Green.bold(), "enoch");
  510. assert_eq!(expected, table.render_user(user));
  511. }
  512. #[test]
  513. fn different_unnamed() {
  514. let mut table = Table::default();
  515. table.colours.users.user_someone_else = Red.normal();
  516. let user = f::User(1000);
  517. let expected = Cell::paint(Red.normal(), "1000");
  518. assert_eq!(expected, table.render_user(user));
  519. }
  520. #[test]
  521. fn overflow() {
  522. let mut table = Table::default();
  523. table.colours.users.user_someone_else = Blue.underline();
  524. let user = f::User(2_147_483_648);
  525. let expected = Cell::paint(Blue.underline(), "2147483648");
  526. assert_eq!(expected, table.render_user(user));
  527. }
  528. }
  529. mod groups {
  530. use super::*;
  531. #[test]
  532. fn named() {
  533. let mut table = Table::default();
  534. table.colours.users.group_not_yours = Fixed(101).normal();
  535. let mut users = MockUsers::with_current_uid(1000);
  536. users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] });
  537. table.users = users;
  538. let group = f::Group(100);
  539. let expected = Cell::paint(Fixed(101).normal(), "folk");
  540. assert_eq!(expected, table.render_group(group))
  541. }
  542. #[test]
  543. fn unnamed() {
  544. let mut table = Table::default();
  545. table.colours.users.group_not_yours = Fixed(87).normal();
  546. let users = MockUsers::with_current_uid(1000);
  547. table.users = users;
  548. let group = f::Group(100);
  549. let expected = Cell::paint(Fixed(87).normal(), "100");
  550. assert_eq!(expected, table.render_group(group));
  551. }
  552. #[test]
  553. fn primary() {
  554. let mut table = Table::default();
  555. table.colours.users.group_yours = Fixed(64).normal();
  556. let mut users = MockUsers::with_current_uid(2);
  557. users.add_user(newser(2, "eve", 100));
  558. users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] });
  559. table.users = users;
  560. let group = f::Group(100);
  561. let expected = Cell::paint(Fixed(64).normal(), "folk");
  562. assert_eq!(expected, table.render_group(group))
  563. }
  564. #[test]
  565. fn secondary() {
  566. let mut table = Table::default();
  567. table.colours.users.group_yours = Fixed(31).normal();
  568. let mut users = MockUsers::with_current_uid(2);
  569. users.add_user(newser(2, "eve", 666));
  570. users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![ "eve".to_string() ] });
  571. table.users = users;
  572. let group = f::Group(100);
  573. let expected = Cell::paint(Fixed(31).normal(), "folk");
  574. assert_eq!(expected, table.render_group(group))
  575. }
  576. #[test]
  577. fn overflow() {
  578. let mut table = Table::default();
  579. table.colours.users.group_not_yours = Blue.underline();
  580. let group = f::Group(2_147_483_648);
  581. let expected = Cell::paint(Blue.underline(), "2147483648");
  582. assert_eq!(expected, table.render_group(group));
  583. }
  584. }
  585. }