file.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. use std::io::{fs, IoResult};
  2. use std::io;
  3. use ansi_term::{ANSIString, Colour, Style};
  4. use ansi_term::Style::Plain;
  5. use ansi_term::Colour::{Red, Green, Yellow, Blue, Purple, Cyan, Fixed};
  6. use users::Users;
  7. use number_prefix::{binary_prefix, decimal_prefix, Prefixed, Standalone, PrefixNames};
  8. use column::{Column, SizeFormat, Cell};
  9. use column::Column::*;
  10. use dir::Dir;
  11. use filetype::HasType;
  12. /// This grey value is directly in between white and black, so it's guaranteed
  13. /// to show up on either backgrounded terminal.
  14. pub static GREY: Colour = Fixed(244);
  15. /// A **File** is a wrapper around one of Rust's Path objects, along with
  16. /// associated data about the file.
  17. ///
  18. /// Each file is definitely going to have its filename displayed at least
  19. /// once, have its file extension extracted at least once, and have its stat
  20. /// information queried at least once, so it makes sense to do all this at the
  21. /// start and hold on to all the information.
  22. pub struct File<'a> {
  23. pub name: String,
  24. pub dir: Option<&'a Dir>,
  25. pub ext: Option<String>,
  26. pub path: Path,
  27. pub stat: io::FileStat,
  28. }
  29. impl<'a> File<'a> {
  30. /// Create a new File object from the given Path, inside the given Dir, if
  31. /// appropriate. Paths specified directly on the command-line have no Dirs.
  32. ///
  33. /// This uses lstat instead of stat, which doesn't follow symbolic links.
  34. pub fn from_path(path: &Path, parent: Option<&'a Dir>) -> IoResult<File<'a>> {
  35. fs::lstat(path).map(|stat| File::with_stat(stat, path, parent))
  36. }
  37. /// Create a new File object from the given Stat result, and other data.
  38. pub fn with_stat(stat: io::FileStat, path: &Path, parent: Option<&'a Dir>) -> File<'a> {
  39. let v = path.filename().unwrap(); // fails if / or . or ..
  40. let filename = String::from_utf8_lossy(v);
  41. File {
  42. path: path.clone(),
  43. dir: parent,
  44. stat: stat,
  45. name: filename.to_string(),
  46. ext: ext(filename.as_slice()),
  47. }
  48. }
  49. /// Whether this file is a dotfile or not.
  50. pub fn is_dotfile(&self) -> bool {
  51. self.name.as_slice().starts_with(".")
  52. }
  53. /// Whether this file is a temporary file or not.
  54. pub fn is_tmpfile(&self) -> bool {
  55. let name = self.name.as_slice();
  56. name.ends_with("~") || (name.starts_with("#") && name.ends_with("#"))
  57. }
  58. /// Get the data for a column, formatted as a coloured string.
  59. pub fn display<U: Users>(&self, column: &Column, users_cache: &mut U) -> Cell {
  60. match *column {
  61. Permissions => self.permissions_string(),
  62. FileName => self.file_name_view(),
  63. FileSize(f) => self.file_size(f),
  64. HardLinks => self.hard_links(),
  65. Inode => self.inode(),
  66. Blocks => self.blocks(),
  67. User => self.user(users_cache),
  68. Group => self.group(users_cache),
  69. }
  70. }
  71. /// The "file name view" is what's displayed in the column and lines
  72. /// views, but *not* in the grid view.
  73. ///
  74. /// It consists of the file name coloured in the appropriate style, and,
  75. /// if it's a symlink, an arrow pointing to the file it links to, also
  76. /// coloured in the appropriate style.
  77. ///
  78. /// If the symlink target doesn't exist, then instead of displaying
  79. /// an error, highlight the target and arrow in red. The error would
  80. /// be shown out of context, and it's almost always because the
  81. /// target doesn't exist.
  82. pub fn file_name_view(&self) -> Cell {
  83. let name = &*self.name;
  84. let style = self.file_colour();
  85. if self.stat.kind == io::FileType::Symlink {
  86. match fs::readlink(&self.path) {
  87. Ok(path) => {
  88. let target_path = match self.dir {
  89. Some(dir) => dir.path.join(path),
  90. None => path,
  91. };
  92. match self.target_file(&target_path) {
  93. Ok(file) => Cell {
  94. length: 0, // These lengths are never actually used...
  95. text: format!("{} {} {}{}{}",
  96. style.paint(name),
  97. GREY.paint("=>"),
  98. Cyan.paint(target_path.dirname_str().unwrap()),
  99. Cyan.paint("/"),
  100. file.file_colour().paint(file.name.as_slice())),
  101. },
  102. Err(filename) => Cell {
  103. length: 0, // ...because the rightmost column lengths are ignored!
  104. text: format!("{} {} {}",
  105. style.paint(name),
  106. Red.paint("=>"),
  107. Red.underline().paint(filename.as_slice())),
  108. },
  109. }
  110. }
  111. Err(_) => Cell::paint(style, name),
  112. }
  113. }
  114. else {
  115. Cell::paint(style, name)
  116. }
  117. }
  118. /// The `ansi_term::Style` that this file's name should be painted.
  119. pub fn file_colour(&self) -> Style {
  120. self.get_type().style()
  121. }
  122. /// The Unicode 'display width' of the filename.
  123. ///
  124. /// This is related to the number of graphemes in the string: most
  125. /// characters are 1 columns wide, but in some contexts, certain
  126. /// characters are actually 2 columns wide.
  127. pub fn file_name_width(&self) -> usize {
  128. self.name.as_slice().width(false)
  129. }
  130. /// Assuming the current file is a symlink, follows the link and
  131. /// returns a File object from the path the link points to.
  132. ///
  133. /// If statting the file fails (usually because the file on the
  134. /// other end doesn't exist), returns the *filename* of the file
  135. /// that should be there.
  136. fn target_file(&self, target_path: &Path) -> Result<File, String> {
  137. let v = target_path.filename().unwrap();
  138. let filename = String::from_utf8_lossy(v);
  139. // Use stat instead of lstat - we *want* to follow links.
  140. if let Ok(stat) = fs::stat(target_path) {
  141. Ok(File {
  142. path: target_path.clone(),
  143. dir: self.dir,
  144. stat: stat,
  145. name: filename.to_string(),
  146. ext: ext(filename.as_slice()),
  147. })
  148. }
  149. else {
  150. Err(filename.to_string())
  151. }
  152. }
  153. /// This file's number of hard links as a coloured string.
  154. fn hard_links(&self) -> Cell {
  155. let style = if self.has_multiple_links() { Red.on(Yellow) } else { Red.normal() };
  156. Cell::paint(style, &*self.stat.unstable.nlink.to_string())
  157. }
  158. /// Whether this is a regular file with more than one link.
  159. ///
  160. /// This is important, because a file with multiple links is uncommon,
  161. /// while you can come across directories and other types with multiple
  162. /// links much more often.
  163. fn has_multiple_links(&self) -> bool {
  164. self.stat.kind == io::FileType::RegularFile && self.stat.unstable.nlink > 1
  165. }
  166. /// This file's inode as a coloured string.
  167. fn inode(&self) -> Cell {
  168. Cell::paint(Purple.normal(), &*self.stat.unstable.inode.to_string())
  169. }
  170. /// This file's number of filesystem blocks (if available) as a coloured string.
  171. fn blocks(&self) -> Cell {
  172. if self.stat.kind == io::FileType::RegularFile || self.stat.kind == io::FileType::Symlink {
  173. Cell::paint(Cyan.normal(), &*self.stat.unstable.blocks.to_string())
  174. }
  175. else {
  176. Cell { text: GREY.paint("-").to_string(), length: 1 }
  177. }
  178. }
  179. /// This file's owner's username as a coloured string.
  180. ///
  181. /// If the user is not present, then it formats the uid as a number
  182. /// instead. This usually happens when a user is deleted, but still owns
  183. /// files.
  184. fn user<U: Users>(&self, users_cache: &mut U) -> Cell {
  185. let uid = self.stat.unstable.uid as i32;
  186. let user_name = match users_cache.get_user_by_uid(uid) {
  187. Some(user) => user.name,
  188. None => uid.to_string(),
  189. };
  190. let style = if users_cache.get_current_uid() == uid { Yellow.bold() } else { Plain };
  191. Cell::paint(style, &*user_name)
  192. }
  193. /// This file's group name as a coloured string.
  194. ///
  195. /// As above, if not present, it formats the gid as a number instead.
  196. fn group<U: Users>(&self, users_cache: &mut U) -> Cell {
  197. let gid = self.stat.unstable.gid as u32;
  198. let mut style = Plain;
  199. let group_name = match users_cache.get_group_by_gid(gid) {
  200. Some(group) => {
  201. let current_uid = users_cache.get_current_uid();
  202. if let Some(current_user) = users_cache.get_user_by_uid(current_uid) {
  203. if current_user.primary_group == group.gid || group.members.contains(&current_user.name) {
  204. style = Yellow.bold();
  205. }
  206. }
  207. group.name
  208. },
  209. None => gid.to_string(),
  210. };
  211. Cell::paint(style, &*group_name)
  212. }
  213. /// This file's size, formatted using the given way, as a coloured string.
  214. ///
  215. /// For directories, no size is given. Although they do have a size on
  216. /// some filesystems, I've never looked at one of those numbers and gained
  217. /// any information from it, so by emitting "-" instead, the table is less
  218. /// cluttered with numbers.
  219. fn file_size(&self, size_format: SizeFormat) -> Cell {
  220. if self.stat.kind == io::FileType::Directory {
  221. Cell { text: GREY.paint("-").to_string(), length: 1 }
  222. }
  223. else {
  224. let result = match size_format {
  225. SizeFormat::DecimalBytes => decimal_prefix(self.stat.size as f64),
  226. SizeFormat::BinaryBytes => binary_prefix(self.stat.size as f64),
  227. SizeFormat::JustBytes => return Cell::paint(Green.bold(), &*self.stat.size.to_string())
  228. };
  229. match result {
  230. Standalone(bytes) => Cell::paint(Green.bold(), &*bytes.to_string()),
  231. Prefixed(prefix, n) => {
  232. let number = if n < 10f64 { format!("{:.1}", n) } else { format!("{:.0}", n) };
  233. let symbol = prefix.symbol();
  234. Cell {
  235. text: format!("{}{}", Green.bold().paint(&*number), Green.paint(symbol)),
  236. length: number.len() + symbol.len(),
  237. }
  238. }
  239. }
  240. }
  241. }
  242. /// This file's type, represented by a coloured character.
  243. ///
  244. /// Although the file type can usually be guessed from the colour of the
  245. /// file, `ls` puts this character there, so people will expect it.
  246. fn type_char(&self) -> ANSIString {
  247. return match self.stat.kind {
  248. io::FileType::RegularFile => Plain.paint("."),
  249. io::FileType::Directory => Blue.paint("d"),
  250. io::FileType::NamedPipe => Yellow.paint("|"),
  251. io::FileType::BlockSpecial => Purple.paint("s"),
  252. io::FileType::Symlink => Cyan.paint("l"),
  253. io::FileType::Unknown => Plain.paint("?"),
  254. }
  255. }
  256. /// Generate the "rwxrwxrwx" permissions string, like how ls does it.
  257. ///
  258. /// Each character is given its own colour. The first three permission
  259. /// bits are bold because they're the ones used most often, and executable
  260. /// files are underlined to make them stand out more.
  261. fn permissions_string(&self) -> Cell {
  262. let bits = self.stat.perm;
  263. let executable_colour = match self.stat.kind {
  264. io::FileType::RegularFile => Green.bold().underline(),
  265. _ => Green.bold(),
  266. };
  267. let string = format!("{}{}{}{}{}{}{}{}{}{}",
  268. self.type_char(),
  269. File::permission_bit(&bits, io::USER_READ, "r", Yellow.bold()),
  270. File::permission_bit(&bits, io::USER_WRITE, "w", Red.bold()),
  271. File::permission_bit(&bits, io::USER_EXECUTE, "x", executable_colour),
  272. File::permission_bit(&bits, io::GROUP_READ, "r", Yellow.normal()),
  273. File::permission_bit(&bits, io::GROUP_WRITE, "w", Red.normal()),
  274. File::permission_bit(&bits, io::GROUP_EXECUTE, "x", Green.normal()),
  275. File::permission_bit(&bits, io::OTHER_READ, "r", Yellow.normal()),
  276. File::permission_bit(&bits, io::OTHER_WRITE, "w", Red.normal()),
  277. File::permission_bit(&bits, io::OTHER_EXECUTE, "x", Green.normal()),
  278. );
  279. Cell { text: string, length: 10 }
  280. }
  281. /// Helper method for the permissions string.
  282. fn permission_bit(bits: &io::FilePermission, bit: io::FilePermission, character: &'static str, style: Style) -> ANSIString<'static> {
  283. if bits.contains(bit) {
  284. style.paint(character)
  285. }
  286. else {
  287. GREY.paint("-")
  288. }
  289. }
  290. /// For this file, return a vector of alternate file paths that, if any of
  291. /// them exist, mean that *this* file should be coloured as `Compiled`.
  292. ///
  293. /// The point of this is to highlight compiled files such as `foo.o` when
  294. /// their source file `foo.c` exists in the same directory. It's too
  295. /// dangerous to highlight *all* compiled, so the paths in this vector
  296. /// are checked for existence first: for example, `foo.js` is perfectly
  297. /// valid without `foo.coffee`.
  298. pub fn get_source_files(&self) -> Vec<Path> {
  299. if let Some(ref ext) = self.ext {
  300. match ext.as_slice() {
  301. "class" => vec![self.path.with_extension("java")], // Java
  302. "css" => vec![self.path.with_extension("sass"), self.path.with_extension("less")], // SASS, Less
  303. "elc" => vec![self.path.with_extension("el")], // Emacs Lisp
  304. "hi" => vec![self.path.with_extension("hs")], // Haskell
  305. "js" => vec![self.path.with_extension("coffee"), self.path.with_extension("ts")], // CoffeeScript, TypeScript
  306. "o" => vec![self.path.with_extension("c"), self.path.with_extension("cpp")], // C, C++
  307. "pyc" => vec![self.path.with_extension("py")], // Python
  308. "aux" => vec![self.path.with_extension("tex")], // TeX: auxiliary file
  309. "bbl" => vec![self.path.with_extension("tex")], // BibTeX bibliography file
  310. "blg" => vec![self.path.with_extension("tex")], // BibTeX log file
  311. "lof" => vec![self.path.with_extension("tex")], // TeX list of figures
  312. "log" => vec![self.path.with_extension("tex")], // TeX log file
  313. "lot" => vec![self.path.with_extension("tex")], // TeX list of tables
  314. "toc" => vec![self.path.with_extension("tex")], // TeX table of contents
  315. _ => vec![], // No source files if none of the above
  316. }
  317. }
  318. else {
  319. vec![] // No source files if there's no extension, either!
  320. }
  321. }
  322. }
  323. /// Extract an extension from a string, if one is present.
  324. ///
  325. /// The extension is the series of characters after the last dot. This
  326. /// deliberately counts dotfiles, so the ".git" folder has the extension "git".
  327. fn ext<'a>(name: &'a str) -> Option<String> {
  328. name.rfind('.').map(|p| name[p+1..].to_string())
  329. }