path: optimize common dir checking
[git.git] / builtin / clean.c
blobdf53def63f29e295e09261b9bd56960cf27582b1
1 /*
2 * "git clean" builtin command
4 * Copyright (C) 2007 Shawn Bohrer
6 * Based on git-clean.sh by Pavel Roskin
7 */
9 #include "builtin.h"
10 #include "cache.h"
11 #include "dir.h"
12 #include "parse-options.h"
13 #include "string-list.h"
14 #include "quote.h"
15 #include "column.h"
16 #include "color.h"
17 #include "pathspec.h"
19 static int force = -1; /* unset */
20 static int interactive;
21 static struct string_list del_list = STRING_LIST_INIT_DUP;
22 static unsigned int colopts;
24 static const char *const builtin_clean_usage[] = {
25 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
26 NULL
29 static const char *msg_remove = N_("Removing %s\n");
30 static const char *msg_would_remove = N_("Would remove %s\n");
31 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
32 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
33 static const char *msg_warn_remove_failed = N_("failed to remove %s");
35 static int clean_use_color = -1;
36 static char clean_colors[][COLOR_MAXLEN] = {
37 GIT_COLOR_RESET,
38 GIT_COLOR_NORMAL, /* PLAIN */
39 GIT_COLOR_BOLD_BLUE, /* PROMPT */
40 GIT_COLOR_BOLD, /* HEADER */
41 GIT_COLOR_BOLD_RED, /* HELP */
42 GIT_COLOR_BOLD_RED, /* ERROR */
44 enum color_clean {
45 CLEAN_COLOR_RESET = 0,
46 CLEAN_COLOR_PLAIN = 1,
47 CLEAN_COLOR_PROMPT = 2,
48 CLEAN_COLOR_HEADER = 3,
49 CLEAN_COLOR_HELP = 4,
50 CLEAN_COLOR_ERROR = 5
53 #define MENU_OPTS_SINGLETON 01
54 #define MENU_OPTS_IMMEDIATE 02
55 #define MENU_OPTS_LIST_ONLY 04
57 struct menu_opts {
58 const char *header;
59 const char *prompt;
60 int flags;
63 #define MENU_RETURN_NO_LOOP 10
65 struct menu_item {
66 char hotkey;
67 const char *title;
68 int selected;
69 int (*fn)(void);
72 enum menu_stuff_type {
73 MENU_STUFF_TYPE_STRING_LIST = 1,
74 MENU_STUFF_TYPE_MENU_ITEM
77 struct menu_stuff {
78 enum menu_stuff_type type;
79 int nr;
80 void *stuff;
83 static int parse_clean_color_slot(const char *var)
85 if (!strcasecmp(var, "reset"))
86 return CLEAN_COLOR_RESET;
87 if (!strcasecmp(var, "plain"))
88 return CLEAN_COLOR_PLAIN;
89 if (!strcasecmp(var, "prompt"))
90 return CLEAN_COLOR_PROMPT;
91 if (!strcasecmp(var, "header"))
92 return CLEAN_COLOR_HEADER;
93 if (!strcasecmp(var, "help"))
94 return CLEAN_COLOR_HELP;
95 if (!strcasecmp(var, "error"))
96 return CLEAN_COLOR_ERROR;
97 return -1;
100 static int git_clean_config(const char *var, const char *value, void *cb)
102 const char *slot_name;
104 if (starts_with(var, "column."))
105 return git_column_config(var, value, "clean", &colopts);
107 /* honors the color.interactive* config variables which also
108 applied in git-add--interactive and git-stash */
109 if (!strcmp(var, "color.interactive")) {
110 clean_use_color = git_config_colorbool(var, value);
111 return 0;
113 if (skip_prefix(var, "color.interactive.", &slot_name)) {
114 int slot = parse_clean_color_slot(slot_name);
115 if (slot < 0)
116 return 0;
117 if (!value)
118 return config_error_nonbool(var);
119 return color_parse(value, clean_colors[slot]);
122 if (!strcmp(var, "clean.requireforce")) {
123 force = !git_config_bool(var, value);
124 return 0;
127 /* inspect the color.ui config variable and others */
128 return git_color_default_config(var, value, cb);
131 static const char *clean_get_color(enum color_clean ix)
133 if (want_color(clean_use_color))
134 return clean_colors[ix];
135 return "";
138 static void clean_print_color(enum color_clean ix)
140 printf("%s", clean_get_color(ix));
143 static int exclude_cb(const struct option *opt, const char *arg, int unset)
145 struct string_list *exclude_list = opt->value;
146 string_list_append(exclude_list, arg);
147 return 0;
151 * Return 1 if the given path is the root of a git repository or
152 * submodule else 0. Will not return 1 for bare repositories with the
153 * exception of creating a bare repository in "foo/.git" and calling
154 * is_git_repository("foo").
156 static int is_git_repository(struct strbuf *path)
158 int ret = 0;
159 int gitfile_error;
160 size_t orig_path_len = path->len;
161 assert(orig_path_len != 0);
162 if (path->buf[orig_path_len - 1] != '/')
163 strbuf_addch(path, '/');
164 strbuf_addstr(path, ".git");
165 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
166 ret = 1;
167 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
168 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
169 ret = 1; /* This could be a real .git file, take the
170 * safe option and avoid cleaning */
171 strbuf_setlen(path, orig_path_len);
172 return ret;
175 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
176 int dry_run, int quiet, int *dir_gone)
178 DIR *dir;
179 struct strbuf quoted = STRBUF_INIT;
180 struct dirent *e;
181 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
182 struct string_list dels = STRING_LIST_INIT_DUP;
184 *dir_gone = 1;
186 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) && is_git_repository(path)) {
187 if (!quiet) {
188 quote_path_relative(path->buf, prefix, &quoted);
189 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
190 quoted.buf);
193 *dir_gone = 0;
194 return 0;
197 dir = opendir(path->buf);
198 if (!dir) {
199 /* an empty dir could be removed even if it is unreadble */
200 res = dry_run ? 0 : rmdir(path->buf);
201 if (res) {
202 quote_path_relative(path->buf, prefix, &quoted);
203 warning(_(msg_warn_remove_failed), quoted.buf);
204 *dir_gone = 0;
206 return res;
209 if (path->buf[original_len - 1] != '/')
210 strbuf_addch(path, '/');
212 len = path->len;
213 while ((e = readdir(dir)) != NULL) {
214 struct stat st;
215 if (is_dot_or_dotdot(e->d_name))
216 continue;
218 strbuf_setlen(path, len);
219 strbuf_addstr(path, e->d_name);
220 if (lstat(path->buf, &st))
221 ; /* fall thru */
222 else if (S_ISDIR(st.st_mode)) {
223 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
224 ret = 1;
225 if (gone) {
226 quote_path_relative(path->buf, prefix, &quoted);
227 string_list_append(&dels, quoted.buf);
228 } else
229 *dir_gone = 0;
230 continue;
231 } else {
232 res = dry_run ? 0 : unlink(path->buf);
233 if (!res) {
234 quote_path_relative(path->buf, prefix, &quoted);
235 string_list_append(&dels, quoted.buf);
236 } else {
237 quote_path_relative(path->buf, prefix, &quoted);
238 warning(_(msg_warn_remove_failed), quoted.buf);
239 *dir_gone = 0;
240 ret = 1;
242 continue;
245 /* path too long, stat fails, or non-directory still exists */
246 *dir_gone = 0;
247 ret = 1;
248 break;
250 closedir(dir);
252 strbuf_setlen(path, original_len);
254 if (*dir_gone) {
255 res = dry_run ? 0 : rmdir(path->buf);
256 if (!res)
257 *dir_gone = 1;
258 else {
259 quote_path_relative(path->buf, prefix, &quoted);
260 warning(_(msg_warn_remove_failed), quoted.buf);
261 *dir_gone = 0;
262 ret = 1;
266 if (!*dir_gone && !quiet) {
267 int i;
268 for (i = 0; i < dels.nr; i++)
269 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
271 string_list_clear(&dels, 0);
272 return ret;
275 static void pretty_print_dels(void)
277 struct string_list list = STRING_LIST_INIT_DUP;
278 struct string_list_item *item;
279 struct strbuf buf = STRBUF_INIT;
280 const char *qname;
281 struct column_options copts;
283 for_each_string_list_item(item, &del_list) {
284 qname = quote_path_relative(item->string, NULL, &buf);
285 string_list_append(&list, qname);
289 * always enable column display, we only consult column.*
290 * about layout strategy and stuff
292 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
293 memset(&copts, 0, sizeof(copts));
294 copts.indent = " ";
295 copts.padding = 2;
296 print_columns(&list, colopts, &copts);
297 strbuf_release(&buf);
298 string_list_clear(&list, 0);
301 static void pretty_print_menus(struct string_list *menu_list)
303 unsigned int local_colopts = 0;
304 struct column_options copts;
306 local_colopts = COL_ENABLED | COL_ROW;
307 memset(&copts, 0, sizeof(copts));
308 copts.indent = " ";
309 copts.padding = 2;
310 print_columns(menu_list, local_colopts, &copts);
313 static void prompt_help_cmd(int singleton)
315 clean_print_color(CLEAN_COLOR_HELP);
316 printf_ln(singleton ?
317 _("Prompt help:\n"
318 "1 - select a numbered item\n"
319 "foo - select item based on unique prefix\n"
320 " - (empty) select nothing") :
321 _("Prompt help:\n"
322 "1 - select a single item\n"
323 "3-5 - select a range of items\n"
324 "2-3,6-9 - select multiple ranges\n"
325 "foo - select item based on unique prefix\n"
326 "-... - unselect specified items\n"
327 "* - choose all items\n"
328 " - (empty) finish selecting"));
329 clean_print_color(CLEAN_COLOR_RESET);
333 * display menu stuff with number prefix and hotkey highlight
335 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
337 struct string_list menu_list = STRING_LIST_INIT_DUP;
338 struct strbuf menu = STRBUF_INIT;
339 struct menu_item *menu_item;
340 struct string_list_item *string_list_item;
341 int i;
343 switch (stuff->type) {
344 default:
345 die("Bad type of menu_stuff when print menu");
346 case MENU_STUFF_TYPE_MENU_ITEM:
347 menu_item = (struct menu_item *)stuff->stuff;
348 for (i = 0; i < stuff->nr; i++, menu_item++) {
349 const char *p;
350 int highlighted = 0;
352 p = menu_item->title;
353 if ((*chosen)[i] < 0)
354 (*chosen)[i] = menu_item->selected ? 1 : 0;
355 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
356 for (; *p; p++) {
357 if (!highlighted && *p == menu_item->hotkey) {
358 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
359 strbuf_addch(&menu, *p);
360 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
361 highlighted = 1;
362 } else {
363 strbuf_addch(&menu, *p);
366 string_list_append(&menu_list, menu.buf);
367 strbuf_reset(&menu);
369 break;
370 case MENU_STUFF_TYPE_STRING_LIST:
371 i = 0;
372 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
373 if ((*chosen)[i] < 0)
374 (*chosen)[i] = 0;
375 strbuf_addf(&menu, "%s%2d: %s",
376 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
377 string_list_append(&menu_list, menu.buf);
378 strbuf_reset(&menu);
379 i++;
381 break;
384 pretty_print_menus(&menu_list);
386 strbuf_release(&menu);
387 string_list_clear(&menu_list, 0);
390 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
392 struct menu_item *menu_item;
393 struct string_list_item *string_list_item;
394 int i, len, found = 0;
396 len = strlen(choice);
397 switch (menu_stuff->type) {
398 default:
399 die("Bad type of menu_stuff when parse choice");
400 case MENU_STUFF_TYPE_MENU_ITEM:
402 menu_item = (struct menu_item *)menu_stuff->stuff;
403 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
404 if (len == 1 && *choice == menu_item->hotkey) {
405 found = i + 1;
406 break;
408 if (!strncasecmp(choice, menu_item->title, len)) {
409 if (found) {
410 if (len == 1) {
411 /* continue for hotkey matching */
412 found = -1;
413 } else {
414 found = 0;
415 break;
417 } else {
418 found = i + 1;
422 break;
423 case MENU_STUFF_TYPE_STRING_LIST:
424 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
425 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
426 if (!strncasecmp(choice, string_list_item->string, len)) {
427 if (found) {
428 found = 0;
429 break;
431 found = i + 1;
434 break;
436 return found;
441 * Parse user input, and return choice(s) for menu (menu_stuff).
443 * Input
444 * (for single choice)
445 * 1 - select a numbered item
446 * foo - select item based on menu title
447 * - (empty) select nothing
449 * (for multiple choice)
450 * 1 - select a single item
451 * 3-5 - select a range of items
452 * 2-3,6-9 - select multiple ranges
453 * foo - select item based on menu title
454 * -... - unselect specified items
455 * * - choose all items
456 * - (empty) finish selecting
458 * The parse result will be saved in array **chosen, and
459 * return number of total selections.
461 static int parse_choice(struct menu_stuff *menu_stuff,
462 int is_single,
463 struct strbuf input,
464 int **chosen)
466 struct strbuf **choice_list, **ptr;
467 int nr = 0;
468 int i;
470 if (is_single) {
471 choice_list = strbuf_split_max(&input, '\n', 0);
472 } else {
473 char *p = input.buf;
474 do {
475 if (*p == ',')
476 *p = ' ';
477 } while (*p++);
478 choice_list = strbuf_split_max(&input, ' ', 0);
481 for (ptr = choice_list; *ptr; ptr++) {
482 char *p;
483 int choose = 1;
484 int bottom = 0, top = 0;
485 int is_range, is_number;
487 strbuf_trim(*ptr);
488 if (!(*ptr)->len)
489 continue;
491 /* Input that begins with '-'; unchoose */
492 if (*(*ptr)->buf == '-') {
493 choose = 0;
494 strbuf_remove((*ptr), 0, 1);
497 is_range = 0;
498 is_number = 1;
499 for (p = (*ptr)->buf; *p; p++) {
500 if ('-' == *p) {
501 if (!is_range) {
502 is_range = 1;
503 is_number = 0;
504 } else {
505 is_number = 0;
506 is_range = 0;
507 break;
509 } else if (!isdigit(*p)) {
510 is_number = 0;
511 is_range = 0;
512 break;
516 if (is_number) {
517 bottom = atoi((*ptr)->buf);
518 top = bottom;
519 } else if (is_range) {
520 bottom = atoi((*ptr)->buf);
521 /* a range can be specified like 5-7 or 5- */
522 if (!*(strchr((*ptr)->buf, '-') + 1))
523 top = menu_stuff->nr;
524 else
525 top = atoi(strchr((*ptr)->buf, '-') + 1);
526 } else if (!strcmp((*ptr)->buf, "*")) {
527 bottom = 1;
528 top = menu_stuff->nr;
529 } else {
530 bottom = find_unique((*ptr)->buf, menu_stuff);
531 top = bottom;
534 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
535 (is_single && bottom != top)) {
536 clean_print_color(CLEAN_COLOR_ERROR);
537 printf_ln(_("Huh (%s)?"), (*ptr)->buf);
538 clean_print_color(CLEAN_COLOR_RESET);
539 continue;
542 for (i = bottom; i <= top; i++)
543 (*chosen)[i-1] = choose;
546 strbuf_list_free(choice_list);
548 for (i = 0; i < menu_stuff->nr; i++)
549 nr += (*chosen)[i];
550 return nr;
554 * Implement a git-add-interactive compatible UI, which is borrowed
555 * from git-add--interactive.perl.
557 * Return value:
559 * - Return an array of integers
560 * - , and it is up to you to free the allocated memory.
561 * - The array ends with EOF.
562 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
564 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
566 struct strbuf choice = STRBUF_INIT;
567 int *chosen, *result;
568 int nr = 0;
569 int eof = 0;
570 int i;
572 chosen = xmalloc(sizeof(int) * stuff->nr);
573 /* set chosen as uninitialized */
574 for (i = 0; i < stuff->nr; i++)
575 chosen[i] = -1;
577 for (;;) {
578 if (opts->header) {
579 printf_ln("%s%s%s",
580 clean_get_color(CLEAN_COLOR_HEADER),
581 _(opts->header),
582 clean_get_color(CLEAN_COLOR_RESET));
585 /* chosen will be initialized by print_highlight_menu_stuff */
586 print_highlight_menu_stuff(stuff, &chosen);
588 if (opts->flags & MENU_OPTS_LIST_ONLY)
589 break;
591 if (opts->prompt) {
592 printf("%s%s%s%s",
593 clean_get_color(CLEAN_COLOR_PROMPT),
594 _(opts->prompt),
595 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
596 clean_get_color(CLEAN_COLOR_RESET));
599 if (strbuf_getline(&choice, stdin, '\n') != EOF) {
600 strbuf_trim(&choice);
601 } else {
602 eof = 1;
603 break;
606 /* help for prompt */
607 if (!strcmp(choice.buf, "?")) {
608 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
609 continue;
612 /* for a multiple-choice menu, press ENTER (empty) will return back */
613 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
614 break;
616 nr = parse_choice(stuff,
617 opts->flags & MENU_OPTS_SINGLETON,
618 choice,
619 &chosen);
621 if (opts->flags & MENU_OPTS_SINGLETON) {
622 if (nr)
623 break;
624 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
625 break;
629 if (eof) {
630 result = xmalloc(sizeof(int));
631 *result = EOF;
632 } else {
633 int j = 0;
636 * recalculate nr, if return back from menu directly with
637 * default selections.
639 if (!nr) {
640 for (i = 0; i < stuff->nr; i++)
641 nr += chosen[i];
644 result = xcalloc(nr + 1, sizeof(int));
645 for (i = 0; i < stuff->nr && j < nr; i++) {
646 if (chosen[i])
647 result[j++] = i;
649 result[j] = EOF;
652 free(chosen);
653 strbuf_release(&choice);
654 return result;
657 static int clean_cmd(void)
659 return MENU_RETURN_NO_LOOP;
662 static int filter_by_patterns_cmd(void)
664 struct dir_struct dir;
665 struct strbuf confirm = STRBUF_INIT;
666 struct strbuf **ignore_list;
667 struct string_list_item *item;
668 struct exclude_list *el;
669 int changed = -1, i;
671 for (;;) {
672 if (!del_list.nr)
673 break;
675 if (changed)
676 pretty_print_dels();
678 clean_print_color(CLEAN_COLOR_PROMPT);
679 printf(_("Input ignore patterns>> "));
680 clean_print_color(CLEAN_COLOR_RESET);
681 if (strbuf_getline(&confirm, stdin, '\n') != EOF)
682 strbuf_trim(&confirm);
683 else
684 putchar('\n');
686 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
687 if (!confirm.len)
688 break;
690 memset(&dir, 0, sizeof(dir));
691 el = add_exclude_list(&dir, EXC_CMDL, "manual exclude");
692 ignore_list = strbuf_split_max(&confirm, ' ', 0);
694 for (i = 0; ignore_list[i]; i++) {
695 strbuf_trim(ignore_list[i]);
696 if (!ignore_list[i]->len)
697 continue;
699 add_exclude(ignore_list[i]->buf, "", 0, el, -(i+1));
702 changed = 0;
703 for_each_string_list_item(item, &del_list) {
704 int dtype = DT_UNKNOWN;
706 if (is_excluded(&dir, item->string, &dtype)) {
707 *item->string = '\0';
708 changed++;
712 if (changed) {
713 string_list_remove_empty_items(&del_list, 0);
714 } else {
715 clean_print_color(CLEAN_COLOR_ERROR);
716 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
717 clean_print_color(CLEAN_COLOR_RESET);
720 strbuf_list_free(ignore_list);
721 clear_directory(&dir);
724 strbuf_release(&confirm);
725 return 0;
728 static int select_by_numbers_cmd(void)
730 struct menu_opts menu_opts;
731 struct menu_stuff menu_stuff;
732 struct string_list_item *items;
733 int *chosen;
734 int i, j;
736 menu_opts.header = NULL;
737 menu_opts.prompt = N_("Select items to delete");
738 menu_opts.flags = 0;
740 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
741 menu_stuff.stuff = &del_list;
742 menu_stuff.nr = del_list.nr;
744 chosen = list_and_choose(&menu_opts, &menu_stuff);
745 items = del_list.items;
746 for (i = 0, j = 0; i < del_list.nr; i++) {
747 if (i < chosen[j]) {
748 *(items[i].string) = '\0';
749 } else if (i == chosen[j]) {
750 /* delete selected item */
751 j++;
752 continue;
753 } else {
754 /* end of chosen (chosen[j] == EOF), won't delete */
755 *(items[i].string) = '\0';
759 string_list_remove_empty_items(&del_list, 0);
761 free(chosen);
762 return 0;
765 static int ask_each_cmd(void)
767 struct strbuf confirm = STRBUF_INIT;
768 struct strbuf buf = STRBUF_INIT;
769 struct string_list_item *item;
770 const char *qname;
771 int changed = 0, eof = 0;
773 for_each_string_list_item(item, &del_list) {
774 /* Ctrl-D should stop removing files */
775 if (!eof) {
776 qname = quote_path_relative(item->string, NULL, &buf);
777 /* TRANSLATORS: Make sure to keep [y/N] as is */
778 printf(_("Remove %s [y/N]? "), qname);
779 if (strbuf_getline(&confirm, stdin, '\n') != EOF) {
780 strbuf_trim(&confirm);
781 } else {
782 putchar('\n');
783 eof = 1;
786 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
787 *item->string = '\0';
788 changed++;
792 if (changed)
793 string_list_remove_empty_items(&del_list, 0);
795 strbuf_release(&buf);
796 strbuf_release(&confirm);
797 return MENU_RETURN_NO_LOOP;
800 static int quit_cmd(void)
802 string_list_clear(&del_list, 0);
803 printf_ln(_("Bye."));
804 return MENU_RETURN_NO_LOOP;
807 static int help_cmd(void)
809 clean_print_color(CLEAN_COLOR_HELP);
810 printf_ln(_(
811 "clean - start cleaning\n"
812 "filter by pattern - exclude items from deletion\n"
813 "select by numbers - select items to be deleted by numbers\n"
814 "ask each - confirm each deletion (like \"rm -i\")\n"
815 "quit - stop cleaning\n"
816 "help - this screen\n"
817 "? - help for prompt selection"
819 clean_print_color(CLEAN_COLOR_RESET);
820 return 0;
823 static void interactive_main_loop(void)
825 while (del_list.nr) {
826 struct menu_opts menu_opts;
827 struct menu_stuff menu_stuff;
828 struct menu_item menus[] = {
829 {'c', "clean", 0, clean_cmd},
830 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
831 {'s', "select by numbers", 0, select_by_numbers_cmd},
832 {'a', "ask each", 0, ask_each_cmd},
833 {'q', "quit", 0, quit_cmd},
834 {'h', "help", 0, help_cmd},
836 int *chosen;
838 menu_opts.header = N_("*** Commands ***");
839 menu_opts.prompt = N_("What now");
840 menu_opts.flags = MENU_OPTS_SINGLETON;
842 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
843 menu_stuff.stuff = menus;
844 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
846 clean_print_color(CLEAN_COLOR_HEADER);
847 printf_ln(Q_("Would remove the following item:",
848 "Would remove the following items:",
849 del_list.nr));
850 clean_print_color(CLEAN_COLOR_RESET);
852 pretty_print_dels();
854 chosen = list_and_choose(&menu_opts, &menu_stuff);
856 if (*chosen != EOF) {
857 int ret;
858 ret = menus[*chosen].fn();
859 if (ret != MENU_RETURN_NO_LOOP) {
860 free(chosen);
861 chosen = NULL;
862 if (!del_list.nr) {
863 clean_print_color(CLEAN_COLOR_ERROR);
864 printf_ln(_("No more files to clean, exiting."));
865 clean_print_color(CLEAN_COLOR_RESET);
866 break;
868 continue;
870 } else {
871 quit_cmd();
874 free(chosen);
875 chosen = NULL;
876 break;
880 int cmd_clean(int argc, const char **argv, const char *prefix)
882 int i, res;
883 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
884 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
885 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
886 struct strbuf abs_path = STRBUF_INIT;
887 struct dir_struct dir;
888 struct pathspec pathspec;
889 struct strbuf buf = STRBUF_INIT;
890 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
891 struct exclude_list *el;
892 struct string_list_item *item;
893 const char *qname;
894 struct option options[] = {
895 OPT__QUIET(&quiet, N_("do not print names of files removed")),
896 OPT__DRY_RUN(&dry_run, N_("dry run")),
897 OPT__FORCE(&force, N_("force")),
898 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
899 OPT_BOOL('d', NULL, &remove_directories,
900 N_("remove whole directories")),
901 { OPTION_CALLBACK, 'e', "exclude", &exclude_list, N_("pattern"),
902 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb },
903 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
904 OPT_BOOL('X', NULL, &ignored_only,
905 N_("remove only ignored files")),
906 OPT_END()
909 git_config(git_clean_config, NULL);
910 if (force < 0)
911 force = 0;
912 else
913 config_set = 1;
915 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
918 memset(&dir, 0, sizeof(dir));
919 if (ignored_only)
920 dir.flags |= DIR_SHOW_IGNORED;
922 if (ignored && ignored_only)
923 die(_("-x and -X cannot be used together"));
925 if (!interactive && !dry_run && !force) {
926 if (config_set)
927 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
928 "refusing to clean"));
929 else
930 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
931 " refusing to clean"));
934 if (force > 1)
935 rm_flags = 0;
937 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
939 if (read_cache() < 0)
940 die(_("index file corrupt"));
942 if (!ignored)
943 setup_standard_excludes(&dir);
945 el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
946 for (i = 0; i < exclude_list.nr; i++)
947 add_exclude(exclude_list.items[i].string, "", 0, el, -(i+1));
949 parse_pathspec(&pathspec, 0,
950 PATHSPEC_PREFER_CWD,
951 prefix, argv);
953 fill_directory(&dir, &pathspec);
955 for (i = 0; i < dir.nr; i++) {
956 struct dir_entry *ent = dir.entries[i];
957 int matches = 0;
958 struct stat st;
959 const char *rel;
961 if (!cache_name_is_other(ent->name, ent->len))
962 continue;
964 if (pathspec.nr)
965 matches = dir_path_match(ent, &pathspec, 0, NULL);
967 if (pathspec.nr && !matches)
968 continue;
970 if (lstat(ent->name, &st))
971 die_errno("Cannot lstat '%s'", ent->name);
973 if (S_ISDIR(st.st_mode) && !remove_directories &&
974 matches != MATCHED_EXACTLY)
975 continue;
977 rel = relative_path(ent->name, prefix, &buf);
978 string_list_append(&del_list, rel);
981 if (interactive && del_list.nr > 0)
982 interactive_main_loop();
984 for_each_string_list_item(item, &del_list) {
985 struct stat st;
987 if (prefix)
988 strbuf_addstr(&abs_path, prefix);
990 strbuf_addstr(&abs_path, item->string);
993 * we might have removed this as part of earlier
994 * recursive directory removal, so lstat() here could
995 * fail with ENOENT.
997 if (lstat(abs_path.buf, &st))
998 continue;
1000 if (S_ISDIR(st.st_mode)) {
1001 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1002 errors++;
1003 if (gone && !quiet) {
1004 qname = quote_path_relative(item->string, NULL, &buf);
1005 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1007 } else {
1008 res = dry_run ? 0 : unlink(abs_path.buf);
1009 if (res) {
1010 qname = quote_path_relative(item->string, NULL, &buf);
1011 warning(_(msg_warn_remove_failed), qname);
1012 errors++;
1013 } else if (!quiet) {
1014 qname = quote_path_relative(item->string, NULL, &buf);
1015 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1018 strbuf_reset(&abs_path);
1021 strbuf_release(&abs_path);
1022 strbuf_release(&buf);
1023 string_list_clear(&del_list, 0);
1024 string_list_clear(&exclude_list, 0);
1025 return (errors != 0);