details.rs 26 KB

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