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