file.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. use std::old_io::{fs, IoResult};
  2. use std::old_io as io;
  3. use std::ascii::AsciiExt;
  4. use std::env::current_dir;
  5. use ansi_term::{ANSIString, ANSIStrings, Colour, Style};
  6. use ansi_term::Style::Plain;
  7. use ansi_term::Colour::{Red, Green, Yellow, Blue, Purple, Cyan, Fixed};
  8. use users::Users;
  9. use locale;
  10. use output::details::UserLocale;
  11. use number_prefix::{binary_prefix, decimal_prefix, Prefixed, Standalone, PrefixNames};
  12. use datetime::local::{LocalDateTime, DatePiece};
  13. use datetime::format::{DateFormat};
  14. use column::{Column, Cell};
  15. use column::Column::*;
  16. use dir::Dir;
  17. use filetype::HasType;
  18. use options::{SizeFormat, TimeType};
  19. use xattr;
  20. use xattr::Attribute;
  21. /// This grey value is directly in between white and black, so it's guaranteed
  22. /// to show up on either backgrounded terminal.
  23. pub static GREY: Colour = Fixed(244);
  24. /// A **File** is a wrapper around one of Rust's Path objects, along with
  25. /// associated data about the file.
  26. ///
  27. /// Each file is definitely going to have its filename displayed at least
  28. /// once, have its file extension extracted at least once, and have its stat
  29. /// information queried at least once, so it makes sense to do all this at the
  30. /// start and hold on to all the information.
  31. pub struct File<'a> {
  32. pub name: String,
  33. pub dir: Option<&'a Dir>,
  34. pub ext: Option<String>,
  35. pub path: Path,
  36. pub stat: io::FileStat,
  37. pub xattrs: Vec<Attribute>,
  38. pub this: Option<Dir>,
  39. }
  40. impl<'a> File<'a> {
  41. /// Create a new File object from the given Path, inside the given Dir, if
  42. /// appropriate. Paths specified directly on the command-line have no Dirs.
  43. ///
  44. /// This uses lstat instead of stat, which doesn't follow symbolic links.
  45. pub fn from_path(path: &Path, parent: Option<&'a Dir>, recurse: bool) -> IoResult<File<'a>> {
  46. fs::lstat(path).map(|stat| File::with_stat(stat, path, parent, recurse))
  47. }
  48. /// Create a new File object from the given Stat result, and other data.
  49. pub fn with_stat(stat: io::FileStat, path: &Path, parent: Option<&'a Dir>, recurse: bool) -> File<'a> {
  50. let filename = path_filename(path);
  51. // If we are recursing, then the `this` field contains a Dir object
  52. // that represents the current File as a directory, if it is a
  53. // directory. This is used for the --tree option.
  54. let this = if recurse && stat.kind == io::FileType::Directory {
  55. Dir::readdir(path).ok()
  56. }
  57. else {
  58. None
  59. };
  60. File {
  61. path: path.clone(),
  62. dir: parent,
  63. stat: stat,
  64. ext: ext(&filename),
  65. xattrs: xattr::llist(path).unwrap_or(Vec::new()),
  66. name: filename.to_string(),
  67. this: this,
  68. }
  69. }
  70. /// Whether this file is a dotfile or not.
  71. pub fn is_dotfile(&self) -> bool {
  72. self.name.starts_with(".")
  73. }
  74. /// Whether this file is a temporary file or not.
  75. pub fn is_tmpfile(&self) -> bool {
  76. let name = &self.name;
  77. name.ends_with("~") || (name.starts_with("#") && name.ends_with("#"))
  78. }
  79. /// Get the data for a column, formatted as a coloured string.
  80. pub fn display<U: Users>(&self, column: &Column, users_cache: &mut U, locale: &UserLocale) -> Cell {
  81. match *column {
  82. Permissions => self.permissions_string(),
  83. FileSize(f) => self.file_size(f, &locale.numeric),
  84. Timestamp(t, y) => self.timestamp(t, y, &locale.time),
  85. HardLinks => self.hard_links(&locale.numeric),
  86. Inode => self.inode(),
  87. Blocks => self.blocks(&locale.numeric),
  88. User => self.user(users_cache),
  89. Group => self.group(users_cache),
  90. GitStatus => self.git_status(),
  91. }
  92. }
  93. /// The "file name view" is what's displayed in the column and lines
  94. /// views, but *not* in the grid view.
  95. ///
  96. /// It consists of the file name coloured in the appropriate style,
  97. /// with special formatting for a symlink.
  98. pub fn file_name_view(&self) -> String {
  99. if self.stat.kind == io::FileType::Symlink {
  100. self.symlink_file_name_view()
  101. }
  102. else {
  103. self.file_colour().paint(&*self.name).to_string()
  104. }
  105. }
  106. /// If this file is a symlink, returns a string displaying its name,
  107. /// and an arrow pointing to the file it links to, which is also
  108. /// coloured in the appropriate style.
  109. ///
  110. /// If the symlink target doesn't exist, then instead of displaying
  111. /// an error, highlight the target and arrow in red. The error would
  112. /// be shown out of context, and it's almost always because the
  113. /// target doesn't exist.
  114. fn symlink_file_name_view(&self) -> String {
  115. let name = &*self.name;
  116. let style = self.file_colour();
  117. if let Ok(path) = fs::readlink(&self.path) {
  118. let target_path = match self.dir {
  119. Some(dir) => dir.join(path),
  120. None => path,
  121. };
  122. match self.target_file(&target_path) {
  123. Ok(file) => {
  124. // Generate a preview for the path this symlink links to.
  125. // The preview should consist of the directory of the file
  126. // (if present) in cyan, an extra slash if necessary, then
  127. // the target file, colourised in the appropriate style.
  128. let mut path_prefix = String::new();
  129. // The root directory has the name "/", which has to be
  130. // catered for separately, otherwise there'll be two
  131. // slashes in the resulting output.
  132. if file.path.is_absolute() && file.name != "/" {
  133. path_prefix.push_str("/");
  134. }
  135. let path_bytes: Vec<&[u8]> = file.path.components().collect();
  136. if !path_bytes.is_empty() {
  137. // Use init() to add all but the last component of the
  138. // path to the prefix. init() panics when given an
  139. // empty list, hence the check.
  140. for component in path_bytes.init().iter() {
  141. let string = String::from_utf8_lossy(component).to_string();
  142. path_prefix.push_str(&string);
  143. path_prefix.push_str("/");
  144. }
  145. }
  146. format!("{} {} {}",
  147. style.paint(name),
  148. GREY.paint("=>"),
  149. ANSIStrings(&[ Cyan.paint(&path_prefix),
  150. file.file_colour().paint(&file.name) ]))
  151. },
  152. Err(filename) => format!("{} {} {}",
  153. style.paint(name),
  154. Red.paint("=>"),
  155. Red.underline().paint(&filename)),
  156. }
  157. }
  158. else {
  159. style.paint(name).to_string()
  160. }
  161. }
  162. /// The `ansi_term::Style` that this file's name should be painted.
  163. pub fn file_colour(&self) -> Style {
  164. self.get_type().style()
  165. }
  166. /// The Unicode 'display width' of the filename.
  167. ///
  168. /// This is related to the number of graphemes in the string: most
  169. /// characters are 1 columns wide, but in some contexts, certain
  170. /// characters are actually 2 columns wide.
  171. pub fn file_name_width(&self) -> usize {
  172. self.name.width(false)
  173. }
  174. /// Assuming the current file is a symlink, follows the link and
  175. /// returns a File object from the path the link points to.
  176. ///
  177. /// If statting the file fails (usually because the file on the
  178. /// other end doesn't exist), returns the *filename* of the file
  179. /// that should be there.
  180. fn target_file(&self, target_path: &Path) -> Result<File, String> {
  181. let filename = path_filename(target_path);
  182. // Use stat instead of lstat - we *want* to follow links.
  183. if let Ok(stat) = fs::stat(target_path) {
  184. Ok(File {
  185. path: target_path.clone(),
  186. dir: self.dir,
  187. stat: stat,
  188. ext: ext(&filename),
  189. xattrs: xattr::list(target_path).unwrap_or(Vec::new()),
  190. name: filename.to_string(),
  191. this: None,
  192. })
  193. }
  194. else {
  195. Err(filename.to_string())
  196. }
  197. }
  198. /// This file's number of hard links as a coloured string.
  199. fn hard_links(&self, locale: &locale::Numeric) -> Cell {
  200. let style = if self.has_multiple_links() { Red.on(Yellow) } else { Red.normal() };
  201. Cell::paint(style, &locale.format_int(self.stat.unstable.nlink as isize)[..])
  202. }
  203. /// Whether this is a regular file with more than one link.
  204. ///
  205. /// This is important, because a file with multiple links is uncommon,
  206. /// while you can come across directories and other types with multiple
  207. /// links much more often.
  208. fn has_multiple_links(&self) -> bool {
  209. self.stat.kind == io::FileType::RegularFile && self.stat.unstable.nlink > 1
  210. }
  211. /// This file's inode as a coloured string.
  212. fn inode(&self) -> Cell {
  213. Cell::paint(Purple.normal(), &*self.stat.unstable.inode.to_string())
  214. }
  215. /// This file's number of filesystem blocks (if available) as a coloured string.
  216. fn blocks(&self, locale: &locale::Numeric) -> Cell {
  217. if self.stat.kind == io::FileType::RegularFile || self.stat.kind == io::FileType::Symlink {
  218. Cell::paint(Cyan.normal(), &locale.format_int(self.stat.unstable.blocks as isize)[..])
  219. }
  220. else {
  221. Cell { text: GREY.paint("-").to_string(), length: 1 }
  222. }
  223. }
  224. /// This file's owner's username as a coloured string.
  225. ///
  226. /// If the user is not present, then it formats the uid as a number
  227. /// instead. This usually happens when a user is deleted, but still owns
  228. /// files.
  229. fn user<U: Users>(&self, users_cache: &mut U) -> Cell {
  230. let uid = self.stat.unstable.uid as i32;
  231. let user_name = match users_cache.get_user_by_uid(uid) {
  232. Some(user) => user.name,
  233. None => self.stat.unstable.uid.to_string(),
  234. };
  235. let style = if users_cache.get_current_uid() == uid { Yellow.bold() } else { Plain };
  236. Cell::paint(style, &*user_name)
  237. }
  238. /// This file's group name as a coloured string.
  239. ///
  240. /// As above, if not present, it formats the gid as a number instead.
  241. fn group<U: Users>(&self, users_cache: &mut U) -> Cell {
  242. let gid = self.stat.unstable.gid as u32;
  243. let mut style = Plain;
  244. let group_name = match users_cache.get_group_by_gid(gid) {
  245. Some(group) => {
  246. let current_uid = users_cache.get_current_uid();
  247. if let Some(current_user) = users_cache.get_user_by_uid(current_uid) {
  248. if current_user.primary_group == group.gid || group.members.contains(&current_user.name) {
  249. style = Yellow.bold();
  250. }
  251. }
  252. group.name
  253. },
  254. None => self.stat.unstable.gid.to_string(),
  255. };
  256. Cell::paint(style, &*group_name)
  257. }
  258. /// This file's size, formatted using the given way, as a coloured string.
  259. ///
  260. /// For directories, no size is given. Although they do have a size on
  261. /// some filesystems, I've never looked at one of those numbers and gained
  262. /// any information from it, so by emitting "-" instead, the table is less
  263. /// cluttered with numbers.
  264. fn file_size(&self, size_format: SizeFormat, locale: &locale::Numeric) -> Cell {
  265. if self.stat.kind == io::FileType::Directory {
  266. Cell { text: GREY.paint("-").to_string(), length: 1 }
  267. }
  268. else {
  269. let result = match size_format {
  270. SizeFormat::DecimalBytes => decimal_prefix(self.stat.size as f64),
  271. SizeFormat::BinaryBytes => binary_prefix(self.stat.size as f64),
  272. SizeFormat::JustBytes => return Cell::paint(Green.bold(), &locale.format_int(self.stat.size as isize)[..]),
  273. };
  274. match result {
  275. Standalone(bytes) => Cell::paint(Green.bold(), &*bytes.to_string()),
  276. Prefixed(prefix, n) => {
  277. let number = if n < 10f64 { locale.format_float(n, 1) } else { locale.format_int(n as isize) };
  278. let symbol = prefix.symbol();
  279. Cell {
  280. text: ANSIStrings( &[ Green.bold().paint(&number[..]), Green.paint(symbol) ]).to_string(),
  281. length: number.len() + symbol.len(),
  282. }
  283. }
  284. }
  285. }
  286. }
  287. fn timestamp(&self, time_type: TimeType, current_year: i64, locale: &locale::Time) -> Cell {
  288. // Need to convert these values from milliseconds into seconds.
  289. let time_in_seconds = match time_type {
  290. TimeType::FileAccessed => self.stat.accessed,
  291. TimeType::FileModified => self.stat.modified,
  292. TimeType::FileCreated => self.stat.created,
  293. } as i64 / 1000;
  294. let date = LocalDateTime::at(time_in_seconds);
  295. let format = if date.year() == current_year {
  296. DateFormat::parse("{2>:D} {:M} {2>:h}:{02>:m}").unwrap()
  297. }
  298. else {
  299. DateFormat::parse("{2>:D} {:M} {5>:Y}").unwrap()
  300. };
  301. Cell::paint(Blue.normal(), &format.format(date, locale))
  302. }
  303. /// This file's type, represented by a coloured character.
  304. ///
  305. /// Although the file type can usually be guessed from the colour of the
  306. /// file, `ls` puts this character there, so people will expect it.
  307. fn type_char(&self) -> ANSIString {
  308. return match self.stat.kind {
  309. io::FileType::RegularFile => Plain.paint("."),
  310. io::FileType::Directory => Blue.paint("d"),
  311. io::FileType::NamedPipe => Yellow.paint("|"),
  312. io::FileType::BlockSpecial => Purple.paint("s"),
  313. io::FileType::Symlink => Cyan.paint("l"),
  314. io::FileType::Unknown => Plain.paint("?"),
  315. }
  316. }
  317. /// Marker indicating that the file contains extended attributes
  318. ///
  319. /// Returns “@” or “ ” depending on wheter the file contains an extented
  320. /// attribute or not. Also returns “ ” in case the attributes cannot be read
  321. /// for some reason.
  322. fn attribute_marker(&self) -> ANSIString {
  323. if self.xattrs.len() > 0 { Plain.paint("@") } else { Plain.paint(" ") }
  324. }
  325. /// Generate the "rwxrwxrwx" permissions string, like how ls does it.
  326. ///
  327. /// Each character is given its own colour. The first three permission
  328. /// bits are bold because they're the ones used most often, and executable
  329. /// files are underlined to make them stand out more.
  330. fn permissions_string(&self) -> Cell {
  331. let bits = self.stat.perm;
  332. let executable_colour = match self.stat.kind {
  333. io::FileType::RegularFile => Green.bold().underline(),
  334. _ => Green.bold(),
  335. };
  336. let string = ANSIStrings(&[
  337. self.type_char(),
  338. File::permission_bit(&bits, io::USER_READ, "r", Yellow.bold()),
  339. File::permission_bit(&bits, io::USER_WRITE, "w", Red.bold()),
  340. File::permission_bit(&bits, io::USER_EXECUTE, "x", executable_colour),
  341. File::permission_bit(&bits, io::GROUP_READ, "r", Yellow.normal()),
  342. File::permission_bit(&bits, io::GROUP_WRITE, "w", Red.normal()),
  343. File::permission_bit(&bits, io::GROUP_EXECUTE, "x", Green.normal()),
  344. File::permission_bit(&bits, io::OTHER_READ, "r", Yellow.normal()),
  345. File::permission_bit(&bits, io::OTHER_WRITE, "w", Red.normal()),
  346. File::permission_bit(&bits, io::OTHER_EXECUTE, "x", Green.normal()),
  347. self.attribute_marker()
  348. ]).to_string();
  349. Cell { text: string, length: 11 }
  350. }
  351. /// Helper method for the permissions string.
  352. fn permission_bit(bits: &io::FilePermission, bit: io::FilePermission, character: &'static str, style: Style) -> ANSIString<'static> {
  353. if bits.contains(bit) {
  354. style.paint(character)
  355. }
  356. else {
  357. GREY.paint("-")
  358. }
  359. }
  360. /// For this file, return a vector of alternate file paths that, if any of
  361. /// them exist, mean that *this* file should be coloured as `Compiled`.
  362. ///
  363. /// The point of this is to highlight compiled files such as `foo.o` when
  364. /// their source file `foo.c` exists in the same directory. It's too
  365. /// dangerous to highlight *all* compiled, so the paths in this vector
  366. /// are checked for existence first: for example, `foo.js` is perfectly
  367. /// valid without `foo.coffee`.
  368. pub fn get_source_files(&self) -> Vec<Path> {
  369. if let Some(ref ext) = self.ext {
  370. match &ext[..] {
  371. "class" => vec![self.path.with_extension("java")], // Java
  372. "css" => vec![self.path.with_extension("sass"), self.path.with_extension("less")], // SASS, Less
  373. "elc" => vec![self.path.with_extension("el")], // Emacs Lisp
  374. "hi" => vec![self.path.with_extension("hs")], // Haskell
  375. "js" => vec![self.path.with_extension("coffee"), self.path.with_extension("ts")], // CoffeeScript, TypeScript
  376. "o" => vec![self.path.with_extension("c"), self.path.with_extension("cpp")], // C, C++
  377. "pyc" => vec![self.path.with_extension("py")], // Python
  378. "aux" => vec![self.path.with_extension("tex")], // TeX: auxiliary file
  379. "bbl" => vec![self.path.with_extension("tex")], // BibTeX bibliography file
  380. "blg" => vec![self.path.with_extension("tex")], // BibTeX log file
  381. "lof" => vec![self.path.with_extension("tex")], // TeX list of figures
  382. "log" => vec![self.path.with_extension("tex")], // TeX log file
  383. "lot" => vec![self.path.with_extension("tex")], // TeX list of tables
  384. "toc" => vec![self.path.with_extension("tex")], // TeX table of contents
  385. _ => vec![], // No source files if none of the above
  386. }
  387. }
  388. else {
  389. vec![] // No source files if there's no extension, either!
  390. }
  391. }
  392. fn git_status(&self) -> Cell {
  393. let status = match self.dir {
  394. Some(d) => d.git_status(&current_dir().unwrap_or(Path::new(".")).join(&self.path),
  395. self.stat.kind == io::FileType::Directory),
  396. None => GREY.paint("--").to_string(),
  397. };
  398. Cell { text: status, length: 2 }
  399. }
  400. }
  401. /// Extract the filename to display from a path, converting it from UTF-8
  402. /// lossily, into a String.
  403. ///
  404. /// The filename to display is the last component of the path. However,
  405. /// the path has no components for `.`, `..`, and `/`, so in these
  406. /// cases, the entire path is used.
  407. fn path_filename(path: &Path) -> String {
  408. let bytes = match path.components().last() {
  409. Some(b) => b,
  410. None => path.as_vec(),
  411. };
  412. String::from_utf8_lossy(bytes).to_string()
  413. }
  414. /// Extract an extension from a string, if one is present, in lowercase.
  415. ///
  416. /// The extension is the series of characters after the last dot. This
  417. /// deliberately counts dotfiles, so the ".git" folder has the extension "git".
  418. ///
  419. /// ASCII lowercasing is used because these extensions are only compared
  420. /// against a pre-compiled list of extensions which are known to only exist
  421. /// within ASCII, so it's alright.
  422. fn ext<'a>(name: &'a str) -> Option<String> {
  423. name.rfind('.').map(|p| name[p+1..].to_ascii_lowercase())
  424. }
  425. #[cfg(test)]
  426. pub mod test {
  427. pub use super::*;
  428. pub use super::path_filename;
  429. pub use column::{Cell, Column};
  430. pub use std::old_io as io;
  431. pub use output::details::UserLocale;
  432. pub use users::{User, Group};
  433. pub use users::mock::MockUsers;
  434. pub use ansi_term::Style::Plain;
  435. pub use ansi_term::Colour::Yellow;
  436. #[test]
  437. fn current_filename() {
  438. let filename = path_filename(&Path::new("."));
  439. assert_eq!(&filename[..], ".")
  440. }
  441. #[test]
  442. fn parent_filename() {
  443. let filename = path_filename(&Path::new(".."));
  444. assert_eq!(&filename[..], "..")
  445. }
  446. #[test]
  447. fn extension() {
  448. assert_eq!(Some("dat".to_string()), super::ext("fester.dat"))
  449. }
  450. #[test]
  451. fn dotfile() {
  452. assert_eq!(Some("vimrc".to_string()), super::ext(".vimrc"))
  453. }
  454. #[test]
  455. fn no_extension() {
  456. assert_eq!(None, super::ext("jarlsberg"))
  457. }
  458. pub fn new_file(stat: io::FileStat, path: &'static str) -> File {
  459. File::with_stat(stat, &Path::new(path), None, false)
  460. }
  461. pub fn dummy_stat() -> io::FileStat {
  462. io::FileStat {
  463. size: 0,
  464. kind: io::FileType::RegularFile,
  465. created: 0,
  466. modified: 0,
  467. accessed: 0,
  468. perm: io::USER_READ,
  469. unstable: io::UnstableFileStat {
  470. inode: 0,
  471. device: 0,
  472. rdev: 0,
  473. nlink: 0,
  474. uid: 0,
  475. gid: 0,
  476. blksize: 0,
  477. blocks: 0,
  478. flags: 0,
  479. gen: 0,
  480. }
  481. }
  482. }
  483. pub fn dummy_locale() -> UserLocale {
  484. UserLocale::default()
  485. }
  486. mod users {
  487. use super::*;
  488. #[test]
  489. fn named() {
  490. let mut stat = dummy_stat();
  491. stat.unstable.uid = 1000;
  492. let file = new_file(stat, "/hi");
  493. let mut users = MockUsers::with_current_uid(1000);
  494. users.add_user(User { uid: 1000, name: "enoch".to_string(), primary_group: 100 });
  495. let cell = Cell::paint(Yellow.bold(), "enoch");
  496. assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
  497. }
  498. #[test]
  499. fn unnamed() {
  500. let mut stat = dummy_stat();
  501. stat.unstable.uid = 1000;
  502. let file = new_file(stat, "/hi");
  503. let mut users = MockUsers::with_current_uid(1000);
  504. let cell = Cell::paint(Yellow.bold(), "1000");
  505. assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
  506. }
  507. #[test]
  508. fn different_named() {
  509. let mut stat = dummy_stat();
  510. stat.unstable.uid = 1000;
  511. let file = new_file(stat, "/hi");
  512. let mut users = MockUsers::with_current_uid(3);
  513. users.add_user(User { uid: 1000, name: "enoch".to_string(), primary_group: 100 });
  514. let cell = Cell::paint(Plain, "enoch");
  515. assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
  516. }
  517. #[test]
  518. fn different_unnamed() {
  519. let mut stat = dummy_stat();
  520. stat.unstable.uid = 1000;
  521. let file = new_file(stat, "/hi");
  522. let mut users = MockUsers::with_current_uid(3);
  523. let cell = Cell::paint(Plain, "1000");
  524. assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
  525. }
  526. #[test]
  527. fn overflow() {
  528. let mut stat = dummy_stat();
  529. stat.unstable.uid = 2_147_483_648;
  530. let file = new_file(stat, "/hi");
  531. let mut users = MockUsers::with_current_uid(3);
  532. let cell = Cell::paint(Plain, "2147483648");
  533. assert_eq!(cell, file.display(&Column::User, &mut users, &dummy_locale()))
  534. }
  535. }
  536. mod groups {
  537. use super::*;
  538. #[test]
  539. fn named() {
  540. let mut stat = dummy_stat();
  541. stat.unstable.gid = 100;
  542. let file = new_file(stat, "/hi");
  543. let mut users = MockUsers::with_current_uid(3);
  544. users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] });
  545. let cell = Cell::paint(Plain, "folk");
  546. assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
  547. }
  548. #[test]
  549. fn unnamed() {
  550. let mut stat = dummy_stat();
  551. stat.unstable.gid = 100;
  552. let file = new_file(stat, "/hi");
  553. let mut users = MockUsers::with_current_uid(3);
  554. let cell = Cell::paint(Plain, "100");
  555. assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
  556. }
  557. #[test]
  558. fn primary() {
  559. let mut stat = dummy_stat();
  560. stat.unstable.gid = 100;
  561. let file = new_file(stat, "/hi");
  562. let mut users = MockUsers::with_current_uid(3);
  563. users.add_user(User { uid: 3, name: "eve".to_string(), primary_group: 100 });
  564. users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![] });
  565. let cell = Cell::paint(Yellow.bold(), "folk");
  566. assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
  567. }
  568. #[test]
  569. fn secondary() {
  570. let mut stat = dummy_stat();
  571. stat.unstable.gid = 100;
  572. let file = new_file(stat, "/hi");
  573. let mut users = MockUsers::with_current_uid(3);
  574. users.add_user(User { uid: 3, name: "eve".to_string(), primary_group: 12 });
  575. users.add_group(Group { gid: 100, name: "folk".to_string(), members: vec![ "eve".to_string() ] });
  576. let cell = Cell::paint(Yellow.bold(), "folk");
  577. assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
  578. }
  579. #[test]
  580. fn overflow() {
  581. let mut stat = dummy_stat();
  582. stat.unstable.gid = 2_147_483_648;
  583. let file = new_file(stat, "/hi");
  584. let mut users = MockUsers::with_current_uid(3);
  585. let cell = Cell::paint(Plain, "2147483648");
  586. assert_eq!(cell, file.display(&Column::Group, &mut users, &dummy_locale()))
  587. }
  588. }
  589. }