file.rs 17 KB

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