file.rs 19 KB

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