file.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan, Fixed};
  2. use std::io::{fs, IoResult};
  3. use std::io;
  4. use column::{Column, Permissions, FileName, FileSize, User, Group, HardLinks, Inode, Blocks};
  5. use format::{format_metric_bytes, format_IEC_bytes};
  6. use unix::Unix;
  7. use sort::SortPart;
  8. use dir::Dir;
  9. use filetype::HasType;
  10. // Instead of working with Rust's Paths, we have our own File object
  11. // that holds the Path and various cached information. Each file is
  12. // definitely going to have its filename used at least once, its stat
  13. // information queried at least once, and its file extension extracted
  14. // at least once, so we may as well carry around that information with
  15. // the actual path.
  16. pub struct File<'a> {
  17. pub name: &'a str,
  18. pub dir: &'a Dir<'a>,
  19. pub ext: Option<&'a str>,
  20. pub path: &'a Path,
  21. pub stat: io::FileStat,
  22. pub parts: Vec<SortPart>,
  23. }
  24. impl<'a> File<'a> {
  25. pub fn from_path(path: &'a Path, parent: &'a Dir) -> IoResult<File<'a>> {
  26. // Getting the string from a filename fails whenever it's not
  27. // UTF-8 representable - just assume it is for now.
  28. let filename: &str = path.filename_str().unwrap();
  29. // Use lstat here instead of file.stat(), as it doesn't follow
  30. // symbolic links. Otherwise, the stat() call will fail if it
  31. // encounters a link that's target is non-existent.
  32. fs::lstat(path).map(|stat| File {
  33. path: path,
  34. dir: parent,
  35. stat: stat,
  36. name: filename,
  37. ext: File::ext(filename),
  38. parts: SortPart::split_into_parts(filename),
  39. })
  40. }
  41. fn ext(name: &'a str) -> Option<&'a str> {
  42. // The extension is the series of characters after a dot at
  43. // the end of a filename. This deliberately also counts
  44. // dotfiles - the ".git" folder has the extension "git".
  45. let re = regex!(r"\.([^.]+)$");
  46. re.captures(name).map(|caps| caps.at(1))
  47. }
  48. pub fn is_dotfile(&self) -> bool {
  49. self.name.starts_with(".")
  50. }
  51. pub fn is_tmpfile(&self) -> bool {
  52. self.name.ends_with("~") || (self.name.starts_with("#") && self.name.ends_with("#"))
  53. }
  54. // Highlight the compiled versions of files. Some of them, like .o,
  55. // get special highlighting when they're alone because there's no
  56. // point in existing without their source. Others can be perfectly
  57. // content without their source files, such as how .js is valid
  58. // without a .coffee.
  59. pub fn get_source_files(&self) -> Vec<Path> {
  60. match self.ext {
  61. Some("class") => vec![self.path.with_extension("java")], // Java
  62. Some("elc") => vec![self.path.with_extension("el")], // Emacs Lisp
  63. Some("hi") => vec![self.path.with_extension("hs")], // Haskell
  64. Some("o") => vec![self.path.with_extension("c"), self.path.with_extension("cpp")], // C, C++
  65. Some("pyc") => vec![self.path.with_extension("py")], // Python
  66. Some("js") => vec![self.path.with_extension("coffee"), self.path.with_extension("ts")], // CoffeeScript, TypeScript
  67. Some("css") => vec![self.path.with_extension("sass"), self.path.with_extension("less")], // SASS, Less
  68. Some("aux") => vec![self.path.with_extension("tex")], // TeX: auxiliary file
  69. Some("bbl") => vec![self.path.with_extension("tex")], // BibTeX bibliography file
  70. Some("blg") => vec![self.path.with_extension("tex")], // BibTeX log file
  71. Some("lof") => vec![self.path.with_extension("tex")], // list of figures
  72. Some("log") => vec![self.path.with_extension("tex")], // TeX log file
  73. Some("lot") => vec![self.path.with_extension("tex")], // list of tables
  74. Some("toc") => vec![self.path.with_extension("tex")], // table of contents
  75. _ => vec![],
  76. }
  77. }
  78. pub fn display(&self, column: &Column, unix: &mut Unix) -> String {
  79. match *column {
  80. Permissions => self.permissions_string(),
  81. FileName => self.file_name(),
  82. FileSize(use_iec) => self.file_size(use_iec),
  83. // A file with multiple links is interesting, but
  84. // directories and suchlike can have multiple links all
  85. // the time.
  86. HardLinks => {
  87. let style = if self.stat.kind == io::TypeFile && self.stat.unstable.nlink > 1 { Red.on(Yellow) } else { Red.normal() };
  88. style.paint(self.stat.unstable.nlink.to_str().as_slice())
  89. },
  90. Inode => Purple.paint(self.stat.unstable.inode.to_str().as_slice()),
  91. Blocks => {
  92. if self.stat.kind == io::TypeFile || self.stat.kind == io::TypeSymlink {
  93. Cyan.paint(self.stat.unstable.blocks.to_str().as_slice())
  94. }
  95. else {
  96. Fixed(244).paint("-")
  97. }
  98. },
  99. // Display the ID if the user/group doesn't exist, which
  100. // usually means it was deleted but its files weren't.
  101. User => {
  102. let uid = self.stat.unstable.uid as u32;
  103. unix.load_user(uid);
  104. let style = if unix.uid == uid { Yellow.bold() } else { Plain };
  105. let string = unix.get_user_name(uid).unwrap_or(uid.to_str());
  106. style.paint(string.as_slice())
  107. },
  108. Group => {
  109. let gid = self.stat.unstable.gid as u32;
  110. unix.load_group(gid);
  111. let name = unix.get_group_name(gid).unwrap_or(gid.to_str());
  112. let style = if unix.is_group_member(gid) { Yellow.normal() } else { Plain };
  113. style.paint(name.as_slice())
  114. },
  115. }
  116. }
  117. fn file_name(&self) -> String {
  118. let displayed_name = self.file_colour().paint(self.name);
  119. if self.stat.kind == io::TypeSymlink {
  120. match fs::readlink(self.path) {
  121. Ok(path) => {
  122. let target_path = if path.is_absolute() { path } else { self.dir.path.join(path) };
  123. format!("{} {}", displayed_name, self.target_file_name_and_arrow(target_path))
  124. }
  125. Err(_) => displayed_name,
  126. }
  127. }
  128. else {
  129. displayed_name
  130. }
  131. }
  132. fn target_file_name_and_arrow(&self, target_path: Path) -> String {
  133. let filename = target_path.as_str().unwrap();
  134. let link_target = fs::stat(&target_path).map(|stat| File {
  135. path: &target_path,
  136. dir: self.dir,
  137. stat: stat,
  138. name: filename,
  139. ext: File::ext(filename),
  140. parts: vec![], // not needed
  141. });
  142. // Statting a path usually fails because the file at the other
  143. // end doesn't exist. Show this by highlighting the target
  144. // file in red instead of displaying an error, because the
  145. // error would be shown out of context and it's almost always
  146. // that reason anyway.
  147. match link_target {
  148. Ok(file) => format!("{} {}", Fixed(244).paint("=>"), file.file_colour().paint(filename)),
  149. Err(_) => format!("{} {}", Red.paint("=>"), Red.underline().paint(filename)),
  150. }
  151. }
  152. fn file_size(&self, use_iec_prefixes: bool) -> String {
  153. // Don't report file sizes for directories. I've never looked
  154. // at one of those numbers and gained any information from it.
  155. if self.stat.kind == io::TypeDirectory {
  156. Fixed(244).paint("-")
  157. } else {
  158. let (size, suffix) = if use_iec_prefixes {
  159. format_IEC_bytes(self.stat.size)
  160. } else {
  161. format_metric_bytes(self.stat.size)
  162. };
  163. return format!("{}{}", Green.bold().paint(size.as_slice()), Green.paint(suffix.as_slice()));
  164. }
  165. }
  166. fn type_char(&self) -> String {
  167. return match self.stat.kind {
  168. io::TypeFile => ".".to_string(),
  169. io::TypeDirectory => Blue.paint("d"),
  170. io::TypeNamedPipe => Yellow.paint("|"),
  171. io::TypeBlockSpecial => Purple.paint("s"),
  172. io::TypeSymlink => Cyan.paint("l"),
  173. io::TypeUnknown => "?".to_string(),
  174. }
  175. }
  176. fn file_colour(&self) -> Style {
  177. self.get_type().style()
  178. }
  179. fn permissions_string(&self) -> String {
  180. let bits = self.stat.perm;
  181. return format!("{}{}{}{}{}{}{}{}{}{}",
  182. self.type_char(),
  183. // The first three are bold because they're the ones used
  184. // most often.
  185. File::permission_bit(bits, io::UserRead, "r", Yellow.bold()),
  186. File::permission_bit(bits, io::UserWrite, "w", Red.bold()),
  187. File::permission_bit(bits, io::UserExecute, "x", Green.bold().underline()),
  188. File::permission_bit(bits, io::GroupRead, "r", Yellow.normal()),
  189. File::permission_bit(bits, io::GroupWrite, "w", Red.normal()),
  190. File::permission_bit(bits, io::GroupExecute, "x", Green.normal()),
  191. File::permission_bit(bits, io::OtherRead, "r", Yellow.normal()),
  192. File::permission_bit(bits, io::OtherWrite, "w", Red.normal()),
  193. File::permission_bit(bits, io::OtherExecute, "x", Green.normal()),
  194. );
  195. }
  196. fn permission_bit(bits: io::FilePermission, bit: io::FilePermission, character: &'static str, style: Style) -> String {
  197. if bits.contains(bit) {
  198. style.paint(character.as_slice())
  199. } else {
  200. Black.bold().paint("-".as_slice())
  201. }
  202. }
  203. }