stash: teach 'push' (and 'create_stash') to honor pathspec
[git.git] / builtin / clean.c
blob0371010afbad54283ceca9883f2a9fbe6da4686b
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;
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;
157 struct string_list dels = STRING_LIST_INIT_DUP;
159 *dir_gone = 1;
161 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) && is_nonbare_repository_dir(path)) {
162 if (!quiet) {
163 quote_path_relative(path->buf, prefix, &quoted);
164 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
165 quoted.buf);
168 *dir_gone = 0;
169 return 0;
172 dir = opendir(path->buf);
173 if (!dir) {
174 /* an empty dir could be removed even if it is unreadble */
175 res = dry_run ? 0 : rmdir(path->buf);
176 if (res) {
177 quote_path_relative(path->buf, prefix, &quoted);
178 warning(_(msg_warn_remove_failed), quoted.buf);
179 *dir_gone = 0;
181 return res;
184 strbuf_complete(path, '/');
186 len = path->len;
187 while ((e = readdir(dir)) != NULL) {
188 struct stat st;
189 if (is_dot_or_dotdot(e->d_name))
190 continue;
192 strbuf_setlen(path, len);
193 strbuf_addstr(path, e->d_name);
194 if (lstat(path->buf, &st))
195 ; /* fall thru */
196 else if (S_ISDIR(st.st_mode)) {
197 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
198 ret = 1;
199 if (gone) {
200 quote_path_relative(path->buf, prefix, &quoted);
201 string_list_append(&dels, quoted.buf);
202 } else
203 *dir_gone = 0;
204 continue;
205 } else {
206 res = dry_run ? 0 : unlink(path->buf);
207 if (!res) {
208 quote_path_relative(path->buf, prefix, &quoted);
209 string_list_append(&dels, quoted.buf);
210 } else {
211 quote_path_relative(path->buf, prefix, &quoted);
212 warning(_(msg_warn_remove_failed), quoted.buf);
213 *dir_gone = 0;
214 ret = 1;
216 continue;
219 /* path too long, stat fails, or non-directory still exists */
220 *dir_gone = 0;
221 ret = 1;
222 break;
224 closedir(dir);
226 strbuf_setlen(path, original_len);
228 if (*dir_gone) {
229 res = dry_run ? 0 : rmdir(path->buf);
230 if (!res)
231 *dir_gone = 1;
232 else {
233 quote_path_relative(path->buf, prefix, &quoted);
234 warning(_(msg_warn_remove_failed), quoted.buf);
235 *dir_gone = 0;
236 ret = 1;
240 if (!*dir_gone && !quiet) {
241 int i;
242 for (i = 0; i < dels.nr; i++)
243 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
245 string_list_clear(&dels, 0);
246 return ret;
249 static void pretty_print_dels(void)
251 struct string_list list = STRING_LIST_INIT_DUP;
252 struct string_list_item *item;
253 struct strbuf buf = STRBUF_INIT;
254 const char *qname;
255 struct column_options copts;
257 for_each_string_list_item(item, &del_list) {
258 qname = quote_path_relative(item->string, NULL, &buf);
259 string_list_append(&list, qname);
263 * always enable column display, we only consult column.*
264 * about layout strategy and stuff
266 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
267 memset(&copts, 0, sizeof(copts));
268 copts.indent = " ";
269 copts.padding = 2;
270 print_columns(&list, colopts, &copts);
271 strbuf_release(&buf);
272 string_list_clear(&list, 0);
275 static void pretty_print_menus(struct string_list *menu_list)
277 unsigned int local_colopts = 0;
278 struct column_options copts;
280 local_colopts = COL_ENABLED | COL_ROW;
281 memset(&copts, 0, sizeof(copts));
282 copts.indent = " ";
283 copts.padding = 2;
284 print_columns(menu_list, local_colopts, &copts);
287 static void prompt_help_cmd(int singleton)
289 clean_print_color(CLEAN_COLOR_HELP);
290 printf_ln(singleton ?
291 _("Prompt help:\n"
292 "1 - select a numbered item\n"
293 "foo - select item based on unique prefix\n"
294 " - (empty) select nothing") :
295 _("Prompt help:\n"
296 "1 - select a single item\n"
297 "3-5 - select a range of items\n"
298 "2-3,6-9 - select multiple ranges\n"
299 "foo - select item based on unique prefix\n"
300 "-... - unselect specified items\n"
301 "* - choose all items\n"
302 " - (empty) finish selecting"));
303 clean_print_color(CLEAN_COLOR_RESET);
307 * display menu stuff with number prefix and hotkey highlight
309 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
311 struct string_list menu_list = STRING_LIST_INIT_DUP;
312 struct strbuf menu = STRBUF_INIT;
313 struct menu_item *menu_item;
314 struct string_list_item *string_list_item;
315 int i;
317 switch (stuff->type) {
318 default:
319 die("Bad type of menu_stuff when print menu");
320 case MENU_STUFF_TYPE_MENU_ITEM:
321 menu_item = (struct menu_item *)stuff->stuff;
322 for (i = 0; i < stuff->nr; i++, menu_item++) {
323 const char *p;
324 int highlighted = 0;
326 p = menu_item->title;
327 if ((*chosen)[i] < 0)
328 (*chosen)[i] = menu_item->selected ? 1 : 0;
329 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
330 for (; *p; p++) {
331 if (!highlighted && *p == menu_item->hotkey) {
332 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
333 strbuf_addch(&menu, *p);
334 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
335 highlighted = 1;
336 } else {
337 strbuf_addch(&menu, *p);
340 string_list_append(&menu_list, menu.buf);
341 strbuf_reset(&menu);
343 break;
344 case MENU_STUFF_TYPE_STRING_LIST:
345 i = 0;
346 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
347 if ((*chosen)[i] < 0)
348 (*chosen)[i] = 0;
349 strbuf_addf(&menu, "%s%2d: %s",
350 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
351 string_list_append(&menu_list, menu.buf);
352 strbuf_reset(&menu);
353 i++;
355 break;
358 pretty_print_menus(&menu_list);
360 strbuf_release(&menu);
361 string_list_clear(&menu_list, 0);
364 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
366 struct menu_item *menu_item;
367 struct string_list_item *string_list_item;
368 int i, len, found = 0;
370 len = strlen(choice);
371 switch (menu_stuff->type) {
372 default:
373 die("Bad type of menu_stuff when parse choice");
374 case MENU_STUFF_TYPE_MENU_ITEM:
376 menu_item = (struct menu_item *)menu_stuff->stuff;
377 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
378 if (len == 1 && *choice == menu_item->hotkey) {
379 found = i + 1;
380 break;
382 if (!strncasecmp(choice, menu_item->title, len)) {
383 if (found) {
384 if (len == 1) {
385 /* continue for hotkey matching */
386 found = -1;
387 } else {
388 found = 0;
389 break;
391 } else {
392 found = i + 1;
396 break;
397 case MENU_STUFF_TYPE_STRING_LIST:
398 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
399 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
400 if (!strncasecmp(choice, string_list_item->string, len)) {
401 if (found) {
402 found = 0;
403 break;
405 found = i + 1;
408 break;
410 return found;
415 * Parse user input, and return choice(s) for menu (menu_stuff).
417 * Input
418 * (for single choice)
419 * 1 - select a numbered item
420 * foo - select item based on menu title
421 * - (empty) select nothing
423 * (for multiple choice)
424 * 1 - select a single item
425 * 3-5 - select a range of items
426 * 2-3,6-9 - select multiple ranges
427 * foo - select item based on menu title
428 * -... - unselect specified items
429 * * - choose all items
430 * - (empty) finish selecting
432 * The parse result will be saved in array **chosen, and
433 * return number of total selections.
435 static int parse_choice(struct menu_stuff *menu_stuff,
436 int is_single,
437 struct strbuf input,
438 int **chosen)
440 struct strbuf **choice_list, **ptr;
441 int nr = 0;
442 int i;
444 if (is_single) {
445 choice_list = strbuf_split_max(&input, '\n', 0);
446 } else {
447 char *p = input.buf;
448 do {
449 if (*p == ',')
450 *p = ' ';
451 } while (*p++);
452 choice_list = strbuf_split_max(&input, ' ', 0);
455 for (ptr = choice_list; *ptr; ptr++) {
456 char *p;
457 int choose = 1;
458 int bottom = 0, top = 0;
459 int is_range, is_number;
461 strbuf_trim(*ptr);
462 if (!(*ptr)->len)
463 continue;
465 /* Input that begins with '-'; unchoose */
466 if (*(*ptr)->buf == '-') {
467 choose = 0;
468 strbuf_remove((*ptr), 0, 1);
471 is_range = 0;
472 is_number = 1;
473 for (p = (*ptr)->buf; *p; p++) {
474 if ('-' == *p) {
475 if (!is_range) {
476 is_range = 1;
477 is_number = 0;
478 } else {
479 is_number = 0;
480 is_range = 0;
481 break;
483 } else if (!isdigit(*p)) {
484 is_number = 0;
485 is_range = 0;
486 break;
490 if (is_number) {
491 bottom = atoi((*ptr)->buf);
492 top = bottom;
493 } else if (is_range) {
494 bottom = atoi((*ptr)->buf);
495 /* a range can be specified like 5-7 or 5- */
496 if (!*(strchr((*ptr)->buf, '-') + 1))
497 top = menu_stuff->nr;
498 else
499 top = atoi(strchr((*ptr)->buf, '-') + 1);
500 } else if (!strcmp((*ptr)->buf, "*")) {
501 bottom = 1;
502 top = menu_stuff->nr;
503 } else {
504 bottom = find_unique((*ptr)->buf, menu_stuff);
505 top = bottom;
508 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
509 (is_single && bottom != top)) {
510 clean_print_color(CLEAN_COLOR_ERROR);
511 printf_ln(_("Huh (%s)?"), (*ptr)->buf);
512 clean_print_color(CLEAN_COLOR_RESET);
513 continue;
516 for (i = bottom; i <= top; i++)
517 (*chosen)[i-1] = choose;
520 strbuf_list_free(choice_list);
522 for (i = 0; i < menu_stuff->nr; i++)
523 nr += (*chosen)[i];
524 return nr;
528 * Implement a git-add-interactive compatible UI, which is borrowed
529 * from git-add--interactive.perl.
531 * Return value:
533 * - Return an array of integers
534 * - , and it is up to you to free the allocated memory.
535 * - The array ends with EOF.
536 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
538 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
540 struct strbuf choice = STRBUF_INIT;
541 int *chosen, *result;
542 int nr = 0;
543 int eof = 0;
544 int i;
546 ALLOC_ARRAY(chosen, stuff->nr);
547 /* set chosen as uninitialized */
548 for (i = 0; i < stuff->nr; i++)
549 chosen[i] = -1;
551 for (;;) {
552 if (opts->header) {
553 printf_ln("%s%s%s",
554 clean_get_color(CLEAN_COLOR_HEADER),
555 _(opts->header),
556 clean_get_color(CLEAN_COLOR_RESET));
559 /* chosen will be initialized by print_highlight_menu_stuff */
560 print_highlight_menu_stuff(stuff, &chosen);
562 if (opts->flags & MENU_OPTS_LIST_ONLY)
563 break;
565 if (opts->prompt) {
566 printf("%s%s%s%s",
567 clean_get_color(CLEAN_COLOR_PROMPT),
568 _(opts->prompt),
569 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
570 clean_get_color(CLEAN_COLOR_RESET));
573 if (strbuf_getline_lf(&choice, stdin) != EOF) {
574 strbuf_trim(&choice);
575 } else {
576 eof = 1;
577 break;
580 /* help for prompt */
581 if (!strcmp(choice.buf, "?")) {
582 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
583 continue;
586 /* for a multiple-choice menu, press ENTER (empty) will return back */
587 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
588 break;
590 nr = parse_choice(stuff,
591 opts->flags & MENU_OPTS_SINGLETON,
592 choice,
593 &chosen);
595 if (opts->flags & MENU_OPTS_SINGLETON) {
596 if (nr)
597 break;
598 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
599 break;
603 if (eof) {
604 result = xmalloc(sizeof(int));
605 *result = EOF;
606 } else {
607 int j = 0;
610 * recalculate nr, if return back from menu directly with
611 * default selections.
613 if (!nr) {
614 for (i = 0; i < stuff->nr; i++)
615 nr += chosen[i];
618 result = xcalloc(st_add(nr, 1), sizeof(int));
619 for (i = 0; i < stuff->nr && j < nr; i++) {
620 if (chosen[i])
621 result[j++] = i;
623 result[j] = EOF;
626 free(chosen);
627 strbuf_release(&choice);
628 return result;
631 static int clean_cmd(void)
633 return MENU_RETURN_NO_LOOP;
636 static int filter_by_patterns_cmd(void)
638 struct dir_struct dir;
639 struct strbuf confirm = STRBUF_INIT;
640 struct strbuf **ignore_list;
641 struct string_list_item *item;
642 struct exclude_list *el;
643 int changed = -1, i;
645 for (;;) {
646 if (!del_list.nr)
647 break;
649 if (changed)
650 pretty_print_dels();
652 clean_print_color(CLEAN_COLOR_PROMPT);
653 printf(_("Input ignore patterns>> "));
654 clean_print_color(CLEAN_COLOR_RESET);
655 if (strbuf_getline_lf(&confirm, stdin) != EOF)
656 strbuf_trim(&confirm);
657 else
658 putchar('\n');
660 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
661 if (!confirm.len)
662 break;
664 memset(&dir, 0, sizeof(dir));
665 el = add_exclude_list(&dir, EXC_CMDL, "manual exclude");
666 ignore_list = strbuf_split_max(&confirm, ' ', 0);
668 for (i = 0; ignore_list[i]; i++) {
669 strbuf_trim(ignore_list[i]);
670 if (!ignore_list[i]->len)
671 continue;
673 add_exclude(ignore_list[i]->buf, "", 0, el, -(i+1));
676 changed = 0;
677 for_each_string_list_item(item, &del_list) {
678 int dtype = DT_UNKNOWN;
680 if (is_excluded(&dir, item->string, &dtype)) {
681 *item->string = '\0';
682 changed++;
686 if (changed) {
687 string_list_remove_empty_items(&del_list, 0);
688 } else {
689 clean_print_color(CLEAN_COLOR_ERROR);
690 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
691 clean_print_color(CLEAN_COLOR_RESET);
694 strbuf_list_free(ignore_list);
695 clear_directory(&dir);
698 strbuf_release(&confirm);
699 return 0;
702 static int select_by_numbers_cmd(void)
704 struct menu_opts menu_opts;
705 struct menu_stuff menu_stuff;
706 struct string_list_item *items;
707 int *chosen;
708 int i, j;
710 menu_opts.header = NULL;
711 menu_opts.prompt = N_("Select items to delete");
712 menu_opts.flags = 0;
714 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
715 menu_stuff.stuff = &del_list;
716 menu_stuff.nr = del_list.nr;
718 chosen = list_and_choose(&menu_opts, &menu_stuff);
719 items = del_list.items;
720 for (i = 0, j = 0; i < del_list.nr; i++) {
721 if (i < chosen[j]) {
722 *(items[i].string) = '\0';
723 } else if (i == chosen[j]) {
724 /* delete selected item */
725 j++;
726 continue;
727 } else {
728 /* end of chosen (chosen[j] == EOF), won't delete */
729 *(items[i].string) = '\0';
733 string_list_remove_empty_items(&del_list, 0);
735 free(chosen);
736 return 0;
739 static int ask_each_cmd(void)
741 struct strbuf confirm = STRBUF_INIT;
742 struct strbuf buf = STRBUF_INIT;
743 struct string_list_item *item;
744 const char *qname;
745 int changed = 0, eof = 0;
747 for_each_string_list_item(item, &del_list) {
748 /* Ctrl-D should stop removing files */
749 if (!eof) {
750 qname = quote_path_relative(item->string, NULL, &buf);
751 /* TRANSLATORS: Make sure to keep [y/N] as is */
752 printf(_("Remove %s [y/N]? "), qname);
753 if (strbuf_getline_lf(&confirm, stdin) != EOF) {
754 strbuf_trim(&confirm);
755 } else {
756 putchar('\n');
757 eof = 1;
760 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
761 *item->string = '\0';
762 changed++;
766 if (changed)
767 string_list_remove_empty_items(&del_list, 0);
769 strbuf_release(&buf);
770 strbuf_release(&confirm);
771 return MENU_RETURN_NO_LOOP;
774 static int quit_cmd(void)
776 string_list_clear(&del_list, 0);
777 printf_ln(_("Bye."));
778 return MENU_RETURN_NO_LOOP;
781 static int help_cmd(void)
783 clean_print_color(CLEAN_COLOR_HELP);
784 printf_ln(_(
785 "clean - start cleaning\n"
786 "filter by pattern - exclude items from deletion\n"
787 "select by numbers - select items to be deleted by numbers\n"
788 "ask each - confirm each deletion (like \"rm -i\")\n"
789 "quit - stop cleaning\n"
790 "help - this screen\n"
791 "? - help for prompt selection"
793 clean_print_color(CLEAN_COLOR_RESET);
794 return 0;
797 static void interactive_main_loop(void)
799 while (del_list.nr) {
800 struct menu_opts menu_opts;
801 struct menu_stuff menu_stuff;
802 struct menu_item menus[] = {
803 {'c', "clean", 0, clean_cmd},
804 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
805 {'s', "select by numbers", 0, select_by_numbers_cmd},
806 {'a', "ask each", 0, ask_each_cmd},
807 {'q', "quit", 0, quit_cmd},
808 {'h', "help", 0, help_cmd},
810 int *chosen;
812 menu_opts.header = N_("*** Commands ***");
813 menu_opts.prompt = N_("What now");
814 menu_opts.flags = MENU_OPTS_SINGLETON;
816 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
817 menu_stuff.stuff = menus;
818 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
820 clean_print_color(CLEAN_COLOR_HEADER);
821 printf_ln(Q_("Would remove the following item:",
822 "Would remove the following items:",
823 del_list.nr));
824 clean_print_color(CLEAN_COLOR_RESET);
826 pretty_print_dels();
828 chosen = list_and_choose(&menu_opts, &menu_stuff);
830 if (*chosen != EOF) {
831 int ret;
832 ret = menus[*chosen].fn();
833 if (ret != MENU_RETURN_NO_LOOP) {
834 free(chosen);
835 chosen = NULL;
836 if (!del_list.nr) {
837 clean_print_color(CLEAN_COLOR_ERROR);
838 printf_ln(_("No more files to clean, exiting."));
839 clean_print_color(CLEAN_COLOR_RESET);
840 break;
842 continue;
844 } else {
845 quit_cmd();
848 free(chosen);
849 chosen = NULL;
850 break;
854 int cmd_clean(int argc, const char **argv, const char *prefix)
856 int i, res;
857 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
858 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
859 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
860 struct strbuf abs_path = STRBUF_INIT;
861 struct dir_struct dir;
862 struct pathspec pathspec;
863 struct strbuf buf = STRBUF_INIT;
864 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
865 struct exclude_list *el;
866 struct string_list_item *item;
867 const char *qname;
868 struct option options[] = {
869 OPT__QUIET(&quiet, N_("do not print names of files removed")),
870 OPT__DRY_RUN(&dry_run, N_("dry run")),
871 OPT__FORCE(&force, N_("force")),
872 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
873 OPT_BOOL('d', NULL, &remove_directories,
874 N_("remove whole directories")),
875 { OPTION_CALLBACK, 'e', "exclude", &exclude_list, N_("pattern"),
876 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb },
877 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
878 OPT_BOOL('X', NULL, &ignored_only,
879 N_("remove only ignored files")),
880 OPT_END()
883 git_config(git_clean_config, NULL);
884 if (force < 0)
885 force = 0;
886 else
887 config_set = 1;
889 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
892 memset(&dir, 0, sizeof(dir));
893 if (ignored_only)
894 dir.flags |= DIR_SHOW_IGNORED;
896 if (ignored && ignored_only)
897 die(_("-x and -X cannot be used together"));
899 if (!interactive && !dry_run && !force) {
900 if (config_set)
901 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
902 "refusing to clean"));
903 else
904 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
905 " refusing to clean"));
908 if (force > 1)
909 rm_flags = 0;
911 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
913 if (read_cache() < 0)
914 die(_("index file corrupt"));
916 if (!ignored)
917 setup_standard_excludes(&dir);
919 el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
920 for (i = 0; i < exclude_list.nr; i++)
921 add_exclude(exclude_list.items[i].string, "", 0, el, -(i+1));
923 parse_pathspec(&pathspec, 0,
924 PATHSPEC_PREFER_CWD,
925 prefix, argv);
927 fill_directory(&dir, &pathspec);
929 for (i = 0; i < dir.nr; i++) {
930 struct dir_entry *ent = dir.entries[i];
931 int matches = 0;
932 struct stat st;
933 const char *rel;
935 if (!cache_name_is_other(ent->name, ent->len))
936 continue;
938 if (pathspec.nr)
939 matches = dir_path_match(ent, &pathspec, 0, NULL);
941 if (pathspec.nr && !matches)
942 continue;
944 if (lstat(ent->name, &st))
945 die_errno("Cannot lstat '%s'", ent->name);
947 if (S_ISDIR(st.st_mode) && !remove_directories &&
948 matches != MATCHED_EXACTLY)
949 continue;
951 rel = relative_path(ent->name, prefix, &buf);
952 string_list_append(&del_list, rel);
955 if (interactive && del_list.nr > 0)
956 interactive_main_loop();
958 for_each_string_list_item(item, &del_list) {
959 struct stat st;
961 if (prefix)
962 strbuf_addstr(&abs_path, prefix);
964 strbuf_addstr(&abs_path, item->string);
967 * we might have removed this as part of earlier
968 * recursive directory removal, so lstat() here could
969 * fail with ENOENT.
971 if (lstat(abs_path.buf, &st))
972 continue;
974 if (S_ISDIR(st.st_mode)) {
975 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
976 errors++;
977 if (gone && !quiet) {
978 qname = quote_path_relative(item->string, NULL, &buf);
979 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
981 } else {
982 res = dry_run ? 0 : unlink(abs_path.buf);
983 if (res) {
984 qname = quote_path_relative(item->string, NULL, &buf);
985 warning(_(msg_warn_remove_failed), qname);
986 errors++;
987 } else if (!quiet) {
988 qname = quote_path_relative(item->string, NULL, &buf);
989 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
992 strbuf_reset(&abs_path);
995 strbuf_release(&abs_path);
996 strbuf_release(&buf);
997 string_list_clear(&del_list, 0);
998 string_list_clear(&exclude_list, 0);
999 return (errors != 0);