1
0

file.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. //! Files, and methods and fields to access their metadata.
  2. use std::io;
  3. #[cfg(unix)]
  4. use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
  5. #[cfg(windows)]
  6. use std::os::windows::fs::MetadataExt;
  7. use std::path::{Path, PathBuf};
  8. use chrono::prelude::*;
  9. use log::*;
  10. use crate::ALL_MOUNTS;
  11. use crate::fs::dir::Dir;
  12. use crate::fs::feature::xattr;
  13. use crate::fs::feature::xattr::{FileAttributes, Attribute};
  14. use crate::fs::fields as f;
  15. use super::mounts::MountedFs;
  16. /// A **File** is a wrapper around one of Rust’s `PathBuf` values, along with
  17. /// associated data about the file.
  18. ///
  19. /// Each file is definitely going to have its filename displayed at least
  20. /// once, have its file extension extracted at least once, and have its metadata
  21. /// information queried at least once, so it makes sense to do all this at the
  22. /// start and hold on to all the information.
  23. pub struct File<'dir> {
  24. /// The filename portion of this file’s path, including the extension.
  25. ///
  26. /// This is used to compare against certain filenames (such as checking if
  27. /// it’s “Makefile” or something) and to highlight only the filename in
  28. /// colour when displaying the path.
  29. pub name: String,
  30. /// The file’s name’s extension, if present, extracted from the name.
  31. ///
  32. /// This is queried many times over, so it’s worth caching it.
  33. pub ext: Option<String>,
  34. /// The path that begat this file.
  35. ///
  36. /// Even though the file’s name is extracted, the path needs to be kept
  37. /// around, as certain operations involve looking up the file’s absolute
  38. /// location (such as searching for compiled files) or using its original
  39. /// path (following a symlink).
  40. pub path: PathBuf,
  41. /// A cached `metadata` (`stat`) call for this file.
  42. ///
  43. /// This too is queried multiple times, and is *not* cached by the OS, as
  44. /// it could easily change between invocations — but exa is so short-lived
  45. /// it’s better to just cache it.
  46. pub metadata: std::fs::Metadata,
  47. /// A reference to the directory that contains this file, if any.
  48. ///
  49. /// Filenames that get passed in on the command-line directly will have no
  50. /// parent directory reference — although they technically have one on the
  51. /// filesystem, we’ll never need to look at it, so it’ll be `None`.
  52. /// However, *directories* that get passed in will produce files that
  53. /// contain a reference to it, which is used in certain operations (such
  54. /// as looking up compiled files).
  55. pub parent_dir: Option<&'dir Dir>,
  56. /// Whether this is one of the two `--all all` directories, `.` and `..`.
  57. ///
  58. /// Unlike all other entries, these are not returned as part of the
  59. /// directory’s children, and are in fact added specifically by exa; this
  60. /// means that they should be skipped when recursing.
  61. pub is_all_all: bool,
  62. /// Whether to dereference symbolic links when querying for information.
  63. ///
  64. /// For instance, when querying the size of a symbolic link, if
  65. /// dereferencing is enabled, the size of the target will be displayed
  66. /// instead.
  67. pub deref_links: bool,
  68. /// The extended attributes of this file.
  69. pub extended_attributes: Vec<Attribute>,
  70. /// The absolute value of this path, used to look up mount points.
  71. pub absolute_path: Option<PathBuf>,
  72. }
  73. impl<'dir> File<'dir> {
  74. pub fn from_args<PD, FN>(path: PathBuf, parent_dir: PD, filename: FN, deref_links: bool) -> io::Result<File<'dir>>
  75. where PD: Into<Option<&'dir Dir>>,
  76. FN: Into<Option<String>>
  77. {
  78. let parent_dir = parent_dir.into();
  79. let name = filename.into().unwrap_or_else(|| File::filename(&path));
  80. let ext = File::ext(&path);
  81. debug!("Statting file {:?}", &path);
  82. let metadata = std::fs::symlink_metadata(&path)?;
  83. let is_all_all = false;
  84. let extended_attributes = File::gather_extended_attributes(&path);
  85. let absolute_path = std::fs::canonicalize(&path).ok();
  86. Ok(File { name, ext, path, metadata, parent_dir, is_all_all, deref_links, extended_attributes, absolute_path })
  87. }
  88. pub fn new_aa_current(parent_dir: &'dir Dir) -> io::Result<File<'dir>> {
  89. let path = parent_dir.path.clone();
  90. let ext = File::ext(&path);
  91. debug!("Statting file {:?}", &path);
  92. let metadata = std::fs::symlink_metadata(&path)?;
  93. let is_all_all = true;
  94. let parent_dir = Some(parent_dir);
  95. let extended_attributes = File::gather_extended_attributes(&path);
  96. let absolute_path = std::fs::canonicalize(&path).ok();
  97. Ok(File { path, parent_dir, metadata, ext, name: ".".into(), is_all_all, deref_links: false, extended_attributes, absolute_path })
  98. }
  99. pub fn new_aa_parent(path: PathBuf, parent_dir: &'dir Dir) -> io::Result<File<'dir>> {
  100. let ext = File::ext(&path);
  101. debug!("Statting file {:?}", &path);
  102. let metadata = std::fs::symlink_metadata(&path)?;
  103. let is_all_all = true;
  104. let parent_dir = Some(parent_dir);
  105. let extended_attributes = File::gather_extended_attributes(&path);
  106. let absolute_path = std::fs::canonicalize(&path).ok();
  107. Ok(File { path, parent_dir, metadata, ext, name: "..".into(), is_all_all, deref_links: false, extended_attributes, absolute_path })
  108. }
  109. /// A file’s name is derived from its string. This needs to handle directories
  110. /// such as `/` or `..`, which have no `file_name` component. So instead, just
  111. /// use the last component as the name.
  112. pub fn filename(path: &Path) -> String {
  113. if let Some(back) = path.components().next_back() {
  114. back.as_os_str().to_string_lossy().to_string()
  115. }
  116. else {
  117. // use the path as fallback
  118. error!("Path {:?} has no last component", path);
  119. path.display().to_string()
  120. }
  121. }
  122. /// Extract an extension from a file path, if one is present, in lowercase.
  123. ///
  124. /// The extension is the series of characters after the last dot. This
  125. /// deliberately counts dotfiles, so the “.git” folder has the extension “git”.
  126. ///
  127. /// ASCII lowercasing is used because these extensions are only compared
  128. /// against a pre-compiled list of extensions which are known to only exist
  129. /// within ASCII, so it’s alright.
  130. fn ext(path: &Path) -> Option<String> {
  131. let name = path.file_name().map(|f| f.to_string_lossy().to_string())?;
  132. name.rfind('.')
  133. .map(|p| name[p + 1 ..]
  134. .to_ascii_lowercase())
  135. }
  136. /// Read the extended attributes of a file path.
  137. fn gather_extended_attributes(path: &Path) -> Vec<Attribute> {
  138. if xattr::ENABLED {
  139. match path.symlink_attributes() {
  140. Ok(xattrs) => xattrs,
  141. Err(e) => {
  142. error!("Error looking up extended attributes for {}: {}", path.display(), e);
  143. Vec::new()
  144. }
  145. }
  146. } else {
  147. Vec::new()
  148. }
  149. }
  150. /// Whether this file is a directory on the filesystem.
  151. pub fn is_directory(&self) -> bool {
  152. self.metadata.is_dir()
  153. }
  154. /// Whether this file is a directory, or a symlink pointing to a directory.
  155. pub fn points_to_directory(&self) -> bool {
  156. if self.is_directory() {
  157. return true;
  158. }
  159. if self.is_link() {
  160. let target = self.link_target();
  161. if let FileTarget::Ok(target) = target {
  162. return target.points_to_directory();
  163. }
  164. }
  165. false
  166. }
  167. /// If this file is a directory on the filesystem, then clone its
  168. /// `PathBuf` for use in one of our own `Dir` values, and read a list of
  169. /// its contents.
  170. ///
  171. /// Returns an IO error upon failure, but this shouldn’t be used to check
  172. /// if a `File` is a directory or not! For that, just use `is_directory()`.
  173. pub fn to_dir(&self) -> io::Result<Dir> {
  174. Dir::read_dir(self.path.clone())
  175. }
  176. /// Whether this file is a regular file on the filesystem — that is, not a
  177. /// directory, a link, or anything else treated specially.
  178. pub fn is_file(&self) -> bool {
  179. self.metadata.is_file()
  180. }
  181. /// Whether this file is both a regular file *and* executable for the
  182. /// current user. An executable file has a different purpose from an
  183. /// executable directory, so they should be highlighted differently.
  184. #[cfg(unix)]
  185. pub fn is_executable_file(&self) -> bool {
  186. let bit = modes::USER_EXECUTE;
  187. self.is_file() && (self.metadata.permissions().mode() & bit) == bit
  188. }
  189. /// Whether this file is a symlink on the filesystem.
  190. pub fn is_link(&self) -> bool {
  191. self.metadata.file_type().is_symlink()
  192. }
  193. /// Whether this file is a named pipe on the filesystem.
  194. #[cfg(unix)]
  195. pub fn is_pipe(&self) -> bool {
  196. self.metadata.file_type().is_fifo()
  197. }
  198. /// Whether this file is a char device on the filesystem.
  199. #[cfg(unix)]
  200. pub fn is_char_device(&self) -> bool {
  201. self.metadata.file_type().is_char_device()
  202. }
  203. /// Whether this file is a block device on the filesystem.
  204. #[cfg(unix)]
  205. pub fn is_block_device(&self) -> bool {
  206. self.metadata.file_type().is_block_device()
  207. }
  208. /// Whether this file is a socket on the filesystem.
  209. #[cfg(unix)]
  210. pub fn is_socket(&self) -> bool {
  211. self.metadata.file_type().is_socket()
  212. }
  213. /// Whether this file is a mount point
  214. pub fn is_mount_point(&self) -> bool {
  215. if cfg!(target_os = "linux") && self.is_directory() {
  216. return match self.absolute_path.as_ref() {
  217. Some(path) => ALL_MOUNTS.contains_key(path),
  218. None => false,
  219. }
  220. }
  221. false
  222. }
  223. /// The filesystem device and type for a mount point
  224. pub fn mount_point_info(&self) -> Option<&MountedFs> {
  225. if cfg!(target_os = "linux") {
  226. return self.absolute_path.as_ref().and_then(|p|ALL_MOUNTS.get(p));
  227. }
  228. None
  229. }
  230. /// Re-prefixes the path pointed to by this file, if it’s a symlink, to
  231. /// make it an absolute path that can be accessed from whichever
  232. /// directory exa is being run from.
  233. fn reorient_target_path(&self, path: &Path) -> PathBuf {
  234. if path.is_absolute() {
  235. path.to_path_buf()
  236. }
  237. else if let Some(dir) = self.parent_dir {
  238. dir.join(path)
  239. }
  240. else if let Some(parent) = self.path.parent() {
  241. parent.join(path)
  242. }
  243. else {
  244. self.path.join(path)
  245. }
  246. }
  247. /// Again assuming this file is a symlink, follows that link and returns
  248. /// the result of following it.
  249. ///
  250. /// For a working symlink that the user is allowed to follow,
  251. /// this will be the `File` object at the other end, which can then have
  252. /// its name, colour, and other details read.
  253. ///
  254. /// For a broken symlink, returns where the file *would* be, if it
  255. /// existed. If this file cannot be read at all, returns the error that
  256. /// we got when we tried to read it.
  257. pub fn link_target(&self) -> FileTarget<'dir> {
  258. // We need to be careful to treat the path actually pointed to by
  259. // this file — which could be absolute or relative — to the path
  260. // we actually look up and turn into a `File` — which needs to be
  261. // absolute to be accessible from any directory.
  262. debug!("Reading link {:?}", &self.path);
  263. let path = match std::fs::read_link(&self.path) {
  264. Ok(p) => p,
  265. Err(e) => return FileTarget::Err(e),
  266. };
  267. let absolute_path = self.reorient_target_path(&path);
  268. // Use plain `metadata` instead of `symlink_metadata` - we *want* to
  269. // follow links.
  270. match std::fs::metadata(&absolute_path) {
  271. Ok(metadata) => {
  272. let ext = File::ext(&path);
  273. let name = File::filename(&path);
  274. let extended_attributes = File::gather_extended_attributes(&absolute_path);
  275. let file = File {
  276. parent_dir: None,
  277. path,
  278. ext,
  279. metadata,
  280. name,
  281. is_all_all: false,
  282. deref_links: self.deref_links,
  283. extended_attributes,
  284. absolute_path: Some(absolute_path)
  285. };
  286. FileTarget::Ok(Box::new(file))
  287. }
  288. Err(e) => {
  289. error!("Error following link {:?}: {:#?}", &path, e);
  290. FileTarget::Broken(path)
  291. }
  292. }
  293. }
  294. /// Assuming this file is a symlink, follows that link and any further
  295. /// links recursively, returning the result from following the trail.
  296. ///
  297. /// For a working symlink that the user is allowed to follow,
  298. /// this will be the `File` object at the other end, which can then have
  299. /// its name, colour, and other details read.
  300. ///
  301. /// For a broken symlink, returns where the file *would* be, if it
  302. /// existed. If this file cannot be read at all, returns the error that
  303. /// we got when we tried to read it.
  304. pub fn link_target_recurse(&self) -> FileTarget<'dir> {
  305. let target = self.link_target();
  306. if let FileTarget::Ok(f) = target {
  307. if f.is_link() {
  308. return f.link_target_recurse();
  309. }
  310. return FileTarget::Ok(f);
  311. }
  312. target
  313. }
  314. /// This file’s number of hard links.
  315. ///
  316. /// It also reports whether this is both a regular file, and a file with
  317. /// multiple links. This is important, because a file with multiple links
  318. /// is uncommon, while you come across directories and other types
  319. /// with multiple links much more often. Thus, it should get highlighted
  320. /// more attentively.
  321. #[cfg(unix)]
  322. pub fn links(&self) -> f::Links {
  323. let count = self.metadata.nlink();
  324. f::Links {
  325. count,
  326. multiple: self.is_file() && count > 1,
  327. }
  328. }
  329. /// This file’s inode.
  330. #[cfg(unix)]
  331. pub fn inode(&self) -> f::Inode {
  332. f::Inode(self.metadata.ino())
  333. }
  334. /// This actual size the file takes up on disk, in bytes.
  335. #[cfg(unix)]
  336. pub fn blocksize(&self) -> f::Blocksize {
  337. if self.is_file() || self.is_link() {
  338. // Note that metadata.blocks returns the number of blocks
  339. // for 512 byte blocks according to the POSIX standard
  340. // even though the physical block size may be different.
  341. f::Blocksize::Some(self.metadata.blocks() * 512)
  342. }
  343. else {
  344. f::Blocksize::None
  345. }
  346. }
  347. /// The ID of the user that own this file. If dereferencing links, the links
  348. /// may be broken, in which case `None` will be returned.
  349. #[cfg(unix)]
  350. pub fn user(&self) -> Option<f::User> {
  351. if self.is_link() && self.deref_links {
  352. match self.link_target_recurse() {
  353. FileTarget::Ok(f) => return f.user(),
  354. _ => return None,
  355. }
  356. }
  357. Some(f::User(self.metadata.uid()))
  358. }
  359. /// The ID of the group that owns this file.
  360. #[cfg(unix)]
  361. pub fn group(&self) -> Option<f::Group> {
  362. if self.is_link() && self.deref_links {
  363. match self.link_target_recurse() {
  364. FileTarget::Ok(f) => return f.group(),
  365. _ => return None,
  366. }
  367. }
  368. Some(f::Group(self.metadata.gid()))
  369. }
  370. /// This file’s size, if it’s a regular file.
  371. ///
  372. /// For directories, no size is given. Although they do have a size on
  373. /// some filesystems, I’ve never looked at one of those numbers and gained
  374. /// any information from it. So it’s going to be hidden instead.
  375. ///
  376. /// Block and character devices return their device IDs, because they
  377. /// usually just have a file size of zero.
  378. ///
  379. /// Links will return the size of their target (recursively through other
  380. /// links) if dereferencing is enabled, otherwise the size of the link
  381. /// itself.
  382. #[cfg(unix)]
  383. pub fn size(&self) -> f::Size {
  384. if self.is_link() {
  385. let target = self.link_target();
  386. if let FileTarget::Ok(target) = target {
  387. return target.size();
  388. }
  389. }
  390. if self.is_directory() {
  391. f::Size::None
  392. }
  393. else if self.is_char_device() || self.is_block_device() {
  394. let device_ids = self.metadata.rdev().to_be_bytes();
  395. // In C-land, getting the major and minor device IDs is done with
  396. // preprocessor macros called `major` and `minor` that depend on
  397. // the size of `dev_t`, but we just take the second-to-last and
  398. // last bytes.
  399. f::Size::DeviceIDs(f::DeviceIDs {
  400. major: device_ids[6],
  401. minor: device_ids[7],
  402. })
  403. }
  404. else if self.is_link() && self.deref_links {
  405. match self.link_target() {
  406. FileTarget::Ok(f) => f.size(),
  407. _ => f::Size::None
  408. }
  409. } else {
  410. f::Size::Some(self.metadata.len())
  411. }
  412. }
  413. /// Returns the size of the file or indicates no size if it's a directory.
  414. ///
  415. /// For Windows platforms, the size of directories is not computed and will
  416. /// return `Size::None`.
  417. #[cfg(windows)]
  418. pub fn size(&self) -> f::Size {
  419. if self.is_directory() {
  420. f::Size::None
  421. }
  422. else {
  423. f::Size::Some(self.metadata.len())
  424. }
  425. }
  426. /// Determines if the directory is empty or not.
  427. ///
  428. /// For Unix platforms, this function first checks the link count to quickly
  429. /// determine non-empty directories. On most UNIX filesystems the link count
  430. /// is two plus the number of subdirectories. If the link count is less than
  431. /// or equal to 2, it then checks the directory contents to determine if
  432. /// it's truly empty. The naive approach used here checks the contents
  433. /// directly, as certain filesystems make it difficult to infer emptiness
  434. /// based on directory size alone.
  435. #[cfg(unix)]
  436. pub fn is_empty_dir(&self) -> bool {
  437. if self.is_directory() {
  438. if self.metadata.nlink() > 2 {
  439. // Directories will have a link count of two if they do not have any subdirectories.
  440. // The '.' entry is a link to itself and the '..' is a link to the parent directory.
  441. // A subdirectory will have a link to its parent directory increasing the link count
  442. // above two. This will avoid the expensive read_dir call below when a directory
  443. // has subdirectories.
  444. false
  445. } else {
  446. self.is_empty_directory()
  447. }
  448. } else {
  449. false
  450. }
  451. }
  452. /// Determines if the directory is empty or not.
  453. ///
  454. /// For Windows platforms, this function checks the directory contents directly
  455. /// to determine if it's empty. Since certain filesystems on Windows make it
  456. /// challenging to infer emptiness based on directory size, this approach is used.
  457. #[cfg(windows)]
  458. pub fn is_empty_dir(&self) -> bool {
  459. if self.is_directory() {
  460. self.is_empty_directory()
  461. } else {
  462. false
  463. }
  464. }
  465. /// Checks the contents of the directory to determine if it's empty.
  466. ///
  467. /// This function avoids counting '.' and '..' when determining if the directory is
  468. /// empty. If any other entries are found, it returns `false`.
  469. ///
  470. /// The naive approach, as one would think that this info may have been cached.
  471. /// but as mentioned in the size function comment above, different filesystems
  472. /// make it difficult to get any info about a dir by it's size, so this may be it.
  473. fn is_empty_directory(&self) -> bool {
  474. match Dir::read_dir(self.path.clone()) {
  475. // . & .. are skipped, if the returned iterator has .next(), it's not empty
  476. Ok(has_files) => has_files.files(super::DotFilter::Dotfiles, None, false, false).next().is_none(),
  477. Err(_) => false,
  478. }
  479. }
  480. /// This file’s last modified timestamp, if available on this platform.
  481. pub fn modified_time(&self) -> Option<NaiveDateTime> {
  482. if self.is_link() && self.deref_links {
  483. return match self.link_target_recurse() {
  484. FileTarget::Ok(f) => f.modified_time(),
  485. _ => None,
  486. };
  487. }
  488. self.metadata.modified().map(|st| DateTime::<Utc>::from(st).naive_utc()).ok()
  489. }
  490. /// This file’s last changed timestamp, if available on this platform.
  491. #[cfg(unix)]
  492. pub fn changed_time(&self) -> Option<NaiveDateTime> {
  493. if self.is_link() && self.deref_links {
  494. return match self.link_target_recurse() {
  495. FileTarget::Ok(f) => f.changed_time(),
  496. _ => None,
  497. };
  498. }
  499. NaiveDateTime::from_timestamp_opt(
  500. self.metadata.ctime(),
  501. self.metadata.ctime_nsec() as u32,
  502. )
  503. }
  504. #[cfg(windows)]
  505. pub fn changed_time(&self) -> Option<NaiveDateTime> {
  506. self.modified_time()
  507. }
  508. /// This file’s last accessed timestamp, if available on this platform.
  509. pub fn accessed_time(&self) -> Option<NaiveDateTime> {
  510. if self.is_link() && self.deref_links {
  511. return match self.link_target_recurse() {
  512. FileTarget::Ok(f) => f.accessed_time(),
  513. _ => None,
  514. };
  515. }
  516. self.metadata.accessed().map(|st| DateTime::<Utc>::from(st).naive_utc()).ok()
  517. }
  518. /// This file’s created timestamp, if available on this platform.
  519. pub fn created_time(&self) -> Option<NaiveDateTime> {
  520. if self.is_link() && self.deref_links {
  521. return match self.link_target_recurse() {
  522. FileTarget::Ok(f) => f.created_time(),
  523. _ => None,
  524. };
  525. }
  526. self.metadata.created().map(|st| DateTime::<Utc>::from(st).naive_utc()).ok()
  527. }
  528. /// This file’s ‘type’.
  529. ///
  530. /// This is used a the leftmost character of the permissions column.
  531. /// The file type can usually be guessed from the colour of the file, but
  532. /// ls puts this character there.
  533. #[cfg(unix)]
  534. pub fn type_char(&self) -> f::Type {
  535. if self.is_file() {
  536. f::Type::File
  537. }
  538. else if self.is_directory() {
  539. f::Type::Directory
  540. }
  541. else if self.is_pipe() {
  542. f::Type::Pipe
  543. }
  544. else if self.is_link() {
  545. f::Type::Link
  546. }
  547. else if self.is_char_device() {
  548. f::Type::CharDevice
  549. }
  550. else if self.is_block_device() {
  551. f::Type::BlockDevice
  552. }
  553. else if self.is_socket() {
  554. f::Type::Socket
  555. }
  556. else {
  557. f::Type::Special
  558. }
  559. }
  560. #[cfg(windows)]
  561. pub fn type_char(&self) -> f::Type {
  562. if self.is_file() {
  563. f::Type::File
  564. }
  565. else if self.is_directory() {
  566. f::Type::Directory
  567. }
  568. else {
  569. f::Type::Special
  570. }
  571. }
  572. /// This file’s permissions, with flags for each bit.
  573. #[cfg(unix)]
  574. pub fn permissions(&self) -> Option<f::Permissions> {
  575. if self.is_link() && self.deref_links {
  576. // If the chain of links is broken, we instead fall through and
  577. // return the permissions of the original link, as would have been
  578. // done if we were not dereferencing.
  579. match self.link_target_recurse() {
  580. FileTarget::Ok(f) => return f.permissions(),
  581. _ => return None,
  582. }
  583. }
  584. let bits = self.metadata.mode();
  585. let has_bit = |bit| bits & bit == bit;
  586. Some(f::Permissions {
  587. user_read: has_bit(modes::USER_READ),
  588. user_write: has_bit(modes::USER_WRITE),
  589. user_execute: has_bit(modes::USER_EXECUTE),
  590. group_read: has_bit(modes::GROUP_READ),
  591. group_write: has_bit(modes::GROUP_WRITE),
  592. group_execute: has_bit(modes::GROUP_EXECUTE),
  593. other_read: has_bit(modes::OTHER_READ),
  594. other_write: has_bit(modes::OTHER_WRITE),
  595. other_execute: has_bit(modes::OTHER_EXECUTE),
  596. sticky: has_bit(modes::STICKY),
  597. setgid: has_bit(modes::SETGID),
  598. setuid: has_bit(modes::SETUID),
  599. })
  600. }
  601. #[cfg(windows)]
  602. pub fn attributes(&self) -> f::Attributes {
  603. let bits = self.metadata.file_attributes();
  604. let has_bit = |bit| bits & bit == bit;
  605. // https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
  606. f::Attributes {
  607. directory: has_bit(0x10),
  608. archive: has_bit(0x20),
  609. readonly: has_bit(0x1),
  610. hidden: has_bit(0x2),
  611. system: has_bit(0x4),
  612. reparse_point: has_bit(0x400),
  613. }
  614. }
  615. /// This file’s security context field.
  616. pub fn security_context(&self) -> f::SecurityContext<'_> {
  617. let context = match &self.extended_attributes.iter().find(|a| a.name == "security.selinux") {
  618. Some(attr) => f::SecurityContextType::SELinux(&attr.value),
  619. None => f::SecurityContextType::None
  620. };
  621. f::SecurityContext { context }
  622. }
  623. }
  624. impl<'a> AsRef<File<'a>> for File<'a> {
  625. fn as_ref(&self) -> &File<'a> {
  626. self
  627. }
  628. }
  629. /// The result of following a symlink.
  630. pub enum FileTarget<'dir> {
  631. /// The symlink pointed at a file that exists.
  632. Ok(Box<File<'dir>>),
  633. /// The symlink pointed at a file that does not exist. Holds the path
  634. /// where the file would be, if it existed.
  635. Broken(PathBuf),
  636. /// There was an IO error when following the link. This can happen if the
  637. /// file isn’t a link to begin with, but also if, say, we don’t have
  638. /// permission to follow it.
  639. Err(io::Error),
  640. // Err is its own variant, instead of having the whole thing be inside an
  641. // `io::Result`, because being unable to follow a symlink is not a serious
  642. // error — we just display the error message and move on.
  643. }
  644. impl<'dir> FileTarget<'dir> {
  645. /// Whether this link doesn’t lead to a file, for whatever reason. This
  646. /// gets used to determine how to highlight the link in grid views.
  647. pub fn is_broken(&self) -> bool {
  648. matches!(self, Self::Broken(_) | Self::Err(_))
  649. }
  650. }
  651. /// More readable aliases for the permission bits exposed by libc.
  652. #[allow(trivial_numeric_casts)]
  653. #[cfg(unix)]
  654. mod modes {
  655. // The `libc::mode_t` type’s actual type varies, but the value returned
  656. // from `metadata.permissions().mode()` is always `u32`.
  657. pub type Mode = u32;
  658. pub const USER_READ: Mode = libc::S_IRUSR as Mode;
  659. pub const USER_WRITE: Mode = libc::S_IWUSR as Mode;
  660. pub const USER_EXECUTE: Mode = libc::S_IXUSR as Mode;
  661. pub const GROUP_READ: Mode = libc::S_IRGRP as Mode;
  662. pub const GROUP_WRITE: Mode = libc::S_IWGRP as Mode;
  663. pub const GROUP_EXECUTE: Mode = libc::S_IXGRP as Mode;
  664. pub const OTHER_READ: Mode = libc::S_IROTH as Mode;
  665. pub const OTHER_WRITE: Mode = libc::S_IWOTH as Mode;
  666. pub const OTHER_EXECUTE: Mode = libc::S_IXOTH as Mode;
  667. pub const STICKY: Mode = libc::S_ISVTX as Mode;
  668. pub const SETGID: Mode = libc::S_ISGID as Mode;
  669. pub const SETUID: Mode = libc::S_ISUID as Mode;
  670. }
  671. #[cfg(test)]
  672. mod ext_test {
  673. use super::File;
  674. use std::path::Path;
  675. #[test]
  676. fn extension() {
  677. assert_eq!(Some("dat".to_string()), File::ext(Path::new("fester.dat")))
  678. }
  679. #[test]
  680. fn dotfile() {
  681. assert_eq!(Some("vimrc".to_string()), File::ext(Path::new(".vimrc")))
  682. }
  683. #[test]
  684. fn no_extension() {
  685. assert_eq!(None, File::ext(Path::new("jarlsberg")))
  686. }
  687. }
  688. #[cfg(test)]
  689. mod filename_test {
  690. use super::File;
  691. use std::path::Path;
  692. #[test]
  693. fn file() {
  694. assert_eq!("fester.dat", File::filename(Path::new("fester.dat")))
  695. }
  696. #[test]
  697. fn no_path() {
  698. assert_eq!("foo.wha", File::filename(Path::new("/var/cache/foo.wha")))
  699. }
  700. #[test]
  701. fn here() {
  702. assert_eq!(".", File::filename(Path::new(".")))
  703. }
  704. #[test]
  705. fn there() {
  706. assert_eq!("..", File::filename(Path::new("..")))
  707. }
  708. #[test]
  709. fn everywhere() {
  710. assert_eq!("..", File::filename(Path::new("./..")))
  711. }
  712. #[test]
  713. #[cfg(unix)]
  714. fn topmost() {
  715. assert_eq!("/", File::filename(Path::new("/")))
  716. }
  717. }