t: teach lint that RHS of 'local VAR=VAL' needs to be quoted
[alt-git.git] / builtin / clean.c
blob29efe841537b341776bdca2fc70f3df4d333e066
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 "config.h"
13 #include "dir.h"
14 #include "gettext.h"
15 #include "parse-options.h"
16 #include "path.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 require_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,
108 const struct config_context *ctx, void *cb)
110 const char *slot_name;
112 if (starts_with(var, "column."))
113 return git_column_config(var, value, "clean", &colopts);
115 /* honors the color.interactive* config variables which also
116 applied in git-add--interactive and git-stash */
117 if (!strcmp(var, "color.interactive")) {
118 clean_use_color = git_config_colorbool(var, value);
119 return 0;
121 if (skip_prefix(var, "color.interactive.", &slot_name)) {
122 int slot = LOOKUP_CONFIG(color_interactive_slots, slot_name);
123 if (slot < 0)
124 return 0;
125 if (!value)
126 return config_error_nonbool(var);
127 return color_parse(value, clean_colors[slot]);
130 if (!strcmp(var, "clean.requireforce")) {
131 require_force = git_config_bool(var, value);
132 return 0;
135 if (git_color_config(var, value, cb) < 0)
136 return -1;
138 return git_default_config(var, value, ctx, cb);
141 static const char *clean_get_color(enum color_clean ix)
143 if (want_color(clean_use_color))
144 return clean_colors[ix];
145 return "";
148 static void clean_print_color(enum color_clean ix)
150 printf("%s", clean_get_color(ix));
153 static int exclude_cb(const struct option *opt, const char *arg, int unset)
155 struct string_list *exclude_list = opt->value;
156 BUG_ON_OPT_NEG(unset);
157 string_list_append(exclude_list, arg);
158 return 0;
161 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
162 int dry_run, int quiet, int *dir_gone)
164 DIR *dir;
165 struct strbuf quoted = STRBUF_INIT;
166 struct strbuf realpath = STRBUF_INIT;
167 struct strbuf real_ocwd = STRBUF_INIT;
168 struct dirent *e;
169 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
170 struct string_list dels = STRING_LIST_INIT_DUP;
172 *dir_gone = 1;
174 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
175 is_nonbare_repository_dir(path)) {
176 if (!quiet) {
177 quote_path(path->buf, prefix, &quoted, 0);
178 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
179 quoted.buf);
182 *dir_gone = 0;
183 goto out;
186 dir = opendir(path->buf);
187 if (!dir) {
188 /* an empty dir could be removed even if it is unreadble */
189 res = dry_run ? 0 : rmdir(path->buf);
190 if (res) {
191 int saved_errno = errno;
192 quote_path(path->buf, prefix, &quoted, 0);
193 errno = saved_errno;
194 warning_errno(_(msg_warn_remove_failed), quoted.buf);
195 *dir_gone = 0;
197 ret = res;
198 goto out;
201 strbuf_complete(path, '/');
203 len = path->len;
204 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
205 struct stat st;
207 strbuf_setlen(path, len);
208 strbuf_addstr(path, e->d_name);
209 if (lstat(path->buf, &st))
210 warning_errno(_(msg_warn_lstat_failed), path->buf);
211 else if (S_ISDIR(st.st_mode)) {
212 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
213 ret = 1;
214 if (gone) {
215 quote_path(path->buf, prefix, &quoted, 0);
216 string_list_append(&dels, quoted.buf);
217 } else
218 *dir_gone = 0;
219 continue;
220 } else {
221 res = dry_run ? 0 : unlink(path->buf);
222 if (!res) {
223 quote_path(path->buf, prefix, &quoted, 0);
224 string_list_append(&dels, quoted.buf);
225 } else {
226 int saved_errno = errno;
227 quote_path(path->buf, prefix, &quoted, 0);
228 errno = saved_errno;
229 warning_errno(_(msg_warn_remove_failed), quoted.buf);
230 *dir_gone = 0;
231 ret = 1;
233 continue;
236 /* path too long, stat fails, or non-directory still exists */
237 *dir_gone = 0;
238 ret = 1;
239 break;
241 closedir(dir);
243 strbuf_setlen(path, original_len);
245 if (*dir_gone) {
247 * Normalize path components in path->buf, e.g. change '\' to
248 * '/' on Windows.
250 strbuf_realpath(&realpath, path->buf, 1);
253 * path and realpath are absolute; for comparison, we would
254 * like to transform startup_info->original_cwd to an absolute
255 * path too.
257 if (startup_info->original_cwd)
258 strbuf_realpath(&real_ocwd,
259 startup_info->original_cwd, 1);
261 if (!strbuf_cmp(&realpath, &real_ocwd)) {
262 printf("%s", dry_run ? _(msg_would_skip_cwd) : _(msg_skip_cwd));
263 *dir_gone = 0;
264 } else {
265 res = dry_run ? 0 : rmdir(path->buf);
266 if (!res)
267 *dir_gone = 1;
268 else {
269 int saved_errno = errno;
270 quote_path(path->buf, prefix, &quoted, 0);
271 errno = saved_errno;
272 warning_errno(_(msg_warn_remove_failed), quoted.buf);
273 *dir_gone = 0;
274 ret = 1;
279 if (!*dir_gone && !quiet) {
280 int i;
281 for (i = 0; i < dels.nr; i++)
282 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
284 out:
285 strbuf_release(&realpath);
286 strbuf_release(&real_ocwd);
287 strbuf_release(&quoted);
288 string_list_clear(&dels, 0);
289 return ret;
292 static void pretty_print_dels(void)
294 struct string_list list = STRING_LIST_INIT_DUP;
295 struct string_list_item *item;
296 struct strbuf buf = STRBUF_INIT;
297 const char *qname;
298 struct column_options copts;
300 for_each_string_list_item(item, &del_list) {
301 qname = quote_path(item->string, NULL, &buf, 0);
302 string_list_append(&list, qname);
306 * always enable column display, we only consult column.*
307 * about layout strategy and stuff
309 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
310 memset(&copts, 0, sizeof(copts));
311 copts.indent = " ";
312 copts.padding = 2;
313 print_columns(&list, colopts, &copts);
314 strbuf_release(&buf);
315 string_list_clear(&list, 0);
318 static void pretty_print_menus(struct string_list *menu_list)
320 unsigned int local_colopts = 0;
321 struct column_options copts;
323 local_colopts = COL_ENABLED | COL_ROW;
324 memset(&copts, 0, sizeof(copts));
325 copts.indent = " ";
326 copts.padding = 2;
327 print_columns(menu_list, local_colopts, &copts);
330 static void prompt_help_cmd(int singleton)
332 clean_print_color(CLEAN_COLOR_HELP);
333 printf(singleton ?
334 _("Prompt help:\n"
335 "1 - select a numbered item\n"
336 "foo - select item based on unique prefix\n"
337 " - (empty) select nothing\n") :
338 _("Prompt help:\n"
339 "1 - select a single item\n"
340 "3-5 - select a range of items\n"
341 "2-3,6-9 - select multiple ranges\n"
342 "foo - select item based on unique prefix\n"
343 "-... - unselect specified items\n"
344 "* - choose all items\n"
345 " - (empty) finish selecting\n"));
346 clean_print_color(CLEAN_COLOR_RESET);
350 * display menu stuff with number prefix and hotkey highlight
352 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
354 struct string_list menu_list = STRING_LIST_INIT_DUP;
355 struct strbuf menu = STRBUF_INIT;
356 struct menu_item *menu_item;
357 struct string_list_item *string_list_item;
358 int i;
360 switch (stuff->type) {
361 default:
362 die("Bad type of menu_stuff when print menu");
363 case MENU_STUFF_TYPE_MENU_ITEM:
364 menu_item = (struct menu_item *)stuff->stuff;
365 for (i = 0; i < stuff->nr; i++, menu_item++) {
366 const char *p;
367 int highlighted = 0;
369 p = menu_item->title;
370 if ((*chosen)[i] < 0)
371 (*chosen)[i] = menu_item->selected ? 1 : 0;
372 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
373 for (; *p; p++) {
374 if (!highlighted && *p == menu_item->hotkey) {
375 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
376 strbuf_addch(&menu, *p);
377 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
378 highlighted = 1;
379 } else {
380 strbuf_addch(&menu, *p);
383 string_list_append(&menu_list, menu.buf);
384 strbuf_reset(&menu);
386 break;
387 case MENU_STUFF_TYPE_STRING_LIST:
388 i = 0;
389 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
390 if ((*chosen)[i] < 0)
391 (*chosen)[i] = 0;
392 strbuf_addf(&menu, "%s%2d: %s",
393 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
394 string_list_append(&menu_list, menu.buf);
395 strbuf_reset(&menu);
396 i++;
398 break;
401 pretty_print_menus(&menu_list);
403 strbuf_release(&menu);
404 string_list_clear(&menu_list, 0);
407 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
409 struct menu_item *menu_item;
410 struct string_list_item *string_list_item;
411 int i, len, found = 0;
413 len = strlen(choice);
414 switch (menu_stuff->type) {
415 default:
416 die("Bad type of menu_stuff when parse choice");
417 case MENU_STUFF_TYPE_MENU_ITEM:
419 menu_item = (struct menu_item *)menu_stuff->stuff;
420 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
421 if (len == 1 && *choice == menu_item->hotkey) {
422 found = i + 1;
423 break;
425 if (!strncasecmp(choice, menu_item->title, len)) {
426 if (found) {
427 if (len == 1) {
428 /* continue for hotkey matching */
429 found = -1;
430 } else {
431 found = 0;
432 break;
434 } else {
435 found = i + 1;
439 break;
440 case MENU_STUFF_TYPE_STRING_LIST:
441 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
442 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
443 if (!strncasecmp(choice, string_list_item->string, len)) {
444 if (found) {
445 found = 0;
446 break;
448 found = i + 1;
451 break;
453 return found;
457 * Parse user input, and return choice(s) for menu (menu_stuff).
459 * Input
460 * (for single choice)
461 * 1 - select a numbered item
462 * foo - select item based on menu title
463 * - (empty) select nothing
465 * (for multiple choice)
466 * 1 - select a single item
467 * 3-5 - select a range of items
468 * 2-3,6-9 - select multiple ranges
469 * foo - select item based on menu title
470 * -... - unselect specified items
471 * * - choose all items
472 * - (empty) finish selecting
474 * The parse result will be saved in array **chosen, and
475 * return number of total selections.
477 static int parse_choice(struct menu_stuff *menu_stuff,
478 int is_single,
479 struct strbuf input,
480 int **chosen)
482 struct strbuf **choice_list, **ptr;
483 int nr = 0;
484 int i;
486 if (is_single) {
487 choice_list = strbuf_split_max(&input, '\n', 0);
488 } else {
489 char *p = input.buf;
490 do {
491 if (*p == ',')
492 *p = ' ';
493 } while (*p++);
494 choice_list = strbuf_split_max(&input, ' ', 0);
497 for (ptr = choice_list; *ptr; ptr++) {
498 char *p;
499 int choose = 1;
500 int bottom = 0, top = 0;
501 int is_range, is_number;
503 strbuf_trim(*ptr);
504 if (!(*ptr)->len)
505 continue;
507 /* Input that begins with '-'; unchoose */
508 if (*(*ptr)->buf == '-') {
509 choose = 0;
510 strbuf_remove((*ptr), 0, 1);
513 is_range = 0;
514 is_number = 1;
515 for (p = (*ptr)->buf; *p; p++) {
516 if ('-' == *p) {
517 if (!is_range) {
518 is_range = 1;
519 is_number = 0;
520 } else {
521 is_number = 0;
522 is_range = 0;
523 break;
525 } else if (!isdigit(*p)) {
526 is_number = 0;
527 is_range = 0;
528 break;
532 if (is_number) {
533 bottom = atoi((*ptr)->buf);
534 top = bottom;
535 } else if (is_range) {
536 bottom = atoi((*ptr)->buf);
537 /* a range can be specified like 5-7 or 5- */
538 if (!*(strchr((*ptr)->buf, '-') + 1))
539 top = menu_stuff->nr;
540 else
541 top = atoi(strchr((*ptr)->buf, '-') + 1);
542 } else if (!strcmp((*ptr)->buf, "*")) {
543 bottom = 1;
544 top = menu_stuff->nr;
545 } else {
546 bottom = find_unique((*ptr)->buf, menu_stuff);
547 top = bottom;
550 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
551 (is_single && bottom != top)) {
552 clean_print_color(CLEAN_COLOR_ERROR);
553 printf(_("Huh (%s)?\n"), (*ptr)->buf);
554 clean_print_color(CLEAN_COLOR_RESET);
555 continue;
558 for (i = bottom; i <= top; i++)
559 (*chosen)[i-1] = choose;
562 strbuf_list_free(choice_list);
564 for (i = 0; i < menu_stuff->nr; i++)
565 nr += (*chosen)[i];
566 return nr;
570 * Implement a git-add-interactive compatible UI, which is borrowed
571 * from add-interactive.c.
573 * Return value:
575 * - Return an array of integers
576 * - , and it is up to you to free the allocated memory.
577 * - The array ends with EOF.
578 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
580 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
582 struct strbuf choice = STRBUF_INIT;
583 int *chosen, *result;
584 int nr = 0;
585 int eof = 0;
586 int i;
588 ALLOC_ARRAY(chosen, stuff->nr);
589 /* set chosen as uninitialized */
590 for (i = 0; i < stuff->nr; i++)
591 chosen[i] = -1;
593 for (;;) {
594 if (opts->header) {
595 printf_ln("%s%s%s",
596 clean_get_color(CLEAN_COLOR_HEADER),
597 _(opts->header),
598 clean_get_color(CLEAN_COLOR_RESET));
601 /* chosen will be initialized by print_highlight_menu_stuff */
602 print_highlight_menu_stuff(stuff, &chosen);
604 if (opts->flags & MENU_OPTS_LIST_ONLY)
605 break;
607 if (opts->prompt) {
608 printf("%s%s%s%s",
609 clean_get_color(CLEAN_COLOR_PROMPT),
610 _(opts->prompt),
611 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
612 clean_get_color(CLEAN_COLOR_RESET));
615 if (git_read_line_interactively(&choice) == EOF) {
616 eof = 1;
617 break;
620 /* help for prompt */
621 if (!strcmp(choice.buf, "?")) {
622 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
623 continue;
626 /* for a multiple-choice menu, press ENTER (empty) will return back */
627 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
628 break;
630 nr = parse_choice(stuff,
631 opts->flags & MENU_OPTS_SINGLETON,
632 choice,
633 &chosen);
635 if (opts->flags & MENU_OPTS_SINGLETON) {
636 if (nr)
637 break;
638 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
639 break;
643 if (eof) {
644 result = xmalloc(sizeof(int));
645 *result = EOF;
646 } else {
647 int j = 0;
650 * recalculate nr, if return back from menu directly with
651 * default selections.
653 if (!nr) {
654 for (i = 0; i < stuff->nr; i++)
655 nr += chosen[i];
658 CALLOC_ARRAY(result, st_add(nr, 1));
659 for (i = 0; i < stuff->nr && j < nr; i++) {
660 if (chosen[i])
661 result[j++] = i;
663 result[j] = EOF;
666 free(chosen);
667 strbuf_release(&choice);
668 return result;
671 static int clean_cmd(void)
673 return MENU_RETURN_NO_LOOP;
676 static int filter_by_patterns_cmd(void)
678 struct dir_struct dir = DIR_INIT;
679 struct strbuf confirm = STRBUF_INIT;
680 struct strbuf **ignore_list;
681 struct string_list_item *item;
682 struct pattern_list *pl;
683 int changed = -1, i;
685 for (;;) {
686 if (!del_list.nr)
687 break;
689 if (changed)
690 pretty_print_dels();
692 clean_print_color(CLEAN_COLOR_PROMPT);
693 printf(_("Input ignore patterns>> "));
694 clean_print_color(CLEAN_COLOR_RESET);
695 if (git_read_line_interactively(&confirm) == EOF)
696 putchar('\n');
698 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
699 if (!confirm.len)
700 break;
702 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
703 ignore_list = strbuf_split_max(&confirm, ' ', 0);
705 for (i = 0; ignore_list[i]; i++) {
706 strbuf_trim(ignore_list[i]);
707 if (!ignore_list[i]->len)
708 continue;
710 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
713 changed = 0;
714 for_each_string_list_item(item, &del_list) {
715 int dtype = DT_UNKNOWN;
717 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
718 *item->string = '\0';
719 changed++;
723 if (changed) {
724 string_list_remove_empty_items(&del_list, 0);
725 } else {
726 clean_print_color(CLEAN_COLOR_ERROR);
727 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
728 clean_print_color(CLEAN_COLOR_RESET);
731 strbuf_list_free(ignore_list);
732 dir_clear(&dir);
735 strbuf_release(&confirm);
736 return 0;
739 static int select_by_numbers_cmd(void)
741 struct menu_opts menu_opts;
742 struct menu_stuff menu_stuff;
743 struct string_list_item *items;
744 int *chosen;
745 int i, j;
747 menu_opts.header = NULL;
748 menu_opts.prompt = N_("Select items to delete");
749 menu_opts.flags = 0;
751 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
752 menu_stuff.stuff = &del_list;
753 menu_stuff.nr = del_list.nr;
755 chosen = list_and_choose(&menu_opts, &menu_stuff);
756 items = del_list.items;
757 for (i = 0, j = 0; i < del_list.nr; i++) {
758 if (i < chosen[j]) {
759 *(items[i].string) = '\0';
760 } else if (i == chosen[j]) {
761 /* delete selected item */
762 j++;
763 continue;
764 } else {
765 /* end of chosen (chosen[j] == EOF), won't delete */
766 *(items[i].string) = '\0';
770 string_list_remove_empty_items(&del_list, 0);
772 free(chosen);
773 return 0;
776 static int ask_each_cmd(void)
778 struct strbuf confirm = STRBUF_INIT;
779 struct strbuf buf = STRBUF_INIT;
780 struct string_list_item *item;
781 const char *qname;
782 int changed = 0, eof = 0;
784 for_each_string_list_item(item, &del_list) {
785 /* Ctrl-D should stop removing files */
786 if (!eof) {
787 qname = quote_path(item->string, NULL, &buf, 0);
788 /* TRANSLATORS: Make sure to keep [y/N] as is */
789 printf(_("Remove %s [y/N]? "), qname);
790 if (git_read_line_interactively(&confirm) == EOF) {
791 putchar('\n');
792 eof = 1;
795 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
796 *item->string = '\0';
797 changed++;
801 if (changed)
802 string_list_remove_empty_items(&del_list, 0);
804 strbuf_release(&buf);
805 strbuf_release(&confirm);
806 return MENU_RETURN_NO_LOOP;
809 static int quit_cmd(void)
811 string_list_clear(&del_list, 0);
812 printf(_("Bye.\n"));
813 return MENU_RETURN_NO_LOOP;
816 static int help_cmd(void)
818 clean_print_color(CLEAN_COLOR_HELP);
819 printf_ln(_(
820 "clean - start cleaning\n"
821 "filter by pattern - exclude items from deletion\n"
822 "select by numbers - select items to be deleted by numbers\n"
823 "ask each - confirm each deletion (like \"rm -i\")\n"
824 "quit - stop cleaning\n"
825 "help - this screen\n"
826 "? - help for prompt selection"
828 clean_print_color(CLEAN_COLOR_RESET);
829 return 0;
832 static void interactive_main_loop(void)
834 while (del_list.nr) {
835 struct menu_opts menu_opts;
836 struct menu_stuff menu_stuff;
837 struct menu_item menus[] = {
838 {'c', "clean", 0, clean_cmd},
839 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
840 {'s', "select by numbers", 0, select_by_numbers_cmd},
841 {'a', "ask each", 0, ask_each_cmd},
842 {'q', "quit", 0, quit_cmd},
843 {'h', "help", 0, help_cmd},
845 int *chosen;
847 menu_opts.header = N_("*** Commands ***");
848 menu_opts.prompt = N_("What now");
849 menu_opts.flags = MENU_OPTS_SINGLETON;
851 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
852 menu_stuff.stuff = menus;
853 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
855 clean_print_color(CLEAN_COLOR_HEADER);
856 printf_ln(Q_("Would remove the following item:",
857 "Would remove the following items:",
858 del_list.nr));
859 clean_print_color(CLEAN_COLOR_RESET);
861 pretty_print_dels();
863 chosen = list_and_choose(&menu_opts, &menu_stuff);
865 if (*chosen != EOF) {
866 int ret;
867 ret = menus[*chosen].fn();
868 if (ret != MENU_RETURN_NO_LOOP) {
869 FREE_AND_NULL(chosen);
870 if (!del_list.nr) {
871 clean_print_color(CLEAN_COLOR_ERROR);
872 printf_ln(_("No more files to clean, exiting."));
873 clean_print_color(CLEAN_COLOR_RESET);
874 break;
876 continue;
878 } else {
879 quit_cmd();
882 FREE_AND_NULL(chosen);
883 break;
887 static void correct_untracked_entries(struct dir_struct *dir)
889 int src, dst, ign;
891 for (src = dst = ign = 0; src < dir->nr; src++) {
892 /* skip paths in ignored[] that cannot be inside entries[src] */
893 while (ign < dir->ignored_nr &&
894 0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
895 ign++;
897 if (ign < dir->ignored_nr &&
898 check_dir_entry_contains(dir->entries[src], dir->ignored[ign])) {
899 /* entries[src] contains an ignored path, so we drop it */
900 free(dir->entries[src]);
901 } else {
902 struct dir_entry *ent = dir->entries[src++];
904 /* entries[src] does not contain an ignored path, so we keep it */
905 dir->entries[dst++] = ent;
907 /* then discard paths in entries[] contained inside entries[src] */
908 while (src < dir->nr &&
909 check_dir_entry_contains(ent, dir->entries[src]))
910 free(dir->entries[src++]);
912 /* compensate for the outer loop's loop control */
913 src--;
916 dir->nr = dst;
919 int cmd_clean(int argc, const char **argv, const char *prefix)
921 int i, res;
922 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
923 int ignored_only = 0, force = 0, errors = 0, gone = 1;
924 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
925 struct strbuf abs_path = STRBUF_INIT;
926 struct dir_struct dir = DIR_INIT;
927 struct pathspec pathspec;
928 struct strbuf buf = STRBUF_INIT;
929 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
930 struct pattern_list *pl;
931 struct string_list_item *item;
932 const char *qname;
933 struct option options[] = {
934 OPT__QUIET(&quiet, N_("do not print names of files removed")),
935 OPT__DRY_RUN(&dry_run, N_("dry run")),
936 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
937 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
938 OPT_BOOL('d', NULL, &remove_directories,
939 N_("remove whole directories")),
940 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
941 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
942 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
943 OPT_BOOL('X', NULL, &ignored_only,
944 N_("remove only ignored files")),
945 OPT_END()
948 git_config(git_clean_config, NULL);
950 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
953 if (require_force != 0 && !force && !interactive && !dry_run)
954 die(_("clean.requireForce is true and -f not given: refusing to clean"));
956 if (force > 1)
957 rm_flags = 0;
958 else
959 dir.flags |= DIR_SKIP_NESTED_GIT;
961 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
963 if (ignored && ignored_only)
964 die(_("options '%s' and '%s' cannot be used together"), "-x", "-X");
965 if (!ignored)
966 setup_standard_excludes(&dir);
967 if (ignored_only)
968 dir.flags |= DIR_SHOW_IGNORED;
970 if (argc) {
972 * Remaining args implies pathspecs specified, and we should
973 * recurse within those.
975 remove_directories = 1;
978 if (remove_directories && !ignored_only) {
980 * We need to know about ignored files too:
982 * If (ignored), then we will delete ignored files as well.
984 * If (!ignored), then even though we not are doing
985 * anything with ignored files, we need to know about them
986 * so that we can avoid deleting a directory of untracked
987 * files that also contains an ignored file within it.
989 * For the (!ignored) case, since we only need to avoid
990 * deleting ignored files, we can set
991 * DIR_SHOW_IGNORED_TOO_MODE_MATCHING in order to avoid
992 * recursing into a directory which is itself ignored.
994 dir.flags |= DIR_SHOW_IGNORED_TOO;
995 if (!ignored)
996 dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
999 * Let the fill_directory() machinery know that we aren't
1000 * just recursing to collect the ignored files; we want all
1001 * the untracked ones so that we can delete them. (Note:
1002 * we could also set DIR_KEEP_UNTRACKED_CONTENTS when
1003 * ignored_only is true, since DIR_KEEP_UNTRACKED_CONTENTS
1004 * only has effect in combination with DIR_SHOW_IGNORED_TOO. It makes
1005 * the code clearer to exclude it, though.
1007 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
1010 prepare_repo_settings(the_repository);
1011 the_repository->settings.command_requires_full_index = 0;
1013 if (repo_read_index(the_repository) < 0)
1014 die(_("index file corrupt"));
1016 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
1017 for (i = 0; i < exclude_list.nr; i++)
1018 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
1020 parse_pathspec(&pathspec, 0,
1021 PATHSPEC_PREFER_CWD,
1022 prefix, argv);
1024 fill_directory(&dir, &the_index, &pathspec);
1025 correct_untracked_entries(&dir);
1027 for (i = 0; i < dir.nr; i++) {
1028 struct dir_entry *ent = dir.entries[i];
1029 struct stat st;
1030 const char *rel;
1032 if (!index_name_is_other(&the_index, ent->name, ent->len))
1033 continue;
1035 if (lstat(ent->name, &st))
1036 die_errno("Cannot lstat '%s'", ent->name);
1038 if (S_ISDIR(st.st_mode) && !remove_directories)
1039 continue;
1041 rel = relative_path(ent->name, prefix, &buf);
1042 string_list_append(&del_list, rel);
1045 dir_clear(&dir);
1047 if (interactive && del_list.nr > 0)
1048 interactive_main_loop();
1050 for_each_string_list_item(item, &del_list) {
1051 struct stat st;
1053 strbuf_reset(&abs_path);
1054 if (prefix)
1055 strbuf_addstr(&abs_path, prefix);
1057 strbuf_addstr(&abs_path, item->string);
1060 * we might have removed this as part of earlier
1061 * recursive directory removal, so lstat() here could
1062 * fail with ENOENT.
1064 if (lstat(abs_path.buf, &st))
1065 continue;
1067 if (S_ISDIR(st.st_mode)) {
1068 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
1069 errors++;
1070 if (gone && !quiet) {
1071 qname = quote_path(item->string, NULL, &buf, 0);
1072 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1074 } else {
1075 res = dry_run ? 0 : unlink(abs_path.buf);
1076 if (res) {
1077 int saved_errno = errno;
1078 qname = quote_path(item->string, NULL, &buf, 0);
1079 errno = saved_errno;
1080 warning_errno(_(msg_warn_remove_failed), qname);
1081 errors++;
1082 } else if (!quiet) {
1083 qname = quote_path(item->string, NULL, &buf, 0);
1084 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1089 strbuf_release(&abs_path);
1090 strbuf_release(&buf);
1091 string_list_clear(&del_list, 0);
1092 string_list_clear(&exclude_list, 0);
1093 clear_pathspec(&pathspec);
1094 return (errors != 0);