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