file.rs 17 KB

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