Skip to content
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 6 commits into from
Jul 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 69 additions & 6 deletions object_store/src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -266,6 +268,7 @@ impl LocalFileSystem {
config: Arc::new(Config {
root: Url::parse("file:///").unwrap(),
}),
automatic_cleanup: false,
}
}

Expand All @@ -282,6 +285,7 @@ impl LocalFileSystem {
config: Arc::new(Config {
root: absolute_path_to_url(path)?,
}),
automatic_cleanup: false,
})
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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;
Copy link
Contributor

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)

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 {
Copy link
Contributor

Choose a reason for hiding this comment

The 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
}
Expand Down Expand Up @@ -1011,6 +1044,8 @@ fn convert_walkdir_result(

#[cfg(test)]
mod tests {
use std::fs;

use futures::TryStreamExt;
use tempfile::{NamedTempFile, TempDir};

Expand Down Expand Up @@ -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"))]
Expand Down
Loading