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