quickwit_common/fs.rs
1// Copyright (C) 2021 Quickwit, Inc.
2//
3// Quickwit is offered under the AGPL v3.0 and as commercial software.
4// For commercial licensing, contact us at hello@quickwit.io.
5//
6// AGPL:
7// This program is free software: you can redistribute it and/or modify
8// it under the terms of the GNU Affero General Public License as
9// published by the Free Software Foundation, either version 3 of the
10// License, or (at your option) any later version.
11//
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU Affero General Public License for more details.
16//
17// You should have received a copy of the GNU Affero General Public License
18// along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20use std::path::Path;
21
22use tokio;
23
24/// Deletes the contents of a directory.
25pub async fn empty_dir<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
26 let mut entries = tokio::fs::read_dir(path).await?;
27 while let Some(entry) = entries.next_entry().await? {
28 if entry.file_type().await?.is_dir() {
29 tokio::fs::remove_dir_all(entry.path()).await?
30 } else {
31 tokio::fs::remove_file(entry.path()).await?;
32 }
33 }
34 Ok(())
35}
36
37#[cfg(test)]
38mod tests {
39 use tempfile;
40
41 use super::*;
42
43 #[tokio::test]
44 async fn test_empty_dir() -> anyhow::Result<()> {
45 let tempdir = tempfile::tempdir()?;
46
47 let file_path = tempdir.path().join("file");
48 tokio::fs::File::create(file_path).await?;
49
50 let subdir = tempdir.path().join("subdir");
51 tokio::fs::create_dir(&subdir).await?;
52
53 let subfile_path = subdir.join("subfile");
54 tokio::fs::File::create(subfile_path).await?;
55
56 empty_dir(tempdir.path()).await?;
57 assert!(tokio::fs::read_dir(tempdir.path())
58 .await?
59 .next_entry()
60 .await?
61 .is_none());
62 Ok(())
63 }
64}