surround %s with quotes when failed to lookup commit
[git/debian.git] / builtin / clean.c
blob78852d28cecb579e824cec08aa56633f411bdcac
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 "repository.h"
18 #include "setup.h"
19 #include "string-list.h"
20 #include "quote.h"
21 #include "column.h"
22 #include "color.h"
23 #include "pathspec.h"
24 #include "help.h"
25 #include "prompt.h"
27 static int force = -1; /* unset */
28 static int interactive;
29 static struct string_list del_list = STRING_LIST_INIT_DUP;
30 static unsigned int colopts;
32 static const char *const builtin_clean_usage[] = {
33 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] [<pathspec>...]"),
34 NULL
37 static const char *msg_remove = N_("Removing %s\n");
38 static const char *msg_would_remove = N_("Would remove %s\n");
39 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
40 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
41 static const char *msg_warn_remove_failed = N_("failed to remove %s");
42 static const char *msg_warn_lstat_failed = N_("could not lstat %s\n");
43 static const char *msg_skip_cwd = N_("Refusing to remove current working directory\n");
44 static const char *msg_would_skip_cwd = N_("Would refuse to remove current working directory\n");
46 enum 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,
52 CLEAN_COLOR_ERROR = 5
55 static 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",
64 static int clean_use_color = -1;
65 static 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,
74 #define MENU_OPTS_SINGLETON 01
75 #define MENU_OPTS_IMMEDIATE 02
76 #define MENU_OPTS_LIST_ONLY 04
78 struct menu_opts {
79 const char *header;
80 const char *prompt;
81 int flags;
84 #define MENU_RETURN_NO_LOOP 10
86 struct menu_item {
87 char hotkey;
88 const char *title;
89 int selected;
90 int (*fn)(void);
93 enum menu_stuff_type {
94 MENU_STUFF_TYPE_STRING_LIST = 1,
95 MENU_STUFF_TYPE_MENU_ITEM
98 struct menu_stuff {
99 enum menu_stuff_type type;
100 int nr;
101 void *stuff;
104 define_list_config_array(color_interactive_slots);
106 static int git_clean_config(const char *var, const char *value, void *cb)
108 const char *slot_name;
110 if (starts_with(var, "column."))
111 return git_column_config(var, value, "clean", &colopts);
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;
119 if (skip_prefix(var, "color.interactive.", &slot_name)) {
120 int slot = LOOKUP_CONFIG(color_interactive_slots, slot_name);
121 if (slot < 0)
122 return 0;
123 if (!value)
124 return config_error_nonbool(var);
125 return color_parse(value, clean_colors[slot]);
128 if (!strcmp(var, "clean.requireforce")) {
129 force = !git_config_bool(var, value);
130 return 0;
133 /* inspect the color.ui config variable and others */
134 return git_color_default_config(var, value, cb);
137 static const char *clean_get_color(enum color_clean ix)
139 if (want_color(clean_use_color))
140 return clean_colors[ix];
141 return "";
144 static void clean_print_color(enum color_clean ix)
146 printf("%s", clean_get_color(ix));
149 static int exclude_cb(const struct option *opt, const char *arg, int unset)
151 struct string_list *exclude_list = opt->value;
152 BUG_ON_OPT_NEG(unset);
153 string_list_append(exclude_list, arg);
154 return 0;
157 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
158 int dry_run, int quiet, int *dir_gone)
160 DIR *dir;
161 struct strbuf quoted = STRBUF_INIT;
162 struct strbuf realpath = STRBUF_INIT;
163 struct strbuf real_ocwd = STRBUF_INIT;
164 struct dirent *e;
165 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
166 struct string_list dels = STRING_LIST_INIT_DUP;
168 *dir_gone = 1;
170 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
171 is_nonbare_repository_dir(path)) {
172 if (!quiet) {
173 quote_path(path->buf, prefix, &quoted, 0);
174 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
175 quoted.buf);
178 *dir_gone = 0;
179 goto out;
182 dir = opendir(path->buf);
183 if (!dir) {
184 /* an empty dir could be removed even if it is unreadble */
185 res = dry_run ? 0 : rmdir(path->buf);
186 if (res) {
187 int saved_errno = errno;
188 quote_path(path->buf, prefix, &quoted, 0);
189 errno = saved_errno;
190 warning_errno(_(msg_warn_remove_failed), quoted.buf);
191 *dir_gone = 0;
193 ret = res;
194 goto out;
197 strbuf_complete(path, '/');
199 len = path->len;
200 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
201 struct stat st;
203 strbuf_setlen(path, len);
204 strbuf_addstr(path, e->d_name);
205 if (lstat(path->buf, &st))
206 warning_errno(_(msg_warn_lstat_failed), path->buf);
207 else if (S_ISDIR(st.st_mode)) {
208 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
209 ret = 1;
210 if (gone) {
211 quote_path(path->buf, prefix, &quoted, 0);
212 string_list_append(&dels, quoted.buf);
213 } else
214 *dir_gone = 0;
215 continue;
216 } else {
217 res = dry_run ? 0 : unlink(path->buf);
218 if (!res) {
219 quote_path(path->buf, prefix, &quoted, 0);
220 string_list_append(&dels, quoted.buf);
221 } else {
222 int saved_errno = errno;
223 quote_path(path->buf, prefix, &quoted, 0);
224 errno = saved_errno;
225 warning_errno(_(msg_warn_remove_failed), quoted.buf);
226 *dir_gone = 0;
227 ret = 1;
229 continue;
232 /* path too long, stat fails, or non-directory still exists */
233 *dir_gone = 0;
234 ret = 1;
235 break;
237 closedir(dir);
239 strbuf_setlen(path, original_len);
241 if (*dir_gone) {
243 * Normalize path components in path->buf, e.g. change '\' to
244 * '/' on Windows.
246 strbuf_realpath(&realpath, path->buf, 1);
249 * path and realpath are absolute; for comparison, we would
250 * like to transform startup_info->original_cwd to an absolute
251 * path too.
253 if (startup_info->original_cwd)
254 strbuf_realpath(&real_ocwd,
255 startup_info->original_cwd, 1);
257 if (!strbuf_cmp(&realpath, &real_ocwd)) {
258 printf("%s", dry_run ? _(msg_would_skip_cwd) : _(msg_skip_cwd));
259 *dir_gone = 0;
260 } else {
261 res = dry_run ? 0 : rmdir(path->buf);
262 if (!res)
263 *dir_gone = 1;
264 else {
265 int saved_errno = errno;
266 quote_path(path->buf, prefix, &quoted, 0);
267 errno = saved_errno;
268 warning_errno(_(msg_warn_remove_failed), quoted.buf);
269 *dir_gone = 0;
270 ret = 1;
275 if (!*dir_gone && !quiet) {
276 int i;
277 for (i = 0; i < dels.nr; i++)
278 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
280 out:
281 strbuf_release(&realpath);
282 strbuf_release(&real_ocwd);
283 strbuf_release(&quoted);
284 string_list_clear(&dels, 0);
285 return ret;
288 static void pretty_print_dels(void)
290 struct string_list list = STRING_LIST_INIT_DUP;
291 struct string_list_item *item;
292 struct strbuf buf = STRBUF_INIT;
293 const char *qname;
294 struct column_options copts;
296 for_each_string_list_item(item, &del_list) {
297 qname = quote_path(item->string, NULL, &buf, 0);
298 string_list_append(&list, qname);
302 * always enable column display, we only consult column.*
303 * about layout strategy and stuff
305 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
306 memset(&copts, 0, sizeof(copts));
307 copts.indent = " ";
308 copts.padding = 2;
309 print_columns(&list, colopts, &copts);
310 strbuf_release(&buf);
311 string_list_clear(&list, 0);
314 static void pretty_print_menus(struct string_list *menu_list)
316 unsigned int local_colopts = 0;
317 struct column_options copts;
319 local_colopts = COL_ENABLED | COL_ROW;
320 memset(&copts, 0, sizeof(copts));
321 copts.indent = " ";
322 copts.padding = 2;
323 print_columns(menu_list, local_colopts, &copts);
326 static void prompt_help_cmd(int singleton)
328 clean_print_color(CLEAN_COLOR_HELP);
329 printf(singleton ?
330 _("Prompt help:\n"
331 "1 - select a numbered item\n"
332 "foo - select item based on unique prefix\n"
333 " - (empty) select nothing\n") :
334 _("Prompt help:\n"
335 "1 - select a single item\n"
336 "3-5 - select a range of items\n"
337 "2-3,6-9 - select multiple ranges\n"
338 "foo - select item based on unique prefix\n"
339 "-... - unselect specified items\n"
340 "* - choose all items\n"
341 " - (empty) finish selecting\n"));
342 clean_print_color(CLEAN_COLOR_RESET);
346 * display menu stuff with number prefix and hotkey highlight
348 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
350 struct string_list menu_list = STRING_LIST_INIT_DUP;
351 struct strbuf menu = STRBUF_INIT;
352 struct menu_item *menu_item;
353 struct string_list_item *string_list_item;
354 int i;
356 switch (stuff->type) {
357 default:
358 die("Bad type of menu_stuff when print menu");
359 case MENU_STUFF_TYPE_MENU_ITEM:
360 menu_item = (struct menu_item *)stuff->stuff;
361 for (i = 0; i < stuff->nr; i++, menu_item++) {
362 const char *p;
363 int highlighted = 0;
365 p = menu_item->title;
366 if ((*chosen)[i] < 0)
367 (*chosen)[i] = menu_item->selected ? 1 : 0;
368 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
369 for (; *p; p++) {
370 if (!highlighted && *p == menu_item->hotkey) {
371 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
372 strbuf_addch(&menu, *p);
373 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
374 highlighted = 1;
375 } else {
376 strbuf_addch(&menu, *p);
379 string_list_append(&menu_list, menu.buf);
380 strbuf_reset(&menu);
382 break;
383 case MENU_STUFF_TYPE_STRING_LIST:
384 i = 0;
385 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
386 if ((*chosen)[i] < 0)
387 (*chosen)[i] = 0;
388 strbuf_addf(&menu, "%s%2d: %s",
389 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
390 string_list_append(&menu_list, menu.buf);
391 strbuf_reset(&menu);
392 i++;
394 break;
397 pretty_print_menus(&menu_list);
399 strbuf_release(&menu);
400 string_list_clear(&menu_list, 0);
403 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
405 struct menu_item *menu_item;
406 struct string_list_item *string_list_item;
407 int i, len, found = 0;
409 len = strlen(choice);
410 switch (menu_stuff->type) {
411 default:
412 die("Bad type of menu_stuff when parse choice");
413 case MENU_STUFF_TYPE_MENU_ITEM:
415 menu_item = (struct menu_item *)menu_stuff->stuff;
416 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
417 if (len == 1 && *choice == menu_item->hotkey) {
418 found = i + 1;
419 break;
421 if (!strncasecmp(choice, menu_item->title, len)) {
422 if (found) {
423 if (len == 1) {
424 /* continue for hotkey matching */
425 found = -1;
426 } else {
427 found = 0;
428 break;
430 } else {
431 found = i + 1;
435 break;
436 case MENU_STUFF_TYPE_STRING_LIST:
437 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
438 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
439 if (!strncasecmp(choice, string_list_item->string, len)) {
440 if (found) {
441 found = 0;
442 break;
444 found = i + 1;
447 break;
449 return found;
453 * Parse user input, and return choice(s) for menu (menu_stuff).
455 * Input
456 * (for single choice)
457 * 1 - select a numbered item
458 * foo - select item based on menu title
459 * - (empty) select nothing
461 * (for multiple choice)
462 * 1 - select a single item
463 * 3-5 - select a range of items
464 * 2-3,6-9 - select multiple ranges
465 * foo - select item based on menu title
466 * -... - unselect specified items
467 * * - choose all items
468 * - (empty) finish selecting
470 * The parse result will be saved in array **chosen, and
471 * return number of total selections.
473 static int parse_choice(struct menu_stuff *menu_stuff,
474 int is_single,
475 struct strbuf input,
476 int **chosen)
478 struct strbuf **choice_list, **ptr;
479 int nr = 0;
480 int i;
482 if (is_single) {
483 choice_list = strbuf_split_max(&input, '\n', 0);
484 } else {
485 char *p = input.buf;
486 do {
487 if (*p == ',')
488 *p = ' ';
489 } while (*p++);
490 choice_list = strbuf_split_max(&input, ' ', 0);
493 for (ptr = choice_list; *ptr; ptr++) {
494 char *p;
495 int choose = 1;
496 int bottom = 0, top = 0;
497 int is_range, is_number;
499 strbuf_trim(*ptr);
500 if (!(*ptr)->len)
501 continue;
503 /* Input that begins with '-'; unchoose */
504 if (*(*ptr)->buf == '-') {
505 choose = 0;
506 strbuf_remove((*ptr), 0, 1);
509 is_range = 0;
510 is_number = 1;
511 for (p = (*ptr)->buf; *p; p++) {
512 if ('-' == *p) {
513 if (!is_range) {
514 is_range = 1;
515 is_number = 0;
516 } else {
517 is_number = 0;
518 is_range = 0;
519 break;
521 } else if (!isdigit(*p)) {
522 is_number = 0;
523 is_range = 0;
524 break;
528 if (is_number) {
529 bottom = atoi((*ptr)->buf);
530 top = bottom;
531 } else if (is_range) {
532 bottom = atoi((*ptr)->buf);
533 /* a range can be specified like 5-7 or 5- */
534 if (!*(strchr((*ptr)->buf, '-') + 1))
535 top = menu_stuff->nr;
536 else
537 top = atoi(strchr((*ptr)->buf, '-') + 1);
538 } else if (!strcmp((*ptr)->buf, "*")) {
539 bottom = 1;
540 top = menu_stuff->nr;
541 } else {
542 bottom = find_unique((*ptr)->buf, menu_stuff);
543 top = bottom;
546 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
547 (is_single && bottom != top)) {
548 clean_print_color(CLEAN_COLOR_ERROR);
549 printf(_("Huh (%s)?\n"), (*ptr)->buf);
550 clean_print_color(CLEAN_COLOR_RESET);
551 continue;
554 for (i = bottom; i <= top; i++)
555 (*chosen)[i-1] = choose;
558 strbuf_list_free(choice_list);
560 for (i = 0; i < menu_stuff->nr; i++)
561 nr += (*chosen)[i];
562 return nr;
566 * Implement a git-add-interactive compatible UI, which is borrowed
567 * from add-interactive.c.
569 * Return value:
571 * - Return an array of integers
572 * - , and it is up to you to free the allocated memory.
573 * - The array ends with EOF.
574 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
576 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
578 struct strbuf choice = STRBUF_INIT;
579 int *chosen, *result;
580 int nr = 0;
581 int eof = 0;
582 int i;
584 ALLOC_ARRAY(chosen, stuff->nr);
585 /* set chosen as uninitialized */
586 for (i = 0; i < stuff->nr; i++)
587 chosen[i] = -1;
589 for (;;) {
590 if (opts->header) {
591 printf_ln("%s%s%s",
592 clean_get_color(CLEAN_COLOR_HEADER),
593 _(opts->header),
594 clean_get_color(CLEAN_COLOR_RESET));
597 /* chosen will be initialized by print_highlight_menu_stuff */
598 print_highlight_menu_stuff(stuff, &chosen);
600 if (opts->flags & MENU_OPTS_LIST_ONLY)
601 break;
603 if (opts->prompt) {
604 printf("%s%s%s%s",
605 clean_get_color(CLEAN_COLOR_PROMPT),
606 _(opts->prompt),
607 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
608 clean_get_color(CLEAN_COLOR_RESET));
611 if (git_read_line_interactively(&choice) == EOF) {
612 eof = 1;
613 break;
616 /* help for prompt */
617 if (!strcmp(choice.buf, "?")) {
618 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
619 continue;
622 /* for a multiple-choice menu, press ENTER (empty) will return back */
623 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
624 break;
626 nr = parse_choice(stuff,
627 opts->flags & MENU_OPTS_SINGLETON,
628 choice,
629 &chosen);
631 if (opts->flags & MENU_OPTS_SINGLETON) {
632 if (nr)
633 break;
634 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
635 break;
639 if (eof) {
640 result = xmalloc(sizeof(int));
641 *result = EOF;
642 } else {
643 int j = 0;
646 * recalculate nr, if return back from menu directly with
647 * default selections.
649 if (!nr) {
650 for (i = 0; i < stuff->nr; i++)
651 nr += chosen[i];
654 CALLOC_ARRAY(result, st_add(nr, 1));
655 for (i = 0; i < stuff->nr && j < nr; i++) {
656 if (chosen[i])
657 result[j++] = i;
659 result[j] = EOF;
662 free(chosen);
663 strbuf_release(&choice);
664 return result;
667 static int clean_cmd(void)
669 return MENU_RETURN_NO_LOOP;
672 static int filter_by_patterns_cmd(void)
674 struct dir_struct dir = DIR_INIT;
675 struct strbuf confirm = STRBUF_INIT;
676 struct strbuf **ignore_list;
677 struct string_list_item *item;
678 struct pattern_list *pl;
679 int changed = -1, i;
681 for (;;) {
682 if (!del_list.nr)
683 break;
685 if (changed)
686 pretty_print_dels();
688 clean_print_color(CLEAN_COLOR_PROMPT);
689 printf(_("Input ignore patterns>> "));
690 clean_print_color(CLEAN_COLOR_RESET);
691 if (git_read_line_interactively(&confirm) == EOF)
692 putchar('\n');
694 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
695 if (!confirm.len)
696 break;
698 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
699 ignore_list = strbuf_split_max(&confirm, ' ', 0);
701 for (i = 0; ignore_list[i]; i++) {
702 strbuf_trim(ignore_list[i]);
703 if (!ignore_list[i]->len)
704 continue;
706 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
709 changed = 0;
710 for_each_string_list_item(item, &del_list) {
711 int dtype = DT_UNKNOWN;
713 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
714 *item->string = '\0';
715 changed++;
719 if (changed) {
720 string_list_remove_empty_items(&del_list, 0);
721 } else {
722 clean_print_color(CLEAN_COLOR_ERROR);
723 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
724 clean_print_color(CLEAN_COLOR_RESET);
727 strbuf_list_free(ignore_list);
728 dir_clear(&dir);
731 strbuf_release(&confirm);
732 return 0;
735 static int select_by_numbers_cmd(void)
737 struct menu_opts menu_opts;
738 struct menu_stuff menu_stuff;
739 struct string_list_item *items;
740 int *chosen;
741 int i, j;
743 menu_opts.header = NULL;
744 menu_opts.prompt = N_("Select items to delete");
745 menu_opts.flags = 0;
747 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
748 menu_stuff.stuff = &del_list;
749 menu_stuff.nr = del_list.nr;
751 chosen = list_and_choose(&menu_opts, &menu_stuff);
752 items = del_list.items;
753 for (i = 0, j = 0; i < del_list.nr; i++) {
754 if (i < chosen[j]) {
755 *(items[i].string) = '\0';
756 } else if (i == chosen[j]) {
757 /* delete selected item */
758 j++;
759 continue;
760 } else {
761 /* end of chosen (chosen[j] == EOF), won't delete */
762 *(items[i].string) = '\0';
766 string_list_remove_empty_items(&del_list, 0);
768 free(chosen);
769 return 0;
772 static int ask_each_cmd(void)
774 struct strbuf confirm = STRBUF_INIT;
775 struct strbuf buf = STRBUF_INIT;
776 struct string_list_item *item;
777 const char *qname;
778 int changed = 0, eof = 0;
780 for_each_string_list_item(item, &del_list) {
781 /* Ctrl-D should stop removing files */
782 if (!eof) {
783 qname = quote_path(item->string, NULL, &buf, 0);
784 /* TRANSLATORS: Make sure to keep [y/N] as is */
785 printf(_("Remove %s [y/N]? "), qname);
786 if (git_read_line_interactively(&confirm) == EOF) {
787 putchar('\n');
788 eof = 1;
791 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
792 *item->string = '\0';
793 changed++;
797 if (changed)
798 string_list_remove_empty_items(&del_list, 0);
800 strbuf_release(&buf);
801 strbuf_release(&confirm);
802 return MENU_RETURN_NO_LOOP;
805 static int quit_cmd(void)
807 string_list_clear(&del_list, 0);
808 printf(_("Bye.\n"));
809 return MENU_RETURN_NO_LOOP;
812 static int help_cmd(void)
814 clean_print_color(CLEAN_COLOR_HELP);
815 printf_ln(_(
816 "clean - start cleaning\n"
817 "filter by pattern - exclude items from deletion\n"
818 "select by numbers - select items to be deleted by numbers\n"
819 "ask each - confirm each deletion (like \"rm -i\")\n"
820 "quit - stop cleaning\n"
821 "help - this screen\n"
822 "? - help for prompt selection"
824 clean_print_color(CLEAN_COLOR_RESET);
825 return 0;
828 static void interactive_main_loop(void)
830 while (del_list.nr) {
831 struct menu_opts menu_opts;
832 struct menu_stuff menu_stuff;
833 struct menu_item menus[] = {
834 {'c', "clean", 0, clean_cmd},
835 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
836 {'s', "select by numbers", 0, select_by_numbers_cmd},
837 {'a', "ask each", 0, ask_each_cmd},
838 {'q', "quit", 0, quit_cmd},
839 {'h', "help", 0, help_cmd},
841 int *chosen;
843 menu_opts.header = N_("*** Commands ***");
844 menu_opts.prompt = N_("What now");
845 menu_opts.flags = MENU_OPTS_SINGLETON;
847 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
848 menu_stuff.stuff = menus;
849 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
851 clean_print_color(CLEAN_COLOR_HEADER);
852 printf_ln(Q_("Would remove the following item:",
853 "Would remove the following items:",
854 del_list.nr));
855 clean_print_color(CLEAN_COLOR_RESET);
857 pretty_print_dels();
859 chosen = list_and_choose(&menu_opts, &menu_stuff);
861 if (*chosen != EOF) {
862 int ret;
863 ret = menus[*chosen].fn();
864 if (ret != MENU_RETURN_NO_LOOP) {
865 FREE_AND_NULL(chosen);
866 if (!del_list.nr) {
867 clean_print_color(CLEAN_COLOR_ERROR);
868 printf_ln(_("No more files to clean, exiting."));
869 clean_print_color(CLEAN_COLOR_RESET);
870 break;
872 continue;
874 } else {
875 quit_cmd();
878 FREE_AND_NULL(chosen);
879 break;
883 static void correct_untracked_entries(struct dir_struct *dir)
885 int src, dst, ign;
887 for (src = dst = ign = 0; src < dir->nr; src++) {
888 /* skip paths in ignored[] that cannot be inside entries[src] */
889 while (ign < dir->ignored_nr &&
890 0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
891 ign++;
893 if (ign < dir->ignored_nr &&
894 check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
895 /* entries[src] contains an ignored path, so we drop it */
896 free(dir->entries[src]);
897 } else {
898 struct dir_entry *ent = dir->entries[src++];
900 /* entries[src] does not contain an ignored path, so we keep it */
901 dir->entries[dst++] = ent;
903 /* then discard paths in entries[] contained inside entries[src] */
904 while (src < dir->nr &&
905 check_dir_entry_contains(ent, dir->entries[src]))
906 free(dir->entries[src++]);
908 /* compensate for the outer loop's loop control */
909 src--;
912 dir->nr = dst;
915 int cmd_clean(int argc, const char **argv, const char *prefix)
917 int i, res;
918 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
919 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
920 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
921 struct strbuf abs_path = STRBUF_INIT;
922 struct dir_struct dir = DIR_INIT;
923 struct pathspec pathspec;
924 struct strbuf buf = STRBUF_INIT;
925 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
926 struct pattern_list *pl;
927 struct string_list_item *item;
928 const char *qname;
929 struct option options[] = {
930 OPT__QUIET(&quiet, N_("do not print names of files removed")),
931 OPT__DRY_RUN(&dry_run, N_("dry run")),
932 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
933 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
934 OPT_BOOL('d', NULL, &remove_directories,
935 N_("remove whole directories")),
936 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
937 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
938 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
939 OPT_BOOL('X', NULL, &ignored_only,
940 N_("remove only ignored files")),
941 OPT_END()
944 git_config(git_clean_config, NULL);
945 if (force < 0)
946 force = 0;
947 else
948 config_set = 1;
950 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
953 if (!interactive && !dry_run && !force) {
954 if (config_set)
955 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
956 "refusing to clean"));
957 else
958 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
959 " refusing to clean"));
962 if (force > 1)
963 rm_flags = 0;
964 else
965 dir.flags |= DIR_SKIP_NESTED_GIT;
967 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
969 if (ignored && ignored_only)
970 die(_("-x and -X cannot be used together"));
971 if (!ignored)
972 setup_standard_excludes(&dir);
973 if (ignored_only)
974 dir.flags |= DIR_SHOW_IGNORED;
976 if (argc) {
978 * Remaining args implies pathspecs specified, and we should
979 * recurse within those.
981 remove_directories = 1;
984 if (remove_directories && !ignored_only) {
986 * We need to know about ignored files too:
988 * If (ignored), then we will delete ignored files as well.
990 * If (!ignored), then even though we not are doing
991 * anything with ignored files, we need to know about them
992 * so that we can avoid deleting a directory of untracked
993 * files that also contains an ignored file within it.
995 * For the (!ignored) case, since we only need to avoid
996 * deleting ignored files, we can set
997 * DIR_SHOW_IGNORED_TOO_MODE_MATCHING in order to avoid
998 * recursing into a directory which is itself ignored.
1000 dir.flags |= DIR_SHOW_IGNORED_TOO;
1001 if (!ignored)
1002 dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
1005 * Let the fill_directory() machinery know that we aren't
1006 * just recursing to collect the ignored files; we want all
1007 * the untracked ones so that we can delete them. (Note:
1008 * we could also set DIR_KEEP_UNTRACKED_CONTENTS when
1009 * ignored_only is true, since DIR_KEEP_UNTRACKED_CONTENTS
1010 * only has effect in combination with DIR_SHOW_IGNORED_TOO. It makes
1011 * the code clearer to exclude it, though.
1013 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
1016 prepare_repo_settings(the_repository);
1017 the_repository->settings.command_requires_full_index = 0;
1019 if (repo_read_index(the_repository) < 0)
1020 die(_("index file corrupt"));
1022 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
1023 for (i = 0; i < exclude_list.nr; i++)
1024 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
1026 parse_pathspec(&pathspec, 0,
1027 PATHSPEC_PREFER_CWD,
1028 prefix, argv);
1030 fill_directory(&dir, &the_index, &pathspec);
1031 correct_untracked_entries(&dir);
1033 for (i = 0; i < dir.nr; i++) {
1034 struct dir_entry *ent = dir.entries[i];
1035 struct stat st;
1036 const char *rel;
1038 if (!index_name_is_other(&the_index, ent->name, ent->len))
1039 continue;
1041 if (lstat(ent->name, &st))
1042 die_errno("Cannot lstat '%s'", ent->name);
1044 if (S_ISDIR(st.st_mode) && !remove_directories)
1045 continue;
1047 rel = relative_path(ent->name, prefix, &buf);
1048 string_list_append(&del_list, rel);
1051 dir_clear(&dir);
1053 if (interactive && del_list.nr > 0)
1054 interactive_main_loop();
1056 for_each_string_list_item(item, &del_list) {
1057 struct stat st;
1059 strbuf_reset(&abs_path);
1060 if (prefix)
1061 strbuf_addstr(&abs_path, prefix);
1063 strbuf_addstr(&abs_path, item->string);
1066 * we might have removed this as part of earlier
1067 * recursive directory removal, so lstat() here could
1068 * fail with ENOENT.
1070 if (lstat(abs_path.buf, &st))
1071 continue;
1073 if (S_ISDIR(st.st_mode)) {
1074 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1075 errors++;
1076 if (gone && !quiet) {
1077 qname = quote_path(item->string, NULL, &buf, 0);
1078 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1080 } else {
1081 res = dry_run ? 0 : unlink(abs_path.buf);
1082 if (res) {
1083 int saved_errno = errno;
1084 qname = quote_path(item->string, NULL, &buf, 0);
1085 errno = saved_errno;
1086 warning_errno(_(msg_warn_remove_failed), qname);
1087 errors++;
1088 } else if (!quiet) {
1089 qname = quote_path(item->string, NULL, &buf, 0);
1090 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1095 strbuf_release(&abs_path);
1096 strbuf_release(&buf);
1097 string_list_clear(&del_list, 0);
1098 string_list_clear(&exclude_list, 0);
1099 clear_pathspec(&pathspec);
1100 return (errors != 0);