Imported Upstream version 2.28.0
[platform/upstream/git.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 #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"
22
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;
27
28 static const char *const builtin_clean_usage[] = {
29         N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
30         NULL
31 };
32
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");
39
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
47 };
48
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",
56 };
57
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,
66 };
67
68 #define MENU_OPTS_SINGLETON             01
69 #define MENU_OPTS_IMMEDIATE             02
70 #define MENU_OPTS_LIST_ONLY             04
71
72 struct menu_opts {
73         const char *header;
74         const char *prompt;
75         int flags;
76 };
77
78 #define MENU_RETURN_NO_LOOP             10
79
80 struct menu_item {
81         char hotkey;
82         const char *title;
83         int selected;
84         int (*fn)(void);
85 };
86
87 enum menu_stuff_type {
88         MENU_STUFF_TYPE_STRING_LIST = 1,
89         MENU_STUFF_TYPE_MENU_ITEM
90 };
91
92 struct menu_stuff {
93         enum menu_stuff_type type;
94         int nr;
95         void *stuff;
96 };
97
98 define_list_config_array(color_interactive_slots);
99
100 static int git_clean_config(const char *var, const char *value, void *cb)
101 {
102         const char *slot_name;
103
104         if (starts_with(var, "column."))
105                 return git_column_config(var, value, "clean", &colopts);
106
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;
112         }
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]);
120         }
121
122         if (!strcmp(var, "clean.requireforce")) {
123                 force = !git_config_bool(var, value);
124                 return 0;
125         }
126
127         /* inspect the color.ui config variable and others */
128         return git_color_default_config(var, value, cb);
129 }
130
131 static const char *clean_get_color(enum color_clean ix)
132 {
133         if (want_color(clean_use_color))
134                 return clean_colors[ix];
135         return "";
136 }
137
138 static void clean_print_color(enum color_clean ix)
139 {
140         printf("%s", clean_get_color(ix));
141 }
142
143 static int exclude_cb(const struct option *opt, const char *arg, int unset)
144 {
145         struct string_list *exclude_list = opt->value;
146         BUG_ON_OPT_NEG(unset);
147         string_list_append(exclude_list, arg);
148         return 0;
149 }
150
151 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
152                 int dry_run, int quiet, int *dir_gone)
153 {
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;
159
160         *dir_gone = 1;
161
162         if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
163             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                         warning_errno(_(msg_warn_lstat_failed), path->buf);
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  * Parse user input, and return choice(s) for menu (menu_stuff).
426  *
427  * Input
428  *     (for single choice)
429  *         1          - select a numbered item
430  *         foo        - select item based on menu title
431  *                    - (empty) select nothing
432  *
433  *     (for multiple choice)
434  *         1          - select a single item
435  *         3-5        - select a range of items
436  *         2-3,6-9    - select multiple ranges
437  *         foo        - select item based on menu title
438  *         -...       - unselect specified items
439  *         *          - choose all items
440  *                    - (empty) finish selecting
441  *
442  * The parse result will be saved in array **chosen, and
443  * return number of total selections.
444  */
445 static int parse_choice(struct menu_stuff *menu_stuff,
446                         int is_single,
447                         struct strbuf input,
448                         int **chosen)
449 {
450         struct strbuf **choice_list, **ptr;
451         int nr = 0;
452         int i;
453
454         if (is_single) {
455                 choice_list = strbuf_split_max(&input, '\n', 0);
456         } else {
457                 char *p = input.buf;
458                 do {
459                         if (*p == ',')
460                                 *p = ' ';
461                 } while (*p++);
462                 choice_list = strbuf_split_max(&input, ' ', 0);
463         }
464
465         for (ptr = choice_list; *ptr; ptr++) {
466                 char *p;
467                 int choose = 1;
468                 int bottom = 0, top = 0;
469                 int is_range, is_number;
470
471                 strbuf_trim(*ptr);
472                 if (!(*ptr)->len)
473                         continue;
474
475                 /* Input that begins with '-'; unchoose */
476                 if (*(*ptr)->buf == '-') {
477                         choose = 0;
478                         strbuf_remove((*ptr), 0, 1);
479                 }
480
481                 is_range = 0;
482                 is_number = 1;
483                 for (p = (*ptr)->buf; *p; p++) {
484                         if ('-' == *p) {
485                                 if (!is_range) {
486                                         is_range = 1;
487                                         is_number = 0;
488                                 } else {
489                                         is_number = 0;
490                                         is_range = 0;
491                                         break;
492                                 }
493                         } else if (!isdigit(*p)) {
494                                 is_number = 0;
495                                 is_range = 0;
496                                 break;
497                         }
498                 }
499
500                 if (is_number) {
501                         bottom = atoi((*ptr)->buf);
502                         top = bottom;
503                 } else if (is_range) {
504                         bottom = atoi((*ptr)->buf);
505                         /* a range can be specified like 5-7 or 5- */
506                         if (!*(strchr((*ptr)->buf, '-') + 1))
507                                 top = menu_stuff->nr;
508                         else
509                                 top = atoi(strchr((*ptr)->buf, '-') + 1);
510                 } else if (!strcmp((*ptr)->buf, "*")) {
511                         bottom = 1;
512                         top = menu_stuff->nr;
513                 } else {
514                         bottom = find_unique((*ptr)->buf, menu_stuff);
515                         top = bottom;
516                 }
517
518                 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
519                     (is_single && bottom != top)) {
520                         clean_print_color(CLEAN_COLOR_ERROR);
521                         printf(_("Huh (%s)?\n"), (*ptr)->buf);
522                         clean_print_color(CLEAN_COLOR_RESET);
523                         continue;
524                 }
525
526                 for (i = bottom; i <= top; i++)
527                         (*chosen)[i-1] = choose;
528         }
529
530         strbuf_list_free(choice_list);
531
532         for (i = 0; i < menu_stuff->nr; i++)
533                 nr += (*chosen)[i];
534         return nr;
535 }
536
537 /*
538  * Implement a git-add-interactive compatible UI, which is borrowed
539  * from git-add--interactive.perl.
540  *
541  * Return value:
542  *
543  *   - Return an array of integers
544  *   - , and it is up to you to free the allocated memory.
545  *   - The array ends with EOF.
546  *   - If user pressed CTRL-D (i.e. EOF), no selection returned.
547  */
548 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
549 {
550         struct strbuf choice = STRBUF_INIT;
551         int *chosen, *result;
552         int nr = 0;
553         int eof = 0;
554         int i;
555
556         ALLOC_ARRAY(chosen, stuff->nr);
557         /* set chosen as uninitialized */
558         for (i = 0; i < stuff->nr; i++)
559                 chosen[i] = -1;
560
561         for (;;) {
562                 if (opts->header) {
563                         printf_ln("%s%s%s",
564                                   clean_get_color(CLEAN_COLOR_HEADER),
565                                   _(opts->header),
566                                   clean_get_color(CLEAN_COLOR_RESET));
567                 }
568
569                 /* chosen will be initialized by print_highlight_menu_stuff */
570                 print_highlight_menu_stuff(stuff, &chosen);
571
572                 if (opts->flags & MENU_OPTS_LIST_ONLY)
573                         break;
574
575                 if (opts->prompt) {
576                         printf("%s%s%s%s",
577                                clean_get_color(CLEAN_COLOR_PROMPT),
578                                _(opts->prompt),
579                                opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
580                                clean_get_color(CLEAN_COLOR_RESET));
581                 }
582
583                 if (git_read_line_interactively(&choice) == EOF) {
584                         eof = 1;
585                         break;
586                 }
587
588                 /* help for prompt */
589                 if (!strcmp(choice.buf, "?")) {
590                         prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
591                         continue;
592                 }
593
594                 /* for a multiple-choice menu, press ENTER (empty) will return back */
595                 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
596                         break;
597
598                 nr = parse_choice(stuff,
599                                   opts->flags & MENU_OPTS_SINGLETON,
600                                   choice,
601                                   &chosen);
602
603                 if (opts->flags & MENU_OPTS_SINGLETON) {
604                         if (nr)
605                                 break;
606                 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
607                         break;
608                 }
609         }
610
611         if (eof) {
612                 result = xmalloc(sizeof(int));
613                 *result = EOF;
614         } else {
615                 int j = 0;
616
617                 /*
618                  * recalculate nr, if return back from menu directly with
619                  * default selections.
620                  */
621                 if (!nr) {
622                         for (i = 0; i < stuff->nr; i++)
623                                 nr += chosen[i];
624                 }
625
626                 result = xcalloc(st_add(nr, 1), sizeof(int));
627                 for (i = 0; i < stuff->nr && j < nr; i++) {
628                         if (chosen[i])
629                                 result[j++] = i;
630                 }
631                 result[j] = EOF;
632         }
633
634         free(chosen);
635         strbuf_release(&choice);
636         return result;
637 }
638
639 static int clean_cmd(void)
640 {
641         return MENU_RETURN_NO_LOOP;
642 }
643
644 static int filter_by_patterns_cmd(void)
645 {
646         struct dir_struct dir;
647         struct strbuf confirm = STRBUF_INIT;
648         struct strbuf **ignore_list;
649         struct string_list_item *item;
650         struct pattern_list *pl;
651         int changed = -1, i;
652
653         for (;;) {
654                 if (!del_list.nr)
655                         break;
656
657                 if (changed)
658                         pretty_print_dels();
659
660                 clean_print_color(CLEAN_COLOR_PROMPT);
661                 printf(_("Input ignore patterns>> "));
662                 clean_print_color(CLEAN_COLOR_RESET);
663                 if (git_read_line_interactively(&confirm) == EOF)
664                         putchar('\n');
665
666                 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
667                 if (!confirm.len)
668                         break;
669
670                 memset(&dir, 0, sizeof(dir));
671                 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
672                 ignore_list = strbuf_split_max(&confirm, ' ', 0);
673
674                 for (i = 0; ignore_list[i]; i++) {
675                         strbuf_trim(ignore_list[i]);
676                         if (!ignore_list[i]->len)
677                                 continue;
678
679                         add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
680                 }
681
682                 changed = 0;
683                 for_each_string_list_item(item, &del_list) {
684                         int dtype = DT_UNKNOWN;
685
686                         if (is_excluded(&dir, &the_index, item->string, &dtype)) {
687                                 *item->string = '\0';
688                                 changed++;
689                         }
690                 }
691
692                 if (changed) {
693                         string_list_remove_empty_items(&del_list, 0);
694                 } else {
695                         clean_print_color(CLEAN_COLOR_ERROR);
696                         printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
697                         clean_print_color(CLEAN_COLOR_RESET);
698                 }
699
700                 strbuf_list_free(ignore_list);
701                 clear_directory(&dir);
702         }
703
704         strbuf_release(&confirm);
705         return 0;
706 }
707
708 static int select_by_numbers_cmd(void)
709 {
710         struct menu_opts menu_opts;
711         struct menu_stuff menu_stuff;
712         struct string_list_item *items;
713         int *chosen;
714         int i, j;
715
716         menu_opts.header = NULL;
717         menu_opts.prompt = N_("Select items to delete");
718         menu_opts.flags = 0;
719
720         menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
721         menu_stuff.stuff = &del_list;
722         menu_stuff.nr = del_list.nr;
723
724         chosen = list_and_choose(&menu_opts, &menu_stuff);
725         items = del_list.items;
726         for (i = 0, j = 0; i < del_list.nr; i++) {
727                 if (i < chosen[j]) {
728                         *(items[i].string) = '\0';
729                 } else if (i == chosen[j]) {
730                         /* delete selected item */
731                         j++;
732                         continue;
733                 } else {
734                         /* end of chosen (chosen[j] == EOF), won't delete */
735                         *(items[i].string) = '\0';
736                 }
737         }
738
739         string_list_remove_empty_items(&del_list, 0);
740
741         free(chosen);
742         return 0;
743 }
744
745 static int ask_each_cmd(void)
746 {
747         struct strbuf confirm = STRBUF_INIT;
748         struct strbuf buf = STRBUF_INIT;
749         struct string_list_item *item;
750         const char *qname;
751         int changed = 0, eof = 0;
752
753         for_each_string_list_item(item, &del_list) {
754                 /* Ctrl-D should stop removing files */
755                 if (!eof) {
756                         qname = quote_path_relative(item->string, NULL, &buf);
757                         /* TRANSLATORS: Make sure to keep [y/N] as is */
758                         printf(_("Remove %s [y/N]? "), qname);
759                         if (git_read_line_interactively(&confirm) == EOF) {
760                                 putchar('\n');
761                                 eof = 1;
762                         }
763                 }
764                 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
765                         *item->string = '\0';
766                         changed++;
767                 }
768         }
769
770         if (changed)
771                 string_list_remove_empty_items(&del_list, 0);
772
773         strbuf_release(&buf);
774         strbuf_release(&confirm);
775         return MENU_RETURN_NO_LOOP;
776 }
777
778 static int quit_cmd(void)
779 {
780         string_list_clear(&del_list, 0);
781         printf(_("Bye.\n"));
782         return MENU_RETURN_NO_LOOP;
783 }
784
785 static int help_cmd(void)
786 {
787         clean_print_color(CLEAN_COLOR_HELP);
788         printf_ln(_(
789                     "clean               - start cleaning\n"
790                     "filter by pattern   - exclude items from deletion\n"
791                     "select by numbers   - select items to be deleted by numbers\n"
792                     "ask each            - confirm each deletion (like \"rm -i\")\n"
793                     "quit                - stop cleaning\n"
794                     "help                - this screen\n"
795                     "?                   - help for prompt selection"
796                    ));
797         clean_print_color(CLEAN_COLOR_RESET);
798         return 0;
799 }
800
801 static void interactive_main_loop(void)
802 {
803         while (del_list.nr) {
804                 struct menu_opts menu_opts;
805                 struct menu_stuff menu_stuff;
806                 struct menu_item menus[] = {
807                         {'c', "clean",                  0, clean_cmd},
808                         {'f', "filter by pattern",      0, filter_by_patterns_cmd},
809                         {'s', "select by numbers",      0, select_by_numbers_cmd},
810                         {'a', "ask each",               0, ask_each_cmd},
811                         {'q', "quit",                   0, quit_cmd},
812                         {'h', "help",                   0, help_cmd},
813                 };
814                 int *chosen;
815
816                 menu_opts.header = N_("*** Commands ***");
817                 menu_opts.prompt = N_("What now");
818                 menu_opts.flags = MENU_OPTS_SINGLETON;
819
820                 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
821                 menu_stuff.stuff = menus;
822                 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
823
824                 clean_print_color(CLEAN_COLOR_HEADER);
825                 printf_ln(Q_("Would remove the following item:",
826                              "Would remove the following items:",
827                              del_list.nr));
828                 clean_print_color(CLEAN_COLOR_RESET);
829
830                 pretty_print_dels();
831
832                 chosen = list_and_choose(&menu_opts, &menu_stuff);
833
834                 if (*chosen != EOF) {
835                         int ret;
836                         ret = menus[*chosen].fn();
837                         if (ret != MENU_RETURN_NO_LOOP) {
838                                 FREE_AND_NULL(chosen);
839                                 if (!del_list.nr) {
840                                         clean_print_color(CLEAN_COLOR_ERROR);
841                                         printf_ln(_("No more files to clean, exiting."));
842                                         clean_print_color(CLEAN_COLOR_RESET);
843                                         break;
844                                 }
845                                 continue;
846                         }
847                 } else {
848                         quit_cmd();
849                 }
850
851                 FREE_AND_NULL(chosen);
852                 break;
853         }
854 }
855
856 static void correct_untracked_entries(struct dir_struct *dir)
857 {
858         int src, dst, ign;
859
860         for (src = dst = ign = 0; src < dir->nr; src++) {
861                 /* skip paths in ignored[] that cannot be inside entries[src] */
862                 while (ign < dir->ignored_nr &&
863                        0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
864                         ign++;
865
866                 if (ign < dir->ignored_nr &&
867                     check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
868                         /* entries[src] contains an ignored path, so we drop it */
869                         free(dir->entries[src]);
870                 } else {
871                         struct dir_entry *ent = dir->entries[src++];
872
873                         /* entries[src] does not contain an ignored path, so we keep it */
874                         dir->entries[dst++] = ent;
875
876                         /* then discard paths in entries[] contained inside entries[src] */
877                         while (src < dir->nr &&
878                                check_dir_entry_contains(ent, dir->entries[src]))
879                                 free(dir->entries[src++]);
880
881                         /* compensate for the outer loop's loop control */
882                         src--;
883                 }
884         }
885         dir->nr = dst;
886 }
887
888 int cmd_clean(int argc, const char **argv, const char *prefix)
889 {
890         int i, res;
891         int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
892         int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
893         int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
894         struct strbuf abs_path = STRBUF_INIT;
895         struct dir_struct dir;
896         struct pathspec pathspec;
897         struct strbuf buf = STRBUF_INIT;
898         struct string_list exclude_list = STRING_LIST_INIT_NODUP;
899         struct pattern_list *pl;
900         struct string_list_item *item;
901         const char *qname;
902         struct option options[] = {
903                 OPT__QUIET(&quiet, N_("do not print names of files removed")),
904                 OPT__DRY_RUN(&dry_run, N_("dry run")),
905                 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
906                 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
907                 OPT_BOOL('d', NULL, &remove_directories,
908                                 N_("remove whole directories")),
909                 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
910                   N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
911                 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
912                 OPT_BOOL('X', NULL, &ignored_only,
913                                 N_("remove only ignored files")),
914                 OPT_END()
915         };
916
917         git_config(git_clean_config, NULL);
918         if (force < 0)
919                 force = 0;
920         else
921                 config_set = 1;
922
923         argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
924                              0);
925
926         memset(&dir, 0, sizeof(dir));
927         if (!interactive && !dry_run && !force) {
928                 if (config_set)
929                         die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
930                                   "refusing to clean"));
931                 else
932                         die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
933                                   " refusing to clean"));
934         }
935
936         if (force > 1)
937                 rm_flags = 0;
938         else
939                 dir.flags |= DIR_SKIP_NESTED_GIT;
940
941         dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
942
943         if (ignored && ignored_only)
944                 die(_("-x and -X cannot be used together"));
945         if (!ignored)
946                 setup_standard_excludes(&dir);
947         if (ignored_only)
948                 dir.flags |= DIR_SHOW_IGNORED;
949
950         if (argc) {
951                 /*
952                  * Remaining args implies pathspecs specified, and we should
953                  * recurse within those.
954                  */
955                 remove_directories = 1;
956         }
957
958         if (remove_directories && !ignored_only) {
959                 /*
960                  * We need to know about ignored files too:
961                  *
962                  * If (ignored), then we will delete ignored files as well.
963                  *
964                  * If (!ignored), then even though we not are doing
965                  * anything with ignored files, we need to know about them
966                  * so that we can avoid deleting a directory of untracked
967                  * files that also contains an ignored file within it.
968                  *
969                  * For the (!ignored) case, since we only need to avoid
970                  * deleting ignored files, we can set
971                  * DIR_SHOW_IGNORED_TOO_MODE_MATCHING in order to avoid
972                  * recursing into a directory which is itself ignored.
973                  */
974                 dir.flags |= DIR_SHOW_IGNORED_TOO;
975                 if (!ignored)
976                         dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
977
978                 /*
979                  * Let the fill_directory() machinery know that we aren't
980                  * just recursing to collect the ignored files; we want all
981                  * the untracked ones so that we can delete them.  (Note:
982                  * we could also set DIR_KEEP_UNTRACKED_CONTENTS when
983                  * ignored_only is true, since DIR_KEEP_UNTRACKED_CONTENTS
984                  * only has effect in combination with DIR_SHOW_IGNORED_TOO.  It makes
985                  * the code clearer to exclude it, though.
986                  */
987                 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
988         }
989
990         if (read_cache() < 0)
991                 die(_("index file corrupt"));
992
993         pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
994         for (i = 0; i < exclude_list.nr; i++)
995                 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
996
997         parse_pathspec(&pathspec, 0,
998                        PATHSPEC_PREFER_CWD,
999                        prefix, argv);
1000
1001         fill_directory(&dir, &the_index, &pathspec);
1002         correct_untracked_entries(&dir);
1003
1004         for (i = 0; i < dir.nr; i++) {
1005                 struct dir_entry *ent = dir.entries[i];
1006                 int matches = 0;
1007                 struct stat st;
1008                 const char *rel;
1009
1010                 if (!cache_name_is_other(ent->name, ent->len))
1011                         continue;
1012
1013                 if (lstat(ent->name, &st))
1014                         die_errno("Cannot lstat '%s'", ent->name);
1015
1016                 if (S_ISDIR(st.st_mode) && !remove_directories &&
1017                     matches != MATCHED_EXACTLY)
1018                         continue;
1019
1020                 rel = relative_path(ent->name, prefix, &buf);
1021                 string_list_append(&del_list, rel);
1022         }
1023
1024         for (i = 0; i < dir.nr; i++)
1025                 free(dir.entries[i]);
1026
1027         for (i = 0; i < dir.ignored_nr; i++)
1028                 free(dir.ignored[i]);
1029
1030         if (interactive && del_list.nr > 0)
1031                 interactive_main_loop();
1032
1033         for_each_string_list_item(item, &del_list) {
1034                 struct stat st;
1035
1036                 strbuf_reset(&abs_path);
1037                 if (prefix)
1038                         strbuf_addstr(&abs_path, prefix);
1039
1040                 strbuf_addstr(&abs_path, item->string);
1041
1042                 /*
1043                  * we might have removed this as part of earlier
1044                  * recursive directory removal, so lstat() here could
1045                  * fail with ENOENT.
1046                  */
1047                 if (lstat(abs_path.buf, &st))
1048                         continue;
1049
1050                 if (S_ISDIR(st.st_mode)) {
1051                         if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1052                                 errors++;
1053                         if (gone && !quiet) {
1054                                 qname = quote_path_relative(item->string, NULL, &buf);
1055                                 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1056                         }
1057                 } else {
1058                         res = dry_run ? 0 : unlink(abs_path.buf);
1059                         if (res) {
1060                                 int saved_errno = errno;
1061                                 qname = quote_path_relative(item->string, NULL, &buf);
1062                                 errno = saved_errno;
1063                                 warning_errno(_(msg_warn_remove_failed), qname);
1064                                 errors++;
1065                         } else if (!quiet) {
1066                                 qname = quote_path_relative(item->string, NULL, &buf);
1067                                 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1068                         }
1069                 }
1070         }
1071
1072         strbuf_release(&abs_path);
1073         strbuf_release(&buf);
1074         string_list_clear(&del_list, 0);
1075         string_list_clear(&exclude_list, 0);
1076         return (errors != 0);
1077 }