file.rs 18 KB

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