There is an implicit assumption that a directory containing only untracked and ignored files should itself be considered untracked. This makes sense in use cases where we're asking if a directory should be added to the git database, but not when we're asking if a directory can be safely removed from the working tree; as a result, clean -d would assume that an "untracked" directory containing ignored files could be deleted. To get around this, we teach clean -d to collect ignored files and skip over so-called "untracked" directories if they contain any ignored files (while still removing the untracked contents of such dirs). Signed-off-by: Samuel Lijin <sxlijin@xxxxxxxxx> --- builtin/clean.c | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/builtin/clean.c b/builtin/clean.c index d861f836a..25f3efce5 100644 --- a/builtin/clean.c +++ b/builtin/clean.c @@ -859,7 +859,7 @@ static void interactive_main_loop(void) int cmd_clean(int argc, const char **argv, const char *prefix) { - int i, res; + int i, j, k, res; int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0; int ignored_only = 0, config_set = 0, errors = 0, gone = 1; int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT; @@ -911,6 +911,9 @@ int cmd_clean(int argc, const char **argv, const char *prefix) " refusing to clean")); } + if (remove_directories) + dir.flags |= DIR_SHOW_IGNORED_TOO | DIR_KEEP_UNTRACKED_CONTENTS; + if (force > 1) rm_flags = 0; @@ -932,7 +935,7 @@ int cmd_clean(int argc, const char **argv, const char *prefix) fill_directory(&dir, &pathspec); - for (i = 0; i < dir.nr; i++) { + for (k = i = 0; i < dir.nr; i++) { struct dir_entry *ent = dir.entries[i]; int matches = 0; struct stat st; @@ -954,10 +957,35 @@ int cmd_clean(int argc, const char **argv, const char *prefix) matches != MATCHED_EXACTLY) continue; + // skip any dir.entries which contains a dir.ignored + for (; k < dir.ignored_nr; k++) { + if (cmp_dir_entry(&dir.entries[i], + &dir.ignored[k]) < 0) + break; + } + if ((k < dir.ignored_nr) && + check_dir_entry_contains(dir.entries[i], dir.ignored[k])) { + continue; + } + + // current entry does not contain any ignored files rel = relative_path(ent->name, prefix, &buf); string_list_append(&del_list, rel); + + // skip untracked contents of an untracked dir + for (j = i + 1; + j < dir.nr && + check_dir_entry_contains(dir.entries[i], dir.entries[j]); + j++); + i = j - 1; } + for (i = 0; i < dir.nr; i++) + free(dir.entries[i]); + + for (i = 0; i < dir.ignored_nr; i++) + free(dir.ignored[i]); + if (interactive && del_list.nr > 0) interactive_main_loop(); -- 2.12.2