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