Skip to main content

Delete empty parent directories

ID
bb97012
date
2024-08-21 08:23:18+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
3915f6a
message
Delete empty parent directories
changed files
4 files, 28 additions, 2 deletions

Changed files

CHANGELOG.md (481) → CHANGELOG.md (759)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a89052..e6e0fd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
 # Changelog
 
+## v1.2.0 - 2024-08-21
+
+Delete empty parent directories.
+
+If the target directory is the only entry in an otherwise empty directory, then the parent directory will also be deleted (and emptydir will keep going through parent directories until it finds one which is non-empty).
+
 ## v1.1.3 - 2024-08-21
 
 Delete empty folders which only contain a `.jekyll-cache` folder.

Cargo.lock (13005) → Cargo.lock (13005)

diff --git a/Cargo.lock b/Cargo.lock
index 584c299..6a2c3a9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -115,7 +115,7 @@ dependencies = [
 
 [[package]]
 name = "emptydir"
-version = "1.1.3"
+version = "1.2.0"
 dependencies = [
  "clap",
  "colored",

Cargo.toml (203) → Cargo.toml (203)

diff --git a/Cargo.toml b/Cargo.toml
index 62a108c..ecdae58 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "emptydir"
-version = "1.1.3"
+version = "1.2.0"
 edition = "2021"
 
 [dependencies]

src/emptydir.rs (4678) → src/emptydir.rs (5270)

diff --git a/src/emptydir.rs b/src/emptydir.rs
index 3bd7f81..39306df 100644
--- a/src/emptydir.rs
+++ b/src/emptydir.rs
@@ -27,6 +27,26 @@ pub fn emptydir(root: &Path) -> u32 {
         };
     }
 
+    // Now work our way upward through the parent directories, and
+    // delete any of those which are empty.
+    let mut current_parent = root.parent();
+
+    while let Some(parent) = current_parent {
+        if crate::can_be_deleted::can_be_deleted(parent) {
+            match fs::remove_dir_all(parent) {
+                Ok(_) => {
+                    println!("{}", parent.display());
+                    count_deleted += 1;
+                }
+                Err(_) => (),
+            };
+
+            current_parent = parent.parent();
+        } else {
+            break;
+        }
+    }
+
     count_deleted
 }