read-cache*.h: move declarations for read-cache.c functions from cache.h
[alt-git.git] / builtin / clean.c
blob49c7af45b038d54d8b0206c68bd09fcfb423724b
1 /*
2 * "git clean" builtin command
4 * Copyright (C) 2007 Shawn Bohrer
6 * Based on git-clean.sh by Pavel Roskin
7 */
9 #define USE_THE_INDEX_VARIABLE
10 #include "builtin.h"
11 #include "abspath.h"
12 #include "cache.h"
13 #include "config.h"
14 #include "dir.h"
15 #include "gettext.h"
16 #include "parse-options.h"
17 #include "read-cache-ll.h"
18 #include "repository.h"
19 #include "setup.h"
20 #include "string-list.h"
21 #include "quote.h"
22 #include "column.h"
23 #include "color.h"
24 #include "pathspec.h"
25 #include "help.h"
26 #include "prompt.h"
28 static int force = -1; /* unset */
29 static int interactive;
30 static struct string_list del_list = STRING_LIST_INIT_DUP;
31 static unsigned int colopts;
33 static const char *const builtin_clean_usage[] = {
34 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] [<pathspec>...]"),
35 NULL
38 static const char *msg_remove = N_("Removing %s\n");
39 static const char *msg_would_remove = N_("Would remove %s\n");
40 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
41 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
42 static const char *msg_warn_remove_failed = N_("failed to remove %s");
43 static const char *msg_warn_lstat_failed = N_("could not lstat %s\n");
44 static const char *msg_skip_cwd = N_("Refusing to remove current working directory\n");
45 static const char *msg_would_skip_cwd = N_("Would refuse to remove current working directory\n");
47 enum color_clean {
48 CLEAN_COLOR_RESET = 0,
49 CLEAN_COLOR_PLAIN = 1,
50 CLEAN_COLOR_PROMPT = 2,
51 CLEAN_COLOR_HEADER = 3,
52 CLEAN_COLOR_HELP = 4,
53 CLEAN_COLOR_ERROR = 5
56 static const char *color_interactive_slots[] = {
57 [CLEAN_COLOR_ERROR] = "error",
58 [CLEAN_COLOR_HEADER] = "header",
59 [CLEAN_COLOR_HELP] = "help",
60 [CLEAN_COLOR_PLAIN] = "plain",
61 [CLEAN_COLOR_PROMPT] = "prompt",
62 [CLEAN_COLOR_RESET] = "reset",
65 static int clean_use_color = -1;
66 static char clean_colors[][COLOR_MAXLEN] = {
67 [CLEAN_COLOR_ERROR] = GIT_COLOR_BOLD_RED,
68 [CLEAN_COLOR_HEADER] = GIT_COLOR_BOLD,
69 [CLEAN_COLOR_HELP] = GIT_COLOR_BOLD_RED,
70 [CLEAN_COLOR_PLAIN] = GIT_COLOR_NORMAL,
71 [CLEAN_COLOR_PROMPT] = GIT_COLOR_BOLD_BLUE,
72 [CLEAN_COLOR_RESET] = GIT_COLOR_RESET,
75 #define MENU_OPTS_SINGLETON 01
76 #define MENU_OPTS_IMMEDIATE 02
77 #define MENU_OPTS_LIST_ONLY 04
79 struct menu_opts {
80 const char *header;
81 const char *prompt;
82 int flags;
85 #define MENU_RETURN_NO_LOOP 10
87 struct menu_item {
88 char hotkey;
89 const char *title;
90 int selected;
91 int (*fn)(void);
94 enum menu_stuff_type {
95 MENU_STUFF_TYPE_STRING_LIST = 1,
96 MENU_STUFF_TYPE_MENU_ITEM
99 struct menu_stuff {
100 enum menu_stuff_type type;
101 int nr;
102 void *stuff;
105 define_list_config_array(color_interactive_slots);
107 static int git_clean_config(const char *var, const char *value, void *cb)
109 const char *slot_name;
111 if (starts_with(var, "column."))
112 return git_column_config(var, value, "clean", &colopts);
114 /* honors the color.interactive* config variables which also
115 applied in git-add--interactive and git-stash */
116 if (!strcmp(var, "color.interactive")) {
117 clean_use_color = git_config_colorbool(var, value);
118 return 0;
120 if (skip_prefix(var, "color.interactive.", &slot_name)) {
121 int slot = LOOKUP_CONFIG(color_interactive_slots, slot_name);
122 if (slot < 0)
123 return 0;
124 if (!value)
125 return config_error_nonbool(var);
126 return color_parse(value, clean_colors[slot]);
129 if (!strcmp(var, "clean.requireforce")) {
130 force = !git_config_bool(var, value);
131 return 0;
134 /* inspect the color.ui config variable and others */
135 return git_color_default_config(var, value, cb);
138 static const char *clean_get_color(enum color_clean ix)
140 if (want_color(clean_use_color))
141 return clean_colors[ix];
142 return "";
145 static void clean_print_color(enum color_clean ix)
147 printf("%s", clean_get_color(ix));
150 static int exclude_cb(const struct option *opt, const char *arg, int unset)
152 struct string_list *exclude_list = opt->value;
153 BUG_ON_OPT_NEG(unset);
154 string_list_append(exclude_list, arg);
155 return 0;
158 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
159 int dry_run, int quiet, int *dir_gone)
161 DIR *dir;
162 struct strbuf quoted = STRBUF_INIT;
163 struct strbuf realpath = STRBUF_INIT;
164 struct strbuf real_ocwd = STRBUF_INIT;
165 struct dirent *e;
166 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
167 struct string_list dels = STRING_LIST_INIT_DUP;
169 *dir_gone = 1;
171 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
172 is_nonbare_repository_dir(path)) {
173 if (!quiet) {
174 quote_path(path->buf, prefix, &quoted, 0);
175 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
176 quoted.buf);
179 *dir_gone = 0;
180 goto out;
183 dir = opendir(path->buf);
184 if (!dir) {
185 /* an empty dir could be removed even if it is unreadble */
186 res = dry_run ? 0 : rmdir(path->buf);
187 if (res) {
188 int saved_errno = errno;
189 quote_path(path->buf, prefix, &quoted, 0);
190 errno = saved_errno;
191 warning_errno(_(msg_warn_remove_failed), quoted.buf);
192 *dir_gone = 0;
194 ret = res;
195 goto out;
198 strbuf_complete(path, '/');
200 len = path->len;
201 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
202 struct stat st;
204 strbuf_setlen(path, len);
205 strbuf_addstr(path, e->d_name);
206 if (lstat(path->buf, &st))
207 warning_errno(_(msg_warn_lstat_failed), path->buf);
208 else if (S_ISDIR(st.st_mode)) {
209 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
210 ret = 1;
211 if (gone) {
212 quote_path(path->buf, prefix, &quoted, 0);
213 string_list_append(&dels, quoted.buf);
214 } else
215 *dir_gone = 0;
216 continue;
217 } else {
218 res = dry_run ? 0 : unlink(path->buf);
219 if (!res) {
220 quote_path(path->buf, prefix, &quoted, 0);
221 string_list_append(&dels, quoted.buf);
222 } else {
223 int saved_errno = errno;
224 quote_path(path->buf, prefix, &quoted, 0);
225 errno = saved_errno;
226 warning_errno(_(msg_warn_remove_failed), quoted.buf);
227 *dir_gone = 0;
228 ret = 1;
230 continue;
233 /* path too long, stat fails, or non-directory still exists */
234 *dir_gone = 0;
235 ret = 1;
236 break;
238 closedir(dir);
240 strbuf_setlen(path, original_len);
242 if (*dir_gone) {
244 * Normalize path components in path->buf, e.g. change '\' to
245 * '/' on Windows.
247 strbuf_realpath(&realpath, path->buf, 1);
250 * path and realpath are absolute; for comparison, we would
251 * like to transform startup_info->original_cwd to an absolute
252 * path too.
254 if (startup_info->original_cwd)
255 strbuf_realpath(&real_ocwd,
256 startup_info->original_cwd, 1);
258 if (!strbuf_cmp(&realpath, &real_ocwd)) {
259 printf("%s", dry_run ? _(msg_would_skip_cwd) : _(msg_skip_cwd));
260 *dir_gone = 0;
261 } else {
262 res = dry_run ? 0 : rmdir(path->buf);
263 if (!res)
264 *dir_gone = 1;
265 else {
266 int saved_errno = errno;
267 quote_path(path->buf, prefix, &quoted, 0);
268 errno = saved_errno;
269 warning_errno(_(msg_warn_remove_failed), quoted.buf);
270 *dir_gone = 0;
271 ret = 1;
276 if (!*dir_gone && !quiet) {
277 int i;
278 for (i = 0; i < dels.nr; i++)
279 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
281 out:
282 strbuf_release(&realpath);
283 strbuf_release(&real_ocwd);
284 strbuf_release(&quoted);
285 string_list_clear(&dels, 0);
286 return ret;
289 static void pretty_print_dels(void)
291 struct string_list list = STRING_LIST_INIT_DUP;
292 struct string_list_item *item;
293 struct strbuf buf = STRBUF_INIT;
294 const char *qname;
295 struct column_options copts;
297 for_each_string_list_item(item, &del_list) {
298 qname = quote_path(item->string, NULL, &buf, 0);
299 string_list_append(&list, qname);
303 * always enable column display, we only consult column.*
304 * about layout strategy and stuff
306 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
307 memset(&copts, 0, sizeof(copts));
308 copts.indent = " ";
309 copts.padding = 2;
310 print_columns(&list, colopts, &copts);
311 strbuf_release(&buf);
312 string_list_clear(&list, 0);
315 static void pretty_print_menus(struct string_list *menu_list)
317 unsigned int local_colopts = 0;
318 struct column_options copts;
320 local_colopts = COL_ENABLED | COL_ROW;
321 memset(&copts, 0, sizeof(copts));
322 copts.indent = " ";
323 copts.padding = 2;
324 print_columns(menu_list, local_colopts, &copts);
327 static void prompt_help_cmd(int singleton)
329 clean_print_color(CLEAN_COLOR_HELP);
330 printf(singleton ?
331 _("Prompt help:\n"
332 "1 - select a numbered item\n"
333 "foo - select item based on unique prefix\n"
334 " - (empty) select nothing\n") :
335 _("Prompt help:\n"
336 "1 - select a single item\n"
337 "3-5 - select a range of items\n"
338 "2-3,6-9 - select multiple ranges\n"
339 "foo - select item based on unique prefix\n"
340 "-... - unselect specified items\n"
341 "* - choose all items\n"
342 " - (empty) finish selecting\n"));
343 clean_print_color(CLEAN_COLOR_RESET);
347 * display menu stuff with number prefix and hotkey highlight
349 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
351 struct string_list menu_list = STRING_LIST_INIT_DUP;
352 struct strbuf menu = STRBUF_INIT;
353 struct menu_item *menu_item;
354 struct string_list_item *string_list_item;
355 int i;
357 switch (stuff->type) {
358 default:
359 die("Bad type of menu_stuff when print menu");
360 case MENU_STUFF_TYPE_MENU_ITEM:
361 menu_item = (struct menu_item *)stuff->stuff;
362 for (i = 0; i < stuff->nr; i++, menu_item++) {
363 const char *p;
364 int highlighted = 0;
366 p = menu_item->title;
367 if ((*chosen)[i] < 0)
368 (*chosen)[i] = menu_item->selected ? 1 : 0;
369 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
370 for (; *p; p++) {
371 if (!highlighted && *p == menu_item->hotkey) {
372 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
373 strbuf_addch(&menu, *p);
374 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
375 highlighted = 1;
376 } else {
377 strbuf_addch(&menu, *p);
380 string_list_append(&menu_list, menu.buf);
381 strbuf_reset(&menu);
383 break;
384 case MENU_STUFF_TYPE_STRING_LIST:
385 i = 0;
386 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
387 if ((*chosen)[i] < 0)
388 (*chosen)[i] = 0;
389 strbuf_addf(&menu, "%s%2d: %s",
390 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
391 string_list_append(&menu_list, menu.buf);
392 strbuf_reset(&menu);
393 i++;
395 break;
398 pretty_print_menus(&menu_list);
400 strbuf_release(&menu);
401 string_list_clear(&menu_list, 0);
404 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
406 struct menu_item *menu_item;
407 struct string_list_item *string_list_item;
408 int i, len, found = 0;
410 len = strlen(choice);
411 switch (menu_stuff->type) {
412 default:
413 die("Bad type of menu_stuff when parse choice");
414 case MENU_STUFF_TYPE_MENU_ITEM:
416 menu_item = (struct menu_item *)menu_stuff->stuff;
417 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
418 if (len == 1 && *choice == menu_item->hotkey) {
419 found = i + 1;
420 break;
422 if (!strncasecmp(choice, menu_item->title, len)) {
423 if (found) {
424 if (len == 1) {
425 /* continue for hotkey matching */
426 found = -1;
427 } else {
428 found = 0;
429 break;
431 } else {
432 found = i + 1;
436 break;
437 case MENU_STUFF_TYPE_STRING_LIST:
438 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
439 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
440 if (!strncasecmp(choice, string_list_item->string, len)) {
441 if (found) {
442 found = 0;
443 break;
445 found = i + 1;
448 break;
450 return found;
454 * Parse user input, and return choice(s) for menu (menu_stuff).
456 * Input
457 * (for single choice)
458 * 1 - select a numbered item
459 * foo - select item based on menu title
460 * - (empty) select nothing
462 * (for multiple choice)
463 * 1 - select a single item
464 * 3-5 - select a range of items
465 * 2-3,6-9 - select multiple ranges
466 * foo - select item based on menu title
467 * -... - unselect specified items
468 * * - choose all items
469 * - (empty) finish selecting
471 * The parse result will be saved in array **chosen, and
472 * return number of total selections.
474 static int parse_choice(struct menu_stuff *menu_stuff,
475 int is_single,
476 struct strbuf input,
477 int **chosen)
479 struct strbuf **choice_list, **ptr;
480 int nr = 0;
481 int i;
483 if (is_single) {
484 choice_list = strbuf_split_max(&input, '\n', 0);
485 } else {
486 char *p = input.buf;
487 do {
488 if (*p == ',')
489 *p = ' ';
490 } while (*p++);
491 choice_list = strbuf_split_max(&input, ' ', 0);
494 for (ptr = choice_list; *ptr; ptr++) {
495 char *p;
496 int choose = 1;
497 int bottom = 0, top = 0;
498 int is_range, is_number;
500 strbuf_trim(*ptr);
501 if (!(*ptr)->len)
502 continue;
504 /* Input that begins with '-'; unchoose */
505 if (*(*ptr)->buf == '-') {
506 choose = 0;
507 strbuf_remove((*ptr), 0, 1);
510 is_range = 0;
511 is_number = 1;
512 for (p = (*ptr)->buf; *p; p++) {
513 if ('-' == *p) {
514 if (!is_range) {
515 is_range = 1;
516 is_number = 0;
517 } else {
518 is_number = 0;
519 is_range = 0;
520 break;
522 } else if (!isdigit(*p)) {
523 is_number = 0;
524 is_range = 0;
525 break;
529 if (is_number) {
530 bottom = atoi((*ptr)->buf);
531 top = bottom;
532 } else if (is_range) {
533 bottom = atoi((*ptr)->buf);
534 /* a range can be specified like 5-7 or 5- */
535 if (!*(strchr((*ptr)->buf, '-') + 1))
536 top = menu_stuff->nr;
537 else
538 top = atoi(strchr((*ptr)->buf, '-') + 1);
539 } else if (!strcmp((*ptr)->buf, "*")) {
540 bottom = 1;
541 top = menu_stuff->nr;
542 } else {
543 bottom = find_unique((*ptr)->buf, menu_stuff);
544 top = bottom;
547 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
548 (is_single && bottom != top)) {
549 clean_print_color(CLEAN_COLOR_ERROR);
550 printf(_("Huh (%s)?\n"), (*ptr)->buf);
551 clean_print_color(CLEAN_COLOR_RESET);
552 continue;
555 for (i = bottom; i <= top; i++)
556 (*chosen)[i-1] = choose;
559 strbuf_list_free(choice_list);
561 for (i = 0; i < menu_stuff->nr; i++)
562 nr += (*chosen)[i];
563 return nr;
567 * Implement a git-add-interactive compatible UI, which is borrowed
568 * from add-interactive.c.
570 * Return value:
572 * - Return an array of integers
573 * - , and it is up to you to free the allocated memory.
574 * - The array ends with EOF.
575 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
577 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
579 struct strbuf choice = STRBUF_INIT;
580 int *chosen, *result;
581 int nr = 0;
582 int eof = 0;
583 int i;
585 ALLOC_ARRAY(chosen, stuff->nr);
586 /* set chosen as uninitialized */
587 for (i = 0; i < stuff->nr; i++)
588 chosen[i] = -1;
590 for (;;) {
591 if (opts->header) {
592 printf_ln("%s%s%s",
593 clean_get_color(CLEAN_COLOR_HEADER),
594 _(opts->header),
595 clean_get_color(CLEAN_COLOR_RESET));
598 /* chosen will be initialized by print_highlight_menu_stuff */
599 print_highlight_menu_stuff(stuff, &chosen);
601 if (opts->flags & MENU_OPTS_LIST_ONLY)
602 break;
604 if (opts->prompt) {
605 printf("%s%s%s%s",
606 clean_get_color(CLEAN_COLOR_PROMPT),
607 _(opts->prompt),
608 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
609 clean_get_color(CLEAN_COLOR_RESET));
612 if (git_read_line_interactively(&choice) == EOF) {
613 eof = 1;
614 break;
617 /* help for prompt */
618 if (!strcmp(choice.buf, "?")) {
619 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
620 continue;
623 /* for a multiple-choice menu, press ENTER (empty) will return back */
624 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
625 break;
627 nr = parse_choice(stuff,
628 opts->flags & MENU_OPTS_SINGLETON,
629 choice,
630 &chosen);
632 if (opts->flags & MENU_OPTS_SINGLETON) {
633 if (nr)
634 break;
635 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
636 break;
640 if (eof) {
641 result = xmalloc(sizeof(int));
642 *result = EOF;
643 } else {
644 int j = 0;
647 * recalculate nr, if return back from menu directly with
648 * default selections.
650 if (!nr) {
651 for (i = 0; i < stuff->nr; i++)
652 nr += chosen[i];
655 CALLOC_ARRAY(result, st_add(nr, 1));
656 for (i = 0; i < stuff->nr && j < nr; i++) {
657 if (chosen[i])
658 result[j++] = i;
660 result[j] = EOF;
663 free(chosen);
664 strbuf_release(&choice);
665 return result;
668 static int clean_cmd(void)
670 return MENU_RETURN_NO_LOOP;
673 static int filter_by_patterns_cmd(void)
675 struct dir_struct dir = DIR_INIT;
676 struct strbuf confirm = STRBUF_INIT;
677 struct strbuf **ignore_list;
678 struct string_list_item *item;
679 struct pattern_list *pl;
680 int changed = -1, i;
682 for (;;) {
683 if (!del_list.nr)
684 break;
686 if (changed)
687 pretty_print_dels();
689 clean_print_color(CLEAN_COLOR_PROMPT);
690 printf(_("Input ignore patterns>> "));
691 clean_print_color(CLEAN_COLOR_RESET);
692 if (git_read_line_interactively(&confirm) == EOF)
693 putchar('\n');
695 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
696 if (!confirm.len)
697 break;
699 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
700 ignore_list = strbuf_split_max(&confirm, ' ', 0);
702 for (i = 0; ignore_list[i]; i++) {
703 strbuf_trim(ignore_list[i]);
704 if (!ignore_list[i]->len)
705 continue;
707 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
710 changed = 0;
711 for_each_string_list_item(item, &del_list) {
712 int dtype = DT_UNKNOWN;
714 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
715 *item->string = '\0';
716 changed++;
720 if (changed) {
721 string_list_remove_empty_items(&del_list, 0);
722 } else {
723 clean_print_color(CLEAN_COLOR_ERROR);
724 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
725 clean_print_color(CLEAN_COLOR_RESET);
728 strbuf_list_free(ignore_list);
729 dir_clear(&dir);
732 strbuf_release(&confirm);
733 return 0;
736 static int select_by_numbers_cmd(void)
738 struct menu_opts menu_opts;
739 struct menu_stuff menu_stuff;
740 struct string_list_item *items;
741 int *chosen;
742 int i, j;
744 menu_opts.header = NULL;
745 menu_opts.prompt = N_("Select items to delete");
746 menu_opts.flags = 0;
748 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
749 menu_stuff.stuff = &del_list;
750 menu_stuff.nr = del_list.nr;
752 chosen = list_and_choose(&menu_opts, &menu_stuff);
753 items = del_list.items;
754 for (i = 0, j = 0; i < del_list.nr; i++) {
755 if (i < chosen[j]) {
756 *(items[i].string) = '\0';
757 } else if (i == chosen[j]) {
758 /* delete selected item */
759 j++;
760 continue;
761 } else {
762 /* end of chosen (chosen[j] == EOF), won't delete */
763 *(items[i].string) = '\0';
767 string_list_remove_empty_items(&del_list, 0);
769 free(chosen);
770 return 0;
773 static int ask_each_cmd(void)
775 struct strbuf confirm = STRBUF_INIT;
776 struct strbuf buf = STRBUF_INIT;
777 struct string_list_item *item;
778 const char *qname;
779 int changed = 0, eof = 0;
781 for_each_string_list_item(item, &del_list) {
782 /* Ctrl-D should stop removing files */
783 if (!eof) {
784 qname = quote_path(item->string, NULL, &buf, 0);
785 /* TRANSLATORS: Make sure to keep [y/N] as is */
786 printf(_("Remove %s [y/N]? "), qname);
787 if (git_read_line_interactively(&confirm) == EOF) {
788 putchar('\n');
789 eof = 1;
792 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
793 *item->string = '\0';
794 changed++;
798 if (changed)
799 string_list_remove_empty_items(&del_list, 0);
801 strbuf_release(&buf);
802 strbuf_release(&confirm);
803 return MENU_RETURN_NO_LOOP;
806 static int quit_cmd(void)
808 string_list_clear(&del_list, 0);
809 printf(_("Bye.\n"));
810 return MENU_RETURN_NO_LOOP;
813 static int help_cmd(void)
815 clean_print_color(CLEAN_COLOR_HELP);
816 printf_ln(_(
817 "clean - start cleaning\n"
818 "filter by pattern - exclude items from deletion\n"
819 "select by numbers - select items to be deleted by numbers\n"
820 "ask each - confirm each deletion (like \"rm -i\")\n"
821 "quit - stop cleaning\n"
822 "help - this screen\n"
823 "? - help for prompt selection"
825 clean_print_color(CLEAN_COLOR_RESET);
826 return 0;
829 static void interactive_main_loop(void)
831 while (del_list.nr) {
832 struct menu_opts menu_opts;
833 struct menu_stuff menu_stuff;
834 struct menu_item menus[] = {
835 {'c', "clean", 0, clean_cmd},
836 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
837 {'s', "select by numbers", 0, select_by_numbers_cmd},
838 {'a', "ask each", 0, ask_each_cmd},
839 {'q', "quit", 0, quit_cmd},
840 {'h', "help", 0, help_cmd},
842 int *chosen;
844 menu_opts.header = N_("*** Commands ***");
845 menu_opts.prompt = N_("What now");
846 menu_opts.flags = MENU_OPTS_SINGLETON;
848 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
849 menu_stuff.stuff = menus;
850 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
852 clean_print_color(CLEAN_COLOR_HEADER);
853 printf_ln(Q_("Would remove the following item:",
854 "Would remove the following items:",
855 del_list.nr));
856 clean_print_color(CLEAN_COLOR_RESET);
858 pretty_print_dels();
860 chosen = list_and_choose(&menu_opts, &menu_stuff);
862 if (*chosen != EOF) {
863 int ret;
864 ret = menus[*chosen].fn();
865 if (ret != MENU_RETURN_NO_LOOP) {
866 FREE_AND_NULL(chosen);
867 if (!del_list.nr) {
868 clean_print_color(CLEAN_COLOR_ERROR);
869 printf_ln(_("No more files to clean, exiting."));
870 clean_print_color(CLEAN_COLOR_RESET);
871 break;
873 continue;
875 } else {
876 quit_cmd();
879 FREE_AND_NULL(chosen);
880 break;
884 static void correct_untracked_entries(struct dir_struct *dir)
886 int src, dst, ign;
888 for (src = dst = ign = 0; src < dir->nr; src++) {
889 /* skip paths in ignored[] that cannot be inside entries[src] */
890 while (ign < dir->ignored_nr &&
891 0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
892 ign++;
894 if (ign < dir->ignored_nr &&
895 check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
896 /* entries[src] contains an ignored path, so we drop it */
897 free(dir->entries[src]);
898 } else {
899 struct dir_entry *ent = dir->entries[src++];
901 /* entries[src] does not contain an ignored path, so we keep it */
902 dir->entries[dst++] = ent;
904 /* then discard paths in entries[] contained inside entries[src] */
905 while (src < dir->nr &&
906 check_dir_entry_contains(ent, dir->entries[src]))
907 free(dir->entries[src++]);
909 /* compensate for the outer loop's loop control */
910 src--;
913 dir->nr = dst;
916 int cmd_clean(int argc, const char **argv, const char *prefix)
918 int i, res;
919 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
920 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
921 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
922 struct strbuf abs_path = STRBUF_INIT;
923 struct dir_struct dir = DIR_INIT;
924 struct pathspec pathspec;
925 struct strbuf buf = STRBUF_INIT;
926 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
927 struct pattern_list *pl;
928 struct string_list_item *item;
929 const char *qname;
930 struct option options[] = {
931 OPT__QUIET(&quiet, N_("do not print names of files removed")),
932 OPT__DRY_RUN(&dry_run, N_("dry run")),
933 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
934 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
935 OPT_BOOL('d', NULL, &remove_directories,
936 N_("remove whole directories")),
937 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
938 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
939 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
940 OPT_BOOL('X', NULL, &ignored_only,
941 N_("remove only ignored files")),
942 OPT_END()
945 git_config(git_clean_config, NULL);
946 if (force < 0)
947 force = 0;
948 else
949 config_set = 1;
951 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
954 if (!interactive && !dry_run && !force) {
955 if (config_set)
956 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
957 "refusing to clean"));
958 else
959 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
960 " refusing to clean"));
963 if (force > 1)
964 rm_flags = 0;
965 else
966 dir.flags |= DIR_SKIP_NESTED_GIT;
968 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
970 if (ignored && ignored_only)
971 die(_("-x and -X cannot be used together"));
972 if (!ignored)
973 setup_standard_excludes(&dir);
974 if (ignored_only)
975 dir.flags |= DIR_SHOW_IGNORED;
977 if (argc) {
979 * Remaining args implies pathspecs specified, and we should
980 * recurse within those.
982 remove_directories = 1;
985 if (remove_directories && !ignored_only) {
987 * We need to know about ignored files too:
989 * If (ignored), then we will delete ignored files as well.
991 * If (!ignored), then even though we not are doing
992 * anything with ignored files, we need to know about them
993 * so that we can avoid deleting a directory of untracked
994 * files that also contains an ignored file within it.
996 * For the (!ignored) case, since we only need to avoid
997 * deleting ignored files, we can set
998 * DIR_SHOW_IGNORED_TOO_MODE_MATCHING in order to avoid
999 * recursing into a directory which is itself ignored.
1001 dir.flags |= DIR_SHOW_IGNORED_TOO;
1002 if (!ignored)
1003 dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
1006 * Let the fill_directory() machinery know that we aren't
1007 * just recursing to collect the ignored files; we want all
1008 * the untracked ones so that we can delete them. (Note:
1009 * we could also set DIR_KEEP_UNTRACKED_CONTENTS when
1010 * ignored_only is true, since DIR_KEEP_UNTRACKED_CONTENTS
1011 * only has effect in combination with DIR_SHOW_IGNORED_TOO. It makes
1012 * the code clearer to exclude it, though.
1014 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
1017 prepare_repo_settings(the_repository);
1018 the_repository->settings.command_requires_full_index = 0;
1020 if (repo_read_index(the_repository) < 0)
1021 die(_("index file corrupt"));
1023 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
1024 for (i = 0; i < exclude_list.nr; i++)
1025 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
1027 parse_pathspec(&pathspec, 0,
1028 PATHSPEC_PREFER_CWD,
1029 prefix, argv);
1031 fill_directory(&dir, &the_index, &pathspec);
1032 correct_untracked_entries(&dir);
1034 for (i = 0; i < dir.nr; i++) {
1035 struct dir_entry *ent = dir.entries[i];
1036 struct stat st;
1037 const char *rel;
1039 if (!index_name_is_other(&the_index, ent->name, ent->len))
1040 continue;
1042 if (lstat(ent->name, &st))
1043 die_errno("Cannot lstat '%s'", ent->name);
1045 if (S_ISDIR(st.st_mode) && !remove_directories)
1046 continue;
1048 rel = relative_path(ent->name, prefix, &buf);
1049 string_list_append(&del_list, rel);
1052 dir_clear(&dir);
1054 if (interactive && del_list.nr > 0)
1055 interactive_main_loop();
1057 for_each_string_list_item(item, &del_list) {
1058 struct stat st;
1060 strbuf_reset(&abs_path);
1061 if (prefix)
1062 strbuf_addstr(&abs_path, prefix);
1064 strbuf_addstr(&abs_path, item->string);
1067 * we might have removed this as part of earlier
1068 * recursive directory removal, so lstat() here could
1069 * fail with ENOENT.
1071 if (lstat(abs_path.buf, &st))
1072 continue;
1074 if (S_ISDIR(st.st_mode)) {
1075 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1076 errors++;
1077 if (gone && !quiet) {
1078 qname = quote_path(item->string, NULL, &buf, 0);
1079 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1081 } else {
1082 res = dry_run ? 0 : unlink(abs_path.buf);
1083 if (res) {
1084 int saved_errno = errno;
1085 qname = quote_path(item->string, NULL, &buf, 0);
1086 errno = saved_errno;
1087 warning_errno(_(msg_warn_remove_failed), qname);
1088 errors++;
1089 } else if (!quiet) {
1090 qname = quote_path(item->string, NULL, &buf, 0);
1091 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1096 strbuf_release(&abs_path);
1097 strbuf_release(&buf);
1098 string_list_clear(&del_list, 0);
1099 string_list_clear(&exclude_list, 0);
1100 clear_pathspec(&pathspec);
1101 return (errors != 0);