p7300: add performance tests for clean
[git/git.git] / builtin / clean.c
CommitLineData
113f10f2
SB
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 "dir.h"
12#include "parse-options.h"
f538a91e 13#include "refs.h"
07de4eba 14#include "string-list.h"
1fb32894 15#include "quote.h"
1b8fd467 16#include "column.h"
7a9b0b80 17#include "color.h"
893d8399 18#include "pathspec.h"
113f10f2 19
625db1b7 20static int force = -1; /* unset */
17696002 21static int interactive;
396049e5 22static struct string_list del_list = STRING_LIST_INIT_DUP;
1b8fd467 23static unsigned int colopts;
113f10f2
SB
24
25static const char *const builtin_clean_usage[] = {
17696002 26 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
113f10f2
SB
27 NULL
28};
29
f538a91e
ZK
30static const char *msg_remove = N_("Removing %s\n");
31static const char *msg_would_remove = N_("Would remove %s\n");
32static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
33static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
34static const char *msg_warn_remove_failed = N_("failed to remove %s");
35
7a9b0b80
JX
36static int clean_use_color = -1;
37static char clean_colors[][COLOR_MAXLEN] = {
38 GIT_COLOR_RESET,
39 GIT_COLOR_NORMAL, /* PLAIN */
40 GIT_COLOR_BOLD_BLUE, /* PROMPT */
41 GIT_COLOR_BOLD, /* HEADER */
42 GIT_COLOR_BOLD_RED, /* HELP */
43 GIT_COLOR_BOLD_RED, /* ERROR */
44};
45enum color_clean {
46 CLEAN_COLOR_RESET = 0,
47 CLEAN_COLOR_PLAIN = 1,
48 CLEAN_COLOR_PROMPT = 2,
49 CLEAN_COLOR_HEADER = 3,
50 CLEAN_COLOR_HELP = 4,
78273520 51 CLEAN_COLOR_ERROR = 5
7a9b0b80
JX
52};
53
9f93e461
JX
54#define MENU_OPTS_SINGLETON 01
55#define MENU_OPTS_IMMEDIATE 02
56#define MENU_OPTS_LIST_ONLY 04
57
58struct menu_opts {
59 const char *header;
60 const char *prompt;
61 int flags;
62};
63
64#define MENU_RETURN_NO_LOOP 10
65
66struct menu_item {
67 char hotkey;
68 const char *title;
69 int selected;
8687f777 70 int (*fn)(void);
9f93e461
JX
71};
72
73enum menu_stuff_type {
74 MENU_STUFF_TYPE_STRING_LIST = 1,
75 MENU_STUFF_TYPE_MENU_ITEM
76};
77
78struct menu_stuff {
79 enum menu_stuff_type type;
80 int nr;
81 void *stuff;
82};
83
7a9b0b80
JX
84static int parse_clean_color_slot(const char *var)
85{
86 if (!strcasecmp(var, "reset"))
87 return CLEAN_COLOR_RESET;
88 if (!strcasecmp(var, "plain"))
89 return CLEAN_COLOR_PLAIN;
90 if (!strcasecmp(var, "prompt"))
91 return CLEAN_COLOR_PROMPT;
92 if (!strcasecmp(var, "header"))
93 return CLEAN_COLOR_HEADER;
94 if (!strcasecmp(var, "help"))
95 return CLEAN_COLOR_HELP;
96 if (!strcasecmp(var, "error"))
97 return CLEAN_COLOR_ERROR;
98 return -1;
99}
100
ef90d6d4 101static int git_clean_config(const char *var, const char *value, void *cb)
113f10f2 102{
e3f1da98
RS
103 const char *slot_name;
104
59556548 105 if (starts_with(var, "column."))
1b8fd467
JX
106 return git_column_config(var, value, "clean", &colopts);
107
7a9b0b80
JX
108 /* honors the color.interactive* config variables which also
109 applied in git-add--interactive and git-stash */
110 if (!strcmp(var, "color.interactive")) {
111 clean_use_color = git_config_colorbool(var, value);
112 return 0;
113 }
e3f1da98
RS
114 if (skip_prefix(var, "color.interactive.", &slot_name)) {
115 int slot = parse_clean_color_slot(slot_name);
7a9b0b80
JX
116 if (slot < 0)
117 return 0;
118 if (!value)
119 return config_error_nonbool(var);
f6c5a296 120 return color_parse(value, clean_colors[slot]);
7a9b0b80
JX
121 }
122
1b8fd467 123 if (!strcmp(var, "clean.requireforce")) {
113f10f2 124 force = !git_config_bool(var, value);
1b8fd467
JX
125 return 0;
126 }
7a9b0b80
JX
127
128 /* inspect the color.ui config variable and others */
129 return git_color_default_config(var, value, cb);
130}
131
132static const char *clean_get_color(enum color_clean ix)
133{
134 if (want_color(clean_use_color))
135 return clean_colors[ix];
136 return "";
137}
138
139static void clean_print_color(enum color_clean ix)
140{
141 printf("%s", clean_get_color(ix));
113f10f2
SB
142}
143
07de4eba
JH
144static int exclude_cb(const struct option *opt, const char *arg, int unset)
145{
146 struct string_list *exclude_list = opt->value;
147 string_list_append(exclude_list, arg);
148 return 0;
149}
150
f538a91e
ZK
151static 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;
e666b89d 157 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
f538a91e
ZK
158 unsigned char submodule_head[20];
159 struct string_list dels = STRING_LIST_INIT_DUP;
160
161 *dir_gone = 1;
162
163 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
164 !resolve_gitlink_ref(path->buf, "HEAD", submodule_head)) {
165 if (!quiet) {
39598f99 166 quote_path_relative(path->buf, prefix, &quoted);
f538a91e
ZK
167 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
168 quoted.buf);
169 }
170
171 *dir_gone = 0;
172 return 0;
173 }
174
175 dir = opendir(path->buf);
176 if (!dir) {
177 /* an empty dir could be removed even if it is unreadble */
178 res = dry_run ? 0 : rmdir(path->buf);
179 if (res) {
39598f99 180 quote_path_relative(path->buf, prefix, &quoted);
f538a91e
ZK
181 warning(_(msg_warn_remove_failed), quoted.buf);
182 *dir_gone = 0;
183 }
184 return res;
185 }
186
187 if (path->buf[original_len - 1] != '/')
188 strbuf_addch(path, '/');
189
190 len = path->len;
191 while ((e = readdir(dir)) != NULL) {
192 struct stat st;
193 if (is_dot_or_dotdot(e->d_name))
194 continue;
195
196 strbuf_setlen(path, len);
197 strbuf_addstr(path, e->d_name);
198 if (lstat(path->buf, &st))
199 ; /* fall thru */
200 else if (S_ISDIR(st.st_mode)) {
201 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
202 ret = 1;
203 if (gone) {
39598f99 204 quote_path_relative(path->buf, prefix, &quoted);
f538a91e
ZK
205 string_list_append(&dels, quoted.buf);
206 } else
207 *dir_gone = 0;
208 continue;
209 } else {
210 res = dry_run ? 0 : unlink(path->buf);
211 if (!res) {
39598f99 212 quote_path_relative(path->buf, prefix, &quoted);
f538a91e
ZK
213 string_list_append(&dels, quoted.buf);
214 } else {
39598f99 215 quote_path_relative(path->buf, prefix, &quoted);
f538a91e
ZK
216 warning(_(msg_warn_remove_failed), quoted.buf);
217 *dir_gone = 0;
218 ret = 1;
219 }
220 continue;
221 }
222
223 /* path too long, stat fails, or non-directory still exists */
224 *dir_gone = 0;
225 ret = 1;
226 break;
227 }
228 closedir(dir);
229
230 strbuf_setlen(path, original_len);
231
232 if (*dir_gone) {
233 res = dry_run ? 0 : rmdir(path->buf);
234 if (!res)
235 *dir_gone = 1;
236 else {
39598f99 237 quote_path_relative(path->buf, prefix, &quoted);
f538a91e
ZK
238 warning(_(msg_warn_remove_failed), quoted.buf);
239 *dir_gone = 0;
240 ret = 1;
241 }
242 }
243
244 if (!*dir_gone && !quiet) {
e666b89d 245 int i;
f538a91e
ZK
246 for (i = 0; i < dels.nr; i++)
247 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
248 }
249 string_list_clear(&dels, 0);
250 return ret;
251}
252
1b8fd467 253static void pretty_print_dels(void)
17696002 254{
1b8fd467 255 struct string_list list = STRING_LIST_INIT_DUP;
17696002 256 struct string_list_item *item;
1b8fd467 257 struct strbuf buf = STRBUF_INIT;
17696002 258 const char *qname;
1b8fd467
JX
259 struct column_options copts;
260
261 for_each_string_list_item(item, &del_list) {
262 qname = quote_path_relative(item->string, NULL, &buf);
263 string_list_append(&list, qname);
264 }
265
266 /*
267 * always enable column display, we only consult column.*
268 * about layout strategy and stuff
269 */
270 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
271 memset(&copts, 0, sizeof(copts));
272 copts.indent = " ";
273 copts.padding = 2;
274 print_columns(&list, colopts, &copts);
1b8fd467
JX
275 strbuf_release(&buf);
276 string_list_clear(&list, 0);
277}
278
9f93e461
JX
279static void pretty_print_menus(struct string_list *menu_list)
280{
281 unsigned int local_colopts = 0;
282 struct column_options copts;
283
284 local_colopts = COL_ENABLED | COL_ROW;
285 memset(&copts, 0, sizeof(copts));
286 copts.indent = " ";
287 copts.padding = 2;
288 print_columns(menu_list, local_colopts, &copts);
289}
290
291static void prompt_help_cmd(int singleton)
292{
293 clean_print_color(CLEAN_COLOR_HELP);
294 printf_ln(singleton ?
295 _("Prompt help:\n"
296 "1 - select a numbered item\n"
297 "foo - select item based on unique prefix\n"
298 " - (empty) select nothing") :
299 _("Prompt help:\n"
300 "1 - select a single item\n"
301 "3-5 - select a range of items\n"
302 "2-3,6-9 - select multiple ranges\n"
303 "foo - select item based on unique prefix\n"
304 "-... - unselect specified items\n"
305 "* - choose all items\n"
306 " - (empty) finish selecting"));
307 clean_print_color(CLEAN_COLOR_RESET);
308}
309
310/*
311 * display menu stuff with number prefix and hotkey highlight
312 */
313static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
314{
315 struct string_list menu_list = STRING_LIST_INIT_DUP;
316 struct strbuf menu = STRBUF_INIT;
9f93e461
JX
317 struct menu_item *menu_item;
318 struct string_list_item *string_list_item;
319 int i;
320
321 switch (stuff->type) {
322 default:
bef111d0 323 die("Bad type of menu_stuff when print menu");
9f93e461
JX
324 case MENU_STUFF_TYPE_MENU_ITEM:
325 menu_item = (struct menu_item *)stuff->stuff;
326 for (i = 0; i < stuff->nr; i++, menu_item++) {
327 const char *p;
328 int highlighted = 0;
329
330 p = menu_item->title;
331 if ((*chosen)[i] < 0)
332 (*chosen)[i] = menu_item->selected ? 1 : 0;
333 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
334 for (; *p; p++) {
335 if (!highlighted && *p == menu_item->hotkey) {
336 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
337 strbuf_addch(&menu, *p);
338 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
339 highlighted = 1;
340 } else {
341 strbuf_addch(&menu, *p);
342 }
343 }
344 string_list_append(&menu_list, menu.buf);
345 strbuf_reset(&menu);
346 }
347 break;
348 case MENU_STUFF_TYPE_STRING_LIST:
349 i = 0;
350 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
351 if ((*chosen)[i] < 0)
352 (*chosen)[i] = 0;
353 strbuf_addf(&menu, "%s%2d: %s",
354 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
355 string_list_append(&menu_list, menu.buf);
356 strbuf_reset(&menu);
357 i++;
358 }
359 break;
360 }
361
362 pretty_print_menus(&menu_list);
363
364 strbuf_release(&menu);
9f93e461
JX
365 string_list_clear(&menu_list, 0);
366}
367
60838613
JX
368static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
369{
370 struct menu_item *menu_item;
371 struct string_list_item *string_list_item;
372 int i, len, found = 0;
373
374 len = strlen(choice);
375 switch (menu_stuff->type) {
376 default:
377 die("Bad type of menu_stuff when parse choice");
378 case MENU_STUFF_TYPE_MENU_ITEM:
379
380 menu_item = (struct menu_item *)menu_stuff->stuff;
381 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
382 if (len == 1 && *choice == menu_item->hotkey) {
383 found = i + 1;
384 break;
385 }
386 if (!strncasecmp(choice, menu_item->title, len)) {
387 if (found) {
388 if (len == 1) {
389 /* continue for hotkey matching */
390 found = -1;
391 } else {
392 found = 0;
393 break;
394 }
395 } else {
396 found = i + 1;
397 }
398 }
399 }
400 break;
401 case MENU_STUFF_TYPE_STRING_LIST:
402 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
403 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
404 if (!strncasecmp(choice, string_list_item->string, len)) {
405 if (found) {
406 found = 0;
407 break;
408 }
409 found = i + 1;
410 }
411 }
412 break;
413 }
414 return found;
415}
416
417
9f93e461
JX
418/*
419 * Parse user input, and return choice(s) for menu (menu_stuff).
420 *
421 * Input
422 * (for single choice)
423 * 1 - select a numbered item
424 * foo - select item based on menu title
425 * - (empty) select nothing
426 *
427 * (for multiple choice)
428 * 1 - select a single item
429 * 3-5 - select a range of items
430 * 2-3,6-9 - select multiple ranges
431 * foo - select item based on menu title
432 * -... - unselect specified items
433 * * - choose all items
434 * - (empty) finish selecting
435 *
436 * The parse result will be saved in array **chosen, and
437 * return number of total selections.
438 */
439static int parse_choice(struct menu_stuff *menu_stuff,
440 int is_single,
441 struct strbuf input,
442 int **chosen)
443{
444 struct strbuf **choice_list, **ptr;
9f93e461
JX
445 int nr = 0;
446 int i;
447
448 if (is_single) {
449 choice_list = strbuf_split_max(&input, '\n', 0);
450 } else {
451 char *p = input.buf;
452 do {
453 if (*p == ',')
454 *p = ' ';
455 } while (*p++);
456 choice_list = strbuf_split_max(&input, ' ', 0);
457 }
458
459 for (ptr = choice_list; *ptr; ptr++) {
460 char *p;
461 int choose = 1;
462 int bottom = 0, top = 0;
463 int is_range, is_number;
464
465 strbuf_trim(*ptr);
466 if (!(*ptr)->len)
467 continue;
468
469 /* Input that begins with '-'; unchoose */
470 if (*(*ptr)->buf == '-') {
471 choose = 0;
472 strbuf_remove((*ptr), 0, 1);
473 }
474
475 is_range = 0;
476 is_number = 1;
477 for (p = (*ptr)->buf; *p; p++) {
478 if ('-' == *p) {
479 if (!is_range) {
480 is_range = 1;
481 is_number = 0;
482 } else {
483 is_number = 0;
484 is_range = 0;
485 break;
486 }
487 } else if (!isdigit(*p)) {
488 is_number = 0;
489 is_range = 0;
490 break;
491 }
492 }
493
494 if (is_number) {
495 bottom = atoi((*ptr)->buf);
496 top = bottom;
497 } else if (is_range) {
498 bottom = atoi((*ptr)->buf);
499 /* a range can be specified like 5-7 or 5- */
500 if (!*(strchr((*ptr)->buf, '-') + 1))
501 top = menu_stuff->nr;
502 else
503 top = atoi(strchr((*ptr)->buf, '-') + 1);
504 } else if (!strcmp((*ptr)->buf, "*")) {
505 bottom = 1;
506 top = menu_stuff->nr;
507 } else {
60838613
JX
508 bottom = find_unique((*ptr)->buf, menu_stuff);
509 top = bottom;
9f93e461
JX
510 }
511
512 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
513 (is_single && bottom != top)) {
514 clean_print_color(CLEAN_COLOR_ERROR);
515 printf_ln(_("Huh (%s)?"), (*ptr)->buf);
516 clean_print_color(CLEAN_COLOR_RESET);
517 continue;
518 }
519
520 for (i = bottom; i <= top; i++)
521 (*chosen)[i-1] = choose;
522 }
523
524 strbuf_list_free(choice_list);
525
526 for (i = 0; i < menu_stuff->nr; i++)
527 nr += (*chosen)[i];
528 return nr;
529}
530
531/*
532 * Implement a git-add-interactive compatible UI, which is borrowed
533 * from git-add--interactive.perl.
534 *
535 * Return value:
536 *
537 * - Return an array of integers
538 * - , and it is up to you to free the allocated memory.
539 * - The array ends with EOF.
540 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
541 */
542static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
543{
544 struct strbuf choice = STRBUF_INIT;
545 int *chosen, *result;
546 int nr = 0;
547 int eof = 0;
548 int i;
549
550 chosen = xmalloc(sizeof(int) * stuff->nr);
551 /* set chosen as uninitialized */
552 for (i = 0; i < stuff->nr; i++)
553 chosen[i] = -1;
554
555 for (;;) {
556 if (opts->header) {
557 printf_ln("%s%s%s",
558 clean_get_color(CLEAN_COLOR_HEADER),
559 _(opts->header),
560 clean_get_color(CLEAN_COLOR_RESET));
561 }
562
563 /* chosen will be initialized by print_highlight_menu_stuff */
564 print_highlight_menu_stuff(stuff, &chosen);
565
566 if (opts->flags & MENU_OPTS_LIST_ONLY)
567 break;
568
569 if (opts->prompt) {
570 printf("%s%s%s%s",
571 clean_get_color(CLEAN_COLOR_PROMPT),
572 _(opts->prompt),
573 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
574 clean_get_color(CLEAN_COLOR_RESET));
575 }
576
577 if (strbuf_getline(&choice, stdin, '\n') != EOF) {
578 strbuf_trim(&choice);
579 } else {
580 eof = 1;
581 break;
582 }
583
584 /* help for prompt */
585 if (!strcmp(choice.buf, "?")) {
586 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
587 continue;
588 }
589
590 /* for a multiple-choice menu, press ENTER (empty) will return back */
591 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
592 break;
593
594 nr = parse_choice(stuff,
595 opts->flags & MENU_OPTS_SINGLETON,
596 choice,
597 &chosen);
598
599 if (opts->flags & MENU_OPTS_SINGLETON) {
600 if (nr)
601 break;
602 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
603 break;
604 }
605 }
606
607 if (eof) {
608 result = xmalloc(sizeof(int));
609 *result = EOF;
610 } else {
611 int j = 0;
612
613 /*
614 * recalculate nr, if return back from menu directly with
615 * default selections.
616 */
617 if (!nr) {
618 for (i = 0; i < stuff->nr; i++)
619 nr += chosen[i];
620 }
621
51a60f5b 622 result = xcalloc(nr + 1, sizeof(int));
9f93e461
JX
623 for (i = 0; i < stuff->nr && j < nr; i++) {
624 if (chosen[i])
625 result[j++] = i;
626 }
627 result[j] = EOF;
628 }
629
630 free(chosen);
631 strbuf_release(&choice);
632 return result;
633}
634
635static int clean_cmd(void)
1b8fd467 636{
9f93e461
JX
637 return MENU_RETURN_NO_LOOP;
638}
639
d1239264
JX
640static int filter_by_patterns_cmd(void)
641{
642 struct dir_struct dir;
643 struct strbuf confirm = STRBUF_INIT;
644 struct strbuf **ignore_list;
645 struct string_list_item *item;
646 struct exclude_list *el;
647 int changed = -1, i;
648
649 for (;;) {
650 if (!del_list.nr)
651 break;
652
653 if (changed)
654 pretty_print_dels();
655
656 clean_print_color(CLEAN_COLOR_PROMPT);
657 printf(_("Input ignore patterns>> "));
658 clean_print_color(CLEAN_COLOR_RESET);
659 if (strbuf_getline(&confirm, stdin, '\n') != EOF)
660 strbuf_trim(&confirm);
661 else
662 putchar('\n');
663
664 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
665 if (!confirm.len)
666 break;
667
668 memset(&dir, 0, sizeof(dir));
669 el = add_exclude_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_exclude(ignore_list[i]->buf, "", 0, el, -(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, 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 clear_directory(&dir);
700 }
701
702 strbuf_release(&confirm);
703 return 0;
704}
705
c1f1d24a
JX
706static 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
96a799b6
JX
743static 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_relative(item->string, NULL, &buf);
d9130227
JNA
755 /* TRANSLATORS: Make sure to keep [y/N] as is */
756 printf(_("Remove %s [y/N]? "), qname);
96a799b6
JX
757 if (strbuf_getline(&confirm, stdin, '\n') != EOF) {
758 strbuf_trim(&confirm);
759 } else {
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
9f93e461
JX
778static int quit_cmd(void)
779{
780 string_list_clear(&del_list, 0);
781 printf_ln(_("Bye."));
782 return MENU_RETURN_NO_LOOP;
783}
784
785static int help_cmd(void)
786{
787 clean_print_color(CLEAN_COLOR_HELP);
788 printf_ln(_(
789 "clean - start cleaning\n"
d1239264 790 "filter by pattern - exclude items from deletion\n"
c1f1d24a 791 "select by numbers - select items to be deleted by numbers\n"
96a799b6 792 "ask each - confirm each deletion (like \"rm -i\")\n"
9f93e461
JX
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}
17696002 800
9f93e461
JX
801static void interactive_main_loop(void)
802{
17696002 803 while (del_list.nr) {
9f93e461
JX
804 struct menu_opts menu_opts;
805 struct menu_stuff menu_stuff;
806 struct menu_item menus[] = {
807 {'c', "clean", 0, clean_cmd},
d1239264 808 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
c1f1d24a 809 {'s', "select by numbers", 0, select_by_numbers_cmd},
96a799b6 810 {'a', "ask each", 0, ask_each_cmd},
9f93e461
JX
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
7a9b0b80 824 clean_print_color(CLEAN_COLOR_HEADER);
1b8fd467
JX
825 printf_ln(Q_("Would remove the following item:",
826 "Would remove the following items:",
827 del_list.nr));
7a9b0b80 828 clean_print_color(CLEAN_COLOR_RESET);
17696002 829
1b8fd467
JX
830 pretty_print_dels();
831
9f93e461
JX
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(chosen);
839 chosen = NULL;
840 if (!del_list.nr) {
841 clean_print_color(CLEAN_COLOR_ERROR);
842 printf_ln(_("No more files to clean, exiting."));
843 clean_print_color(CLEAN_COLOR_RESET);
844 break;
845 }
17696002
JX
846 continue;
847 }
9f93e461
JX
848 } else {
849 quit_cmd();
17696002 850 }
17696002 851
9f93e461
JX
852 free(chosen);
853 chosen = NULL;
854 break;
855 }
17696002
JX
856}
857
113f10f2
SB
858int cmd_clean(int argc, const char **argv, const char *prefix)
859{
f538a91e
ZK
860 int i, res;
861 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
862 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
a0f4afbe 863 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
396049e5 864 struct strbuf abs_path = STRBUF_INIT;
113f10f2 865 struct dir_struct dir;
893d8399 866 struct pathspec pathspec;
f285a2d7 867 struct strbuf buf = STRBUF_INIT;
bdab6a59 868 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
72aeb187 869 struct exclude_list *el;
396049e5 870 struct string_list_item *item;
1fb32894 871 const char *qname;
113f10f2 872 struct option options[] = {
145f9c81 873 OPT__QUIET(&quiet, N_("do not print names of files removed")),
f538a91e 874 OPT__DRY_RUN(&dry_run, N_("dry run")),
145f9c81 875 OPT__FORCE(&force, N_("force")),
17696002 876 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
d5d09d47 877 OPT_BOOL('d', NULL, &remove_directories,
145f9c81
NTND
878 N_("remove whole directories")),
879 { OPTION_CALLBACK, 'e', "exclude", &exclude_list, N_("pattern"),
880 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb },
d5d09d47
SB
881 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
882 OPT_BOOL('X', NULL, &ignored_only,
145f9c81 883 N_("remove only ignored files")),
113f10f2
SB
884 OPT_END()
885 };
886
ef90d6d4 887 git_config(git_clean_config, NULL);
625db1b7
JH
888 if (force < 0)
889 force = 0;
890 else
891 config_set = 1;
892
37782920
SB
893 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
894 0);
113f10f2
SB
895
896 memset(&dir, 0, sizeof(dir));
1617adc7 897 if (ignored_only)
7c4c97c0 898 dir.flags |= DIR_SHOW_IGNORED;
113f10f2
SB
899
900 if (ignored && ignored_only)
2da57add 901 die(_("-x and -X cannot be used together"));
113f10f2 902
17696002 903 if (!interactive && !dry_run && !force) {
a66f9b2a 904 if (config_set)
235e8d59 905 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
a66f9b2a
ÆAB
906 "refusing to clean"));
907 else
235e8d59
JL
908 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
909 " refusing to clean"));
a66f9b2a 910 }
113f10f2 911
a0f4afbe
JH
912 if (force > 1)
913 rm_flags = 0;
914
7c4c97c0 915 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
113f10f2 916
c28b3d6e 917 if (read_cache() < 0)
2da57add 918 die(_("index file corrupt"));
c28b3d6e 919
1617adc7
SB
920 if (!ignored)
921 setup_standard_excludes(&dir);
113f10f2 922
72aeb187 923 el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
07de4eba 924 for (i = 0; i < exclude_list.nr; i++)
72aeb187 925 add_exclude(exclude_list.items[i].string, "", 0, el, -(i+1));
07de4eba 926
893d8399
NTND
927 parse_pathspec(&pathspec, 0,
928 PATHSPEC_PREFER_CWD,
929 prefix, argv);
113f10f2 930
7327d3d1 931 fill_directory(&dir, &pathspec);
d871c869
JH
932
933 for (i = 0; i < dir.nr; i++) {
934 struct dir_entry *ent = dir.entries[i];
f2d0df71 935 int matches = 0;
113f10f2 936 struct stat st;
396049e5 937 const char *rel;
113f10f2 938
2e70c017
NTND
939 if (!cache_name_is_other(ent->name, ent->len))
940 continue;
113f10f2 941
893d8399 942 if (pathspec.nr)
05b85022 943 matches = dir_path_match(ent, &pathspec, 0, NULL);
d871c869 944
cf424f5f
JK
945 if (pathspec.nr && !matches)
946 continue;
947
838d6a92
DT
948 if (lstat(ent->name, &st))
949 die_errno("Cannot lstat '%s'", ent->name);
950
1f2e1088
JK
951 if (S_ISDIR(st.st_mode) && !remove_directories &&
952 matches != MATCHED_EXACTLY)
953 continue;
954
955 rel = relative_path(ent->name, prefix, &buf);
956 string_list_append(&del_list, rel);
396049e5
JX
957 }
958
17696002
JX
959 if (interactive && del_list.nr > 0)
960 interactive_main_loop();
396049e5
JX
961
962 for_each_string_list_item(item, &del_list) {
963 struct stat st;
964
965 if (prefix)
966 strbuf_addstr(&abs_path, prefix);
967
968 strbuf_addstr(&abs_path, item->string);
969
970 /*
971 * we might have removed this as part of earlier
972 * recursive directory removal, so lstat() here could
973 * fail with ENOENT.
974 */
975 if (lstat(abs_path.buf, &st))
976 continue;
977
978 if (S_ISDIR(st.st_mode)) {
979 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
980 errors++;
981 if (gone && !quiet) {
982 qname = quote_path_relative(item->string, NULL, &buf);
983 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
984 }
985 } else {
986 res = dry_run ? 0 : unlink(abs_path.buf);
f538a91e 987 if (res) {
396049e5 988 qname = quote_path_relative(item->string, NULL, &buf);
f538a91e 989 warning(_(msg_warn_remove_failed), qname);
aa9c83c2 990 errors++;
f538a91e 991 } else if (!quiet) {
396049e5 992 qname = quote_path_relative(item->string, NULL, &buf);
f538a91e 993 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
aa9c83c2 994 }
113f10f2 995 }
396049e5 996 strbuf_reset(&abs_path);
113f10f2
SB
997 }
998
396049e5
JX
999 strbuf_release(&abs_path);
1000 strbuf_release(&buf);
1001 string_list_clear(&del_list, 0);
07de4eba 1002 string_list_clear(&exclude_list, 0);
aa9c83c2 1003 return (errors != 0);
113f10f2 1004}