file.rs 21 KB

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