From 1b6222063b15119f94ef3b6c8cb511a8219175c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Wed, 11 Dec 2024 18:02:55 +0100 Subject: [PATCH] Delete all empty parent directories if they are empty This saves a lot of memory since each directory takes at least one block We are starting to see this as an issue because the filesystems are now much deeper due to the SE050 --- src/store.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/store.rs b/src/store.rs index 2b51bc36161..43e239efafc 100644 --- a/src/store.rs +++ b/src/store.rs @@ -72,7 +72,7 @@ //! - Alternative: subdirectory <==> RP hash, everything else in flat files //! - In any case need to "list dirs excluding . and .." or similar -use littlefs2::{driver::Storage, fs::Filesystem}; +use littlefs2::{driver::Storage, fs::Filesystem, path}; use crate::error::Error; use crate::types::{Bytes, Location}; @@ -554,7 +554,32 @@ pub fn store( #[inline(never)] pub fn delete(store: impl Store, location: Location, path: &Path) -> bool { debug_now!("deleting {}", &path); - store.fs(location).remove(path).is_ok() + let fs = store.fs(location); + if fs.remove(path).is_err() { + return false; + } + + // Only delete ancestors for volatile FS + if location != Location::Volatile { + return true; + } + // first ancestor is the file itself + for parent in path.ancestors().skip(1) { + if &*parent == path!("/") { + break; + } + let Ok(meta) = fs.metadata(&parent) else { + return false; + }; + if meta.is_dir() && meta.is_empty() { + if fs.remove_dir(&parent).is_err() { + return false; + } + } else { + break; + } + } + true } #[inline(never)]