]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/clean.c
Merge branch 'gc/branch-recurse-submodules-fix'
[thirdparty/git.git] / builtin / clean.c
1 /*
2 * "git clean" builtin command
3 *
4 * Copyright (C) 2007 Shawn Bohrer
5 *
6 * Based on git-clean.sh by Pavel Roskin
7 */
8
9 #define USE_THE_INDEX_COMPATIBILITY_MACROS
10 #include "builtin.h"
11 #include "cache.h"
12 #include "config.h"
13 #include "dir.h"
14 #include "parse-options.h"
15 #include "string-list.h"
16 #include "quote.h"
17 #include "column.h"
18 #include "color.h"
19 #include "pathspec.h"
20 #include "help.h"
21 #include "prompt.h"
22
23 static int force = -1; /* unset */
24 static int interactive;
25 static struct string_list del_list = STRING_LIST_INIT_DUP;
26 static unsigned int colopts;
27
28 static const char *const builtin_clean_usage[] = {
29 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
30 NULL
31 };
32
33 static const char *msg_remove = N_("Removing %s\n");
34 static const char *msg_would_remove = N_("Would remove %s\n");
35 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
36 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
37 static const char *msg_warn_remove_failed = N_("failed to remove %s");
38 static const char *msg_warn_lstat_failed = N_("could not lstat %s\n");
39 static const char *msg_skip_cwd = N_("Refusing to remove current working directory\n");
40 static const char *msg_would_skip_cwd = N_("Would refuse to remove current working directory\n");
41
42 enum 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,
48 CLEAN_COLOR_ERROR = 5
49 };
50
51 static 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
60 static int clean_use_color = -1;
61 static 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
70 #define MENU_OPTS_SINGLETON 01
71 #define MENU_OPTS_IMMEDIATE 02
72 #define MENU_OPTS_LIST_ONLY 04
73
74 struct menu_opts {
75 const char *header;
76 const char *prompt;
77 int flags;
78 };
79
80 #define MENU_RETURN_NO_LOOP 10
81
82 struct menu_item {
83 char hotkey;
84 const char *title;
85 int selected;
86 int (*fn)(void);
87 };
88
89 enum menu_stuff_type {
90 MENU_STUFF_TYPE_STRING_LIST = 1,
91 MENU_STUFF_TYPE_MENU_ITEM
92 };
93
94 struct menu_stuff {
95 enum menu_stuff_type type;
96 int nr;
97 void *stuff;
98 };
99
100 define_list_config_array(color_interactive_slots);
101
102 static int git_clean_config(const char *var, const char *value, void *cb)
103 {
104 const char *slot_name;
105
106 if (starts_with(var, "column."))
107 return git_column_config(var, value, "clean", &colopts);
108
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 }
115 if (skip_prefix(var, "color.interactive.", &slot_name)) {
116 int slot = LOOKUP_CONFIG(color_interactive_slots, slot_name);
117 if (slot < 0)
118 return 0;
119 if (!value)
120 return config_error_nonbool(var);
121 return color_parse(value, clean_colors[slot]);
122 }
123
124 if (!strcmp(var, "clean.requireforce")) {
125 force = !git_config_bool(var, value);
126 return 0;
127 }
128
129 /* inspect the color.ui config variable and others */
130 return git_color_default_config(var, value, cb);
131 }
132
133 static 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
140 static void clean_print_color(enum color_clean ix)
141 {
142 printf("%s", clean_get_color(ix));
143 }
144
145 static int exclude_cb(const struct option *opt, const char *arg, int unset)
146 {
147 struct string_list *exclude_list = opt->value;
148 BUG_ON_OPT_NEG(unset);
149 string_list_append(exclude_list, arg);
150 return 0;
151 }
152
153 static 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;
158 struct strbuf realpath = STRBUF_INIT;
159 struct strbuf real_ocwd = STRBUF_INIT;
160 struct dirent *e;
161 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
162 struct string_list dels = STRING_LIST_INIT_DUP;
163
164 *dir_gone = 1;
165
166 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
167 is_nonbare_repository_dir(path)) {
168 if (!quiet) {
169 quote_path(path->buf, prefix, &quoted, 0);
170 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
171 quoted.buf);
172 }
173
174 *dir_gone = 0;
175 goto out;
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) {
183 int saved_errno = errno;
184 quote_path(path->buf, prefix, &quoted, 0);
185 errno = saved_errno;
186 warning_errno(_(msg_warn_remove_failed), quoted.buf);
187 *dir_gone = 0;
188 }
189 ret = res;
190 goto out;
191 }
192
193 strbuf_complete(path, '/');
194
195 len = path->len;
196 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
197 struct stat st;
198
199 strbuf_setlen(path, len);
200 strbuf_addstr(path, e->d_name);
201 if (lstat(path->buf, &st))
202 warning_errno(_(msg_warn_lstat_failed), path->buf);
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) {
207 quote_path(path->buf, prefix, &quoted, 0);
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) {
215 quote_path(path->buf, prefix, &quoted, 0);
216 string_list_append(&dels, quoted.buf);
217 } else {
218 int saved_errno = errno;
219 quote_path(path->buf, prefix, &quoted, 0);
220 errno = saved_errno;
221 warning_errno(_(msg_warn_remove_failed), quoted.buf);
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) {
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));
255 *dir_gone = 0;
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 }
268 }
269 }
270
271 if (!*dir_gone && !quiet) {
272 int i;
273 for (i = 0; i < dels.nr; i++)
274 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
275 }
276 out:
277 strbuf_release(&realpath);
278 strbuf_release(&real_ocwd);
279 strbuf_release(&quoted);
280 string_list_clear(&dels, 0);
281 return ret;
282 }
283
284 static void pretty_print_dels(void)
285 {
286 struct string_list list = STRING_LIST_INIT_DUP;
287 struct string_list_item *item;
288 struct strbuf buf = STRBUF_INIT;
289 const char *qname;
290 struct column_options copts;
291
292 for_each_string_list_item(item, &del_list) {
293 qname = quote_path(item->string, NULL, &buf, 0);
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);
306 strbuf_release(&buf);
307 string_list_clear(&list, 0);
308 }
309
310 static 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
322 static void prompt_help_cmd(int singleton)
323 {
324 clean_print_color(CLEAN_COLOR_HELP);
325 printf(singleton ?
326 _("Prompt help:\n"
327 "1 - select a numbered item\n"
328 "foo - select item based on unique prefix\n"
329 " - (empty) select nothing\n") :
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"
337 " - (empty) finish selecting\n"));
338 clean_print_color(CLEAN_COLOR_RESET);
339 }
340
341 /*
342 * display menu stuff with number prefix and hotkey highlight
343 */
344 static 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;
348 struct menu_item *menu_item;
349 struct string_list_item *string_list_item;
350 int i;
351
352 switch (stuff->type) {
353 default:
354 die("Bad type of menu_stuff when print menu");
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);
396 string_list_clear(&menu_list, 0);
397 }
398
399 static 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
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 */
469 static 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;
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 {
538 bottom = find_unique((*ptr)->buf, menu_stuff);
539 top = bottom;
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);
545 printf(_("Huh (%s)?\n"), (*ptr)->buf);
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 */
572 static 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
580 ALLOC_ARRAY(chosen, stuff->nr);
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
607 if (git_read_line_interactively(&choice) == EOF) {
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
650 CALLOC_ARRAY(result, st_add(nr, 1));
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
663 static int clean_cmd(void)
664 {
665 return MENU_RETURN_NO_LOOP;
666 }
667
668 static int filter_by_patterns_cmd(void)
669 {
670 struct dir_struct dir = DIR_INIT;
671 struct strbuf confirm = STRBUF_INIT;
672 struct strbuf **ignore_list;
673 struct string_list_item *item;
674 struct pattern_list *pl;
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);
687 if (git_read_line_interactively(&confirm) == EOF)
688 putchar('\n');
689
690 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
691 if (!confirm.len)
692 break;
693
694 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
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
702 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
703 }
704
705 changed = 0;
706 for_each_string_list_item(item, &del_list) {
707 int dtype = DT_UNKNOWN;
708
709 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
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);
724 dir_clear(&dir);
725 }
726
727 strbuf_release(&confirm);
728 return 0;
729 }
730
731 static 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
768 static 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) {
779 qname = quote_path(item->string, NULL, &buf, 0);
780 /* TRANSLATORS: Make sure to keep [y/N] as is */
781 printf(_("Remove %s [y/N]? "), qname);
782 if (git_read_line_interactively(&confirm) == EOF) {
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
801 static int quit_cmd(void)
802 {
803 string_list_clear(&del_list, 0);
804 printf(_("Bye.\n"));
805 return MENU_RETURN_NO_LOOP;
806 }
807
808 static int help_cmd(void)
809 {
810 clean_print_color(CLEAN_COLOR_HELP);
811 printf_ln(_(
812 "clean - start cleaning\n"
813 "filter by pattern - exclude items from deletion\n"
814 "select by numbers - select items to be deleted by numbers\n"
815 "ask each - confirm each deletion (like \"rm -i\")\n"
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 }
823
824 static void interactive_main_loop(void)
825 {
826 while (del_list.nr) {
827 struct menu_opts menu_opts;
828 struct menu_stuff menu_stuff;
829 struct menu_item menus[] = {
830 {'c', "clean", 0, clean_cmd},
831 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
832 {'s', "select by numbers", 0, select_by_numbers_cmd},
833 {'a', "ask each", 0, ask_each_cmd},
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
847 clean_print_color(CLEAN_COLOR_HEADER);
848 printf_ln(Q_("Would remove the following item:",
849 "Would remove the following items:",
850 del_list.nr));
851 clean_print_color(CLEAN_COLOR_RESET);
852
853 pretty_print_dels();
854
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) {
861 FREE_AND_NULL(chosen);
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 }
868 continue;
869 }
870 } else {
871 quit_cmd();
872 }
873
874 FREE_AND_NULL(chosen);
875 break;
876 }
877 }
878
879 static 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
911 int cmd_clean(int argc, const char **argv, const char *prefix)
912 {
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;
916 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
917 struct strbuf abs_path = STRBUF_INIT;
918 struct dir_struct dir = DIR_INIT;
919 struct pathspec pathspec;
920 struct strbuf buf = STRBUF_INIT;
921 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
922 struct pattern_list *pl;
923 struct string_list_item *item;
924 const char *qname;
925 struct option options[] = {
926 OPT__QUIET(&quiet, N_("do not print names of files removed")),
927 OPT__DRY_RUN(&dry_run, N_("dry run")),
928 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
929 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
930 OPT_BOOL('d', NULL, &remove_directories,
931 N_("remove whole directories")),
932 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
933 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
934 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
935 OPT_BOOL('X', NULL, &ignored_only,
936 N_("remove only ignored files")),
937 OPT_END()
938 };
939
940 git_config(git_clean_config, NULL);
941 if (force < 0)
942 force = 0;
943 else
944 config_set = 1;
945
946 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
947 0);
948
949 if (!interactive && !dry_run && !force) {
950 if (config_set)
951 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
952 "refusing to clean"));
953 else
954 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
955 " refusing to clean"));
956 }
957
958 if (force > 1)
959 rm_flags = 0;
960 else
961 dir.flags |= DIR_SKIP_NESTED_GIT;
962
963 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
964
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
972 if (argc) {
973 /*
974 * Remaining args implies pathspecs specified, and we should
975 * recurse within those.
976 */
977 remove_directories = 1;
978 }
979
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 }
1011
1012 prepare_repo_settings(the_repository);
1013 the_repository->settings.command_requires_full_index = 0;
1014
1015 if (read_cache() < 0)
1016 die(_("index file corrupt"));
1017
1018 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
1019 for (i = 0; i < exclude_list.nr; i++)
1020 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
1021
1022 parse_pathspec(&pathspec, 0,
1023 PATHSPEC_PREFER_CWD,
1024 prefix, argv);
1025
1026 fill_directory(&dir, &the_index, &pathspec);
1027 correct_untracked_entries(&dir);
1028
1029 for (i = 0; i < dir.nr; i++) {
1030 struct dir_entry *ent = dir.entries[i];
1031 struct stat st;
1032 const char *rel;
1033
1034 if (!cache_name_is_other(ent->name, ent->len))
1035 continue;
1036
1037 if (lstat(ent->name, &st))
1038 die_errno("Cannot lstat '%s'", ent->name);
1039
1040 if (S_ISDIR(st.st_mode) && !remove_directories)
1041 continue;
1042
1043 rel = relative_path(ent->name, prefix, &buf);
1044 string_list_append(&del_list, rel);
1045 }
1046
1047 dir_clear(&dir);
1048
1049 if (interactive && del_list.nr > 0)
1050 interactive_main_loop();
1051
1052 for_each_string_list_item(item, &del_list) {
1053 struct stat st;
1054
1055 strbuf_reset(&abs_path);
1056 if (prefix)
1057 strbuf_addstr(&abs_path, prefix);
1058
1059 strbuf_addstr(&abs_path, item->string);
1060
1061 /*
1062 * we might have removed this as part of earlier
1063 * recursive directory removal, so lstat() here could
1064 * fail with ENOENT.
1065 */
1066 if (lstat(abs_path.buf, &st))
1067 continue;
1068
1069 if (S_ISDIR(st.st_mode)) {
1070 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1071 errors++;
1072 if (gone && !quiet) {
1073 qname = quote_path(item->string, NULL, &buf, 0);
1074 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1075 }
1076 } else {
1077 res = dry_run ? 0 : unlink(abs_path.buf);
1078 if (res) {
1079 int saved_errno = errno;
1080 qname = quote_path(item->string, NULL, &buf, 0);
1081 errno = saved_errno;
1082 warning_errno(_(msg_warn_remove_failed), qname);
1083 errors++;
1084 } else if (!quiet) {
1085 qname = quote_path(item->string, NULL, &buf, 0);
1086 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1087 }
1088 }
1089 }
1090
1091 strbuf_release(&abs_path);
1092 strbuf_release(&buf);
1093 string_list_clear(&del_list, 0);
1094 string_list_clear(&exclude_list, 0);
1095 return (errors != 0);
1096 }