file.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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 self.absolute_path.as_ref().is_some_and(|p|ALL_MOUNTS.contains_key(p));
  217. }
  218. false
  219. }
  220. /// The filesystem device and type for a mount point
  221. pub fn mount_point_info(&self) -> Option<&MountedFs> {
  222. if cfg!(target_os = "linux") {
  223. return self.absolute_path.as_ref().and_then(|p|ALL_MOUNTS.get(p));
  224. }
  225. None
  226. }
  227. /// Re-prefixes the path pointed to by this file, if it’s a symlink, to
  228. /// make it an absolute path that can be accessed from whichever
  229. /// directory exa is being run from.
  230. fn reorient_target_path(&self, path: &Path) -> PathBuf {
  231. if path.is_absolute() {
  232. path.to_path_buf()
  233. }
  234. else if let Some(dir) = self.parent_dir {
  235. dir.join(path)
  236. }
  237. else if let Some(parent) = self.path.parent() {
  238. parent.join(path)
  239. }
  240. else {
  241. self.path.join(path)
  242. }
  243. }
  244. /// Again assuming this file is a symlink, follows that link and returns
  245. /// the result of following it.
  246. ///
  247. /// For a working symlink that the user is allowed to follow,
  248. /// this will be the `File` object at the other end, which can then have
  249. /// its name, colour, and other details read.
  250. ///
  251. /// For a broken symlink, returns where the file *would* be, if it
  252. /// existed. If this file cannot be read at all, returns the error that
  253. /// we got when we tried to read it.
  254. pub fn link_target(&self) -> FileTarget<'dir> {
  255. // We need to be careful to treat the path actually pointed to by
  256. // this file — which could be absolute or relative — to the path
  257. // we actually look up and turn into a `File` — which needs to be
  258. // absolute to be accessible from any directory.
  259. debug!("Reading link {:?}", &self.path);
  260. let path = match std::fs::read_link(&self.path) {
  261. Ok(p) => p,
  262. Err(e) => return FileTarget::Err(e),
  263. };
  264. let absolute_path = self.reorient_target_path(&path);
  265. // Use plain `metadata` instead of `symlink_metadata` - we *want* to
  266. // follow links.
  267. match std::fs::metadata(&absolute_path) {
  268. Ok(metadata) => {
  269. let ext = File::ext(&path);
  270. let name = File::filename(&path);
  271. let extended_attributes = File::gather_extended_attributes(&absolute_path);
  272. let file = File {
  273. parent_dir: None,
  274. path,
  275. ext,
  276. metadata,
  277. name,
  278. is_all_all: false,
  279. deref_links: self.deref_links,
  280. extended_attributes,
  281. absolute_path: Some(absolute_path)
  282. };
  283. FileTarget::Ok(Box::new(file))
  284. }
  285. Err(e) => {
  286. error!("Error following link {:?}: {:#?}", &path, e);
  287. FileTarget::Broken(path)
  288. }
  289. }
  290. }
  291. /// Assuming this file is a symlink, follows that link and any further
  292. /// links recursively, returning the result from following the trail.
  293. ///
  294. /// For a working symlink that the user is allowed to follow,
  295. /// this will be the `File` object at the other end, which can then have
  296. /// its name, colour, and other details read.
  297. ///
  298. /// For a broken symlink, returns where the file *would* be, if it
  299. /// existed. If this file cannot be read at all, returns the error that
  300. /// we got when we tried to read it.
  301. pub fn link_target_recurse(&self) -> FileTarget<'dir> {
  302. let target = self.link_target();
  303. if let FileTarget::Ok(f) = target {
  304. if f.is_link() {
  305. return f.link_target_recurse();
  306. }
  307. return FileTarget::Ok(f);
  308. }
  309. target
  310. }
  311. /// This file’s number of hard links.
  312. ///
  313. /// It also reports whether this is both a regular file, and a file with
  314. /// multiple links. This is important, because a file with multiple links
  315. /// is uncommon, while you come across directories and other types
  316. /// with multiple links much more often. Thus, it should get highlighted
  317. /// more attentively.
  318. #[cfg(unix)]
  319. pub fn links(&self) -> f::Links {
  320. let count = self.metadata.nlink();
  321. f::Links {
  322. count,
  323. multiple: self.is_file() && count > 1,
  324. }
  325. }
  326. /// This file’s inode.
  327. #[cfg(unix)]
  328. pub fn inode(&self) -> f::Inode {
  329. f::Inode(self.metadata.ino())
  330. }
  331. /// This actual size the file takes up on disk, in bytes.
  332. #[cfg(unix)]
  333. pub fn blocksize(&self) -> f::Blocksize {
  334. if self.is_file() || self.is_link() {
  335. // Note that metadata.blocks returns the number of blocks
  336. // for 512 byte blocks according to the POSIX standard
  337. // even though the physical block size may be different.
  338. f::Blocksize::Some(self.metadata.blocks() * 512)
  339. }
  340. else {
  341. f::Blocksize::None
  342. }
  343. }
  344. /// The ID of the user that own this file. If dereferencing links, the links
  345. /// may be broken, in which case `None` will be returned.
  346. #[cfg(unix)]
  347. pub fn user(&self) -> Option<f::User> {
  348. if self.is_link() && self.deref_links {
  349. match self.link_target_recurse() {
  350. FileTarget::Ok(f) => return f.user(),
  351. _ => return None,
  352. }
  353. }
  354. Some(f::User(self.metadata.uid()))
  355. }
  356. /// The ID of the group that owns this file.
  357. #[cfg(unix)]
  358. pub fn group(&self) -> Option<f::Group> {
  359. if self.is_link() && self.deref_links {
  360. match self.link_target_recurse() {
  361. FileTarget::Ok(f) => return f.group(),
  362. _ => return None,
  363. }
  364. }
  365. Some(f::Group(self.metadata.gid()))
  366. }
  367. /// This file’s size, if it’s a regular file.
  368. ///
  369. /// For directories, no size is given. Although they do have a size on
  370. /// some filesystems, I’ve never looked at one of those numbers and gained
  371. /// any information from it. So it’s going to be hidden instead.
  372. ///
  373. /// Block and character devices return their device IDs, because they
  374. /// usually just have a file size of zero.
  375. ///
  376. /// Links will return the size of their target (recursively through other
  377. /// links) if dereferencing is enabled, otherwise the size of the link
  378. /// itself.
  379. #[cfg(unix)]
  380. pub fn size(&self) -> f::Size {
  381. if self.is_link() {
  382. let target = self.link_target();
  383. if let FileTarget::Ok(target) = target {
  384. return target.size();
  385. }
  386. }
  387. if self.is_directory() {
  388. f::Size::None
  389. }
  390. else if self.is_char_device() || self.is_block_device() {
  391. let device_ids = self.metadata.rdev().to_be_bytes();
  392. // In C-land, getting the major and minor device IDs is done with
  393. // preprocessor macros called `major` and `minor` that depend on
  394. // the size of `dev_t`, but we just take the second-to-last and
  395. // last bytes.
  396. f::Size::DeviceIDs(f::DeviceIDs {
  397. major: device_ids[6],
  398. minor: device_ids[7],
  399. })
  400. }
  401. else if self.is_link() && self.deref_links {
  402. match self.link_target() {
  403. FileTarget::Ok(f) => f.size(),
  404. _ => f::Size::None
  405. }
  406. } else {
  407. f::Size::Some(self.metadata.len())
  408. }
  409. }
  410. /// Returns the size of the file or indicates no size if it's a directory.
  411. ///
  412. /// For Windows platforms, the size of directories is not computed and will
  413. /// return `Size::None`.
  414. #[cfg(windows)]
  415. pub fn size(&self) -> f::Size {
  416. if self.is_directory() {
  417. f::Size::None
  418. }
  419. else {
  420. f::Size::Some(self.metadata.len())
  421. }
  422. }
  423. /// Determines if the directory is empty or not.
  424. ///
  425. /// For Unix platforms, this function first checks the link count to quickly
  426. /// determine non-empty directories. On most UNIX filesystems the link count
  427. /// is two plus the number of subdirectories. If the link count is less than
  428. /// or equal to 2, it then checks the directory contents to determine if
  429. /// it's truly empty. The naive approach used here checks the contents
  430. /// directly, as certain filesystems make it difficult to infer emptiness
  431. /// based on directory size alone.
  432. #[cfg(unix)]
  433. pub fn is_empty_dir(&self) -> bool {
  434. if self.is_directory() {
  435. if self.metadata.nlink() > 2 {
  436. // Directories will have a link count of two if they do not have any subdirectories.
  437. // The '.' entry is a link to itself and the '..' is a link to the parent directory.
  438. // A subdirectory will have a link to its parent directory increasing the link count
  439. // above two. This will avoid the expensive read_dir call below when a directory
  440. // has subdirectories.
  441. false
  442. } else {
  443. self.is_empty_directory()
  444. }
  445. } else {
  446. false
  447. }
  448. }
  449. /// Determines if the directory is empty or not.
  450. ///
  451. /// For Windows platforms, this function checks the directory contents directly
  452. /// to determine if it's empty. Since certain filesystems on Windows make it
  453. /// challenging to infer emptiness based on directory size, this approach is used.
  454. #[cfg(windows)]
  455. pub fn is_empty_dir(&self) -> bool {
  456. if self.is_directory() {
  457. self.is_empty_directory()
  458. } else {
  459. false
  460. }
  461. }
  462. /// Checks the contents of the directory to determine if it's empty.
  463. ///
  464. /// This function avoids counting '.' and '..' when determining if the directory is
  465. /// empty. If any other entries are found, it returns `false`.
  466. ///
  467. /// The naive approach, as one would think that this info may have been cached.
  468. /// but as mentioned in the size function comment above, different filesystems
  469. /// make it difficult to get any info about a dir by it's size, so this may be it.
  470. fn is_empty_directory(&self) -> bool {
  471. match Dir::read_dir(self.path.clone()) {
  472. // . & .. are skipped, if the returned iterator has .next(), it's not empty
  473. Ok(has_files) => has_files.files(super::DotFilter::Dotfiles, None, false, false).next().is_none(),
  474. Err(_) => false,
  475. }
  476. }
  477. /// This file’s last modified timestamp, if available on this platform.
  478. pub fn modified_time(&self) -> Option<NaiveDateTime> {
  479. if self.is_link() && self.deref_links {
  480. return match self.link_target_recurse() {
  481. FileTarget::Ok(f) => f.modified_time(),
  482. _ => None,
  483. };
  484. }
  485. self.metadata.modified().map(|st| DateTime::<Utc>::from(st).naive_utc()).ok()
  486. }
  487. /// This file’s last changed timestamp, if available on this platform.
  488. #[cfg(unix)]
  489. pub fn changed_time(&self) -> Option<NaiveDateTime> {
  490. if self.is_link() && self.deref_links {
  491. return match self.link_target_recurse() {
  492. FileTarget::Ok(f) => f.changed_time(),
  493. _ => None,
  494. };
  495. }
  496. NaiveDateTime::from_timestamp_opt(
  497. self.metadata.ctime(),
  498. self.metadata.ctime_nsec() as u32,
  499. )
  500. }
  501. #[cfg(windows)]
  502. pub fn changed_time(&self) -> Option<NaiveDateTime> {
  503. self.modified_time()
  504. }
  505. /// This file’s last accessed timestamp, if available on this platform.
  506. pub fn accessed_time(&self) -> Option<NaiveDateTime> {
  507. if self.is_link() && self.deref_links {
  508. return match self.link_target_recurse() {
  509. FileTarget::Ok(f) => f.accessed_time(),
  510. _ => None,
  511. };
  512. }
  513. self.metadata.accessed().map(|st| DateTime::<Utc>::from(st).naive_utc()).ok()
  514. }
  515. /// This file’s created timestamp, if available on this platform.
  516. pub fn created_time(&self) -> Option<NaiveDateTime> {
  517. if self.is_link() && self.deref_links {
  518. return match self.link_target_recurse() {
  519. FileTarget::Ok(f) => f.created_time(),
  520. _ => None,
  521. };
  522. }
  523. self.metadata.created().map(|st| DateTime::<Utc>::from(st).naive_utc()).ok()
  524. }
  525. /// This file’s ‘type’.
  526. ///
  527. /// This is used a the leftmost character of the permissions column.
  528. /// The file type can usually be guessed from the colour of the file, but
  529. /// ls puts this character there.
  530. #[cfg(unix)]
  531. pub fn type_char(&self) -> f::Type {
  532. if self.is_file() {
  533. f::Type::File
  534. }
  535. else if self.is_directory() {
  536. f::Type::Directory
  537. }
  538. else if self.is_pipe() {
  539. f::Type::Pipe
  540. }
  541. else if self.is_link() {
  542. f::Type::Link
  543. }
  544. else if self.is_char_device() {
  545. f::Type::CharDevice
  546. }
  547. else if self.is_block_device() {
  548. f::Type::BlockDevice
  549. }
  550. else if self.is_socket() {
  551. f::Type::Socket
  552. }
  553. else {
  554. f::Type::Special
  555. }
  556. }
  557. #[cfg(windows)]
  558. pub fn type_char(&self) -> f::Type {
  559. if self.is_file() {
  560. f::Type::File
  561. }
  562. else if self.is_directory() {
  563. f::Type::Directory
  564. }
  565. else {
  566. f::Type::Special
  567. }
  568. }
  569. /// This file’s permissions, with flags for each bit.
  570. #[cfg(unix)]
  571. pub fn permissions(&self) -> Option<f::Permissions> {
  572. if self.is_link() && self.deref_links {
  573. // If the chain of links is broken, we instead fall through and
  574. // return the permissions of the original link, as would have been
  575. // done if we were not dereferencing.
  576. match self.link_target_recurse() {
  577. FileTarget::Ok(f) => return f.permissions(),
  578. _ => return None,
  579. }
  580. }
  581. let bits = self.metadata.mode();
  582. let has_bit = |bit| bits & bit == bit;
  583. Some(f::Permissions {
  584. user_read: has_bit(modes::USER_READ),
  585. user_write: has_bit(modes::USER_WRITE),
  586. user_execute: has_bit(modes::USER_EXECUTE),
  587. group_read: has_bit(modes::GROUP_READ),
  588. group_write: has_bit(modes::GROUP_WRITE),
  589. group_execute: has_bit(modes::GROUP_EXECUTE),
  590. other_read: has_bit(modes::OTHER_READ),
  591. other_write: has_bit(modes::OTHER_WRITE),
  592. other_execute: has_bit(modes::OTHER_EXECUTE),
  593. sticky: has_bit(modes::STICKY),
  594. setgid: has_bit(modes::SETGID),
  595. setuid: has_bit(modes::SETUID),
  596. })
  597. }
  598. #[cfg(windows)]
  599. pub fn attributes(&self) -> f::Attributes {
  600. let bits = self.metadata.file_attributes();
  601. let has_bit = |bit| bits & bit == bit;
  602. // https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
  603. f::Attributes {
  604. directory: has_bit(0x10),
  605. archive: has_bit(0x20),
  606. readonly: has_bit(0x1),
  607. hidden: has_bit(0x2),
  608. system: has_bit(0x4),
  609. reparse_point: has_bit(0x400),
  610. }
  611. }
  612. /// This file’s security context field.
  613. pub fn security_context(&self) -> f::SecurityContext<'_> {
  614. let context = match &self.extended_attributes.iter().find(|a| a.name == "security.selinux") {
  615. Some(attr) => f::SecurityContextType::SELinux(&attr.value),
  616. None => f::SecurityContextType::None
  617. };
  618. f::SecurityContext { context }
  619. }
  620. }
  621. impl<'a> AsRef<File<'a>> for File<'a> {
  622. fn as_ref(&self) -> &File<'a> {
  623. self
  624. }
  625. }
  626. /// The result of following a symlink.
  627. pub enum FileTarget<'dir> {
  628. /// The symlink pointed at a file that exists.
  629. Ok(Box<File<'dir>>),
  630. /// The symlink pointed at a file that does not exist. Holds the path
  631. /// where the file would be, if it existed.
  632. Broken(PathBuf),
  633. /// There was an IO error when following the link. This can happen if the
  634. /// file isn’t a link to begin with, but also if, say, we don’t have
  635. /// permission to follow it.
  636. Err(io::Error),
  637. // Err is its own variant, instead of having the whole thing be inside an
  638. // `io::Result`, because being unable to follow a symlink is not a serious
  639. // error — we just display the error message and move on.
  640. }
  641. impl<'dir> FileTarget<'dir> {
  642. /// Whether this link doesn’t lead to a file, for whatever reason. This
  643. /// gets used to determine how to highlight the link in grid views.
  644. pub fn is_broken(&self) -> bool {
  645. matches!(self, Self::Broken(_) | Self::Err(_))
  646. }
  647. }
  648. /// More readable aliases for the permission bits exposed by libc.
  649. #[allow(trivial_numeric_casts)]
  650. #[cfg(unix)]
  651. mod modes {
  652. // The `libc::mode_t` type’s actual type varies, but the value returned
  653. // from `metadata.permissions().mode()` is always `u32`.
  654. pub type Mode = u32;
  655. pub const USER_READ: Mode = libc::S_IRUSR as Mode;
  656. pub const USER_WRITE: Mode = libc::S_IWUSR as Mode;
  657. pub const USER_EXECUTE: Mode = libc::S_IXUSR as Mode;
  658. pub const GROUP_READ: Mode = libc::S_IRGRP as Mode;
  659. pub const GROUP_WRITE: Mode = libc::S_IWGRP as Mode;
  660. pub const GROUP_EXECUTE: Mode = libc::S_IXGRP as Mode;
  661. pub const OTHER_READ: Mode = libc::S_IROTH as Mode;
  662. pub const OTHER_WRITE: Mode = libc::S_IWOTH as Mode;
  663. pub const OTHER_EXECUTE: Mode = libc::S_IXOTH as Mode;
  664. pub const STICKY: Mode = libc::S_ISVTX as Mode;
  665. pub const SETGID: Mode = libc::S_ISGID as Mode;
  666. pub const SETUID: Mode = libc::S_ISUID as Mode;
  667. }
  668. #[cfg(test)]
  669. mod ext_test {
  670. use super::File;
  671. use std::path::Path;
  672. #[test]
  673. fn extension() {
  674. assert_eq!(Some("dat".to_string()), File::ext(Path::new("fester.dat")))
  675. }
  676. #[test]
  677. fn dotfile() {
  678. assert_eq!(Some("vimrc".to_string()), File::ext(Path::new(".vimrc")))
  679. }
  680. #[test]
  681. fn no_extension() {
  682. assert_eq!(None, File::ext(Path::new("jarlsberg")))
  683. }
  684. }
  685. #[cfg(test)]
  686. mod filename_test {
  687. use super::File;
  688. use std::path::Path;
  689. #[test]
  690. fn file() {
  691. assert_eq!("fester.dat", File::filename(Path::new("fester.dat")))
  692. }
  693. #[test]
  694. fn no_path() {
  695. assert_eq!("foo.wha", File::filename(Path::new("/var/cache/foo.wha")))
  696. }
  697. #[test]
  698. fn here() {
  699. assert_eq!(".", File::filename(Path::new(".")))
  700. }
  701. #[test]
  702. fn there() {
  703. assert_eq!("..", File::filename(Path::new("..")))
  704. }
  705. #[test]
  706. fn everywhere() {
  707. assert_eq!("..", File::filename(Path::new("./..")))
  708. }
  709. #[test]
  710. #[cfg(unix)]
  711. fn topmost() {
  712. assert_eq!("/", File::filename(Path::new("/")))
  713. }
  714. }