Git 2.34.8
[git.git] / builtin / clean.c
blob98a2860409bb4820af393ea9e50e58124fd7873e
1 /*
2 * "git clean" builtin command
4 * Copyright (C) 2007 Shawn Bohrer
6 * Based on git-clean.sh by Pavel Roskin
7 */
9 #define USE_THE_INDEX_COMPATIBILITY_MACROS
10 #include "builtin.h"
11 #include "cache.h"
12 #include "config.h"
13 #include "dir.h"
14 #include "parse-options.h"
15 #include "string-list.h"
16 #include "quote.h"
17 #include "column.h"
18 #include "color.h"
19 #include "pathspec.h"
20 #include "help.h"
21 #include "prompt.h"
23 static int force = -1; /* unset */
24 static int interactive;
25 static struct string_list del_list = STRING_LIST_INIT_DUP;
26 static unsigned int colopts;
28 static const char *const builtin_clean_usage[] = {
29 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
30 NULL
33 static const char *msg_remove = N_("Removing %s\n");
34 static const char *msg_would_remove = N_("Would remove %s\n");
35 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
36 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
37 static const char *msg_warn_remove_failed = N_("failed to remove %s");
38 static const char *msg_warn_lstat_failed = N_("could not lstat %s\n");
40 enum color_clean {
41 CLEAN_COLOR_RESET = 0,
42 CLEAN_COLOR_PLAIN = 1,
43 CLEAN_COLOR_PROMPT = 2,
44 CLEAN_COLOR_HEADER = 3,
45 CLEAN_COLOR_HELP = 4,
46 CLEAN_COLOR_ERROR = 5
49 static const char *color_interactive_slots[] = {
50 [CLEAN_COLOR_ERROR] = "error",
51 [CLEAN_COLOR_HEADER] = "header",
52 [CLEAN_COLOR_HELP] = "help",
53 [CLEAN_COLOR_PLAIN] = "plain",
54 [CLEAN_COLOR_PROMPT] = "prompt",
55 [CLEAN_COLOR_RESET] = "reset",
58 static int clean_use_color = -1;
59 static char clean_colors[][COLOR_MAXLEN] = {
60 [CLEAN_COLOR_ERROR] = GIT_COLOR_BOLD_RED,
61 [CLEAN_COLOR_HEADER] = GIT_COLOR_BOLD,
62 [CLEAN_COLOR_HELP] = GIT_COLOR_BOLD_RED,
63 [CLEAN_COLOR_PLAIN] = GIT_COLOR_NORMAL,
64 [CLEAN_COLOR_PROMPT] = GIT_COLOR_BOLD_BLUE,
65 [CLEAN_COLOR_RESET] = GIT_COLOR_RESET,
68 #define MENU_OPTS_SINGLETON 01
69 #define MENU_OPTS_IMMEDIATE 02
70 #define MENU_OPTS_LIST_ONLY 04
72 struct menu_opts {
73 const char *header;
74 const char *prompt;
75 int flags;
78 #define MENU_RETURN_NO_LOOP 10
80 struct menu_item {
81 char hotkey;
82 const char *title;
83 int selected;
84 int (*fn)(void);
87 enum menu_stuff_type {
88 MENU_STUFF_TYPE_STRING_LIST = 1,
89 MENU_STUFF_TYPE_MENU_ITEM
92 struct menu_stuff {
93 enum menu_stuff_type type;
94 int nr;
95 void *stuff;
98 define_list_config_array(color_interactive_slots);
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 = LOOKUP_CONFIG(color_interactive_slots, 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 BUG_ON_OPT_NEG(unset);
147 string_list_append(exclude_list, arg);
148 return 0;
151 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
152 int dry_run, int quiet, int *dir_gone)
154 DIR *dir;
155 struct strbuf quoted = STRBUF_INIT;
156 struct dirent *e;
157 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
158 struct string_list dels = STRING_LIST_INIT_DUP;
160 *dir_gone = 1;
162 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
163 is_nonbare_repository_dir(path)) {
164 if (!quiet) {
165 quote_path(path->buf, prefix, &quoted, 0);
166 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
167 quoted.buf);
170 *dir_gone = 0;
171 goto out;
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 int saved_errno = errno;
180 quote_path(path->buf, prefix, &quoted, 0);
181 errno = saved_errno;
182 warning_errno(_(msg_warn_remove_failed), quoted.buf);
183 *dir_gone = 0;
185 ret = res;
186 goto out;
189 strbuf_complete(path, '/');
191 len = path->len;
192 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
193 struct stat st;
195 strbuf_setlen(path, len);
196 strbuf_addstr(path, e->d_name);
197 if (lstat(path->buf, &st))
198 warning_errno(_(msg_warn_lstat_failed), path->buf);
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(path->buf, prefix, &quoted, 0);
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(path->buf, prefix, &quoted, 0);
212 string_list_append(&dels, quoted.buf);
213 } else {
214 int saved_errno = errno;
215 quote_path(path->buf, prefix, &quoted, 0);
216 errno = saved_errno;
217 warning_errno(_(msg_warn_remove_failed), quoted.buf);
218 *dir_gone = 0;
219 ret = 1;
221 continue;
224 /* path too long, stat fails, or non-directory still exists */
225 *dir_gone = 0;
226 ret = 1;
227 break;
229 closedir(dir);
231 strbuf_setlen(path, original_len);
233 if (*dir_gone) {
234 res = dry_run ? 0 : rmdir(path->buf);
235 if (!res)
236 *dir_gone = 1;
237 else {
238 int saved_errno = errno;
239 quote_path(path->buf, prefix, &quoted, 0);
240 errno = saved_errno;
241 warning_errno(_(msg_warn_remove_failed), quoted.buf);
242 *dir_gone = 0;
243 ret = 1;
247 if (!*dir_gone && !quiet) {
248 int i;
249 for (i = 0; i < dels.nr; i++)
250 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
252 out:
253 strbuf_release(&quoted);
254 string_list_clear(&dels, 0);
255 return ret;
258 static void pretty_print_dels(void)
260 struct string_list list = STRING_LIST_INIT_DUP;
261 struct string_list_item *item;
262 struct strbuf buf = STRBUF_INIT;
263 const char *qname;
264 struct column_options copts;
266 for_each_string_list_item(item, &del_list) {
267 qname = quote_path(item->string, NULL, &buf, 0);
268 string_list_append(&list, qname);
272 * always enable column display, we only consult column.*
273 * about layout strategy and stuff
275 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
276 memset(&copts, 0, sizeof(copts));
277 copts.indent = " ";
278 copts.padding = 2;
279 print_columns(&list, colopts, &copts);
280 strbuf_release(&buf);
281 string_list_clear(&list, 0);
284 static void pretty_print_menus(struct string_list *menu_list)
286 unsigned int local_colopts = 0;
287 struct column_options copts;
289 local_colopts = COL_ENABLED | COL_ROW;
290 memset(&copts, 0, sizeof(copts));
291 copts.indent = " ";
292 copts.padding = 2;
293 print_columns(menu_list, local_colopts, &copts);
296 static void prompt_help_cmd(int singleton)
298 clean_print_color(CLEAN_COLOR_HELP);
299 printf(singleton ?
300 _("Prompt help:\n"
301 "1 - select a numbered item\n"
302 "foo - select item based on unique prefix\n"
303 " - (empty) select nothing\n") :
304 _("Prompt help:\n"
305 "1 - select a single item\n"
306 "3-5 - select a range of items\n"
307 "2-3,6-9 - select multiple ranges\n"
308 "foo - select item based on unique prefix\n"
309 "-... - unselect specified items\n"
310 "* - choose all items\n"
311 " - (empty) finish selecting\n"));
312 clean_print_color(CLEAN_COLOR_RESET);
316 * display menu stuff with number prefix and hotkey highlight
318 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
320 struct string_list menu_list = STRING_LIST_INIT_DUP;
321 struct strbuf menu = STRBUF_INIT;
322 struct menu_item *menu_item;
323 struct string_list_item *string_list_item;
324 int i;
326 switch (stuff->type) {
327 default:
328 die("Bad type of menu_stuff when print menu");
329 case MENU_STUFF_TYPE_MENU_ITEM:
330 menu_item = (struct menu_item *)stuff->stuff;
331 for (i = 0; i < stuff->nr; i++, menu_item++) {
332 const char *p;
333 int highlighted = 0;
335 p = menu_item->title;
336 if ((*chosen)[i] < 0)
337 (*chosen)[i] = menu_item->selected ? 1 : 0;
338 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
339 for (; *p; p++) {
340 if (!highlighted && *p == menu_item->hotkey) {
341 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
342 strbuf_addch(&menu, *p);
343 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
344 highlighted = 1;
345 } else {
346 strbuf_addch(&menu, *p);
349 string_list_append(&menu_list, menu.buf);
350 strbuf_reset(&menu);
352 break;
353 case MENU_STUFF_TYPE_STRING_LIST:
354 i = 0;
355 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
356 if ((*chosen)[i] < 0)
357 (*chosen)[i] = 0;
358 strbuf_addf(&menu, "%s%2d: %s",
359 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
360 string_list_append(&menu_list, menu.buf);
361 strbuf_reset(&menu);
362 i++;
364 break;
367 pretty_print_menus(&menu_list);
369 strbuf_release(&menu);
370 string_list_clear(&menu_list, 0);
373 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
375 struct menu_item *menu_item;
376 struct string_list_item *string_list_item;
377 int i, len, found = 0;
379 len = strlen(choice);
380 switch (menu_stuff->type) {
381 default:
382 die("Bad type of menu_stuff when parse choice");
383 case MENU_STUFF_TYPE_MENU_ITEM:
385 menu_item = (struct menu_item *)menu_stuff->stuff;
386 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
387 if (len == 1 && *choice == menu_item->hotkey) {
388 found = i + 1;
389 break;
391 if (!strncasecmp(choice, menu_item->title, len)) {
392 if (found) {
393 if (len == 1) {
394 /* continue for hotkey matching */
395 found = -1;
396 } else {
397 found = 0;
398 break;
400 } else {
401 found = i + 1;
405 break;
406 case MENU_STUFF_TYPE_STRING_LIST:
407 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
408 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
409 if (!strncasecmp(choice, string_list_item->string, len)) {
410 if (found) {
411 found = 0;
412 break;
414 found = i + 1;
417 break;
419 return found;
423 * Parse user input, and return choice(s) for menu (menu_stuff).
425 * Input
426 * (for single choice)
427 * 1 - select a numbered item
428 * foo - select item based on menu title
429 * - (empty) select nothing
431 * (for multiple choice)
432 * 1 - select a single item
433 * 3-5 - select a range of items
434 * 2-3,6-9 - select multiple ranges
435 * foo - select item based on menu title
436 * -... - unselect specified items
437 * * - choose all items
438 * - (empty) finish selecting
440 * The parse result will be saved in array **chosen, and
441 * return number of total selections.
443 static int parse_choice(struct menu_stuff *menu_stuff,
444 int is_single,
445 struct strbuf input,
446 int **chosen)
448 struct strbuf **choice_list, **ptr;
449 int nr = 0;
450 int i;
452 if (is_single) {
453 choice_list = strbuf_split_max(&input, '\n', 0);
454 } else {
455 char *p = input.buf;
456 do {
457 if (*p == ',')
458 *p = ' ';
459 } while (*p++);
460 choice_list = strbuf_split_max(&input, ' ', 0);
463 for (ptr = choice_list; *ptr; ptr++) {
464 char *p;
465 int choose = 1;
466 int bottom = 0, top = 0;
467 int is_range, is_number;
469 strbuf_trim(*ptr);
470 if (!(*ptr)->len)
471 continue;
473 /* Input that begins with '-'; unchoose */
474 if (*(*ptr)->buf == '-') {
475 choose = 0;
476 strbuf_remove((*ptr), 0, 1);
479 is_range = 0;
480 is_number = 1;
481 for (p = (*ptr)->buf; *p; p++) {
482 if ('-' == *p) {
483 if (!is_range) {
484 is_range = 1;
485 is_number = 0;
486 } else {
487 is_number = 0;
488 is_range = 0;
489 break;
491 } else if (!isdigit(*p)) {
492 is_number = 0;
493 is_range = 0;
494 break;
498 if (is_number) {
499 bottom = atoi((*ptr)->buf);
500 top = bottom;
501 } else if (is_range) {
502 bottom = atoi((*ptr)->buf);
503 /* a range can be specified like 5-7 or 5- */
504 if (!*(strchr((*ptr)->buf, '-') + 1))
505 top = menu_stuff->nr;
506 else
507 top = atoi(strchr((*ptr)->buf, '-') + 1);
508 } else if (!strcmp((*ptr)->buf, "*")) {
509 bottom = 1;
510 top = menu_stuff->nr;
511 } else {
512 bottom = find_unique((*ptr)->buf, menu_stuff);
513 top = bottom;
516 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
517 (is_single && bottom != top)) {
518 clean_print_color(CLEAN_COLOR_ERROR);
519 printf(_("Huh (%s)?\n"), (*ptr)->buf);
520 clean_print_color(CLEAN_COLOR_RESET);
521 continue;
524 for (i = bottom; i <= top; i++)
525 (*chosen)[i-1] = choose;
528 strbuf_list_free(choice_list);
530 for (i = 0; i < menu_stuff->nr; i++)
531 nr += (*chosen)[i];
532 return nr;
536 * Implement a git-add-interactive compatible UI, which is borrowed
537 * from git-add--interactive.perl.
539 * Return value:
541 * - Return an array of integers
542 * - , and it is up to you to free the allocated memory.
543 * - The array ends with EOF.
544 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
546 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
548 struct strbuf choice = STRBUF_INIT;
549 int *chosen, *result;
550 int nr = 0;
551 int eof = 0;
552 int i;
554 ALLOC_ARRAY(chosen, stuff->nr);
555 /* set chosen as uninitialized */
556 for (i = 0; i < stuff->nr; i++)
557 chosen[i] = -1;
559 for (;;) {
560 if (opts->header) {
561 printf_ln("%s%s%s",
562 clean_get_color(CLEAN_COLOR_HEADER),
563 _(opts->header),
564 clean_get_color(CLEAN_COLOR_RESET));
567 /* chosen will be initialized by print_highlight_menu_stuff */
568 print_highlight_menu_stuff(stuff, &chosen);
570 if (opts->flags & MENU_OPTS_LIST_ONLY)
571 break;
573 if (opts->prompt) {
574 printf("%s%s%s%s",
575 clean_get_color(CLEAN_COLOR_PROMPT),
576 _(opts->prompt),
577 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
578 clean_get_color(CLEAN_COLOR_RESET));
581 if (git_read_line_interactively(&choice) == EOF) {
582 eof = 1;
583 break;
586 /* help for prompt */
587 if (!strcmp(choice.buf, "?")) {
588 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
589 continue;
592 /* for a multiple-choice menu, press ENTER (empty) will return back */
593 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
594 break;
596 nr = parse_choice(stuff,
597 opts->flags & MENU_OPTS_SINGLETON,
598 choice,
599 &chosen);
601 if (opts->flags & MENU_OPTS_SINGLETON) {
602 if (nr)
603 break;
604 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
605 break;
609 if (eof) {
610 result = xmalloc(sizeof(int));
611 *result = EOF;
612 } else {
613 int j = 0;
616 * recalculate nr, if return back from menu directly with
617 * default selections.
619 if (!nr) {
620 for (i = 0; i < stuff->nr; i++)
621 nr += chosen[i];
624 CALLOC_ARRAY(result, st_add(nr, 1));
625 for (i = 0; i < stuff->nr && j < nr; i++) {
626 if (chosen[i])
627 result[j++] = i;
629 result[j] = EOF;
632 free(chosen);
633 strbuf_release(&choice);
634 return result;
637 static int clean_cmd(void)
639 return MENU_RETURN_NO_LOOP;
642 static int filter_by_patterns_cmd(void)
644 struct dir_struct dir = DIR_INIT;
645 struct strbuf confirm = STRBUF_INIT;
646 struct strbuf **ignore_list;
647 struct string_list_item *item;
648 struct pattern_list *pl;
649 int changed = -1, i;
651 for (;;) {
652 if (!del_list.nr)
653 break;
655 if (changed)
656 pretty_print_dels();
658 clean_print_color(CLEAN_COLOR_PROMPT);
659 printf(_("Input ignore patterns>> "));
660 clean_print_color(CLEAN_COLOR_RESET);
661 if (git_read_line_interactively(&confirm) == EOF)
662 putchar('\n');
664 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
665 if (!confirm.len)
666 break;
668 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
669 ignore_list = strbuf_split_max(&confirm, ' ', 0);
671 for (i = 0; ignore_list[i]; i++) {
672 strbuf_trim(ignore_list[i]);
673 if (!ignore_list[i]->len)
674 continue;
676 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
679 changed = 0;
680 for_each_string_list_item(item, &del_list) {
681 int dtype = DT_UNKNOWN;
683 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
684 *item->string = '\0';
685 changed++;
689 if (changed) {
690 string_list_remove_empty_items(&del_list, 0);
691 } else {
692 clean_print_color(CLEAN_COLOR_ERROR);
693 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
694 clean_print_color(CLEAN_COLOR_RESET);
697 strbuf_list_free(ignore_list);
698 dir_clear(&dir);
701 strbuf_release(&confirm);
702 return 0;
705 static int select_by_numbers_cmd(void)
707 struct menu_opts menu_opts;
708 struct menu_stuff menu_stuff;
709 struct string_list_item *items;
710 int *chosen;
711 int i, j;
713 menu_opts.header = NULL;
714 menu_opts.prompt = N_("Select items to delete");
715 menu_opts.flags = 0;
717 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
718 menu_stuff.stuff = &del_list;
719 menu_stuff.nr = del_list.nr;
721 chosen = list_and_choose(&menu_opts, &menu_stuff);
722 items = del_list.items;
723 for (i = 0, j = 0; i < del_list.nr; i++) {
724 if (i < chosen[j]) {
725 *(items[i].string) = '\0';
726 } else if (i == chosen[j]) {
727 /* delete selected item */
728 j++;
729 continue;
730 } else {
731 /* end of chosen (chosen[j] == EOF), won't delete */
732 *(items[i].string) = '\0';
736 string_list_remove_empty_items(&del_list, 0);
738 free(chosen);
739 return 0;
742 static int ask_each_cmd(void)
744 struct strbuf confirm = STRBUF_INIT;
745 struct strbuf buf = STRBUF_INIT;
746 struct string_list_item *item;
747 const char *qname;
748 int changed = 0, eof = 0;
750 for_each_string_list_item(item, &del_list) {
751 /* Ctrl-D should stop removing files */
752 if (!eof) {
753 qname = quote_path(item->string, NULL, &buf, 0);
754 /* TRANSLATORS: Make sure to keep [y/N] as is */
755 printf(_("Remove %s [y/N]? "), qname);
756 if (git_read_line_interactively(&confirm) == EOF) {
757 putchar('\n');
758 eof = 1;
761 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
762 *item->string = '\0';
763 changed++;
767 if (changed)
768 string_list_remove_empty_items(&del_list, 0);
770 strbuf_release(&buf);
771 strbuf_release(&confirm);
772 return MENU_RETURN_NO_LOOP;
775 static int quit_cmd(void)
777 string_list_clear(&del_list, 0);
778 printf(_("Bye.\n"));
779 return MENU_RETURN_NO_LOOP;
782 static int help_cmd(void)
784 clean_print_color(CLEAN_COLOR_HELP);
785 printf_ln(_(
786 "clean - start cleaning\n"
787 "filter by pattern - exclude items from deletion\n"
788 "select by numbers - select items to be deleted by numbers\n"
789 "ask each - confirm each deletion (like \"rm -i\")\n"
790 "quit - stop cleaning\n"
791 "help - this screen\n"
792 "? - help for prompt selection"
794 clean_print_color(CLEAN_COLOR_RESET);
795 return 0;
798 static void interactive_main_loop(void)
800 while (del_list.nr) {
801 struct menu_opts menu_opts;
802 struct menu_stuff menu_stuff;
803 struct menu_item menus[] = {
804 {'c', "clean", 0, clean_cmd},
805 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
806 {'s', "select by numbers", 0, select_by_numbers_cmd},
807 {'a', "ask each", 0, ask_each_cmd},
808 {'q', "quit", 0, quit_cmd},
809 {'h', "help", 0, help_cmd},
811 int *chosen;
813 menu_opts.header = N_("*** Commands ***");
814 menu_opts.prompt = N_("What now");
815 menu_opts.flags = MENU_OPTS_SINGLETON;
817 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
818 menu_stuff.stuff = menus;
819 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
821 clean_print_color(CLEAN_COLOR_HEADER);
822 printf_ln(Q_("Would remove the following item:",
823 "Would remove the following items:",
824 del_list.nr));
825 clean_print_color(CLEAN_COLOR_RESET);
827 pretty_print_dels();
829 chosen = list_and_choose(&menu_opts, &menu_stuff);
831 if (*chosen != EOF) {
832 int ret;
833 ret = menus[*chosen].fn();
834 if (ret != MENU_RETURN_NO_LOOP) {
835 FREE_AND_NULL(chosen);
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_AND_NULL(chosen);
849 break;
853 static void correct_untracked_entries(struct dir_struct *dir)
855 int src, dst, ign;
857 for (src = dst = ign = 0; src < dir->nr; src++) {
858 /* skip paths in ignored[] that cannot be inside entries[src] */
859 while (ign < dir->ignored_nr &&
860 0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
861 ign++;
863 if (ign < dir->ignored_nr &&
864 check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
865 /* entries[src] contains an ignored path, so we drop it */
866 free(dir->entries[src]);
867 } else {
868 struct dir_entry *ent = dir->entries[src++];
870 /* entries[src] does not contain an ignored path, so we keep it */
871 dir->entries[dst++] = ent;
873 /* then discard paths in entries[] contained inside entries[src] */
874 while (src < dir->nr &&
875 check_dir_entry_contains(ent, dir->entries[src]))
876 free(dir->entries[src++]);
878 /* compensate for the outer loop's loop control */
879 src--;
882 dir->nr = dst;
885 int cmd_clean(int argc, const char **argv, const char *prefix)
887 int i, res;
888 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
889 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
890 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
891 struct strbuf abs_path = STRBUF_INIT;
892 struct dir_struct dir = DIR_INIT;
893 struct pathspec pathspec;
894 struct strbuf buf = STRBUF_INIT;
895 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
896 struct pattern_list *pl;
897 struct string_list_item *item;
898 const char *qname;
899 struct option options[] = {
900 OPT__QUIET(&quiet, N_("do not print names of files removed")),
901 OPT__DRY_RUN(&dry_run, N_("dry run")),
902 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
903 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
904 OPT_BOOL('d', NULL, &remove_directories,
905 N_("remove whole directories")),
906 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
907 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
908 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
909 OPT_BOOL('X', NULL, &ignored_only,
910 N_("remove only ignored files")),
911 OPT_END()
914 git_config(git_clean_config, NULL);
915 if (force < 0)
916 force = 0;
917 else
918 config_set = 1;
920 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
923 if (!interactive && !dry_run && !force) {
924 if (config_set)
925 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
926 "refusing to clean"));
927 else
928 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
929 " refusing to clean"));
932 if (force > 1)
933 rm_flags = 0;
934 else
935 dir.flags |= DIR_SKIP_NESTED_GIT;
937 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
939 if (ignored && ignored_only)
940 die(_("-x and -X cannot be used together"));
941 if (!ignored)
942 setup_standard_excludes(&dir);
943 if (ignored_only)
944 dir.flags |= DIR_SHOW_IGNORED;
946 if (argc) {
948 * Remaining args implies pathspecs specified, and we should
949 * recurse within those.
951 remove_directories = 1;
954 if (remove_directories && !ignored_only) {
956 * We need to know about ignored files too:
958 * If (ignored), then we will delete ignored files as well.
960 * If (!ignored), then even though we not are doing
961 * anything with ignored files, we need to know about them
962 * so that we can avoid deleting a directory of untracked
963 * files that also contains an ignored file within it.
965 * For the (!ignored) case, since we only need to avoid
966 * deleting ignored files, we can set
967 * DIR_SHOW_IGNORED_TOO_MODE_MATCHING in order to avoid
968 * recursing into a directory which is itself ignored.
970 dir.flags |= DIR_SHOW_IGNORED_TOO;
971 if (!ignored)
972 dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
975 * Let the fill_directory() machinery know that we aren't
976 * just recursing to collect the ignored files; we want all
977 * the untracked ones so that we can delete them. (Note:
978 * we could also set DIR_KEEP_UNTRACKED_CONTENTS when
979 * ignored_only is true, since DIR_KEEP_UNTRACKED_CONTENTS
980 * only has effect in combination with DIR_SHOW_IGNORED_TOO. It makes
981 * the code clearer to exclude it, though.
983 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
986 if (read_cache() < 0)
987 die(_("index file corrupt"));
989 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
990 for (i = 0; i < exclude_list.nr; i++)
991 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
993 parse_pathspec(&pathspec, 0,
994 PATHSPEC_PREFER_CWD,
995 prefix, argv);
997 fill_directory(&dir, &the_index, &pathspec);
998 correct_untracked_entries(&dir);
1000 for (i = 0; i < dir.nr; i++) {
1001 struct dir_entry *ent = dir.entries[i];
1002 struct stat st;
1003 const char *rel;
1005 if (!cache_name_is_other(ent->name, ent->len))
1006 continue;
1008 if (lstat(ent->name, &st))
1009 die_errno("Cannot lstat '%s'", ent->name);
1011 if (S_ISDIR(st.st_mode) && !remove_directories)
1012 continue;
1014 rel = relative_path(ent->name, prefix, &buf);
1015 string_list_append(&del_list, rel);
1018 dir_clear(&dir);
1020 if (interactive && del_list.nr > 0)
1021 interactive_main_loop();
1023 for_each_string_list_item(item, &del_list) {
1024 struct stat st;
1026 strbuf_reset(&abs_path);
1027 if (prefix)
1028 strbuf_addstr(&abs_path, prefix);
1030 strbuf_addstr(&abs_path, item->string);
1033 * we might have removed this as part of earlier
1034 * recursive directory removal, so lstat() here could
1035 * fail with ENOENT.
1037 if (lstat(abs_path.buf, &st))
1038 continue;
1040 if (S_ISDIR(st.st_mode)) {
1041 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1042 errors++;
1043 if (gone && !quiet) {
1044 qname = quote_path(item->string, NULL, &buf, 0);
1045 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1047 } else {
1048 res = dry_run ? 0 : unlink(abs_path.buf);
1049 if (res) {
1050 int saved_errno = errno;
1051 qname = quote_path(item->string, NULL, &buf, 0);
1052 errno = saved_errno;
1053 warning_errno(_(msg_warn_remove_failed), qname);
1054 errors++;
1055 } else if (!quiet) {
1056 qname = quote_path(item->string, NULL, &buf, 0);
1057 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1062 strbuf_release(&abs_path);
1063 strbuf_release(&buf);
1064 string_list_clear(&del_list, 0);
1065 string_list_clear(&exclude_list, 0);
1066 return (errors != 0);