file.rs 22 KB

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