The second batch
[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(path->buf, prefix, &quoted, 0);
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(path->buf, prefix, &quoted, 0);
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_skip_dot_and_dotdot(dir)) != NULL) {
193                 struct stat st;
194
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;
220                         }
221                         continue;
222                 }
223
224                 /* path too long, stat fails, or non-directory still exists */
225                 *dir_gone = 0;
226                 ret = 1;
227                 break;
228         }
229         closedir(dir);
230
231         strbuf_setlen(path, original_len);
232
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;
244                 }
245         }
246
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);
251         }
252 out:
253         strbuf_release(&quoted);
254         string_list_clear(&dels, 0);
255         return ret;
256 }
257
258 static void pretty_print_dels(void)
259 {
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;
265
266         for_each_string_list_item(item, &del_list) {
267                 qname = quote_path(item->string, NULL, &buf, 0);
268                 string_list_append(&list, qname);
269         }
270
271         /*
272          * always enable column display, we only consult column.*
273          * about layout strategy and stuff
274          */
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);
282 }
283
284 static void pretty_print_menus(struct string_list *menu_list)
285 {
286         unsigned int local_colopts = 0;
287         struct column_options copts;
288
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);
294 }
295
296 static void prompt_help_cmd(int singleton)
297 {
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);
313 }
314
315 /*
316  * display menu stuff with number prefix and hotkey highlight
317  */
318 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
319 {
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;
325
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;
334
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);
347                                 }
348                         }
349                         string_list_append(&menu_list, menu.buf);
350                         strbuf_reset(&menu);
351                 }
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++;
363                 }
364                 break;
365         }
366
367         pretty_print_menus(&menu_list);
368
369         strbuf_release(&menu);
370         string_list_clear(&menu_list, 0);
371 }
372
373 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
374 {
375         struct menu_item *menu_item;
376         struct string_list_item *string_list_item;
377         int i, len, found = 0;
378
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:
384
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;
390                         }
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;
399                                         }
400                                 } else {
401                                         found = i + 1;
402                                 }
403                         }
404                 }
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;
413                                 }
414                                 found = i + 1;
415                         }
416                 }
417                 break;
418         }
419         return found;
420 }
421
422 /*
423  * Parse user input, and return choice(s) for menu (menu_stuff).
424  *
425  * Input
426  *     (for single choice)
427  *         1          - select a numbered item
428  *         foo        - select item based on menu title
429  *                    - (empty) select nothing
430  *
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
439  *
440  * The parse result will be saved in array **chosen, and
441  * return number of total selections.
442  */
443 static int parse_choice(struct menu_stuff *menu_stuff,
444                         int is_single,
445                         struct strbuf input,
446                         int **chosen)
447 {
448         struct strbuf **choice_list, **ptr;
449         int nr = 0;
450         int i;
451
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);
461         }
462
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;
468
469                 strbuf_trim(*ptr);
470                 if (!(*ptr)->len)
471                         continue;
472
473                 /* Input that begins with '-'; unchoose */
474                 if (*(*ptr)->buf == '-') {
475                         choose = 0;
476                         strbuf_remove((*ptr), 0, 1);
477                 }
478
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;
490                                 }
491                         } else if (!isdigit(*p)) {
492                                 is_number = 0;
493                                 is_range = 0;
494                                 break;
495                         }
496                 }
497
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;
514                 }
515
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;
522                 }
523
524                 for (i = bottom; i <= top; i++)
525                         (*chosen)[i-1] = choose;
526         }
527
528         strbuf_list_free(choice_list);
529
530         for (i = 0; i < menu_stuff->nr; i++)
531                 nr += (*chosen)[i];
532         return nr;
533 }
534
535 /*
536  * Implement a git-add-interactive compatible UI, which is borrowed
537  * from git-add--interactive.perl.
538  *
539  * Return value:
540  *
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.
545  */
546 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
547 {
548         struct strbuf choice = STRBUF_INIT;
549         int *chosen, *result;
550         int nr = 0;
551         int eof = 0;
552         int i;
553
554         ALLOC_ARRAY(chosen, stuff->nr);
555         /* set chosen as uninitialized */
556         for (i = 0; i < stuff->nr; i++)
557                 chosen[i] = -1;
558
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));
565                 }
566
567                 /* chosen will be initialized by print_highlight_menu_stuff */
568                 print_highlight_menu_stuff(stuff, &chosen);
569
570                 if (opts->flags & MENU_OPTS_LIST_ONLY)
571                         break;
572
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));
579                 }
580
581                 if (git_read_line_interactively(&choice) == EOF) {
582                         eof = 1;
583                         break;
584                 }
585
586                 /* help for prompt */
587                 if (!strcmp(choice.buf, "?")) {
588                         prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
589                         continue;
590                 }
591
592                 /* for a multiple-choice menu, press ENTER (empty) will return back */
593                 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
594                         break;
595
596                 nr = parse_choice(stuff,
597                                   opts->flags & MENU_OPTS_SINGLETON,
598                                   choice,
599                                   &chosen);
600
601                 if (opts->flags & MENU_OPTS_SINGLETON) {
602                         if (nr)
603                                 break;
604                 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
605                         break;
606                 }
607         }
608
609         if (eof) {
610                 result = xmalloc(sizeof(int));
611                 *result = EOF;
612         } else {
613                 int j = 0;
614
615                 /*
616                  * recalculate nr, if return back from menu directly with
617                  * default selections.
618                  */
619                 if (!nr) {
620                         for (i = 0; i < stuff->nr; i++)
621                                 nr += chosen[i];
622                 }
623
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;
628                 }
629                 result[j] = EOF;
630         }
631
632         free(chosen);
633         strbuf_release(&choice);
634         return result;
635 }
636
637 static int clean_cmd(void)
638 {
639         return MENU_RETURN_NO_LOOP;
640 }
641
642 static int filter_by_patterns_cmd(void)
643 {
644         struct dir_struct dir;
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;
650
651         for (;;) {
652                 if (!del_list.nr)
653                         break;
654
655                 if (changed)
656                         pretty_print_dels();
657
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');
663
664                 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
665                 if (!confirm.len)
666                         break;
667
668                 dir_init(&dir);
669                 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
670                 ignore_list = strbuf_split_max(&confirm, ' ', 0);
671
672                 for (i = 0; ignore_list[i]; i++) {
673                         strbuf_trim(ignore_list[i]);
674                         if (!ignore_list[i]->len)
675                                 continue;
676
677                         add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
678                 }
679
680                 changed = 0;
681                 for_each_string_list_item(item, &del_list) {
682                         int dtype = DT_UNKNOWN;
683
684                         if (is_excluded(&dir, &the_index, item->string, &dtype)) {
685                                 *item->string = '\0';
686                                 changed++;
687                         }
688                 }
689
690                 if (changed) {
691                         string_list_remove_empty_items(&del_list, 0);
692                 } else {
693                         clean_print_color(CLEAN_COLOR_ERROR);
694                         printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
695                         clean_print_color(CLEAN_COLOR_RESET);
696                 }
697
698                 strbuf_list_free(ignore_list);
699                 dir_clear(&dir);
700         }
701
702         strbuf_release(&confirm);
703         return 0;
704 }
705
706 static int select_by_numbers_cmd(void)
707 {
708         struct menu_opts menu_opts;
709         struct menu_stuff menu_stuff;
710         struct string_list_item *items;
711         int *chosen;
712         int i, j;
713
714         menu_opts.header = NULL;
715         menu_opts.prompt = N_("Select items to delete");
716         menu_opts.flags = 0;
717
718         menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
719         menu_stuff.stuff = &del_list;
720         menu_stuff.nr = del_list.nr;
721
722         chosen = list_and_choose(&menu_opts, &menu_stuff);
723         items = del_list.items;
724         for (i = 0, j = 0; i < del_list.nr; i++) {
725                 if (i < chosen[j]) {
726                         *(items[i].string) = '\0';
727                 } else if (i == chosen[j]) {
728                         /* delete selected item */
729                         j++;
730                         continue;
731                 } else {
732                         /* end of chosen (chosen[j] == EOF), won't delete */
733                         *(items[i].string) = '\0';
734                 }
735         }
736
737         string_list_remove_empty_items(&del_list, 0);
738
739         free(chosen);
740         return 0;
741 }
742
743 static int ask_each_cmd(void)
744 {
745         struct strbuf confirm = STRBUF_INIT;
746         struct strbuf buf = STRBUF_INIT;
747         struct string_list_item *item;
748         const char *qname;
749         int changed = 0, eof = 0;
750
751         for_each_string_list_item(item, &del_list) {
752                 /* Ctrl-D should stop removing files */
753                 if (!eof) {
754                         qname = quote_path(item->string, NULL, &buf, 0);
755                         /* TRANSLATORS: Make sure to keep [y/N] as is */
756                         printf(_("Remove %s [y/N]? "), qname);
757                         if (git_read_line_interactively(&confirm) == EOF) {
758                                 putchar('\n');
759                                 eof = 1;
760                         }
761                 }
762                 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
763                         *item->string = '\0';
764                         changed++;
765                 }
766         }
767
768         if (changed)
769                 string_list_remove_empty_items(&del_list, 0);
770
771         strbuf_release(&buf);
772         strbuf_release(&confirm);
773         return MENU_RETURN_NO_LOOP;
774 }
775
776 static int quit_cmd(void)
777 {
778         string_list_clear(&del_list, 0);
779         printf(_("Bye.\n"));
780         return MENU_RETURN_NO_LOOP;
781 }
782
783 static int help_cmd(void)
784 {
785         clean_print_color(CLEAN_COLOR_HELP);
786         printf_ln(_(
787                     "clean               - start cleaning\n"
788                     "filter by pattern   - exclude items from deletion\n"
789                     "select by numbers   - select items to be deleted by numbers\n"
790                     "ask each            - confirm each deletion (like \"rm -i\")\n"
791                     "quit                - stop cleaning\n"
792                     "help                - this screen\n"
793                     "?                   - help for prompt selection"
794                    ));
795         clean_print_color(CLEAN_COLOR_RESET);
796         return 0;
797 }
798
799 static void interactive_main_loop(void)
800 {
801         while (del_list.nr) {
802                 struct menu_opts menu_opts;
803                 struct menu_stuff menu_stuff;
804                 struct menu_item menus[] = {
805                         {'c', "clean",                  0, clean_cmd},
806                         {'f', "filter by pattern",      0, filter_by_patterns_cmd},
807                         {'s', "select by numbers",      0, select_by_numbers_cmd},
808                         {'a', "ask each",               0, ask_each_cmd},
809                         {'q', "quit",                   0, quit_cmd},
810                         {'h', "help",                   0, help_cmd},
811                 };
812                 int *chosen;
813
814                 menu_opts.header = N_("*** Commands ***");
815                 menu_opts.prompt = N_("What now");
816                 menu_opts.flags = MENU_OPTS_SINGLETON;
817
818                 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
819                 menu_stuff.stuff = menus;
820                 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
821
822                 clean_print_color(CLEAN_COLOR_HEADER);
823                 printf_ln(Q_("Would remove the following item:",
824                              "Would remove the following items:",
825                              del_list.nr));
826                 clean_print_color(CLEAN_COLOR_RESET);
827
828                 pretty_print_dels();
829
830                 chosen = list_and_choose(&menu_opts, &menu_stuff);
831
832                 if (*chosen != EOF) {
833                         int ret;
834                         ret = menus[*chosen].fn();
835                         if (ret != MENU_RETURN_NO_LOOP) {
836                                 FREE_AND_NULL(chosen);
837                                 if (!del_list.nr) {
838                                         clean_print_color(CLEAN_COLOR_ERROR);
839                                         printf_ln(_("No more files to clean, exiting."));
840                                         clean_print_color(CLEAN_COLOR_RESET);
841                                         break;
842                                 }
843                                 continue;
844                         }
845                 } else {
846                         quit_cmd();
847                 }
848
849                 FREE_AND_NULL(chosen);
850                 break;
851         }
852 }
853
854 static void correct_untracked_entries(struct dir_struct *dir)
855 {
856         int src, dst, ign;
857
858         for (src = dst = ign = 0; src < dir->nr; src++) {
859                 /* skip paths in ignored[] that cannot be inside entries[src] */
860                 while (ign < dir->ignored_nr &&
861                        0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
862                         ign++;
863
864                 if (ign < dir->ignored_nr &&
865                     check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
866                         /* entries[src] contains an ignored path, so we drop it */
867                         free(dir->entries[src]);
868                 } else {
869                         struct dir_entry *ent = dir->entries[src++];
870
871                         /* entries[src] does not contain an ignored path, so we keep it */
872                         dir->entries[dst++] = ent;
873
874                         /* then discard paths in entries[] contained inside entries[src] */
875                         while (src < dir->nr &&
876                                check_dir_entry_contains(ent, dir->entries[src]))
877                                 free(dir->entries[src++]);
878
879                         /* compensate for the outer loop's loop control */
880                         src--;
881                 }
882         }
883         dir->nr = dst;
884 }
885
886 int cmd_clean(int argc, const char **argv, const char *prefix)
887 {
888         int i, res;
889         int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
890         int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
891         int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
892         struct strbuf abs_path = STRBUF_INIT;
893         struct dir_struct dir;
894         struct pathspec pathspec;
895         struct strbuf buf = STRBUF_INIT;
896         struct string_list exclude_list = STRING_LIST_INIT_NODUP;
897         struct pattern_list *pl;
898         struct string_list_item *item;
899         const char *qname;
900         struct option options[] = {
901                 OPT__QUIET(&quiet, N_("do not print names of files removed")),
902                 OPT__DRY_RUN(&dry_run, N_("dry run")),
903                 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
904                 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
905                 OPT_BOOL('d', NULL, &remove_directories,
906                                 N_("remove whole directories")),
907                 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
908                   N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
909                 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
910                 OPT_BOOL('X', NULL, &ignored_only,
911                                 N_("remove only ignored files")),
912                 OPT_END()
913         };
914
915         git_config(git_clean_config, NULL);
916         if (force < 0)
917                 force = 0;
918         else
919                 config_set = 1;
920
921         argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
922                              0);
923
924         dir_init(&dir);
925         if (!interactive && !dry_run && !force) {
926                 if (config_set)
927                         die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
928                                   "refusing to clean"));
929                 else
930                         die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
931                                   " refusing to clean"));
932         }
933
934         if (force > 1)
935                 rm_flags = 0;
936         else
937                 dir.flags |= DIR_SKIP_NESTED_GIT;
938
939         dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
940
941         if (ignored && ignored_only)
942                 die(_("-x and -X cannot be used together"));
943         if (!ignored)
944                 setup_standard_excludes(&dir);
945         if (ignored_only)
946                 dir.flags |= DIR_SHOW_IGNORED;
947
948         if (argc) {
949                 /*
950                  * Remaining args implies pathspecs specified, and we should
951                  * recurse within those.
952                  */
953                 remove_directories = 1;
954         }
955
956         if (remove_directories && !ignored_only) {
957                 /*
958                  * We need to know about ignored files too:
959                  *
960                  * If (ignored), then we will delete ignored files as well.
961                  *
962                  * If (!ignored), then even though we not are doing
963                  * anything with ignored files, we need to know about them
964                  * so that we can avoid deleting a directory of untracked
965                  * files that also contains an ignored file within it.
966                  *
967                  * For the (!ignored) case, since we only need to avoid
968                  * deleting ignored files, we can set
969                  * DIR_SHOW_IGNORED_TOO_MODE_MATCHING in order to avoid
970                  * recursing into a directory which is itself ignored.
971                  */
972                 dir.flags |= DIR_SHOW_IGNORED_TOO;
973                 if (!ignored)
974                         dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
975
976                 /*
977                  * Let the fill_directory() machinery know that we aren't
978                  * just recursing to collect the ignored files; we want all
979                  * the untracked ones so that we can delete them.  (Note:
980                  * we could also set DIR_KEEP_UNTRACKED_CONTENTS when
981                  * ignored_only is true, since DIR_KEEP_UNTRACKED_CONTENTS
982                  * only has effect in combination with DIR_SHOW_IGNORED_TOO.  It makes
983                  * the code clearer to exclude it, though.
984                  */
985                 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
986         }
987
988         if (read_cache() < 0)
989                 die(_("index file corrupt"));
990
991         pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
992         for (i = 0; i < exclude_list.nr; i++)
993                 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
994
995         parse_pathspec(&pathspec, 0,
996                        PATHSPEC_PREFER_CWD,
997                        prefix, argv);
998
999         fill_directory(&dir, &the_index, &pathspec);
1000         correct_untracked_entries(&dir);
1001
1002         for (i = 0; i < dir.nr; i++) {
1003                 struct dir_entry *ent = dir.entries[i];
1004                 struct stat st;
1005                 const char *rel;
1006
1007                 if (!cache_name_is_other(ent->name, ent->len))
1008                         continue;
1009
1010                 if (lstat(ent->name, &st))
1011                         die_errno("Cannot lstat '%s'", ent->name);
1012
1013                 if (S_ISDIR(st.st_mode) && !remove_directories)
1014                         continue;
1015
1016                 rel = relative_path(ent->name, prefix, &buf);
1017                 string_list_append(&del_list, rel);
1018         }
1019
1020         dir_clear(&dir);
1021
1022         if (interactive && del_list.nr > 0)
1023                 interactive_main_loop();
1024
1025         for_each_string_list_item(item, &del_list) {
1026                 struct stat st;
1027
1028                 strbuf_reset(&abs_path);
1029                 if (prefix)
1030                         strbuf_addstr(&abs_path, prefix);
1031
1032                 strbuf_addstr(&abs_path, item->string);
1033
1034                 /*
1035                  * we might have removed this as part of earlier
1036                  * recursive directory removal, so lstat() here could
1037                  * fail with ENOENT.
1038                  */
1039                 if (lstat(abs_path.buf, &st))
1040                         continue;
1041
1042                 if (S_ISDIR(st.st_mode)) {
1043                         if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1044                                 errors++;
1045                         if (gone && !quiet) {
1046                                 qname = quote_path(item->string, NULL, &buf, 0);
1047                                 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1048                         }
1049                 } else {
1050                         res = dry_run ? 0 : unlink(abs_path.buf);
1051                         if (res) {
1052                                 int saved_errno = errno;
1053                                 qname = quote_path(item->string, NULL, &buf, 0);
1054                                 errno = saved_errno;
1055                                 warning_errno(_(msg_warn_remove_failed), qname);
1056                                 errors++;
1057                         } else if (!quiet) {
1058                                 qname = quote_path(item->string, NULL, &buf, 0);
1059                                 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1060                         }
1061                 }
1062         }
1063
1064         strbuf_release(&abs_path);
1065         strbuf_release(&buf);
1066         string_list_clear(&del_list, 0);
1067         string_list_clear(&exclude_list, 0);
1068         return (errors != 0);
1069 }