details.rs 26 KB

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