Merge branch 'jt/fsck-code-cleanup' into maint
[git] / builtin / clean.c
1 /*
2  * "git clean" builtin command
3  *
4  * Copyright (C) 2007 Shawn Bohrer
5  *
6  * Based on git-clean.sh by Pavel Roskin
7  */
8
9 #include "builtin.h"
10 #include "cache.h"
11 #include "config.h"
12 #include "dir.h"
13 #include "parse-options.h"
14 #include "string-list.h"
15 #include "quote.h"
16 #include "column.h"
17 #include "color.h"
18 #include "pathspec.h"
19
20 static int force = -1; /* unset */
21 static int interactive;
22 static struct string_list del_list = STRING_LIST_INIT_DUP;
23 static unsigned int colopts;
24
25 static const char *const builtin_clean_usage[] = {
26         N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
27         NULL
28 };
29
30 static const char *msg_remove = N_("Removing %s\n");
31 static const char *msg_would_remove = N_("Would remove %s\n");
32 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
33 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
34 static const char *msg_warn_remove_failed = N_("failed to remove %s");
35
36 enum color_clean {
37         CLEAN_COLOR_RESET = 0,
38         CLEAN_COLOR_PLAIN = 1,
39         CLEAN_COLOR_PROMPT = 2,
40         CLEAN_COLOR_HEADER = 3,
41         CLEAN_COLOR_HELP = 4,
42         CLEAN_COLOR_ERROR = 5
43 };
44
45 static int clean_use_color = -1;
46 static char clean_colors[][COLOR_MAXLEN] = {
47         [CLEAN_COLOR_ERROR] = GIT_COLOR_BOLD_RED,
48         [CLEAN_COLOR_HEADER] = GIT_COLOR_BOLD,
49         [CLEAN_COLOR_HELP] = GIT_COLOR_BOLD_RED,
50         [CLEAN_COLOR_PLAIN] = GIT_COLOR_NORMAL,
51         [CLEAN_COLOR_PROMPT] = GIT_COLOR_BOLD_BLUE,
52         [CLEAN_COLOR_RESET] = GIT_COLOR_RESET,
53 };
54
55 #define MENU_OPTS_SINGLETON             01
56 #define MENU_OPTS_IMMEDIATE             02
57 #define MENU_OPTS_LIST_ONLY             04
58
59 struct menu_opts {
60         const char *header;
61         const char *prompt;
62         int flags;
63 };
64
65 #define MENU_RETURN_NO_LOOP             10
66
67 struct menu_item {
68         char hotkey;
69         const char *title;
70         int selected;
71         int (*fn)(void);
72 };
73
74 enum menu_stuff_type {
75         MENU_STUFF_TYPE_STRING_LIST = 1,
76         MENU_STUFF_TYPE_MENU_ITEM
77 };
78
79 struct menu_stuff {
80         enum menu_stuff_type type;
81         int nr;
82         void *stuff;
83 };
84
85 static int parse_clean_color_slot(const char *var)
86 {
87         if (!strcasecmp(var, "reset"))
88                 return CLEAN_COLOR_RESET;
89         if (!strcasecmp(var, "plain"))
90                 return CLEAN_COLOR_PLAIN;
91         if (!strcasecmp(var, "prompt"))
92                 return CLEAN_COLOR_PROMPT;
93         if (!strcasecmp(var, "header"))
94                 return CLEAN_COLOR_HEADER;
95         if (!strcasecmp(var, "help"))
96                 return CLEAN_COLOR_HELP;
97         if (!strcasecmp(var, "error"))
98                 return CLEAN_COLOR_ERROR;
99         return -1;
100 }
101
102 static int git_clean_config(const char *var, const char *value, void *cb)
103 {
104         const char *slot_name;
105
106         if (starts_with(var, "column."))
107                 return git_column_config(var, value, "clean", &colopts);
108
109         /* honors the color.interactive* config variables which also
110            applied in git-add--interactive and git-stash */
111         if (!strcmp(var, "color.interactive")) {
112                 clean_use_color = git_config_colorbool(var, value);
113                 return 0;
114         }
115         if (skip_prefix(var, "color.interactive.", &slot_name)) {
116                 int slot = parse_clean_color_slot(slot_name);
117                 if (slot < 0)
118                         return 0;
119                 if (!value)
120                         return config_error_nonbool(var);
121                 return color_parse(value, clean_colors[slot]);
122         }
123
124         if (!strcmp(var, "clean.requireforce")) {
125                 force = !git_config_bool(var, value);
126                 return 0;
127         }
128
129         /* inspect the color.ui config variable and others */
130         return git_color_default_config(var, value, cb);
131 }
132
133 static const char *clean_get_color(enum color_clean ix)
134 {
135         if (want_color(clean_use_color))
136                 return clean_colors[ix];
137         return "";
138 }
139
140 static void clean_print_color(enum color_clean ix)
141 {
142         printf("%s", clean_get_color(ix));
143 }
144
145 static int exclude_cb(const struct option *opt, const char *arg, int unset)
146 {
147         struct string_list *exclude_list = opt->value;
148         string_list_append(exclude_list, arg);
149         return 0;
150 }
151
152 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
153                 int dry_run, int quiet, int *dir_gone)
154 {
155         DIR *dir;
156         struct strbuf quoted = STRBUF_INIT;
157         struct dirent *e;
158         int res = 0, ret = 0, gone = 1, original_len = path->len, len;
159         struct string_list dels = STRING_LIST_INIT_DUP;
160
161         *dir_gone = 1;
162
163         if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) && is_nonbare_repository_dir(path)) {
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);
168                 }
169
170                 *dir_gone = 0;
171                 goto out;
172         }
173
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_relative(path->buf, prefix, &quoted);
181                         errno = saved_errno;
182                         warning_errno(_(msg_warn_remove_failed), quoted.buf);
183                         *dir_gone = 0;
184                 }
185                 ret = res;
186                 goto out;
187         }
188
189         strbuf_complete(path, '/');
190
191         len = path->len;
192         while ((e = readdir(dir)) != NULL) {
193                 struct stat st;
194                 if (is_dot_or_dotdot(e->d_name))
195                         continue;
196
197                 strbuf_setlen(path, len);
198                 strbuf_addstr(path, e->d_name);
199                 if (lstat(path->buf, &st))
200                         ; /* fall thru */
201                 else if (S_ISDIR(st.st_mode)) {
202                         if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
203                                 ret = 1;
204                         if (gone) {
205                                 quote_path_relative(path->buf, prefix, &quoted);
206                                 string_list_append(&dels, quoted.buf);
207                         } else
208                                 *dir_gone = 0;
209                         continue;
210                 } else {
211                         res = dry_run ? 0 : unlink(path->buf);
212                         if (!res) {
213                                 quote_path_relative(path->buf, prefix, &quoted);
214                                 string_list_append(&dels, quoted.buf);
215                         } else {
216                                 int saved_errno = errno;
217                                 quote_path_relative(path->buf, prefix, &quoted);
218                                 errno = saved_errno;
219                                 warning_errno(_(msg_warn_remove_failed), quoted.buf);
220                                 *dir_gone = 0;
221                                 ret = 1;
222                         }
223                         continue;
224                 }
225
226                 /* path too long, stat fails, or non-directory still exists */
227                 *dir_gone = 0;
228                 ret = 1;
229                 break;
230         }
231         closedir(dir);
232
233         strbuf_setlen(path, original_len);
234
235         if (*dir_gone) {
236                 res = dry_run ? 0 : rmdir(path->buf);
237                 if (!res)
238                         *dir_gone = 1;
239                 else {
240                         int saved_errno = errno;
241                         quote_path_relative(path->buf, prefix, &quoted);
242                         errno = saved_errno;
243                         warning_errno(_(msg_warn_remove_failed), quoted.buf);
244                         *dir_gone = 0;
245                         ret = 1;
246                 }
247         }
248
249         if (!*dir_gone && !quiet) {
250                 int i;
251                 for (i = 0; i < dels.nr; i++)
252                         printf(dry_run ?  _(msg_would_remove) : _(msg_remove), dels.items[i].string);
253         }
254 out:
255         strbuf_release(&quoted);
256         string_list_clear(&dels, 0);
257         return ret;
258 }
259
260 static void pretty_print_dels(void)
261 {
262         struct string_list list = STRING_LIST_INIT_DUP;
263         struct string_list_item *item;
264         struct strbuf buf = STRBUF_INIT;
265         const char *qname;
266         struct column_options copts;
267
268         for_each_string_list_item(item, &del_list) {
269                 qname = quote_path_relative(item->string, NULL, &buf);
270                 string_list_append(&list, qname);
271         }
272
273         /*
274          * always enable column display, we only consult column.*
275          * about layout strategy and stuff
276          */
277         colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
278         memset(&copts, 0, sizeof(copts));
279         copts.indent = "  ";
280         copts.padding = 2;
281         print_columns(&list, colopts, &copts);
282         strbuf_release(&buf);
283         string_list_clear(&list, 0);
284 }
285
286 static void pretty_print_menus(struct string_list *menu_list)
287 {
288         unsigned int local_colopts = 0;
289         struct column_options copts;
290
291         local_colopts = COL_ENABLED | COL_ROW;
292         memset(&copts, 0, sizeof(copts));
293         copts.indent = "  ";
294         copts.padding = 2;
295         print_columns(menu_list, local_colopts, &copts);
296 }
297
298 static void prompt_help_cmd(int singleton)
299 {
300         clean_print_color(CLEAN_COLOR_HELP);
301         printf(singleton ?
302                   _("Prompt help:\n"
303                     "1          - select a numbered item\n"
304                     "foo        - select item based on unique prefix\n"
305                     "           - (empty) select nothing\n") :
306                   _("Prompt help:\n"
307                     "1          - select a single item\n"
308                     "3-5        - select a range of items\n"
309                     "2-3,6-9    - select multiple ranges\n"
310                     "foo        - select item based on unique prefix\n"
311                     "-...       - unselect specified items\n"
312                     "*          - choose all items\n"
313                     "           - (empty) finish selecting\n"));
314         clean_print_color(CLEAN_COLOR_RESET);
315 }
316
317 /*
318  * display menu stuff with number prefix and hotkey highlight
319  */
320 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
321 {
322         struct string_list menu_list = STRING_LIST_INIT_DUP;
323         struct strbuf menu = STRBUF_INIT;
324         struct menu_item *menu_item;
325         struct string_list_item *string_list_item;
326         int i;
327
328         switch (stuff->type) {
329         default:
330                 die("Bad type of menu_stuff when print menu");
331         case MENU_STUFF_TYPE_MENU_ITEM:
332                 menu_item = (struct menu_item *)stuff->stuff;
333                 for (i = 0; i < stuff->nr; i++, menu_item++) {
334                         const char *p;
335                         int highlighted = 0;
336
337                         p = menu_item->title;
338                         if ((*chosen)[i] < 0)
339                                 (*chosen)[i] = menu_item->selected ? 1 : 0;
340                         strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
341                         for (; *p; p++) {
342                                 if (!highlighted && *p == menu_item->hotkey) {
343                                         strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
344                                         strbuf_addch(&menu, *p);
345                                         strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
346                                         highlighted = 1;
347                                 } else {
348                                         strbuf_addch(&menu, *p);
349                                 }
350                         }
351                         string_list_append(&menu_list, menu.buf);
352                         strbuf_reset(&menu);
353                 }
354                 break;
355         case MENU_STUFF_TYPE_STRING_LIST:
356                 i = 0;
357                 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
358                         if ((*chosen)[i] < 0)
359                                 (*chosen)[i] = 0;
360                         strbuf_addf(&menu, "%s%2d: %s",
361                                     (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
362                         string_list_append(&menu_list, menu.buf);
363                         strbuf_reset(&menu);
364                         i++;
365                 }
366                 break;
367         }
368
369         pretty_print_menus(&menu_list);
370
371         strbuf_release(&menu);
372         string_list_clear(&menu_list, 0);
373 }
374
375 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
376 {
377         struct menu_item *menu_item;
378         struct string_list_item *string_list_item;
379         int i, len, found = 0;
380
381         len = strlen(choice);
382         switch (menu_stuff->type) {
383         default:
384                 die("Bad type of menu_stuff when parse choice");
385         case MENU_STUFF_TYPE_MENU_ITEM:
386
387                 menu_item = (struct menu_item *)menu_stuff->stuff;
388                 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
389                         if (len == 1 && *choice == menu_item->hotkey) {
390                                 found = i + 1;
391                                 break;
392                         }
393                         if (!strncasecmp(choice, menu_item->title, len)) {
394                                 if (found) {
395                                         if (len == 1) {
396                                                 /* continue for hotkey matching */
397                                                 found = -1;
398                                         } else {
399                                                 found = 0;
400                                                 break;
401                                         }
402                                 } else {
403                                         found = i + 1;
404                                 }
405                         }
406                 }
407                 break;
408         case MENU_STUFF_TYPE_STRING_LIST:
409                 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
410                 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
411                         if (!strncasecmp(choice, string_list_item->string, len)) {
412                                 if (found) {
413                                         found = 0;
414                                         break;
415                                 }
416                                 found = i + 1;
417                         }
418                 }
419                 break;
420         }
421         return found;
422 }
423
424
425 /*
426  * Parse user input, and return choice(s) for menu (menu_stuff).
427  *
428  * Input
429  *     (for single choice)
430  *         1          - select a numbered item
431  *         foo        - select item based on menu title
432  *                    - (empty) select nothing
433  *
434  *     (for multiple choice)
435  *         1          - select a single item
436  *         3-5        - select a range of items
437  *         2-3,6-9    - select multiple ranges
438  *         foo        - select item based on menu title
439  *         -...       - unselect specified items
440  *         *          - choose all items
441  *                    - (empty) finish selecting
442  *
443  * The parse result will be saved in array **chosen, and
444  * return number of total selections.
445  */
446 static int parse_choice(struct menu_stuff *menu_stuff,
447                         int is_single,
448                         struct strbuf input,
449                         int **chosen)
450 {
451         struct strbuf **choice_list, **ptr;
452         int nr = 0;
453         int i;
454
455         if (is_single) {
456                 choice_list = strbuf_split_max(&input, '\n', 0);
457         } else {
458                 char *p = input.buf;
459                 do {
460                         if (*p == ',')
461                                 *p = ' ';
462                 } while (*p++);
463                 choice_list = strbuf_split_max(&input, ' ', 0);
464         }
465
466         for (ptr = choice_list; *ptr; ptr++) {
467                 char *p;
468                 int choose = 1;
469                 int bottom = 0, top = 0;
470                 int is_range, is_number;
471
472                 strbuf_trim(*ptr);
473                 if (!(*ptr)->len)
474                         continue;
475
476                 /* Input that begins with '-'; unchoose */
477                 if (*(*ptr)->buf == '-') {
478                         choose = 0;
479                         strbuf_remove((*ptr), 0, 1);
480                 }
481
482                 is_range = 0;
483                 is_number = 1;
484                 for (p = (*ptr)->buf; *p; p++) {
485                         if ('-' == *p) {
486                                 if (!is_range) {
487                                         is_range = 1;
488                                         is_number = 0;
489                                 } else {
490                                         is_number = 0;
491                                         is_range = 0;
492                                         break;
493                                 }
494                         } else if (!isdigit(*p)) {
495                                 is_number = 0;
496                                 is_range = 0;
497                                 break;
498                         }
499                 }
500
501                 if (is_number) {
502                         bottom = atoi((*ptr)->buf);
503                         top = bottom;
504                 } else if (is_range) {
505                         bottom = atoi((*ptr)->buf);
506                         /* a range can be specified like 5-7 or 5- */
507                         if (!*(strchr((*ptr)->buf, '-') + 1))
508                                 top = menu_stuff->nr;
509                         else
510                                 top = atoi(strchr((*ptr)->buf, '-') + 1);
511                 } else if (!strcmp((*ptr)->buf, "*")) {
512                         bottom = 1;
513                         top = menu_stuff->nr;
514                 } else {
515                         bottom = find_unique((*ptr)->buf, menu_stuff);
516                         top = bottom;
517                 }
518
519                 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
520                     (is_single && bottom != top)) {
521                         clean_print_color(CLEAN_COLOR_ERROR);
522                         printf(_("Huh (%s)?\n"), (*ptr)->buf);
523                         clean_print_color(CLEAN_COLOR_RESET);
524                         continue;
525                 }
526
527                 for (i = bottom; i <= top; i++)
528                         (*chosen)[i-1] = choose;
529         }
530
531         strbuf_list_free(choice_list);
532
533         for (i = 0; i < menu_stuff->nr; i++)
534                 nr += (*chosen)[i];
535         return nr;
536 }
537
538 /*
539  * Implement a git-add-interactive compatible UI, which is borrowed
540  * from git-add--interactive.perl.
541  *
542  * Return value:
543  *
544  *   - Return an array of integers
545  *   - , and it is up to you to free the allocated memory.
546  *   - The array ends with EOF.
547  *   - If user pressed CTRL-D (i.e. EOF), no selection returned.
548  */
549 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
550 {
551         struct strbuf choice = STRBUF_INIT;
552         int *chosen, *result;
553         int nr = 0;
554         int eof = 0;
555         int i;
556
557         ALLOC_ARRAY(chosen, stuff->nr);
558         /* set chosen as uninitialized */
559         for (i = 0; i < stuff->nr; i++)
560                 chosen[i] = -1;
561
562         for (;;) {
563                 if (opts->header) {
564                         printf_ln("%s%s%s",
565                                   clean_get_color(CLEAN_COLOR_HEADER),
566                                   _(opts->header),
567                                   clean_get_color(CLEAN_COLOR_RESET));
568                 }
569
570                 /* chosen will be initialized by print_highlight_menu_stuff */
571                 print_highlight_menu_stuff(stuff, &chosen);
572
573                 if (opts->flags & MENU_OPTS_LIST_ONLY)
574                         break;
575
576                 if (opts->prompt) {
577                         printf("%s%s%s%s",
578                                clean_get_color(CLEAN_COLOR_PROMPT),
579                                _(opts->prompt),
580                                opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
581                                clean_get_color(CLEAN_COLOR_RESET));
582                 }
583
584                 if (strbuf_getline_lf(&choice, stdin) != EOF) {
585                         strbuf_trim(&choice);
586                 } else {
587                         eof = 1;
588                         break;
589                 }
590
591                 /* help for prompt */
592                 if (!strcmp(choice.buf, "?")) {
593                         prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
594                         continue;
595                 }
596
597                 /* for a multiple-choice menu, press ENTER (empty) will return back */
598                 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
599                         break;
600
601                 nr = parse_choice(stuff,
602                                   opts->flags & MENU_OPTS_SINGLETON,
603                                   choice,
604                                   &chosen);
605
606                 if (opts->flags & MENU_OPTS_SINGLETON) {
607                         if (nr)
608                                 break;
609                 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
610                         break;
611                 }
612         }
613
614         if (eof) {
615                 result = xmalloc(sizeof(int));
616                 *result = EOF;
617         } else {
618                 int j = 0;
619
620                 /*
621                  * recalculate nr, if return back from menu directly with
622                  * default selections.
623                  */
624                 if (!nr) {
625                         for (i = 0; i < stuff->nr; i++)
626                                 nr += chosen[i];
627                 }
628
629                 result = xcalloc(st_add(nr, 1), sizeof(int));
630                 for (i = 0; i < stuff->nr && j < nr; i++) {
631                         if (chosen[i])
632                                 result[j++] = i;
633                 }
634                 result[j] = EOF;
635         }
636
637         free(chosen);
638         strbuf_release(&choice);
639         return result;
640 }
641
642 static int clean_cmd(void)
643 {
644         return MENU_RETURN_NO_LOOP;
645 }
646
647 static int filter_by_patterns_cmd(void)
648 {
649         struct dir_struct dir;
650         struct strbuf confirm = STRBUF_INIT;
651         struct strbuf **ignore_list;
652         struct string_list_item *item;
653         struct exclude_list *el;
654         int changed = -1, i;
655
656         for (;;) {
657                 if (!del_list.nr)
658                         break;
659
660                 if (changed)
661                         pretty_print_dels();
662
663                 clean_print_color(CLEAN_COLOR_PROMPT);
664                 printf(_("Input ignore patterns>> "));
665                 clean_print_color(CLEAN_COLOR_RESET);
666                 if (strbuf_getline_lf(&confirm, stdin) != EOF)
667                         strbuf_trim(&confirm);
668                 else
669                         putchar('\n');
670
671                 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
672                 if (!confirm.len)
673                         break;
674
675                 memset(&dir, 0, sizeof(dir));
676                 el = add_exclude_list(&dir, EXC_CMDL, "manual exclude");
677                 ignore_list = strbuf_split_max(&confirm, ' ', 0);
678
679                 for (i = 0; ignore_list[i]; i++) {
680                         strbuf_trim(ignore_list[i]);
681                         if (!ignore_list[i]->len)
682                                 continue;
683
684                         add_exclude(ignore_list[i]->buf, "", 0, el, -(i+1));
685                 }
686
687                 changed = 0;
688                 for_each_string_list_item(item, &del_list) {
689                         int dtype = DT_UNKNOWN;
690
691                         if (is_excluded(&dir, &the_index, item->string, &dtype)) {
692                                 *item->string = '\0';
693                                 changed++;
694                         }
695                 }
696
697                 if (changed) {
698                         string_list_remove_empty_items(&del_list, 0);
699                 } else {
700                         clean_print_color(CLEAN_COLOR_ERROR);
701                         printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
702                         clean_print_color(CLEAN_COLOR_RESET);
703                 }
704
705                 strbuf_list_free(ignore_list);
706                 clear_directory(&dir);
707         }
708
709         strbuf_release(&confirm);
710         return 0;
711 }
712
713 static int select_by_numbers_cmd(void)
714 {
715         struct menu_opts menu_opts;
716         struct menu_stuff menu_stuff;
717         struct string_list_item *items;
718         int *chosen;
719         int i, j;
720
721         menu_opts.header = NULL;
722         menu_opts.prompt = N_("Select items to delete");
723         menu_opts.flags = 0;
724
725         menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
726         menu_stuff.stuff = &del_list;
727         menu_stuff.nr = del_list.nr;
728
729         chosen = list_and_choose(&menu_opts, &menu_stuff);
730         items = del_list.items;
731         for (i = 0, j = 0; i < del_list.nr; i++) {
732                 if (i < chosen[j]) {
733                         *(items[i].string) = '\0';
734                 } else if (i == chosen[j]) {
735                         /* delete selected item */
736                         j++;
737                         continue;
738                 } else {
739                         /* end of chosen (chosen[j] == EOF), won't delete */
740                         *(items[i].string) = '\0';
741                 }
742         }
743
744         string_list_remove_empty_items(&del_list, 0);
745
746         free(chosen);
747         return 0;
748 }
749
750 static int ask_each_cmd(void)
751 {
752         struct strbuf confirm = STRBUF_INIT;
753         struct strbuf buf = STRBUF_INIT;
754         struct string_list_item *item;
755         const char *qname;
756         int changed = 0, eof = 0;
757
758         for_each_string_list_item(item, &del_list) {
759                 /* Ctrl-D should stop removing files */
760                 if (!eof) {
761                         qname = quote_path_relative(item->string, NULL, &buf);
762                         /* TRANSLATORS: Make sure to keep [y/N] as is */
763                         printf(_("Remove %s [y/N]? "), qname);
764                         if (strbuf_getline_lf(&confirm, stdin) != EOF) {
765                                 strbuf_trim(&confirm);
766                         } else {
767                                 putchar('\n');
768                                 eof = 1;
769                         }
770                 }
771                 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
772                         *item->string = '\0';
773                         changed++;
774                 }
775         }
776
777         if (changed)
778                 string_list_remove_empty_items(&del_list, 0);
779
780         strbuf_release(&buf);
781         strbuf_release(&confirm);
782         return MENU_RETURN_NO_LOOP;
783 }
784
785 static int quit_cmd(void)
786 {
787         string_list_clear(&del_list, 0);
788         printf(_("Bye.\n"));
789         return MENU_RETURN_NO_LOOP;
790 }
791
792 static int help_cmd(void)
793 {
794         clean_print_color(CLEAN_COLOR_HELP);
795         printf_ln(_(
796                     "clean               - start cleaning\n"
797                     "filter by pattern   - exclude items from deletion\n"
798                     "select by numbers   - select items to be deleted by numbers\n"
799                     "ask each            - confirm each deletion (like \"rm -i\")\n"
800                     "quit                - stop cleaning\n"
801                     "help                - this screen\n"
802                     "?                   - help for prompt selection"
803                    ));
804         clean_print_color(CLEAN_COLOR_RESET);
805         return 0;
806 }
807
808 static void interactive_main_loop(void)
809 {
810         while (del_list.nr) {
811                 struct menu_opts menu_opts;
812                 struct menu_stuff menu_stuff;
813                 struct menu_item menus[] = {
814                         {'c', "clean",                  0, clean_cmd},
815                         {'f', "filter by pattern",      0, filter_by_patterns_cmd},
816                         {'s', "select by numbers",      0, select_by_numbers_cmd},
817                         {'a', "ask each",               0, ask_each_cmd},
818                         {'q', "quit",                   0, quit_cmd},
819                         {'h', "help",                   0, help_cmd},
820                 };
821                 int *chosen;
822
823                 menu_opts.header = N_("*** Commands ***");
824                 menu_opts.prompt = N_("What now");
825                 menu_opts.flags = MENU_OPTS_SINGLETON;
826
827                 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
828                 menu_stuff.stuff = menus;
829                 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
830
831                 clean_print_color(CLEAN_COLOR_HEADER);
832                 printf_ln(Q_("Would remove the following item:",
833                              "Would remove the following items:",
834                              del_list.nr));
835                 clean_print_color(CLEAN_COLOR_RESET);
836
837                 pretty_print_dels();
838
839                 chosen = list_and_choose(&menu_opts, &menu_stuff);
840
841                 if (*chosen != EOF) {
842                         int ret;
843                         ret = menus[*chosen].fn();
844                         if (ret != MENU_RETURN_NO_LOOP) {
845                                 FREE_AND_NULL(chosen);
846                                 if (!del_list.nr) {
847                                         clean_print_color(CLEAN_COLOR_ERROR);
848                                         printf_ln(_("No more files to clean, exiting."));
849                                         clean_print_color(CLEAN_COLOR_RESET);
850                                         break;
851                                 }
852                                 continue;
853                         }
854                 } else {
855                         quit_cmd();
856                 }
857
858                 FREE_AND_NULL(chosen);
859                 break;
860         }
861 }
862
863 static void correct_untracked_entries(struct dir_struct *dir)
864 {
865         int src, dst, ign;
866
867         for (src = dst = ign = 0; src < dir->nr; src++) {
868                 /* skip paths in ignored[] that cannot be inside entries[src] */
869                 while (ign < dir->ignored_nr &&
870                        0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
871                         ign++;
872
873                 if (ign < dir->ignored_nr &&
874                     check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
875                         /* entries[src] contains an ignored path, so we drop it */
876                         free(dir->entries[src]);
877                 } else {
878                         struct dir_entry *ent = dir->entries[src++];
879
880                         /* entries[src] does not contain an ignored path, so we keep it */
881                         dir->entries[dst++] = ent;
882
883                         /* then discard paths in entries[] contained inside entries[src] */
884                         while (src < dir->nr &&
885                                check_dir_entry_contains(ent, dir->entries[src]))
886                                 free(dir->entries[src++]);
887
888                         /* compensate for the outer loop's loop control */
889                         src--;
890                 }
891         }
892         dir->nr = dst;
893 }
894
895 int cmd_clean(int argc, const char **argv, const char *prefix)
896 {
897         int i, res;
898         int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
899         int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
900         int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
901         struct strbuf abs_path = STRBUF_INIT;
902         struct dir_struct dir;
903         struct pathspec pathspec;
904         struct strbuf buf = STRBUF_INIT;
905         struct string_list exclude_list = STRING_LIST_INIT_NODUP;
906         struct exclude_list *el;
907         struct string_list_item *item;
908         const char *qname;
909         struct option options[] = {
910                 OPT__QUIET(&quiet, N_("do not print names of files removed")),
911                 OPT__DRY_RUN(&dry_run, N_("dry run")),
912                 OPT__FORCE(&force, N_("force")),
913                 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
914                 OPT_BOOL('d', NULL, &remove_directories,
915                                 N_("remove whole directories")),
916                 { OPTION_CALLBACK, 'e', "exclude", &exclude_list, N_("pattern"),
917                   N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb },
918                 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
919                 OPT_BOOL('X', NULL, &ignored_only,
920                                 N_("remove only ignored files")),
921                 OPT_END()
922         };
923
924         git_config(git_clean_config, NULL);
925         if (force < 0)
926                 force = 0;
927         else
928                 config_set = 1;
929
930         argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
931                              0);
932
933         memset(&dir, 0, sizeof(dir));
934         if (ignored_only)
935                 dir.flags |= DIR_SHOW_IGNORED;
936
937         if (ignored && ignored_only)
938                 die(_("-x and -X cannot be used together"));
939
940         if (!interactive && !dry_run && !force) {
941                 if (config_set)
942                         die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
943                                   "refusing to clean"));
944                 else
945                         die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
946                                   " refusing to clean"));
947         }
948
949         if (force > 1)
950                 rm_flags = 0;
951
952         dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
953
954         if (remove_directories)
955                 dir.flags |= DIR_SHOW_IGNORED_TOO | DIR_KEEP_UNTRACKED_CONTENTS;
956
957         if (read_cache() < 0)
958                 die(_("index file corrupt"));
959
960         if (!ignored)
961                 setup_standard_excludes(&dir);
962
963         el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
964         for (i = 0; i < exclude_list.nr; i++)
965                 add_exclude(exclude_list.items[i].string, "", 0, el, -(i+1));
966
967         parse_pathspec(&pathspec, 0,
968                        PATHSPEC_PREFER_CWD,
969                        prefix, argv);
970
971         fill_directory(&dir, &the_index, &pathspec);
972         correct_untracked_entries(&dir);
973
974         for (i = 0; i < dir.nr; i++) {
975                 struct dir_entry *ent = dir.entries[i];
976                 int matches = 0;
977                 struct stat st;
978                 const char *rel;
979
980                 if (!cache_name_is_other(ent->name, ent->len))
981                         continue;
982
983                 if (pathspec.nr)
984                         matches = dir_path_match(ent, &pathspec, 0, NULL);
985
986                 if (pathspec.nr && !matches)
987                         continue;
988
989                 if (lstat(ent->name, &st))
990                         die_errno("Cannot lstat '%s'", ent->name);
991
992                 if (S_ISDIR(st.st_mode) && !remove_directories &&
993                     matches != MATCHED_EXACTLY)
994                         continue;
995
996                 rel = relative_path(ent->name, prefix, &buf);
997                 string_list_append(&del_list, rel);
998         }
999
1000         for (i = 0; i < dir.nr; i++)
1001                 free(dir.entries[i]);
1002
1003         for (i = 0; i < dir.ignored_nr; i++)
1004                 free(dir.ignored[i]);
1005
1006         if (interactive && del_list.nr > 0)
1007                 interactive_main_loop();
1008
1009         for_each_string_list_item(item, &del_list) {
1010                 struct stat st;
1011
1012                 if (prefix)
1013                         strbuf_addstr(&abs_path, prefix);
1014
1015                 strbuf_addstr(&abs_path, item->string);
1016
1017                 /*
1018                  * we might have removed this as part of earlier
1019                  * recursive directory removal, so lstat() here could
1020                  * fail with ENOENT.
1021                  */
1022                 if (lstat(abs_path.buf, &st))
1023                         continue;
1024
1025                 if (S_ISDIR(st.st_mode)) {
1026                         if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1027                                 errors++;
1028                         if (gone && !quiet) {
1029                                 qname = quote_path_relative(item->string, NULL, &buf);
1030                                 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1031                         }
1032                 } else {
1033                         res = dry_run ? 0 : unlink(abs_path.buf);
1034                         if (res) {
1035                                 int saved_errno = errno;
1036                                 qname = quote_path_relative(item->string, NULL, &buf);
1037                                 errno = saved_errno;
1038                                 warning_errno(_(msg_warn_remove_failed), qname);
1039                                 errors++;
1040                         } else if (!quiet) {
1041                                 qname = quote_path_relative(item->string, NULL, &buf);
1042                                 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1043                         }
1044                 }
1045                 strbuf_reset(&abs_path);
1046         }
1047
1048         strbuf_release(&abs_path);
1049         strbuf_release(&buf);
1050         string_list_clear(&del_list, 0);
1051         string_list_clear(&exclude_list, 0);
1052         return (errors != 0);
1053 }