-
Notifications
You must be signed in to change notification settings - Fork 867
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Automatically cleanup empty dirs in LocalFileSystem #5978
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -240,6 +240,8 @@ impl From<Error> for super::Error { | |
#[derive(Debug)] | ||
pub struct LocalFileSystem { | ||
config: Arc<Config>, | ||
// if you want to delete empty directories when deleting files | ||
automatic_cleanup: bool, | ||
} | ||
|
||
#[derive(Debug)] | ||
|
@@ -266,6 +268,7 @@ impl LocalFileSystem { | |
config: Arc::new(Config { | ||
root: Url::parse("file:///").unwrap(), | ||
}), | ||
automatic_cleanup: false, | ||
} | ||
} | ||
|
||
|
@@ -282,6 +285,7 @@ impl LocalFileSystem { | |
config: Arc::new(Config { | ||
root: absolute_path_to_url(path)?, | ||
}), | ||
automatic_cleanup: false, | ||
}) | ||
} | ||
|
||
|
@@ -295,6 +299,12 @@ impl LocalFileSystem { | |
); | ||
self.config.prefix_to_filesystem(location) | ||
} | ||
|
||
/// Enable automatic cleanup of empty directories when deleting files | ||
pub fn with_automatic_cleanup(mut self, automatic_cleanup: bool) -> Self { | ||
self.automatic_cleanup = automatic_cleanup; | ||
self | ||
} | ||
} | ||
|
||
impl Config { | ||
|
@@ -465,13 +475,36 @@ impl ObjectStore for LocalFileSystem { | |
} | ||
|
||
async fn delete(&self, location: &Path) -> Result<()> { | ||
let config = Arc::clone(&self.config); | ||
let path = self.path_to_filesystem(location)?; | ||
maybe_spawn_blocking(move || match std::fs::remove_file(&path) { | ||
Ok(_) => Ok(()), | ||
Err(e) => Err(match e.kind() { | ||
ErrorKind::NotFound => Error::NotFound { path, source: e }.into(), | ||
_ => Error::UnableToDeleteFile { path, source: e }.into(), | ||
}), | ||
let automactic_cleanup = self.automatic_cleanup; | ||
maybe_spawn_blocking(move || { | ||
if let Err(e) = std::fs::remove_file(&path) { | ||
Err(match e.kind() { | ||
ErrorKind::NotFound => Error::NotFound { path, source: e }.into(), | ||
_ => Error::UnableToDeleteFile { path, source: e }.into(), | ||
}) | ||
} else if automactic_cleanup { | ||
let root = &config.root; | ||
let root = root | ||
.to_file_path() | ||
.map_err(|_| Error::InvalidUrl { url: root.clone() })?; | ||
|
||
// here we will try to traverse up and delete an empty dir if possible until we reach the root or get an error | ||
let mut parent = path.parent(); | ||
|
||
while let Some(loc) = parent { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This looks like a good plan to me -- walk up the path trying to remove any empty directories found, stopping on first error or root |
||
if loc != root && std::fs::remove_dir(loc).is_ok() { | ||
parent = loc.parent(); | ||
} else { | ||
break; | ||
} | ||
} | ||
|
||
Ok(()) | ||
} else { | ||
Ok(()) | ||
} | ||
}) | ||
.await | ||
} | ||
|
@@ -1011,6 +1044,8 @@ fn convert_walkdir_result( | |
|
||
#[cfg(test)] | ||
mod tests { | ||
use std::fs; | ||
|
||
use futures::TryStreamExt; | ||
use tempfile::{NamedTempFile, TempDir}; | ||
|
||
|
@@ -1446,6 +1481,34 @@ mod tests { | |
list.sort_unstable(); | ||
assert_eq!(list, vec![c, a]); | ||
} | ||
|
||
#[tokio::test] | ||
async fn delete_dirs_automatically() { | ||
let root = TempDir::new().unwrap(); | ||
let integration = LocalFileSystem::new_with_prefix(root.path()) | ||
.unwrap() | ||
.with_automatic_cleanup(true); | ||
let location = Path::from("nested/file/test_file"); | ||
let data = Bytes::from("arbitrary data"); | ||
|
||
integration | ||
.put(&location, data.clone().into()) | ||
.await | ||
.unwrap(); | ||
|
||
let read_data = integration | ||
.get(&location) | ||
.await | ||
.unwrap() | ||
.bytes() | ||
.await | ||
.unwrap(); | ||
|
||
assert_eq!(&*read_data, data); | ||
assert!(fs::read_dir(root.path()).unwrap().count() > 0); | ||
integration.delete(&location).await.unwrap(); | ||
assert!(fs::read_dir(root.path()).unwrap().count() == 0); | ||
} | ||
} | ||
|
||
#[cfg(not(target_arch = "wasm32"))] | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we could add a comment here explaining what is going on / the rationale for this (to clean out directories that were now empty)