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