]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/clean.c
66b4479356d57dc1dab76989b4f6978c68da674e
[thirdparty/git.git] / builtin / clean.c
1 /*
2 * "git clean" builtin command
3 *
4 * Copyright (C) 2007 Shawn Bohrer
5 *
6 * Based on git-clean.sh by Pavel Roskin
7 */
8
9 #define USE_THE_INDEX_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 "read-cache-ll.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"
26
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;
31
32 static const char *const builtin_clean_usage[] = {
33 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] [<pathspec>...]"),
34 NULL
35 };
36
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");
45
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
53 };
54
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",
62 };
63
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,
72 };
73
74 #define MENU_OPTS_SINGLETON 01
75 #define MENU_OPTS_IMMEDIATE 02
76 #define MENU_OPTS_LIST_ONLY 04
77
78 struct menu_opts {
79 const char *header;
80 const char *prompt;
81 int flags;
82 };
83
84 #define MENU_RETURN_NO_LOOP 10
85
86 struct menu_item {
87 char hotkey;
88 const char *title;
89 int selected;
90 int (*fn)(void);
91 };
92
93 enum menu_stuff_type {
94 MENU_STUFF_TYPE_STRING_LIST = 1,
95 MENU_STUFF_TYPE_MENU_ITEM
96 };
97
98 struct menu_stuff {
99 enum menu_stuff_type type;
100 int nr;
101 void *stuff;
102 };
103
104 define_list_config_array(color_interactive_slots);
105
106 static int git_clean_config(const char *var, const char *value, void *cb)
107 {
108 const char *slot_name;
109
110 if (starts_with(var, "column."))
111 return git_column_config(var, value, "clean", &colopts);
112
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;
118 }
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]);
126 }
127
128 if (!strcmp(var, "clean.requireforce")) {
129 force = !git_config_bool(var, value);
130 return 0;
131 }
132
133 /* inspect the color.ui config variable and others */
134 return git_color_default_config(var, value, cb);
135 }
136
137 static const char *clean_get_color(enum color_clean ix)
138 {
139 if (want_color(clean_use_color))
140 return clean_colors[ix];
141 return "";
142 }
143
144 static void clean_print_color(enum color_clean ix)
145 {
146 printf("%s", clean_get_color(ix));
147 }
148
149 static int exclude_cb(const struct option *opt, const char *arg, int unset)
150 {
151 struct string_list *exclude_list = opt->value;
152 BUG_ON_OPT_NEG(unset);
153 string_list_append(exclude_list, arg);
154 return 0;
155 }
156
157 static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
158 int dry_run, int quiet, int *dir_gone)
159 {
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;
167
168 *dir_gone = 1;
169
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);
176 }
177
178 *dir_gone = 0;
179 goto out;
180 }
181
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;
192 }
193 ret = res;
194 goto out;
195 }
196
197 strbuf_complete(path, '/');
198
199 len = path->len;
200 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
201 struct stat st;
202
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;
228 }
229 continue;
230 }
231
232 /* path too long, stat fails, or non-directory still exists */
233 *dir_gone = 0;
234 ret = 1;
235 break;
236 }
237 closedir(dir);
238
239 strbuf_setlen(path, original_len);
240
241 if (*dir_gone) {
242 /*
243 * Normalize path components in path->buf, e.g. change '\' to
244 * '/' on Windows.
245 */
246 strbuf_realpath(&realpath, path->buf, 1);
247
248 /*
249 * path and realpath are absolute; for comparison, we would
250 * like to transform startup_info->original_cwd to an absolute
251 * path too.
252 */
253 if (startup_info->original_cwd)
254 strbuf_realpath(&real_ocwd,
255 startup_info->original_cwd, 1);
256
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;
271 }
272 }
273 }
274
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);
279 }
280 out:
281 strbuf_release(&realpath);
282 strbuf_release(&real_ocwd);
283 strbuf_release(&quoted);
284 string_list_clear(&dels, 0);
285 return ret;
286 }
287
288 static void pretty_print_dels(void)
289 {
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;
295
296 for_each_string_list_item(item, &del_list) {
297 qname = quote_path(item->string, NULL, &buf, 0);
298 string_list_append(&list, qname);
299 }
300
301 /*
302 * always enable column display, we only consult column.*
303 * about layout strategy and stuff
304 */
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);
312 }
313
314 static void pretty_print_menus(struct string_list *menu_list)
315 {
316 unsigned int local_colopts = 0;
317 struct column_options copts;
318
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);
324 }
325
326 static void prompt_help_cmd(int singleton)
327 {
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);
343 }
344
345 /*
346 * display menu stuff with number prefix and hotkey highlight
347 */
348 static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
349 {
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;
355
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;
364
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);
377 }
378 }
379 string_list_append(&menu_list, menu.buf);
380 strbuf_reset(&menu);
381 }
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++;
393 }
394 break;
395 }
396
397 pretty_print_menus(&menu_list);
398
399 strbuf_release(&menu);
400 string_list_clear(&menu_list, 0);
401 }
402
403 static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
404 {
405 struct menu_item *menu_item;
406 struct string_list_item *string_list_item;
407 int i, len, found = 0;
408
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:
414
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;
420 }
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;
429 }
430 } else {
431 found = i + 1;
432 }
433 }
434 }
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;
443 }
444 found = i + 1;
445 }
446 }
447 break;
448 }
449 return found;
450 }
451
452 /*
453 * Parse user input, and return choice(s) for menu (menu_stuff).
454 *
455 * Input
456 * (for single choice)
457 * 1 - select a numbered item
458 * foo - select item based on menu title
459 * - (empty) select nothing
460 *
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
469 *
470 * The parse result will be saved in array **chosen, and
471 * return number of total selections.
472 */
473 static int parse_choice(struct menu_stuff *menu_stuff,
474 int is_single,
475 struct strbuf input,
476 int **chosen)
477 {
478 struct strbuf **choice_list, **ptr;
479 int nr = 0;
480 int i;
481
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);
491 }
492
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;
498
499 strbuf_trim(*ptr);
500 if (!(*ptr)->len)
501 continue;
502
503 /* Input that begins with '-'; unchoose */
504 if (*(*ptr)->buf == '-') {
505 choose = 0;
506 strbuf_remove((*ptr), 0, 1);
507 }
508
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;
520 }
521 } else if (!isdigit(*p)) {
522 is_number = 0;
523 is_range = 0;
524 break;
525 }
526 }
527
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;
544 }
545
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;
552 }
553
554 for (i = bottom; i <= top; i++)
555 (*chosen)[i-1] = choose;
556 }
557
558 strbuf_list_free(choice_list);
559
560 for (i = 0; i < menu_stuff->nr; i++)
561 nr += (*chosen)[i];
562 return nr;
563 }
564
565 /*
566 * Implement a git-add-interactive compatible UI, which is borrowed
567 * from add-interactive.c.
568 *
569 * Return value:
570 *
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.
575 */
576 static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
577 {
578 struct strbuf choice = STRBUF_INIT;
579 int *chosen, *result;
580 int nr = 0;
581 int eof = 0;
582 int i;
583
584 ALLOC_ARRAY(chosen, stuff->nr);
585 /* set chosen as uninitialized */
586 for (i = 0; i < stuff->nr; i++)
587 chosen[i] = -1;
588
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));
595 }
596
597 /* chosen will be initialized by print_highlight_menu_stuff */
598 print_highlight_menu_stuff(stuff, &chosen);
599
600 if (opts->flags & MENU_OPTS_LIST_ONLY)
601 break;
602
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));
609 }
610
611 if (git_read_line_interactively(&choice) == EOF) {
612 eof = 1;
613 break;
614 }
615
616 /* help for prompt */
617 if (!strcmp(choice.buf, "?")) {
618 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
619 continue;
620 }
621
622 /* for a multiple-choice menu, press ENTER (empty) will return back */
623 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
624 break;
625
626 nr = parse_choice(stuff,
627 opts->flags & MENU_OPTS_SINGLETON,
628 choice,
629 &chosen);
630
631 if (opts->flags & MENU_OPTS_SINGLETON) {
632 if (nr)
633 break;
634 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
635 break;
636 }
637 }
638
639 if (eof) {
640 result = xmalloc(sizeof(int));
641 *result = EOF;
642 } else {
643 int j = 0;
644
645 /*
646 * recalculate nr, if return back from menu directly with
647 * default selections.
648 */
649 if (!nr) {
650 for (i = 0; i < stuff->nr; i++)
651 nr += chosen[i];
652 }
653
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;
658 }
659 result[j] = EOF;
660 }
661
662 free(chosen);
663 strbuf_release(&choice);
664 return result;
665 }
666
667 static int clean_cmd(void)
668 {
669 return MENU_RETURN_NO_LOOP;
670 }
671
672 static int filter_by_patterns_cmd(void)
673 {
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;
680
681 for (;;) {
682 if (!del_list.nr)
683 break;
684
685 if (changed)
686 pretty_print_dels();
687
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');
693
694 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
695 if (!confirm.len)
696 break;
697
698 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
699 ignore_list = strbuf_split_max(&confirm, ' ', 0);
700
701 for (i = 0; ignore_list[i]; i++) {
702 strbuf_trim(ignore_list[i]);
703 if (!ignore_list[i]->len)
704 continue;
705
706 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
707 }
708
709 changed = 0;
710 for_each_string_list_item(item, &del_list) {
711 int dtype = DT_UNKNOWN;
712
713 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
714 *item->string = '\0';
715 changed++;
716 }
717 }
718
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);
725 }
726
727 strbuf_list_free(ignore_list);
728 dir_clear(&dir);
729 }
730
731 strbuf_release(&confirm);
732 return 0;
733 }
734
735 static int select_by_numbers_cmd(void)
736 {
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;
742
743 menu_opts.header = NULL;
744 menu_opts.prompt = N_("Select items to delete");
745 menu_opts.flags = 0;
746
747 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
748 menu_stuff.stuff = &del_list;
749 menu_stuff.nr = del_list.nr;
750
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';
763 }
764 }
765
766 string_list_remove_empty_items(&del_list, 0);
767
768 free(chosen);
769 return 0;
770 }
771
772 static int ask_each_cmd(void)
773 {
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;
779
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;
789 }
790 }
791 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
792 *item->string = '\0';
793 changed++;
794 }
795 }
796
797 if (changed)
798 string_list_remove_empty_items(&del_list, 0);
799
800 strbuf_release(&buf);
801 strbuf_release(&confirm);
802 return MENU_RETURN_NO_LOOP;
803 }
804
805 static int quit_cmd(void)
806 {
807 string_list_clear(&del_list, 0);
808 printf(_("Bye.\n"));
809 return MENU_RETURN_NO_LOOP;
810 }
811
812 static int help_cmd(void)
813 {
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"
823 ));
824 clean_print_color(CLEAN_COLOR_RESET);
825 return 0;
826 }
827
828 static void interactive_main_loop(void)
829 {
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},
840 };
841 int *chosen;
842
843 menu_opts.header = N_("*** Commands ***");
844 menu_opts.prompt = N_("What now");
845 menu_opts.flags = MENU_OPTS_SINGLETON;
846
847 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
848 menu_stuff.stuff = menus;
849 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
850
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);
856
857 pretty_print_dels();
858
859 chosen = list_and_choose(&menu_opts, &menu_stuff);
860
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;
871 }
872 continue;
873 }
874 } else {
875 quit_cmd();
876 }
877
878 FREE_AND_NULL(chosen);
879 break;
880 }
881 }
882
883 static void correct_untracked_entries(struct dir_struct *dir)
884 {
885 int src, dst, ign;
886
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++;
892
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++];
899
900 /* entries[src] does not contain an ignored path, so we keep it */
901 dir->entries[dst++] = ent;
902
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++]);
907
908 /* compensate for the outer loop's loop control */
909 src--;
910 }
911 }
912 dir->nr = dst;
913 }
914
915 int cmd_clean(int argc, const char **argv, const char *prefix)
916 {
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()
942 };
943
944 git_config(git_clean_config, NULL);
945 if (force < 0)
946 force = 0;
947 else
948 config_set = 1;
949
950 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
951 0);
952
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"));
960 }
961
962 if (force > 1)
963 rm_flags = 0;
964 else
965 dir.flags |= DIR_SKIP_NESTED_GIT;
966
967 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
968
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;
975
976 if (argc) {
977 /*
978 * Remaining args implies pathspecs specified, and we should
979 * recurse within those.
980 */
981 remove_directories = 1;
982 }
983
984 if (remove_directories && !ignored_only) {
985 /*
986 * We need to know about ignored files too:
987 *
988 * If (ignored), then we will delete ignored files as well.
989 *
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.
994 *
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.
999 */
1000 dir.flags |= DIR_SHOW_IGNORED_TOO;
1001 if (!ignored)
1002 dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
1003
1004 /*
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.
1012 */
1013 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
1014 }
1015
1016 prepare_repo_settings(the_repository);
1017 the_repository->settings.command_requires_full_index = 0;
1018
1019 if (repo_read_index(the_repository) < 0)
1020 die(_("index file corrupt"));
1021
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));
1025
1026 parse_pathspec(&pathspec, 0,
1027 PATHSPEC_PREFER_CWD,
1028 prefix, argv);
1029
1030 fill_directory(&dir, &the_index, &pathspec);
1031 correct_untracked_entries(&dir);
1032
1033 for (i = 0; i < dir.nr; i++) {
1034 struct dir_entry *ent = dir.entries[i];
1035 struct stat st;
1036 const char *rel;
1037
1038 if (!index_name_is_other(&the_index, ent->name, ent->len))
1039 continue;
1040
1041 if (lstat(ent->name, &st))
1042 die_errno("Cannot lstat '%s'", ent->name);
1043
1044 if (S_ISDIR(st.st_mode) && !remove_directories)
1045 continue;
1046
1047 rel = relative_path(ent->name, prefix, &buf);
1048 string_list_append(&del_list, rel);
1049 }
1050
1051 dir_clear(&dir);
1052
1053 if (interactive && del_list.nr > 0)
1054 interactive_main_loop();
1055
1056 for_each_string_list_item(item, &del_list) {
1057 struct stat st;
1058
1059 strbuf_reset(&abs_path);
1060 if (prefix)
1061 strbuf_addstr(&abs_path, prefix);
1062
1063 strbuf_addstr(&abs_path, item->string);
1064
1065 /*
1066 * we might have removed this as part of earlier
1067 * recursive directory removal, so lstat() here could
1068 * fail with ENOENT.
1069 */
1070 if (lstat(abs_path.buf, &st))
1071 continue;
1072
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);
1079 }
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);
1091 }
1092 }
1093 }
1094
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);
1101 }