remove_dir_recursively(): Add flag for skipping removal of toplevel dir
Add the REMOVE_DIR_KEEP_TOPLEVEL flag to remove_dir_recursively() for deleting everything inside the given directory, but _not_ the given directory itself. Note that this does not pass the REMOVE_DIR_KEEP_NESTED_GIT flag, if set, to the recursive invocations of remove_dir_recursively(). It is likely to be a a bug that has been present since REMOVE_DIR_KEEP_NESTED_GIT was introduced (a0f4afb), but this commit keeps the same behaviour for now. Signed-off-by: Johan Herland <johan@herland.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Junio C Hamano committed
Mar 15, 2012 at 15:58 UTC
c844a8035617a602015d74ce329ee88f9b003bf9
2 files changed
+11
-4
dir.c
+10
-4
@@ -1178,6 +1178,7 @@ int remove_dir_recursively(struct strbuf *path, int flag)
1178
struct dirent *e;
1179
int ret = 0, original_len = path->len, len;
1180
int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
1181
+ int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
1182
unsigned char submodule_head[20];
1183
1184
if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
@@ -1185,9 +1186,14 @@ int remove_dir_recursively(struct strbuf *path, int flag)
1186
/* Do not descend and nuke a nested git work tree. */
1187
return 0;
1188
1189
+ flag &= ~(REMOVE_DIR_KEEP_TOPLEVEL|REMOVE_DIR_KEEP_NESTED_GIT);
1190
dir = opendir(path->buf);
1189
- if (!dir)
1190
- return rmdir(path->buf);
1191
+ if (!dir) {
1192
+ if (!keep_toplevel)
1193
+ return rmdir(path->buf);
1194
+ else
1195
+ return -1;
1196
+ }
1197
if (path->buf[original_len - 1] != '/')
1198
strbuf_addch(path, '/');
1199
@@ -1202,7 +1208,7 @@ int remove_dir_recursively(struct strbuf *path, int flag)
1208
if (lstat(path->buf, &st))
1209
; /* fall thru */
1210
else if (S_ISDIR(st.st_mode)) {
1205
- if (!remove_dir_recursively(path, only_empty))
1211
+ if (!remove_dir_recursively(path, flag))
1212
continue; /* happy */
1213
} else if (!only_empty && !unlink(path->buf))
1214
continue; /* happy, too */
@@ -1214,7 +1220,7 @@ int remove_dir_recursively(struct strbuf *path, int flag)
1220
closedir(dir);
1221
1222
strbuf_setlen(path, original_len);
1217
- if (!ret)
1223
+ if (!ret && !keep_toplevel)
1224
ret = rmdir(path->buf);
1225
return ret;
1226
}
dir.h
+1
@@ -102,6 +102,7 @@ extern void setup_standard_excludes(struct dir_struct *dir);
102
103
#define REMOVE_DIR_EMPTY_ONLY 01
104
#define REMOVE_DIR_KEEP_NESTED_GIT 02
105
+#define REMOVE_DIR_KEEP_TOPLEVEL 04
106
extern int remove_dir_recursively(struct strbuf *path, int flag);
107
108
/* tries to remove the path with empty directories along it, ignores ENOENT */