file.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. //! Files, and methods and fields to access their metadata.
  2. use std::fs;
  3. use std::io::Error as IOError;
  4. use std::io::Result as IOResult;
  5. use std::os::unix::fs::{MetadataExt, PermissionsExt, FileTypeExt};
  6. use std::path::{Path, PathBuf};
  7. use fs::dir::Dir;
  8. use fs::fields as f;
  9. /// A **File** is a wrapper around one of Rust's Path objects, along with
  10. /// associated data about the file.
  11. ///
  12. /// Each file is definitely going to have its filename displayed at least
  13. /// once, have its file extension extracted at least once, and have its metadata
  14. /// information queried at least once, so it makes sense to do all this at the
  15. /// start and hold on to all the information.
  16. pub struct File<'dir> {
  17. /// The filename portion of this file's path, including the extension.
  18. ///
  19. /// This is used to compare against certain filenames (such as checking if
  20. /// it’s “Makefile” or something) and to highlight only the filename in
  21. /// colour when displaying the path.
  22. pub name: String,
  23. /// The file’s name’s extension, if present, extracted from the name.
  24. ///
  25. /// This is queried many times over, so it’s worth caching it.
  26. pub ext: Option<String>,
  27. /// The path that begat this file.
  28. ///
  29. /// Even though the file's name is extracted, the path needs to be kept
  30. /// around, as certain operations involve looking up the file's absolute
  31. /// location (such as the Git status, or searching for compiled files).
  32. pub path: PathBuf,
  33. /// A cached `metadata` call for this file.
  34. ///
  35. /// This too is queried multiple times, and is *not* cached by the OS, as
  36. /// it could easily change between invocations - but exa is so short-lived
  37. /// it's better to just cache it.
  38. pub metadata: fs::Metadata,
  39. /// A reference to the directory that contains this file, if present.
  40. ///
  41. /// Filenames that get passed in on the command-line directly will have no
  42. /// parent directory reference - although they technically have one on the
  43. /// filesystem, we'll never need to look at it, so it'll be `None`.
  44. /// However, *directories* that get passed in will produce files that
  45. /// contain a reference to it, which is used in certain operations (such
  46. /// as looking up a file's Git status).
  47. pub parent_dir: Option<&'dir Dir>,
  48. }
  49. impl<'dir> File<'dir> {
  50. pub fn new<PD, FN>(path: PathBuf, parent_dir: PD, filename: FN) -> IOResult<File<'dir>>
  51. where PD: Into<Option<&'dir Dir>>,
  52. FN: Into<Option<String>>
  53. {
  54. let parent_dir = parent_dir.into();
  55. let name = filename.into().unwrap_or_else(|| File::filename(&path));
  56. let ext = File::ext(&path);
  57. debug!("Statting file {:?}", &path);
  58. let metadata = fs::symlink_metadata(&path)?;
  59. Ok(File { path, parent_dir, metadata, ext, name })
  60. }
  61. /// A file’s name is derived from its string. This needs to handle directories
  62. /// such as `/` or `..`, which have no `file_name` component. So instead, just
  63. /// use the last component as the name.
  64. pub fn filename(path: &Path) -> String {
  65. if let Some(back) = path.components().next_back() {
  66. back.as_os_str().to_string_lossy().to_string()
  67. }
  68. else {
  69. // use the path as fallback
  70. error!("Path {:?} has no last component", path);
  71. path.display().to_string()
  72. }
  73. }
  74. /// Extract an extension from a file path, if one is present, in lowercase.
  75. ///
  76. /// The extension is the series of characters after the last dot. This
  77. /// deliberately counts dotfiles, so the ".git" folder has the extension "git".
  78. ///
  79. /// ASCII lowercasing is used because these extensions are only compared
  80. /// against a pre-compiled list of extensions which are known to only exist
  81. /// within ASCII, so it's alright.
  82. fn ext(path: &Path) -> Option<String> {
  83. use std::ascii::AsciiExt;
  84. let name = match path.file_name() {
  85. Some(f) => f.to_string_lossy().to_string(),
  86. None => return None,
  87. };
  88. name.rfind('.').map(|p| name[p+1..].to_ascii_lowercase())
  89. }
  90. /// Whether this file is a directory on the filesystem.
  91. pub fn is_directory(&self) -> bool {
  92. self.metadata.is_dir()
  93. }
  94. /// If this file is a directory on the filesystem, then clone its
  95. /// `PathBuf` for use in one of our own `Dir` objects, and read a list of
  96. /// its contents.
  97. ///
  98. /// Returns an IO error upon failure, but this shouldn't be used to check
  99. /// if a `File` is a directory or not! For that, just use `is_directory()`.
  100. pub fn to_dir(&self, scan_for_git: bool) -> IOResult<Dir> {
  101. Dir::read_dir(self.path.clone(), scan_for_git)
  102. }
  103. /// Whether this file is a regular file on the filesystem - that is, not a
  104. /// directory, a link, or anything else treated specially.
  105. pub fn is_file(&self) -> bool {
  106. self.metadata.is_file()
  107. }
  108. /// Whether this file is both a regular file *and* executable for the
  109. /// current user. Executable files have different semantics than
  110. /// executable directories, and so should be highlighted differently.
  111. pub fn is_executable_file(&self) -> bool {
  112. let bit = modes::USER_EXECUTE;
  113. self.is_file() && (self.metadata.permissions().mode() & bit) == bit
  114. }
  115. /// Whether this file is a symlink on the filesystem.
  116. pub fn is_link(&self) -> bool {
  117. self.metadata.file_type().is_symlink()
  118. }
  119. /// Whether this file is a named pipe on the filesystem.
  120. pub fn is_pipe(&self) -> bool {
  121. self.metadata.file_type().is_fifo()
  122. }
  123. /// Whether this file is a char device on the filesystem.
  124. pub fn is_char_device(&self) -> bool {
  125. self.metadata.file_type().is_char_device()
  126. }
  127. /// Whether this file is a block device on the filesystem.
  128. pub fn is_block_device(&self) -> bool {
  129. self.metadata.file_type().is_block_device()
  130. }
  131. /// Whether this file is a socket on the filesystem.
  132. pub fn is_socket(&self) -> bool {
  133. self.metadata.file_type().is_socket()
  134. }
  135. /// Re-prefixes the path pointed to by this file, if it's a symlink, to
  136. /// make it an absolute path that can be accessed from whichever
  137. /// directory exa is being run from.
  138. fn reorient_target_path(&self, path: &Path) -> PathBuf {
  139. if path.is_absolute() {
  140. path.to_path_buf()
  141. }
  142. else if let Some(dir) = self.parent_dir {
  143. dir.join(&*path)
  144. }
  145. else if let Some(parent) = self.path.parent() {
  146. parent.join(&*path)
  147. }
  148. else {
  149. self.path.join(&*path)
  150. }
  151. }
  152. /// Again assuming this file is a symlink, follows that link and returns
  153. /// the result of following it.
  154. ///
  155. /// For a working symlink that the user is allowed to follow,
  156. /// this will be the `File` object at the other end, which can then have
  157. /// its name, colour, and other details read.
  158. ///
  159. /// For a broken symlink, returns where the file *would* be, if it
  160. /// existed. If this file cannot be read at all, returns the error that
  161. /// we got when we tried to read it.
  162. pub fn link_target(&self) -> FileTarget<'dir> {
  163. // We need to be careful to treat the path actually pointed to by
  164. // this file -- which could be absolute or relative -- to the path
  165. // we actually look up and turn into a `File` -- which needs to be
  166. // absolute to be accessible from any directory.
  167. debug!("Reading link {:?}", &self.path);
  168. let path = match fs::read_link(&self.path) {
  169. Ok(p) => p,
  170. Err(e) => return FileTarget::Err(e),
  171. };
  172. let absolute_path = self.reorient_target_path(&path);
  173. // Use plain `metadata` instead of `symlink_metadata` - we *want* to
  174. // follow links.
  175. match fs::metadata(&absolute_path) {
  176. Ok(metadata) => {
  177. let ext = File::ext(&path);
  178. let name = File::filename(&path);
  179. FileTarget::Ok(File { parent_dir: None, path, ext, metadata, name })
  180. }
  181. Err(e) => {
  182. error!("Error following link {:?}: {:#?}", &path, e);
  183. FileTarget::Broken(path)
  184. }
  185. }
  186. }
  187. /// This file's number of hard links.
  188. ///
  189. /// It also reports whether this is both a regular file, and a file with
  190. /// multiple links. This is important, because a file with multiple links
  191. /// is uncommon, while you can come across directories and other types
  192. /// with multiple links much more often. Thus, it should get highlighted
  193. /// more attentively.
  194. pub fn links(&self) -> f::Links {
  195. let count = self.metadata.nlink();
  196. f::Links {
  197. count: count,
  198. multiple: self.is_file() && count > 1,
  199. }
  200. }
  201. /// This file's inode.
  202. pub fn inode(&self) -> f::Inode {
  203. f::Inode(self.metadata.ino())
  204. }
  205. /// This file's number of filesystem blocks.
  206. ///
  207. /// (Not the size of each block, which we don't actually report on)
  208. pub fn blocks(&self) -> f::Blocks {
  209. if self.is_file() || self.is_link() {
  210. f::Blocks::Some(self.metadata.blocks())
  211. }
  212. else {
  213. f::Blocks::None
  214. }
  215. }
  216. /// The ID of the user that own this file.
  217. pub fn user(&self) -> f::User {
  218. f::User(self.metadata.uid())
  219. }
  220. /// The ID of the group that owns this file.
  221. pub fn group(&self) -> f::Group {
  222. f::Group(self.metadata.gid())
  223. }
  224. /// This file’s size, if it’s a regular file.
  225. ///
  226. /// For directories, no size is given. Although they do have a size on
  227. /// some filesystems, I’ve never looked at one of those numbers and gained
  228. /// any information from it. So it’s going to be hidden instead.
  229. ///
  230. /// Block and character devices return their device IDs, because they
  231. /// usually just have a file size of zero.
  232. pub fn size(&self) -> f::Size {
  233. if self.is_directory() {
  234. f::Size::None
  235. }
  236. else if self.is_char_device() || self.is_block_device() {
  237. let dev = self.metadata.rdev();
  238. f::Size::DeviceIDs(f::DeviceIDs {
  239. major: (dev / 256) as u8,
  240. minor: (dev % 256) as u8,
  241. })
  242. }
  243. else {
  244. f::Size::Some(self.metadata.len())
  245. }
  246. }
  247. /// This file’s last modified timestamp.
  248. pub fn modified_time(&self) -> f::Time {
  249. f::Time {
  250. seconds: self.metadata.mtime(),
  251. nanoseconds: self.metadata.mtime_nsec()
  252. }
  253. }
  254. /// This file’s created timestamp.
  255. pub fn created_time(&self) -> f::Time {
  256. f::Time {
  257. seconds: self.metadata.ctime(),
  258. nanoseconds: self.metadata.ctime_nsec()
  259. }
  260. }
  261. /// This file’s last accessed timestamp.
  262. pub fn accessed_time(&self) -> f::Time {
  263. f::Time {
  264. seconds: self.metadata.atime(),
  265. nanoseconds: self.metadata.atime_nsec()
  266. }
  267. }
  268. /// This file’s ‘type’.
  269. ///
  270. /// This is used a the leftmost character of the permissions column.
  271. /// The file type can usually be guessed from the colour of the file, but
  272. /// ls puts this character there.
  273. pub fn type_char(&self) -> f::Type {
  274. if self.is_file() {
  275. f::Type::File
  276. }
  277. else if self.is_directory() {
  278. f::Type::Directory
  279. }
  280. else if self.is_pipe() {
  281. f::Type::Pipe
  282. }
  283. else if self.is_link() {
  284. f::Type::Link
  285. }
  286. else if self.is_char_device() {
  287. f::Type::CharDevice
  288. }
  289. else if self.is_block_device() {
  290. f::Type::BlockDevice
  291. }
  292. else if self.is_socket() {
  293. f::Type::Socket
  294. }
  295. else {
  296. f::Type::Special
  297. }
  298. }
  299. /// This file’s permissions, with flags for each bit.
  300. pub fn permissions(&self) -> f::Permissions {
  301. let bits = self.metadata.mode();
  302. let has_bit = |bit| { bits & bit == bit };
  303. f::Permissions {
  304. user_read: has_bit(modes::USER_READ),
  305. user_write: has_bit(modes::USER_WRITE),
  306. user_execute: has_bit(modes::USER_EXECUTE),
  307. group_read: has_bit(modes::GROUP_READ),
  308. group_write: has_bit(modes::GROUP_WRITE),
  309. group_execute: has_bit(modes::GROUP_EXECUTE),
  310. other_read: has_bit(modes::OTHER_READ),
  311. other_write: has_bit(modes::OTHER_WRITE),
  312. other_execute: has_bit(modes::OTHER_EXECUTE),
  313. sticky: has_bit(modes::STICKY),
  314. setgid: has_bit(modes::SETGID),
  315. setuid: has_bit(modes::SETUID),
  316. }
  317. }
  318. /// Whether this file’s extension is any of the strings that get passed in.
  319. ///
  320. /// This will always return `false` if the file has no extension.
  321. pub fn extension_is_one_of(&self, choices: &[&str]) -> bool {
  322. match self.ext {
  323. Some(ref ext) => choices.contains(&&ext[..]),
  324. None => false,
  325. }
  326. }
  327. /// Whether this file's name, including extension, is any of the strings
  328. /// that get passed in.
  329. pub fn name_is_one_of(&self, choices: &[&str]) -> bool {
  330. choices.contains(&&self.name[..])
  331. }
  332. /// This file's Git status as two flags: one for staged changes, and the
  333. /// other for unstaged changes.
  334. ///
  335. /// This requires looking at the `git` field of this file's parent
  336. /// directory, so will not work if this file has just been passed in on
  337. /// the command line.
  338. pub fn git_status(&self) -> f::Git {
  339. use std::env::current_dir;
  340. match self.parent_dir {
  341. None => f::Git { staged: f::GitStatus::NotModified, unstaged: f::GitStatus::NotModified },
  342. Some(d) => {
  343. let cwd = match current_dir() {
  344. Err(_) => Path::new(".").join(&self.path),
  345. Ok(dir) => dir.join(&self.path),
  346. };
  347. d.git_status(&cwd, self.is_directory())
  348. },
  349. }
  350. }
  351. }
  352. impl<'a> AsRef<File<'a>> for File<'a> {
  353. fn as_ref(&self) -> &File<'a> {
  354. self
  355. }
  356. }
  357. /// The result of following a symlink.
  358. pub enum FileTarget<'dir> {
  359. /// The symlink pointed at a file that exists.
  360. Ok(File<'dir>),
  361. /// The symlink pointed at a file that does not exist. Holds the path
  362. /// where the file would be, if it existed.
  363. Broken(PathBuf),
  364. /// There was an IO error when following the link. This can happen if the
  365. /// file isn’t a link to begin with, but also if, say, we don’t have
  366. /// permission to follow it.
  367. Err(IOError),
  368. // Err is its own variant, instead of having the whole thing be inside an
  369. // `IOResult`, because being unable to follow a symlink is not a serious
  370. // error -- we just display the error message and move on.
  371. }
  372. impl<'dir> FileTarget<'dir> {
  373. /// Whether this link doesn’t lead to a file, for whatever reason. This
  374. /// gets used to determine how to highlight the link in grid views.
  375. pub fn is_broken(&self) -> bool {
  376. match *self {
  377. FileTarget::Ok(_) => false,
  378. FileTarget::Broken(_) | FileTarget::Err(_) => true,
  379. }
  380. }
  381. }
  382. /// More readable aliases for the permission bits exposed by libc.
  383. #[allow(trivial_numeric_casts)]
  384. mod modes {
  385. use libc;
  386. pub type Mode = u32;
  387. // The `libc::mode_t` type’s actual type varies, but the value returned
  388. // from `metadata.permissions().mode()` is always `u32`.
  389. pub const USER_READ: Mode = libc::S_IRUSR as Mode;
  390. pub const USER_WRITE: Mode = libc::S_IWUSR as Mode;
  391. pub const USER_EXECUTE: Mode = libc::S_IXUSR as Mode;
  392. pub const GROUP_READ: Mode = libc::S_IRGRP as Mode;
  393. pub const GROUP_WRITE: Mode = libc::S_IWGRP as Mode;
  394. pub const GROUP_EXECUTE: Mode = libc::S_IXGRP as Mode;
  395. pub const OTHER_READ: Mode = libc::S_IROTH as Mode;
  396. pub const OTHER_WRITE: Mode = libc::S_IWOTH as Mode;
  397. pub const OTHER_EXECUTE: Mode = libc::S_IXOTH as Mode;
  398. pub const STICKY: Mode = libc::S_ISVTX as Mode;
  399. pub const SETGID: Mode = libc::S_ISGID as Mode;
  400. pub const SETUID: Mode = libc::S_ISUID as Mode;
  401. }
  402. #[cfg(test)]
  403. mod ext_test {
  404. use super::File;
  405. use std::path::Path;
  406. #[test]
  407. fn extension() {
  408. assert_eq!(Some("dat".to_string()), File::ext(Path::new("fester.dat")))
  409. }
  410. #[test]
  411. fn dotfile() {
  412. assert_eq!(Some("vimrc".to_string()), File::ext(Path::new(".vimrc")))
  413. }
  414. #[test]
  415. fn no_extension() {
  416. assert_eq!(None, File::ext(Path::new("jarlsberg")))
  417. }
  418. }
  419. #[cfg(test)]
  420. mod filename_test {
  421. use super::File;
  422. use std::path::Path;
  423. #[test]
  424. fn file() {
  425. assert_eq!("fester.dat", File::filename(Path::new("fester.dat")))
  426. }
  427. #[test]
  428. fn no_path() {
  429. assert_eq!("foo.wha", File::filename(Path::new("/var/cache/foo.wha")))
  430. }
  431. #[test]
  432. fn here() {
  433. assert_eq!(".", File::filename(Path::new(".")))
  434. }
  435. #[test]
  436. fn there() {
  437. assert_eq!("..", File::filename(Path::new("..")))
  438. }
  439. #[test]
  440. fn everywhere() {
  441. assert_eq!("..", File::filename(Path::new("./..")))
  442. }
  443. #[test]
  444. fn topmost() {
  445. assert_eq!("/", File::filename(Path::new("/")))
  446. }
  447. }