From da5b7bea788cef236785d7d3b9b88c5df7dd0a66 Mon Sep 17 00:00:00 2001
From: Cornelius Mika <cornelius.mika@gmail.com>
Date: Sat, 19 Aug 2017 09:49:05 +0200
Subject: [PATCH] home-environment: fix error when deleting empty directories

With --ignore-fail-on-non-empty, non-emptiness is the only failure
that gets ignored by rmdir. In the case that rmdir reaches $HOME and
considers deleting it, it will detect insufficient permissions and
subsequently exit with an error, even if $HOME is not empty.

Prevent this by calling rmdir with a relative path that excludes
$HOME.
---
 modules/home-environment.nix | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)

diff --git a/modules/home-environment.nix b/modules/home-environment.nix
index bd2fb6ffa..e88ea95d4 100644
--- a/modules/home-environment.nix
+++ b/modules/home-environment.nix
@@ -315,16 +315,20 @@ in
             else
               echo "Checking $targetPath  gone (deleting)"
               $DRY_RUN_CMD rm $VERBOSE_ARG "$targetPath"
-              targetDir="$(dirname "$targetPath")"
 
-              # Recursively remove the containing directory. We only
-              # do this if the containing folder is not $HOME since
-              # running rmdir on $HOME will result in a harmless but
-              # unpleasant error message.
-              if [[ "$targetDir" != "$HOME" ]] ; then
+              # Recursively delete empty parent directories.
+              targetDir="$(dirname "$relativePath")"
+              if [[ "$targetDir" != "." ]] ; then
+                pushd "$HOME" > /dev/null
+
+                # Call rmdir with a relative path excluding $HOME.
+                # Otherwise, it might try to delete $HOME and exit
+                # with a permission error.
                 $DRY_RUN_CMD rmdir $VERBOSE_ARG \
                     -p --ignore-fail-on-non-empty \
                     "$targetDir"
+
+                popd > /dev/null
               fi
             fi
           done