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