2 * "git clean" builtin command
4 * Copyright (C) 2007 Shawn Bohrer
6 * Based on git-clean.sh by Pavel Roskin
12 #include "parse-options.h"
13 #include "string-list.h"
19 static int force = -1; /* unset */
20 static int interactive;
21 static struct string_list del_list = STRING_LIST_INIT_DUP;
22 static unsigned int colopts;
24 static const char *const builtin_clean_usage[] = {
25 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] <paths>..."),
29 static const char *msg_remove = N_("Removing %s\n");
30 static const char *msg_would_remove = N_("Would remove %s\n");
31 static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
32 static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
33 static const char *msg_warn_remove_failed = N_("failed to remove %s");
35 static int clean_use_color = -1;
36 static char clean_colors[][COLOR_MAXLEN] = {
38 GIT_COLOR_NORMAL, /* PLAIN */
39 GIT_COLOR_BOLD_BLUE, /* PROMPT */
40 GIT_COLOR_BOLD, /* HEADER */
41 GIT_COLOR_BOLD_RED, /* HELP */
42 GIT_COLOR_BOLD_RED, /* ERROR */
45 CLEAN_COLOR_RESET = 0,
46 CLEAN_COLOR_PLAIN = 1,
47 CLEAN_COLOR_PROMPT = 2,
48 CLEAN_COLOR_HEADER = 3,
53 #define MENU_OPTS_SINGLETON 01
54 #define MENU_OPTS_IMMEDIATE 02
55 #define MENU_OPTS_LIST_ONLY 04
63 #define MENU_RETURN_NO_LOOP 10
72 enum menu_stuff_type {
73 MENU_STUFF_TYPE_STRING_LIST = 1,
74 MENU_STUFF_TYPE_MENU_ITEM
78 enum menu_stuff_type type;
83 static int parse_clean_color_slot(const char *var)
85 if (!strcasecmp(var, "reset"))
86 return CLEAN_COLOR_RESET;
87 if (!strcasecmp(var, "plain"))
88 return CLEAN_COLOR_PLAIN;
89 if (!strcasecmp(var, "prompt"))
90 return CLEAN_COLOR_PROMPT;
91 if (!strcasecmp(var, "header"))
92 return CLEAN_COLOR_HEADER;
93 if (!strcasecmp(var, "help"))
94 return CLEAN_COLOR_HELP;
95 if (!strcasecmp(var, "error"))
96 return CLEAN_COLOR_ERROR;
100 static int git_clean_config(const char *var, const char *value, void *cb)
102 const char *slot_name;
104 if (starts_with(var, "column."))
105 return git_column_config(var, value, "clean", &colopts);
107 /* honors the color.interactive* config variables which also
108 applied in git-add--interactive and git-stash */
109 if (!strcmp(var, "color.interactive")) {
110 clean_use_color = git_config_colorbool(var, value);
113 if (skip_prefix(var, "color.interactive.", &slot_name)) {
114 int slot = parse_clean_color_slot(slot_name);
118 return config_error_nonbool(var);
119 return color_parse(value, clean_colors[slot]);
122 if (!strcmp(var, "clean.requireforce")) {
123 force = !git_config_bool(var, value);
127 /* inspect the color.ui config variable and others */
128 return git_color_default_config(var, value, cb);
131 static const char *clean_get_color(enum color_clean ix)
133 if (want_color(clean_use_color))
134 return clean_colors[ix];
138 static void clean_print_color(enum color_clean ix)
140 printf("%s", clean_get_color(ix));
143 static int exclude_cb(const struct option *opt, const char *arg, int unset)
145 struct string_list *exclude_list = opt->value;
146 string_list_append(exclude_list, arg);
150 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
151 int dry_run, int quiet, int *dir_gone)
154 struct strbuf quoted = STRBUF_INIT;
156 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
157 struct string_list dels = STRING_LIST_INIT_DUP;
161 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) && is_nonbare_repository_dir(path)) {
163 quote_path_relative(path->buf, prefix, "ed);
164 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
172 dir = opendir(path->buf);
174 /* an empty dir could be removed even if it is unreadble */
175 res = dry_run ? 0 : rmdir(path->buf);
177 quote_path_relative(path->buf, prefix, "ed);
178 warning(_(msg_warn_remove_failed), quoted.buf);
184 strbuf_complete(path, '/');
187 while ((e = readdir(dir)) != NULL) {
189 if (is_dot_or_dotdot(e->d_name))
192 strbuf_setlen(path, len);
193 strbuf_addstr(path, e->d_name);
194 if (lstat(path->buf, &st))
196 else if (S_ISDIR(st.st_mode)) {
197 if (remove_dirs(path, prefix, force_flag, dry_run, quiet, &gone))
200 quote_path_relative(path->buf, prefix, "ed);
201 string_list_append(&dels, quoted.buf);
206 res = dry_run ? 0 : unlink(path->buf);
208 quote_path_relative(path->buf, prefix, "ed);
209 string_list_append(&dels, quoted.buf);
211 quote_path_relative(path->buf, prefix, "ed);
212 warning(_(msg_warn_remove_failed), quoted.buf);
219 /* path too long, stat fails, or non-directory still exists */
226 strbuf_setlen(path, original_len);
229 res = dry_run ? 0 : rmdir(path->buf);
233 quote_path_relative(path->buf, prefix, "ed);
234 warning(_(msg_warn_remove_failed), quoted.buf);
240 if (!*dir_gone && !quiet) {
242 for (i = 0; i < dels.nr; i++)
243 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
245 string_list_clear(&dels, 0);
249 static void pretty_print_dels(void)
251 struct string_list list = STRING_LIST_INIT_DUP;
252 struct string_list_item *item;
253 struct strbuf buf = STRBUF_INIT;
255 struct column_options copts;
257 for_each_string_list_item(item, &del_list) {
258 qname = quote_path_relative(item->string, NULL, &buf);
259 string_list_append(&list, qname);
263 * always enable column display, we only consult column.*
264 * about layout strategy and stuff
266 colopts = (colopts & ~COL_ENABLE_MASK) | COL_ENABLED;
267 memset(&copts, 0, sizeof(copts));
270 print_columns(&list, colopts, &copts);
271 strbuf_release(&buf);
272 string_list_clear(&list, 0);
275 static void pretty_print_menus(struct string_list *menu_list)
277 unsigned int local_colopts = 0;
278 struct column_options copts;
280 local_colopts = COL_ENABLED | COL_ROW;
281 memset(&copts, 0, sizeof(copts));
284 print_columns(menu_list, local_colopts, &copts);
287 static void prompt_help_cmd(int singleton)
289 clean_print_color(CLEAN_COLOR_HELP);
290 printf_ln(singleton ?
292 "1 - select a numbered item\n"
293 "foo - select item based on unique prefix\n"
294 " - (empty) select nothing") :
296 "1 - select a single item\n"
297 "3-5 - select a range of items\n"
298 "2-3,6-9 - select multiple ranges\n"
299 "foo - select item based on unique prefix\n"
300 "-... - unselect specified items\n"
301 "* - choose all items\n"
302 " - (empty) finish selecting"));
303 clean_print_color(CLEAN_COLOR_RESET);
307 * display menu stuff with number prefix and hotkey highlight
309 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
311 struct string_list menu_list = STRING_LIST_INIT_DUP;
312 struct strbuf menu = STRBUF_INIT;
313 struct menu_item *menu_item;
314 struct string_list_item *string_list_item;
317 switch (stuff->type) {
319 die("Bad type of menu_stuff when print menu");
320 case MENU_STUFF_TYPE_MENU_ITEM:
321 menu_item = (struct menu_item *)stuff->stuff;
322 for (i = 0; i < stuff->nr; i++, menu_item++) {
326 p = menu_item->title;
327 if ((*chosen)[i] < 0)
328 (*chosen)[i] = menu_item->selected ? 1 : 0;
329 strbuf_addf(&menu, "%s%2d: ", (*chosen)[i] ? "*" : " ", i+1);
331 if (!highlighted && *p == menu_item->hotkey) {
332 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_PROMPT));
333 strbuf_addch(&menu, *p);
334 strbuf_addstr(&menu, clean_get_color(CLEAN_COLOR_RESET));
337 strbuf_addch(&menu, *p);
340 string_list_append(&menu_list, menu.buf);
344 case MENU_STUFF_TYPE_STRING_LIST:
346 for_each_string_list_item(string_list_item, (struct string_list *)stuff->stuff) {
347 if ((*chosen)[i] < 0)
349 strbuf_addf(&menu, "%s%2d: %s",
350 (*chosen)[i] ? "*" : " ", i+1, string_list_item->string);
351 string_list_append(&menu_list, menu.buf);
358 pretty_print_menus(&menu_list);
360 strbuf_release(&menu);
361 string_list_clear(&menu_list, 0);
364 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
366 struct menu_item *menu_item;
367 struct string_list_item *string_list_item;
368 int i, len, found = 0;
370 len = strlen(choice);
371 switch (menu_stuff->type) {
373 die("Bad type of menu_stuff when parse choice");
374 case MENU_STUFF_TYPE_MENU_ITEM:
376 menu_item = (struct menu_item *)menu_stuff->stuff;
377 for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
378 if (len == 1 && *choice == menu_item->hotkey) {
382 if (!strncasecmp(choice, menu_item->title, len)) {
385 /* continue for hotkey matching */
397 case MENU_STUFF_TYPE_STRING_LIST:
398 string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
399 for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
400 if (!strncasecmp(choice, string_list_item->string, len)) {
415 * Parse user input, and return choice(s) for menu (menu_stuff).
418 * (for single choice)
419 * 1 - select a numbered item
420 * foo - select item based on menu title
421 * - (empty) select nothing
423 * (for multiple choice)
424 * 1 - select a single item
425 * 3-5 - select a range of items
426 * 2-3,6-9 - select multiple ranges
427 * foo - select item based on menu title
428 * -... - unselect specified items
429 * * - choose all items
430 * - (empty) finish selecting
432 * The parse result will be saved in array **chosen, and
433 * return number of total selections.
435 static int parse_choice(struct menu_stuff *menu_stuff,
440 struct strbuf **choice_list, **ptr;
445 choice_list = strbuf_split_max(&input, '\n', 0);
452 choice_list = strbuf_split_max(&input, ' ', 0);
455 for (ptr = choice_list; *ptr; ptr++) {
458 int bottom = 0, top = 0;
459 int is_range, is_number;
465 /* Input that begins with '-'; unchoose */
466 if (*(*ptr)->buf == '-') {
468 strbuf_remove((*ptr), 0, 1);
473 for (p = (*ptr)->buf; *p; p++) {
483 } else if (!isdigit(*p)) {
491 bottom = atoi((*ptr)->buf);
493 } else if (is_range) {
494 bottom = atoi((*ptr)->buf);
495 /* a range can be specified like 5-7 or 5- */
496 if (!*(strchr((*ptr)->buf, '-') + 1))
497 top = menu_stuff->nr;
499 top = atoi(strchr((*ptr)->buf, '-') + 1);
500 } else if (!strcmp((*ptr)->buf, "*")) {
502 top = menu_stuff->nr;
504 bottom = find_unique((*ptr)->buf, menu_stuff);
508 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
509 (is_single && bottom != top)) {
510 clean_print_color(CLEAN_COLOR_ERROR);
511 printf_ln(_("Huh (%s)?"), (*ptr)->buf);
512 clean_print_color(CLEAN_COLOR_RESET);
516 for (i = bottom; i <= top; i++)
517 (*chosen)[i-1] = choose;
520 strbuf_list_free(choice_list);
522 for (i = 0; i < menu_stuff->nr; i++)
528 * Implement a git-add-interactive compatible UI, which is borrowed
529 * from git-add--interactive.perl.
533 * - Return an array of integers
534 * - , and it is up to you to free the allocated memory.
535 * - The array ends with EOF.
536 * - If user pressed CTRL-D (i.e. EOF), no selection returned.
538 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
540 struct strbuf choice = STRBUF_INIT;
541 int *chosen, *result;
546 chosen = xmalloc(sizeof(int) * stuff->nr);
547 /* set chosen as uninitialized */
548 for (i = 0; i < stuff->nr; i++)
554 clean_get_color(CLEAN_COLOR_HEADER),
556 clean_get_color(CLEAN_COLOR_RESET));
559 /* chosen will be initialized by print_highlight_menu_stuff */
560 print_highlight_menu_stuff(stuff, &chosen);
562 if (opts->flags & MENU_OPTS_LIST_ONLY)
567 clean_get_color(CLEAN_COLOR_PROMPT),
569 opts->flags & MENU_OPTS_SINGLETON ? "> " : ">> ",
570 clean_get_color(CLEAN_COLOR_RESET));
573 if (strbuf_getline_lf(&choice, stdin) != EOF) {
574 strbuf_trim(&choice);
580 /* help for prompt */
581 if (!strcmp(choice.buf, "?")) {
582 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
586 /* for a multiple-choice menu, press ENTER (empty) will return back */
587 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
590 nr = parse_choice(stuff,
591 opts->flags & MENU_OPTS_SINGLETON,
595 if (opts->flags & MENU_OPTS_SINGLETON) {
598 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
604 result = xmalloc(sizeof(int));
610 * recalculate nr, if return back from menu directly with
611 * default selections.
614 for (i = 0; i < stuff->nr; i++)
618 result = xcalloc(nr + 1, sizeof(int));
619 for (i = 0; i < stuff->nr && j < nr; i++) {
627 strbuf_release(&choice);
631 static int clean_cmd(void)
633 return MENU_RETURN_NO_LOOP;
636 static int filter_by_patterns_cmd(void)
638 struct dir_struct dir;
639 struct strbuf confirm = STRBUF_INIT;
640 struct strbuf **ignore_list;
641 struct string_list_item *item;
642 struct exclude_list *el;
652 clean_print_color(CLEAN_COLOR_PROMPT);
653 printf(_("Input ignore patterns>> "));
654 clean_print_color(CLEAN_COLOR_RESET);
655 if (strbuf_getline_lf(&confirm, stdin) != EOF)
656 strbuf_trim(&confirm);
660 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
664 memset(&dir, 0, sizeof(dir));
665 el = add_exclude_list(&dir, EXC_CMDL, "manual exclude");
666 ignore_list = strbuf_split_max(&confirm, ' ', 0);
668 for (i = 0; ignore_list[i]; i++) {
669 strbuf_trim(ignore_list[i]);
670 if (!ignore_list[i]->len)
673 add_exclude(ignore_list[i]->buf, "", 0, el, -(i+1));
677 for_each_string_list_item(item, &del_list) {
678 int dtype = DT_UNKNOWN;
680 if (is_excluded(&dir, item->string, &dtype)) {
681 *item->string = '\0';
687 string_list_remove_empty_items(&del_list, 0);
689 clean_print_color(CLEAN_COLOR_ERROR);
690 printf_ln(_("WARNING: Cannot find items matched by: %s"), confirm.buf);
691 clean_print_color(CLEAN_COLOR_RESET);
694 strbuf_list_free(ignore_list);
695 clear_directory(&dir);
698 strbuf_release(&confirm);
702 static int select_by_numbers_cmd(void)
704 struct menu_opts menu_opts;
705 struct menu_stuff menu_stuff;
706 struct string_list_item *items;
710 menu_opts.header = NULL;
711 menu_opts.prompt = N_("Select items to delete");
714 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
715 menu_stuff.stuff = &del_list;
716 menu_stuff.nr = del_list.nr;
718 chosen = list_and_choose(&menu_opts, &menu_stuff);
719 items = del_list.items;
720 for (i = 0, j = 0; i < del_list.nr; i++) {
722 *(items[i].string) = '\0';
723 } else if (i == chosen[j]) {
724 /* delete selected item */
728 /* end of chosen (chosen[j] == EOF), won't delete */
729 *(items[i].string) = '\0';
733 string_list_remove_empty_items(&del_list, 0);
739 static int ask_each_cmd(void)
741 struct strbuf confirm = STRBUF_INIT;
742 struct strbuf buf = STRBUF_INIT;
743 struct string_list_item *item;
745 int changed = 0, eof = 0;
747 for_each_string_list_item(item, &del_list) {
748 /* Ctrl-D should stop removing files */
750 qname = quote_path_relative(item->string, NULL, &buf);
751 /* TRANSLATORS: Make sure to keep [y/N] as is */
752 printf(_("Remove %s [y/N]? "), qname);
753 if (strbuf_getline_lf(&confirm, stdin) != EOF) {
754 strbuf_trim(&confirm);
760 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
761 *item->string = '\0';
767 string_list_remove_empty_items(&del_list, 0);
769 strbuf_release(&buf);
770 strbuf_release(&confirm);
771 return MENU_RETURN_NO_LOOP;
774 static int quit_cmd(void)
776 string_list_clear(&del_list, 0);
777 printf_ln(_("Bye."));
778 return MENU_RETURN_NO_LOOP;
781 static int help_cmd(void)
783 clean_print_color(CLEAN_COLOR_HELP);
785 "clean - start cleaning\n"
786 "filter by pattern - exclude items from deletion\n"
787 "select by numbers - select items to be deleted by numbers\n"
788 "ask each - confirm each deletion (like \"rm -i\")\n"
789 "quit - stop cleaning\n"
790 "help - this screen\n"
791 "? - help for prompt selection"
793 clean_print_color(CLEAN_COLOR_RESET);
797 static void interactive_main_loop(void)
799 while (del_list.nr) {
800 struct menu_opts menu_opts;
801 struct menu_stuff menu_stuff;
802 struct menu_item menus[] = {
803 {'c', "clean", 0, clean_cmd},
804 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
805 {'s', "select by numbers", 0, select_by_numbers_cmd},
806 {'a', "ask each", 0, ask_each_cmd},
807 {'q', "quit", 0, quit_cmd},
808 {'h', "help", 0, help_cmd},
812 menu_opts.header = N_("*** Commands ***");
813 menu_opts.prompt = N_("What now");
814 menu_opts.flags = MENU_OPTS_SINGLETON;
816 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
817 menu_stuff.stuff = menus;
818 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
820 clean_print_color(CLEAN_COLOR_HEADER);
821 printf_ln(Q_("Would remove the following item:",
822 "Would remove the following items:",
824 clean_print_color(CLEAN_COLOR_RESET);
828 chosen = list_and_choose(&menu_opts, &menu_stuff);
830 if (*chosen != EOF) {
832 ret = menus[*chosen].fn();
833 if (ret != MENU_RETURN_NO_LOOP) {
837 clean_print_color(CLEAN_COLOR_ERROR);
838 printf_ln(_("No more files to clean, exiting."));
839 clean_print_color(CLEAN_COLOR_RESET);
854 int cmd_clean(int argc, const char **argv, const char *prefix)
857 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
858 int ignored_only = 0, config_set = 0, errors = 0, gone = 1;
859 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
860 struct strbuf abs_path = STRBUF_INIT;
861 struct dir_struct dir;
862 struct pathspec pathspec;
863 struct strbuf buf = STRBUF_INIT;
864 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
865 struct exclude_list *el;
866 struct string_list_item *item;
868 struct option options[] = {
869 OPT__QUIET(&quiet, N_("do not print names of files removed")),
870 OPT__DRY_RUN(&dry_run, N_("dry run")),
871 OPT__FORCE(&force, N_("force")),
872 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
873 OPT_BOOL('d', NULL, &remove_directories,
874 N_("remove whole directories")),
875 { OPTION_CALLBACK, 'e', "exclude", &exclude_list, N_("pattern"),
876 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb },
877 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
878 OPT_BOOL('X', NULL, &ignored_only,
879 N_("remove only ignored files")),
883 git_config(git_clean_config, NULL);
889 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
892 memset(&dir, 0, sizeof(dir));
894 dir.flags |= DIR_SHOW_IGNORED;
896 if (ignored && ignored_only)
897 die(_("-x and -X cannot be used together"));
899 if (!interactive && !dry_run && !force) {
901 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
902 "refusing to clean"));
904 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
905 " refusing to clean"));
911 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
913 if (read_cache() < 0)
914 die(_("index file corrupt"));
917 setup_standard_excludes(&dir);
919 el = add_exclude_list(&dir, EXC_CMDL, "--exclude option");
920 for (i = 0; i < exclude_list.nr; i++)
921 add_exclude(exclude_list.items[i].string, "", 0, el, -(i+1));
923 parse_pathspec(&pathspec, 0,
927 fill_directory(&dir, &pathspec);
929 for (i = 0; i < dir.nr; i++) {
930 struct dir_entry *ent = dir.entries[i];
935 if (!cache_name_is_other(ent->name, ent->len))
939 matches = dir_path_match(ent, &pathspec, 0, NULL);
941 if (pathspec.nr && !matches)
944 if (lstat(ent->name, &st))
945 die_errno("Cannot lstat '%s'", ent->name);
947 if (S_ISDIR(st.st_mode) && !remove_directories &&
948 matches != MATCHED_EXACTLY)
951 rel = relative_path(ent->name, prefix, &buf);
952 string_list_append(&del_list, rel);
955 if (interactive && del_list.nr > 0)
956 interactive_main_loop();
958 for_each_string_list_item(item, &del_list) {
962 strbuf_addstr(&abs_path, prefix);
964 strbuf_addstr(&abs_path, item->string);
967 * we might have removed this as part of earlier
968 * recursive directory removal, so lstat() here could
971 if (lstat(abs_path.buf, &st))
974 if (S_ISDIR(st.st_mode)) {
975 if (remove_dirs(&abs_path, prefix, rm_flags, dry_run, quiet, &gone))
977 if (gone && !quiet) {
978 qname = quote_path_relative(item->string, NULL, &buf);
979 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
982 res = dry_run ? 0 : unlink(abs_path.buf);
984 qname = quote_path_relative(item->string, NULL, &buf);
985 warning(_(msg_warn_remove_failed), qname);
988 qname = quote_path_relative(item->string, NULL, &buf);
989 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
992 strbuf_reset(&abs_path);
995 strbuf_release(&abs_path);
996 strbuf_release(&buf);
997 string_list_clear(&del_list, 0);
998 string_list_clear(&exclude_list, 0);
999 return (errors != 0);