LCOV - code coverage report
Current view: top level - libs/utils/src - fs_ext.rs (source / functions) Coverage Total Hit
Test: 2e3a7638747e564a4f6d1af1cc0c3b3438fbb740.info Lines: 98.0 % 99 97
Test Date: 2024-11-20 01:36:58 Functions: 78.6 % 28 22

            Line data    Source code
       1              : /// Extensions to `std::fs` types.
       2              : use std::{fs, io, path::Path};
       3              : 
       4              : use anyhow::Context;
       5              : 
       6              : mod rename_noreplace;
       7              : pub use rename_noreplace::rename_noreplace;
       8              : 
       9              : pub trait PathExt {
      10              :     /// Returns an error if `self` is not a directory.
      11              :     fn is_empty_dir(&self) -> io::Result<bool>;
      12              : }
      13              : 
      14              : impl<P> PathExt for P
      15              : where
      16              :     P: AsRef<Path>,
      17              : {
      18            3 :     fn is_empty_dir(&self) -> io::Result<bool> {
      19            3 :         Ok(fs::read_dir(self)?.next().is_none())
      20            3 :     }
      21              : }
      22              : 
      23            3 : pub async fn is_directory_empty(path: impl AsRef<Path>) -> anyhow::Result<bool> {
      24            3 :     let mut dir = tokio::fs::read_dir(&path)
      25            3 :         .await
      26            3 :         .context(format!("read_dir({})", path.as_ref().display()))?;
      27            1 :     Ok(dir.next_entry().await?.is_none())
      28            3 : }
      29              : 
      30            3 : pub async fn list_dir(path: impl AsRef<Path>) -> anyhow::Result<Vec<String>> {
      31            3 :     let mut dir = tokio::fs::read_dir(&path)
      32            3 :         .await
      33            3 :         .context(format!("read_dir({})", path.as_ref().display()))?;
      34              : 
      35            3 :     let mut content = vec![];
      36            6 :     while let Some(next) = dir.next_entry().await? {
      37            3 :         let file_name = next.file_name();
      38            3 :         content.push(file_name.to_string_lossy().to_string());
      39            3 :     }
      40              : 
      41            3 :     Ok(content)
      42            3 : }
      43              : 
      44           27 : pub fn ignore_not_found(e: io::Error) -> io::Result<()> {
      45           27 :     if e.kind() == io::ErrorKind::NotFound {
      46           27 :         Ok(())
      47              :     } else {
      48            0 :         Err(e)
      49              :     }
      50           27 : }
      51              : 
      52            8 : pub fn ignore_absent_files<F>(fs_operation: F) -> io::Result<()>
      53            8 : where
      54            8 :     F: Fn() -> io::Result<()>,
      55            8 : {
      56            8 :     fs_operation().or_else(ignore_not_found)
      57            8 : }
      58              : 
      59              : #[cfg(test)]
      60              : mod test {
      61              :     use crate::fs_ext::{is_directory_empty, list_dir};
      62              : 
      63              :     use super::ignore_absent_files;
      64              : 
      65              :     #[test]
      66            1 :     fn is_empty_dir() {
      67              :         use super::PathExt;
      68              : 
      69            1 :         let dir = camino_tempfile::tempdir().unwrap();
      70            1 :         let dir_path = dir.path();
      71            1 : 
      72            1 :         // test positive case
      73            1 :         assert!(
      74            1 :             dir_path.is_empty_dir().expect("test failure"),
      75            0 :             "new tempdir should be empty"
      76              :         );
      77              : 
      78              :         // invoke on a file to ensure it returns an error
      79            1 :         let file_path = dir_path.join("testfile");
      80            1 :         let f = std::fs::File::create(&file_path).unwrap();
      81            1 :         drop(f);
      82            1 :         assert!(file_path.is_empty_dir().is_err());
      83              : 
      84              :         // do it again on a path, we know to be nonexistent
      85            1 :         std::fs::remove_file(&file_path).unwrap();
      86            1 :         assert!(file_path.is_empty_dir().is_err());
      87            1 :     }
      88              : 
      89              :     #[tokio::test]
      90            1 :     async fn is_empty_dir_async() {
      91            1 :         let dir = camino_tempfile::tempdir().unwrap();
      92            1 :         let dir_path = dir.path();
      93            1 : 
      94            1 :         // test positive case
      95            1 :         assert!(
      96            1 :             is_directory_empty(dir_path).await.expect("test failure"),
      97            1 :             "new tempdir should be empty"
      98            1 :         );
      99            1 : 
     100            1 :         // invoke on a file to ensure it returns an error
     101            1 :         let file_path = dir_path.join("testfile");
     102            1 :         let f = std::fs::File::create(&file_path).unwrap();
     103            1 :         drop(f);
     104            1 :         assert!(is_directory_empty(&file_path).await.is_err());
     105            1 : 
     106            1 :         // do it again on a path, we know to be nonexistent
     107            1 :         std::fs::remove_file(&file_path).unwrap();
     108            1 :         assert!(is_directory_empty(file_path).await.is_err());
     109            1 :     }
     110              : 
     111              :     #[test]
     112            1 :     fn ignore_absent_files_works() {
     113            1 :         let dir = camino_tempfile::tempdir().unwrap();
     114            1 : 
     115            1 :         let file_path = dir.path().join("testfile");
     116            1 : 
     117            1 :         ignore_absent_files(|| std::fs::remove_file(&file_path)).expect("should execute normally");
     118            1 : 
     119            1 :         let f = std::fs::File::create(&file_path).unwrap();
     120            1 :         drop(f);
     121            1 : 
     122            1 :         ignore_absent_files(|| std::fs::remove_file(&file_path)).expect("should execute normally");
     123            1 : 
     124            1 :         assert!(!file_path.exists());
     125            1 :     }
     126              : 
     127              :     #[tokio::test]
     128            1 :     async fn list_dir_works() {
     129            1 :         let dir = camino_tempfile::tempdir().unwrap();
     130            1 :         let dir_path = dir.path();
     131            1 : 
     132            1 :         assert!(list_dir(dir_path).await.unwrap().is_empty());
     133            1 : 
     134            1 :         let file_path = dir_path.join("testfile");
     135            1 :         let _ = std::fs::File::create(&file_path).unwrap();
     136            1 : 
     137            1 :         assert_eq!(&list_dir(dir_path).await.unwrap(), &["testfile"]);
     138            1 : 
     139            1 :         let another_dir_path = dir_path.join("testdir");
     140            1 :         std::fs::create_dir(another_dir_path).unwrap();
     141            1 : 
     142            1 :         let expected = &["testdir", "testfile"];
     143            1 :         let mut actual = list_dir(dir_path).await.unwrap();
     144            1 :         actual.sort();
     145            1 :         assert_eq!(actual, expected);
     146            1 :     }
     147              : }
        

Generated by: LCOV version 2.1-beta