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