Git 1.8.4.5
[git.git] / builtin / clean.c
blob3c85e152e140741855590f422c599407b6d6ae55
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 "refs.h"
14 #include "string-list.h"
15 #include "quote.h"
16 #include "column.h"
17 #include "color.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)();
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 if (!prefixcmp(var, "column."))
103 return git_column_config(var, value, "clean", &colopts);
105 /* honors the color.interactive* config variables which also
106 applied in git-add--interactive and git-stash */
107 if (!strcmp(var, "color.interactive")) {
108 clean_use_color = git_config_colorbool(var, value);
109 return 0;
111 if (!prefixcmp(var, "color.interactive.")) {
112 int slot = parse_clean_color_slot(var +
113 strlen("color.interactive."));
114 if (slot < 0)
115 return 0;
116 if (!value)
117 return config_error_nonbool(var);
118 color_parse(value, var, clean_colors[slot]);
119 return 0;
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;
150 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
151 int dry_run, int quiet, int *dir_gone)
153 DIR *dir;
154 struct strbuf quoted = STRBUF_INIT;
155 struct dirent *e;
156 int res = 0, ret = 0, gone = 1, original_len = path->len, len, i;
157 unsigned char submodule_head[20];
158 struct string_list dels = STRING_LIST_INIT_DUP;
160 *dir_gone = 1;
162 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
163 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
164 if (!quiet) {
165 quote_path_relative(path->buf, prefix, &quoted);
166 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
167 quoted.buf);
170 *dir_gone = 0;
171 return 0;
174 dir = opendir(path->buf);
175 if (!dir) {
176 /* an empty dir could be removed even if it is unreadble */
177 res = dry_run ? 0 : rmdir(path->buf);
178 if (res) {
179 quote_path_relative(path->buf, prefix, &quoted);
180 warning(_(msg_warn_remove_failed), quoted.buf);
181 *dir_gone = 0;
183 return res;
186 if (path->buf[original_len - 1] != '/')
187 strbuf_addch(path, '/');
189 len = path->len;
190 while ((e = readdir(dir)) != NULL) {
191 struct stat st;
192 if (is_dot_or_dotdot(e->d_name))
193 continue;
195 strbuf_setlen(path, len);
196 strbuf_addstr(path, e->d_name);
197 if (lstat(path->buf, &st))
198 ; /* fall thru */
199 else if (S_ISDIR(st.st_mode)) {
200 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
201 ret = 1;
202 if (gone) {
203 quote_path_relative(path->buf, prefix, &quoted);
204 string_list_append(&dels, quoted.buf);
205 } else
206 *dir_gone = 0;
207 continue;
208 } else {
209 res = dry_run ? 0 : unlink(path->buf);
210 if (!res) {
211 quote_path_relative(path->buf, prefix, &quoted);
212 string_list_append(&dels, quoted.buf);
213 } else {
214 quote_path_relative(path->buf, prefix, &quoted);
215 warning(_(msg_warn_remove_failed), quoted.buf);
216 *dir_gone = 0;
217 ret = 1;
219 continue;
222 /* path too long, stat fails, or non-directory still exists */
223 *dir_gone = 0;
224 ret = 1;
225 break;
227 closedir(dir);
229 strbuf_setlen(path, original_len);
231 if (*dir_gone) {
232 res = dry_run ? 0 : rmdir(path->buf);
233 if (!res)
234 *dir_gone = 1;
235 else {
236 quote_path_relative(path->buf, prefix, &quoted);
237 warning(_(msg_warn_remove_failed), quoted.buf);
238 *dir_gone = 0;
239 ret = 1;
243 if (!*dir_gone && !quiet) {
244 for (i = 0; i < dels.nr; i++)
245 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
247 string_list_clear(&dels, 0);
248 return ret;
251 static void pretty_print_dels(void)
253 struct string_list list = STRING_LIST_INIT_DUP;
254 struct string_list_item *item;
255 struct strbuf buf = STRBUF_INIT;
256 const char *qname;
257 struct column_options copts;
259 for_each_string_list_item(item, &del_list) {
260 qname = quote_path_relative(item->string, NULL, &buf);
261 string_list_append(&list, qname);
265 * always enable column display, we only consult column.*
266 * about layout strategy and stuff
268 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
269 memset(&copts, 0, sizeof(copts));
270 copts.indent = " ";
271 copts.padding = 2;
272 print_columns(&list, colopts, &copts);
273 strbuf_release(&buf);
274 string_list_clear(&list, 0);
277 static void pretty_print_menus(struct string_list *menu_list)
279 unsigned int local_colopts = 0;
280 struct column_options copts;
282 local_colopts = COL_ENABLED | COL_ROW;
283 memset(&copts, 0, sizeof(copts));
284 copts.indent = " ";
285 copts.padding = 2;
286 print_columns(menu_list, local_colopts, &copts);
289 static void prompt_help_cmd(int singleton)
291 clean_print_color(CLEAN_COLOR_HELP);
292 printf_ln(singleton ?
293 _("Prompt help:\n"
294 "1 - select a numbered item\n"
295 "foo - select item based on unique prefix\n"
296 " - (empty) select nothing") :
297 _("Prompt help:\n"
298 "1 - select a single item\n"
299 "3-5 - select a range of items\n"
300 "2-3,6-9 - select multiple ranges\n"
301 "foo - select item based on unique prefix\n"
302 "-... - unselect specified items\n"
303 "* - choose all items\n"
304 " - (empty) finish selecting"));
305 clean_print_color(CLEAN_COLOR_RESET);
309 * display menu stuff with number prefix and hotkey highlight
311 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
313 struct string_list menu_list = STRING_LIST_INIT_DUP;
314 struct strbuf menu = STRBUF_INIT;
315 struct strbuf buf = STRBUF_INIT;
316 struct menu_item *menu_item;
317 struct string_list_item *string_list_item;
318 int i;
320 switch (stuff->type) {
321 default:
322 die("Bad type of menu_staff when print menu");
323 case MENU_STUFF_TYPE_MENU_ITEM:
324 menu_item = (struct menu_item *)stuff->stuff;
325 for (i = 0; i < stuff->nr; i++, menu_item++) {
326 const char *p;
327 int highlighted = 0;
329 p = menu_item->title;
330 if ((*chosen)[i] < 0)
331 (*chosen)[i] = menu_item->selected ? 1 : 0;
332 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
333 for (; *p; p++) {
334 if (!highlighted && *p == menu_item->hotkey) {
335 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
336 strbuf_addch(&menu, *p);
337 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
338 highlighted = 1;
339 } else {
340 strbuf_addch(&menu, *p);
343 string_list_append(&menu_list, menu.buf);
344 strbuf_reset(&menu);
346 break;
347 case MENU_STUFF_TYPE_STRING_LIST:
348 i = 0;
349 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
350 if ((*chosen)[i] < 0)
351 (*chosen)[i] = 0;
352 strbuf_addf(&menu, "%s%2d: %s",
353 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
354 string_list_append(&menu_list, menu.buf);
355 strbuf_reset(&menu);
356 i++;
358 break;
361 pretty_print_menus(&menu_list);
363 strbuf_release(&menu);
364 strbuf_release(&buf);
365 string_list_clear(&menu_list, 0);
368 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
370 struct menu_item *menu_item;
371 struct string_list_item *string_list_item;
372 int i, len, found = 0;
374 len = strlen(choice);
375 switch (menu_stuff->type) {
376 default:
377 die("Bad type of menu_stuff when parse choice");
378 case MENU_STUFF_TYPE_MENU_ITEM:
380 menu_item = (struct menu_item *)menu_stuff->stuff;
381 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
382 if (len == 1 && *choice == menu_item->hotkey) {
383 found = i + 1;
384 break;
386 if (!strncasecmp(choice, menu_item->title, len)) {
387 if (found) {
388 if (len == 1) {
389 /* continue for hotkey matching */
390 found = -1;
391 } else {
392 found = 0;
393 break;
395 } else {
396 found = i + 1;
400 break;
401 case MENU_STUFF_TYPE_STRING_LIST:
402 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
403 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
404 if (!strncasecmp(choice, string_list_item->string, len)) {
405 if (found) {
406 found = 0;
407 break;
409 found = i + 1;
412 break;
414 return found;
419 * Parse user input, and return choice(s) for menu (menu_stuff).
421 * Input
422 * (for single choice)
423 * 1 - select a numbered item
424 * foo - select item based on menu title
425 * - (empty) select nothing
427 * (for multiple choice)
428 * 1 - select a single item
429 * 3-5 - select a range of items
430 * 2-3,6-9 - select multiple ranges
431 * foo - select item based on menu title
432 * -... - unselect specified items
433 * * - choose all items
434 * - (empty) finish selecting
436 * The parse result will be saved in array **chosen, and
437 * return number of total selections.
439 static int parse_choice(struct menu_stuff *menu_stuff,
440 int is_single,
441 struct strbuf input,
442 int **chosen)
444 struct strbuf **choice_list, **ptr;
445 int nr = 0;
446 int i;
448 if (is_single) {
449 choice_list = strbuf_split_max(&input, '\n', 0);
450 } else {
451 char *p = input.buf;
452 do {
453 if (*p == ',')
454 *p = ' ';
455 } while (*p++);
456 choice_list = strbuf_split_max(&input, ' ', 0);
459 for (ptr = choice_list; *ptr; ptr++) {
460 char *p;
461 int choose = 1;
462 int bottom = 0, top = 0;
463 int is_range, is_number;
465 strbuf_trim(*ptr);
466 if (!(*ptr)->len)
467 continue;
469 /* Input that begins with '-'; unchoose */
470 if (*(*ptr)->buf == '-') {
471 choose = 0;
472 strbuf_remove((*ptr), 0, 1);
475 is_range = 0;
476 is_number = 1;
477 for (p = (*ptr)->buf; *p; p++) {
478 if ('-' == *p) {
479 if (!is_range) {
480 is_range = 1;
481 is_number = 0;
482 } else {
483 is_number = 0;
484 is_range = 0;
485 break;
487 } else if (!isdigit(*p)) {
488 is_number = 0;
489 is_range = 0;
490 break;
494 if (is_number) {
495 bottom = atoi((*ptr)->buf);
496 top = bottom;
497 } else if (is_range) {
498 bottom = atoi((*ptr)->buf);
499 /* a range can be specified like 5-7 or 5- */
500 if (!*(strchr((*ptr)->buf, '-') + 1))
501 top = menu_stuff->nr;
502 else
503 top = atoi(strchr((*ptr)->buf, '-') + 1);
504 } else if (!strcmp((*ptr)->buf, "*")) {
505 bottom = 1;
506 top = menu_stuff->nr;
507 } else {
508 bottom = find_unique((*ptr)->buf, menu_stuff);
509 top = bottom;
512 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
513 (is_single && bottom != top)) {
514 clean_print_color(CLEAN_COLOR_ERROR);
515 printf_ln(_("Huh (%s)?"), (*ptr)->buf);
516 clean_print_color(CLEAN_COLOR_RESET);
517 continue;
520 for (i = bottom; i <= top; i++)
521 (*chosen)[i-1] = choose;
524 strbuf_list_free(choice_list);
526 for (i = 0; i < menu_stuff->nr; i++)
527 nr += (*chosen)[i];
528 return nr;
532 * Implement a git-add-interactive compatible UI, which is borrowed
533 * from git-add--interactive.perl.
535 * Return value:
537 * - Return an array of integers
538 * - , and it is up to you to free the allocated memory.
539 * - The array ends with EOF.
540 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
542 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
544 struct strbuf choice = STRBUF_INIT;
545 int *chosen, *result;
546 int nr = 0;
547 int eof = 0;
548 int i;
550 chosen = xmalloc(sizeof(int) * stuff->nr);
551 /* set chosen as uninitialized */
552 for (i = 0; i < stuff->nr; i++)
553 chosen[i] = -1;
555 for (;;) {
556 if (opts->header) {
557 printf_ln("%s%s%s",
558 clean_get_color(CLEAN_COLOR_HEADER),
559 _(opts->header),
560 clean_get_color(CLEAN_COLOR_RESET));
563 /* chosen will be initialized by print_highlight_menu_stuff */
564 print_highlight_menu_stuff(stuff, &chosen);
566 if (opts->flags & MENU_OPTS_LIST_ONLY)
567 break;
569 if (opts->prompt) {
570 printf("%s%s%s%s",
571 clean_get_color(CLEAN_COLOR_PROMPT),
572 _(opts->prompt),
573 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
574 clean_get_color(CLEAN_COLOR_RESET));
577 if (strbuf_getline(&choice, stdin, '\n') != EOF) {
578 strbuf_trim(&choice);
579 } else {
580 eof = 1;
581 break;
584 /* help for prompt */
585 if (!strcmp(choice.buf, "?")) {
586 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
587 continue;
590 /* for a multiple-choice menu, press ENTER (empty) will return back */
591 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
592 break;
594 nr = parse_choice(stuff,
595 opts->flags & MENU_OPTS_SINGLETON,
596 choice,
597 &chosen);
599 if (opts->flags & MENU_OPTS_SINGLETON) {
600 if (nr)
601 break;
602 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
603 break;
607 if (eof) {
608 result = xmalloc(sizeof(int));
609 *result = EOF;
610 } else {
611 int j = 0;
614 * recalculate nr, if return back from menu directly with
615 * default selections.
617 if (!nr) {
618 for (i = 0; i < stuff->nr; i++)
619 nr += chosen[i];
622 result = xmalloc(sizeof(int) * (nr + 1));
623 memset(result, 0, sizeof(int) * (nr + 1));
624 for (i = 0; i < stuff->nr && j < nr; i++) {
625 if (chosen[i])
626 result[j++] = i;
628 result[j] = EOF;
631 free(chosen);
632 strbuf_release(&choice);
633 return result;
636 static int clean_cmd(void)
638 return MENU_RETURN_NO_LOOP;
641 static int filter_by_patterns_cmd(void)
643 struct dir_struct dir;
644 struct strbuf confirm = STRBUF_INIT;
645 struct strbuf **ignore_list;
646 struct string_list_item *item;
647 struct exclude_list *el;
648 int changed = -1, i;
650 for (;;) {
651 if (!del_list.nr)
652 break;
654 if (changed)
655 pretty_print_dels();
657 clean_print_color(CLEAN_COLOR_PROMPT);
658 printf(_("Input ignore patterns>> "));
659 clean_print_color(CLEAN_COLOR_RESET);
660 if (strbuf_getline(&confirm, stdin, '\n') != EOF)
661 strbuf_trim(&confirm);
662 else
663 putchar('\n');
665 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
666 if (!confirm.len)
667 break;
669 memset(&dir, 0, sizeof(dir));
670 el = add_exclude_list(&dir, EXC_CMDL, "manual exclude");
671 ignore_list = strbuf_split_max(&confirm, ' ', 0);
673 for (i = 0; ignore_list[i]; i++) {
674 strbuf_trim(ignore_list[i]);
675 if (!ignore_list[i]->len)
676 continue;
678 add_exclude(ignore_list[i]->buf, "", 0, el, -(i+1));
681 changed = 0;
682 for_each_string_list_item(item, &del_list) {
683 int dtype = DT_UNKNOWN;
685 if (is_excluded(&dir, item->string, &dtype)) {
686 *item->string = '\0';
687 changed++;
691 if (changed) {
692 string_list_remove_empty_items(&del_list, 0);
693 } else {
694 clean_print_color(CLEAN_COLOR_ERROR);
695 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
696 clean_print_color(CLEAN_COLOR_RESET);
699 strbuf_list_free(ignore_list);
700 clear_directory(&dir);
703 strbuf_release(&confirm);
704 return 0;
707 static int select_by_numbers_cmd(void)
709 struct menu_opts menu_opts;
710 struct menu_stuff menu_stuff;
711 struct string_list_item *items;
712 int *chosen;
713 int i, j;
715 menu_opts.header = NULL;
716 menu_opts.prompt = N_("Select items to delete");
717 menu_opts.flags = 0;
719 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
720 menu_stuff.stuff = &del_list;
721 menu_stuff.nr = del_list.nr;
723 chosen = list_and_choose(&menu_opts, &menu_stuff);
724 items = del_list.items;
725 for (i = 0, j = 0; i < del_list.nr; i++) {
726 if (i < chosen[j]) {
727 *(items[i].string) = '\0';
728 } else if (i == chosen[j]) {
729 /* delete selected item */
730 j++;
731 continue;
732 } else {
733 /* end of chosen (chosen[j] == EOF), won't delete */
734 *(items[i].string) = '\0';
738 string_list_remove_empty_items(&del_list, 0);
740 free(chosen);
741 return 0;
744 static int ask_each_cmd(void)
746 struct strbuf confirm = STRBUF_INIT;
747 struct strbuf buf = STRBUF_INIT;
748 struct string_list_item *item;
749 const char *qname;
750 int changed = 0, eof = 0;
752 for_each_string_list_item(item, &del_list) {
753 /* Ctrl-D should stop removing files */
754 if (!eof) {
755 qname = quote_path_relative(item->string, NULL, &buf);
756 printf(_("remove %s? "), qname);
757 if (strbuf_getline(&confirm, stdin, '\n') != EOF) {
758 strbuf_trim(&confirm);
759 } else {
760 putchar('\n');
761 eof = 1;
764 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
765 *item->string = '\0';
766 changed++;
770 if (changed)
771 string_list_remove_empty_items(&del_list, 0);
773 strbuf_release(&buf);
774 strbuf_release(&confirm);
775 return MENU_RETURN_NO_LOOP;
778 static int quit_cmd(void)
780 string_list_clear(&del_list, 0);
781 printf_ln(_("Bye."));
782 return MENU_RETURN_NO_LOOP;
785 static int help_cmd(void)
787 clean_print_color(CLEAN_COLOR_HELP);
788 printf_ln(_(
789 "clean - start cleaning\n"
790 "filter by pattern - exclude items from deletion\n"
791 "select by numbers - select items to be deleted by numbers\n"
792 "ask each - confirm each deletion (like \"rm -i\")\n"
793 "quit - stop cleaning\n"
794 "help - this screen\n"
795 "? - help for prompt selection"
797 clean_print_color(CLEAN_COLOR_RESET);
798 return 0;
801 static void interactive_main_loop(void)
803 while (del_list.nr) {
804 struct menu_opts menu_opts;
805 struct menu_stuff menu_stuff;
806 struct menu_item menus[] = {
807 {'c', "clean", 0, clean_cmd},
808 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
809 {'s', "select by numbers", 0, select_by_numbers_cmd},
810 {'a', "ask each", 0, ask_each_cmd},
811 {'q', "quit", 0, quit_cmd},
812 {'h', "help", 0, help_cmd},
814 int *chosen;
816 menu_opts.header = N_("*** Commands ***");
817 menu_opts.prompt = N_("What now");
818 menu_opts.flags = MENU_OPTS_SINGLETON;
820 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
821 menu_stuff.stuff = menus;
822 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
824 clean_print_color(CLEAN_COLOR_HEADER);
825 printf_ln(Q_("Would remove the following item:",
826 "Would remove the following items:",
827 del_list.nr));
828 clean_print_color(CLEAN_COLOR_RESET);
830 pretty_print_dels();
832 chosen = list_and_choose(&menu_opts, &menu_stuff);
834 if (*chosen != EOF) {
835 int ret;
836 ret = menus[*chosen].fn();
837 if (ret != MENU_RETURN_NO_LOOP) {
838 free(chosen);
839 chosen = NULL;
840 if (!del_list.nr) {
841 clean_print_color(CLEAN_COLOR_ERROR);
842 printf_ln(_("No more files to clean, exiting."));
843 clean_print_color(CLEAN_COLOR_RESET);
844 break;
846 continue;
848 } else {
849 quit_cmd();
852 free(chosen);
853 chosen = NULL;
854 break;
858 int cmd_clean(int argc, const char **argv, const char *prefix)
860 int i, res;
861 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
862 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
863 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
864 struct strbuf abs_path = STRBUF_INIT;
865 struct dir_struct dir;
866 static const char **pathspec;
867 struct strbuf buf = STRBUF_INIT;
868 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
869 struct exclude_list *el;
870 struct string_list_item *item;
871 const char *qname;
872 char *seen = NULL;
873 struct option options[] = {
874 OPT__QUIET(&quiet, N_("do not print names of files removed")),
875 OPT__DRY_RUN(&dry_run, N_("dry run")),
876 OPT__FORCE(&force, N_("force")),
877 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
878 OPT_BOOLEAN('d', NULL, &remove_directories,
879 N_("remove whole directories")),
880 { OPTION_CALLBACK, 'e', "exclude", &exclude_list, N_("pattern"),
881 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb },
882 OPT_BOOLEAN('x', NULL, &ignored, N_("remove ignored files, too")),
883 OPT_BOOLEAN('X', NULL, &ignored_only,
884 N_("remove only ignored files")),
885 OPT_END()
888 git_config(git_clean_config, NULL);
889 if (force < 0)
890 force = 0;
891 else
892 config_set = 1;
894 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
897 memset(&dir, 0, sizeof(dir));
898 if (ignored_only)
899 dir.flags |= DIR_SHOW_IGNORED;
901 if (ignored && ignored_only)
902 die(_("-x and -X cannot be used together"));
904 if (!interactive && !dry_run && !force) {
905 if (config_set)
906 die(_("clean.requireForce set to true and neither -i, -n nor -f given; "
907 "refusing to clean"));
908 else
909 die(_("clean.requireForce defaults to true and neither -i, -n nor -f given; "
910 "refusing to clean"));
913 if (force > 1)
914 rm_flags = 0;
916 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
918 if (read_cache() < 0)
919 die(_("index file corrupt"));
921 if (!ignored)
922 setup_standard_excludes(&dir);
924 el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
925 for (i = 0; i < exclude_list.nr; i++)
926 add_exclude(exclude_list.items[i].string, "", 0, el, -(i+1));
928 pathspec = get_pathspec(prefix, argv);
930 fill_directory(&dir, pathspec);
932 if (pathspec)
933 seen = xmalloc(argc > 0 ? argc : 1);
935 for (i = 0; i < dir.nr; i++) {
936 struct dir_entry *ent = dir.entries[i];
937 int len, pos;
938 int matches = 0;
939 const struct cache_entry *ce;
940 struct stat st;
941 const char *rel;
944 * Remove the '/' at the end that directory
945 * walking adds for directory entries.
947 len = ent->len;
948 if (len && ent->name[len-1] == '/')
949 len--;
950 pos = cache_name_pos(ent->name, len);
951 if (0 <= pos)
952 continue; /* exact match */
953 pos = -pos - 1;
954 if (pos < active_nr) {
955 ce = active_cache[pos];
956 if (ce_namelen(ce) == len &&
957 !memcmp(ce->name, ent->name, len))
958 continue; /* Yup, this one exists unmerged */
961 if (lstat(ent->name, &st))
962 die_errno("Cannot lstat '%s'", ent->name);
964 if (pathspec) {
965 memset(seen, 0, argc > 0 ? argc : 1);
966 matches = match_pathspec(pathspec, ent->name, len,
967 0, seen);
970 if (S_ISDIR(st.st_mode)) {
971 if (remove_directories || (matches == MATCHED_EXACTLY)) {
972 rel = relative_path(ent->name, prefix, &buf);
973 string_list_append(&del_list, rel);
975 } else {
976 if (pathspec && !matches)
977 continue;
978 rel = relative_path(ent->name, prefix, &buf);
979 string_list_append(&del_list, rel);
983 if (interactive && del_list.nr > 0)
984 interactive_main_loop();
986 for_each_string_list_item(item, &del_list) {
987 struct stat st;
989 if (prefix)
990 strbuf_addstr(&abs_path, prefix);
992 strbuf_addstr(&abs_path, item->string);
995 * we might have removed this as part of earlier
996 * recursive directory removal, so lstat() here could
997 * fail with ENOENT.
999 if (lstat(abs_path.buf, &st))
1000 continue;
1002 if (S_ISDIR(st.st_mode)) {
1003 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1004 errors++;
1005 if (gone && !quiet) {
1006 qname = quote_path_relative(item->string, NULL, &buf);
1007 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1009 } else {
1010 res = dry_run ? 0 : unlink(abs_path.buf);
1011 if (res) {
1012 qname = quote_path_relative(item->string, NULL, &buf);
1013 warning(_(msg_warn_remove_failed), qname);
1014 errors++;
1015 } else if (!quiet) {
1016 qname = quote_path_relative(item->string, NULL, &buf);
1017 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1020 strbuf_reset(&abs_path);
1022 free(seen);
1024 strbuf_release(&abs_path);
1025 strbuf_release(&buf);
1026 string_list_clear(&del_list, 0);
1027 string_list_clear(&exclude_list, 0);
1028 return (errors != 0);