]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/clean.c
Start the 2.46 cycle
[thirdparty/git.git] / builtin / clean.c
CommitLineData
113f10f2
SB
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
07047d68 9#define USE_THE_INDEX_VARIABLE
113f10f2 10#include "builtin.h"
0b027f6c 11#include "abspath.h"
b2141fc1 12#include "config.h"
113f10f2 13#include "dir.h"
f394e093 14#include "gettext.h"
113f10f2 15#include "parse-options.h"
c339932b 16#include "path.h"
08c46a49 17#include "read-cache-ll.h"
d1cbe1e6 18#include "repository.h"
e38da487 19#include "setup.h"
07de4eba 20#include "string-list.h"
1fb32894 21#include "quote.h"
1b8fd467 22#include "column.h"
7a9b0b80 23#include "color.h"
893d8399 24#include "pathspec.h"
3ac68a93 25#include "help.h"
08d383f2 26#include "prompt.h"
113f10f2 27
12a4883f 28static int require_force = -1; /* unset */
17696002 29static int interactive;
396049e5 30static struct string_list del_list = STRING_LIST_INIT_DUP;
1b8fd467 31static unsigned int colopts;
113f10f2
SB
32
33static const char *const builtin_clean_usage[] = {
463ea0cf 34 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] [<pathspec>...]"),
113f10f2
SB
35 NULL
36};
37
f538a91e
ZK
38static const char *msg_remove = N_("Removing %s\n");
39static const char *msg_would_remove = N_("Would remove %s\n");
40static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
41static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
42static const char *msg_warn_remove_failed = N_("failed to remove %s");
b09364c4 43static const char *msg_warn_lstat_failed = N_("could not lstat %s\n");
c65744e7
EN
44static const char *msg_skip_cwd = N_("Refusing to remove current working directory\n");
45static const char *msg_would_skip_cwd = N_("Would refuse to remove current working directory\n");
f538a91e 46
7a9b0b80
JX
47enum 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,
78273520 53 CLEAN_COLOR_ERROR = 5
7a9b0b80
JX
54};
55
a73b3680
NTND
56static 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",
63};
64
512f41cf
JH
65static int clean_use_color = -1;
66static 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,
73};
74
9f93e461
JX
75#define MENU_OPTS_SINGLETON 01
76#define MENU_OPTS_IMMEDIATE 02
77#define MENU_OPTS_LIST_ONLY 04
78
79struct menu_opts {
80 const char *header;
81 const char *prompt;
82 int flags;
83};
84
85#define MENU_RETURN_NO_LOOP 10
86
87struct menu_item {
88 char hotkey;
89 const char *title;
90 int selected;
8687f777 91 int (*fn)(void);
9f93e461
JX
92};
93
94enum menu_stuff_type {
95 MENU_STUFF_TYPE_STRING_LIST = 1,
96 MENU_STUFF_TYPE_MENU_ITEM
97};
98
99struct menu_stuff {
100 enum menu_stuff_type type;
101 int nr;
102 void *stuff;
103};
104
3ac68a93
NTND
105define_list_config_array(color_interactive_slots);
106
a4e7e317
GC
107static int git_clean_config(const char *var, const char *value,
108 const struct config_context *ctx, void *cb)
113f10f2 109{
e3f1da98
RS
110 const char *slot_name;
111
59556548 112 if (starts_with(var, "column."))
1b8fd467
JX
113 return git_column_config(var, value, "clean", &colopts);
114
7a9b0b80
JX
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;
120 }
e3f1da98 121 if (skip_prefix(var, "color.interactive.", &slot_name)) {
a73b3680 122 int slot = LOOKUP_CONFIG(color_interactive_slots, slot_name);
7a9b0b80
JX
123 if (slot < 0)
124 return 0;
125 if (!value)
126 return config_error_nonbool(var);
f6c5a296 127 return color_parse(value, clean_colors[slot]);
7a9b0b80
JX
128 }
129
1b8fd467 130 if (!strcmp(var, "clean.requireforce")) {
12a4883f 131 require_force = git_config_bool(var, value);
1b8fd467
JX
132 return 0;
133 }
7a9b0b80 134
97eeeea2
GC
135 if (git_color_config(var, value, cb) < 0)
136 return -1;
137
a4e7e317 138 return git_default_config(var, value, ctx, cb);
7a9b0b80
JX
139}
140
141static const char *clean_get_color(enum color_clean ix)
142{
143 if (want_color(clean_use_color))
144 return clean_colors[ix];
145 return "";
146}
147
148static void clean_print_color(enum color_clean ix)
149{
150 printf("%s", clean_get_color(ix));
113f10f2
SB
151}
152
07de4eba
JH
153static int exclude_cb(const struct option *opt, const char *arg, int unset)
154{
155 struct string_list *exclude_list = opt->value;
517fe807 156 BUG_ON_OPT_NEG(unset);
07de4eba
JH
157 string_list_append(exclude_list, arg);
158 return 0;
159}
160
f538a91e
ZK
161static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
162 int dry_run, int quiet, int *dir_gone)
163{
164 DIR *dir;
165 struct strbuf quoted = STRBUF_INIT;
c65744e7
EN
166 struct strbuf realpath = STRBUF_INIT;
167 struct strbuf real_ocwd = STRBUF_INIT;
f538a91e 168 struct dirent *e;
e666b89d 169 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
f538a91e
ZK
170 struct string_list dels = STRING_LIST_INIT_DUP;
171
172 *dir_gone = 1;
173
ca8b5390
EN
174 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
175 is_nonbare_repository_dir(path)) {
f538a91e 176 if (!quiet) {
88910c99 177 quote_path(path->buf, prefix, &quoted, 0);
f538a91e
ZK
178 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
179 quoted.buf);
180 }
181
182 *dir_gone = 0;
25a8f80a 183 goto out;
f538a91e
ZK
184 }
185
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) {
cccf97d6 191 int saved_errno = errno;
88910c99 192 quote_path(path->buf, prefix, &quoted, 0);
cccf97d6
NTND
193 errno = saved_errno;
194 warning_errno(_(msg_warn_remove_failed), quoted.buf);
f538a91e
ZK
195 *dir_gone = 0;
196 }
25a8f80a
RS
197 ret = res;
198 goto out;
f538a91e
ZK
199 }
200
00b6c178 201 strbuf_complete(path, '/');
f538a91e
ZK
202
203 len = path->len;
b548f0f1 204 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
f538a91e 205 struct stat st;
f538a91e
ZK
206
207 strbuf_setlen(path, len);
208 strbuf_addstr(path, e->d_name);
209 if (lstat(path->buf, &st))
b09364c4 210 warning_errno(_(msg_warn_lstat_failed), path->buf);
f538a91e
ZK
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) {
88910c99 215 quote_path(path->buf, prefix, &quoted, 0);
f538a91e
ZK
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) {
88910c99 223 quote_path(path->buf, prefix, &quoted, 0);
f538a91e
ZK
224 string_list_append(&dels, quoted.buf);
225 } else {
cccf97d6 226 int saved_errno = errno;
88910c99 227 quote_path(path->buf, prefix, &quoted, 0);
cccf97d6
NTND
228 errno = saved_errno;
229 warning_errno(_(msg_warn_remove_failed), quoted.buf);
f538a91e
ZK
230 *dir_gone = 0;
231 ret = 1;
232 }
233 continue;
234 }
235
236 /* path too long, stat fails, or non-directory still exists */
237 *dir_gone = 0;
238 ret = 1;
239 break;
240 }
241 closedir(dir);
242
243 strbuf_setlen(path, original_len);
244
245 if (*dir_gone) {
c65744e7
EN
246 /*
247 * Normalize path components in path->buf, e.g. change '\' to
248 * '/' on Windows.
249 */
250 strbuf_realpath(&realpath, path->buf, 1);
251
252 /*
253 * path and realpath are absolute; for comparison, we would
254 * like to transform startup_info->original_cwd to an absolute
255 * path too.
256 */
257 if (startup_info->original_cwd)
258 strbuf_realpath(&real_ocwd,
259 startup_info->original_cwd, 1);
260
261 if (!strbuf_cmp(&realpath, &real_ocwd)) {
262 printf("%s", dry_run ? _(msg_would_skip_cwd) : _(msg_skip_cwd));
f538a91e 263 *dir_gone = 0;
c65744e7
EN
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;
275 }
f538a91e
ZK
276 }
277 }
278
279 if (!*dir_gone && !quiet) {
e666b89d 280 int i;
f538a91e
ZK
281 for (i = 0; i < dels.nr; i++)
282 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
283 }
25a8f80a 284out:
c65744e7
EN
285 strbuf_release(&realpath);
286 strbuf_release(&real_ocwd);
25a8f80a 287 strbuf_release(&quoted);
f538a91e
ZK
288 string_list_clear(&dels, 0);
289 return ret;
290}
291
1b8fd467 292static void pretty_print_dels(void)
17696002 293{
1b8fd467 294 struct string_list list = STRING_LIST_INIT_DUP;
17696002 295 struct string_list_item *item;
1b8fd467 296 struct strbuf buf = STRBUF_INIT;
17696002 297 const char *qname;
1b8fd467
JX
298 struct column_options copts;
299
300 for_each_string_list_item(item, &del_list) {
88910c99 301 qname = quote_path(item->string, NULL, &buf, 0);
1b8fd467
JX
302 string_list_append(&list, qname);
303 }
304
305 /*
306 * always enable column display, we only consult column.*
307 * about layout strategy and stuff
308 */
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);
1b8fd467
JX
314 strbuf_release(&buf);
315 string_list_clear(&list, 0);
316}
317
9f93e461
JX
318static void pretty_print_menus(struct string_list *menu_list)
319{
320 unsigned int local_colopts = 0;
321 struct column_options copts;
322
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);
328}
329
330static void prompt_help_cmd(int singleton)
331{
332 clean_print_color(CLEAN_COLOR_HELP);
901707ba 333 printf(singleton ?
9f93e461
JX
334 _("Prompt help:\n"
335 "1 - select a numbered item\n"
336 "foo - select item based on unique prefix\n"
901707ba 337 " - (empty) select nothing\n") :
9f93e461
JX
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"
901707ba 345 " - (empty) finish selecting\n"));
9f93e461
JX
346 clean_print_color(CLEAN_COLOR_RESET);
347}
348
349/*
350 * display menu stuff with number prefix and hotkey highlight
351 */
352static void print_highlight_menu_stuff(struct menu_stuff *stuff, int **chosen)
353{
354 struct string_list menu_list = STRING_LIST_INIT_DUP;
355 struct strbuf menu = STRBUF_INIT;
9f93e461
JX
356 struct menu_item *menu_item;
357 struct string_list_item *string_list_item;
358 int i;
359
360 switch (stuff->type) {
361 default:
bef111d0 362 die("Bad type of menu_stuff when print menu");
9f93e461
JX
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;
368
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);
381 }
382 }
383 string_list_append(&menu_list, menu.buf);
384 strbuf_reset(&menu);
385 }
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++;
397 }
398 break;
399 }
400
401 pretty_print_menus(&menu_list);
402
403 strbuf_release(&menu);
9f93e461
JX
404 string_list_clear(&menu_list, 0);
405}
406
60838613
JX
407static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
408{
409 struct menu_item *menu_item;
410 struct string_list_item *string_list_item;
411 int i, len, found = 0;
412
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:
418
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;
424 }
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;
433 }
434 } else {
435 found = i + 1;
436 }
437 }
438 }
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;
447 }
448 found = i + 1;
449 }
450 }
451 break;
452 }
453 return found;
454}
455
9f93e461
JX
456/*
457 * Parse user input, and return choice(s) for menu (menu_stuff).
458 *
459 * Input
460 * (for single choice)
461 * 1 - select a numbered item
462 * foo - select item based on menu title
463 * - (empty) select nothing
464 *
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
473 *
474 * The parse result will be saved in array **chosen, and
475 * return number of total selections.
476 */
477static int parse_choice(struct menu_stuff *menu_stuff,
478 int is_single,
479 struct strbuf input,
480 int **chosen)
481{
482 struct strbuf **choice_list, **ptr;
9f93e461
JX
483 int nr = 0;
484 int i;
485
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);
495 }
496
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;
502
503 strbuf_trim(*ptr);
504 if (!(*ptr)->len)
505 continue;
506
507 /* Input that begins with '-'; unchoose */
508 if (*(*ptr)->buf == '-') {
509 choose = 0;
510 strbuf_remove((*ptr), 0, 1);
511 }
512
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;
524 }
525 } else if (!isdigit(*p)) {
526 is_number = 0;
527 is_range = 0;
528 break;
529 }
530 }
531
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 {
60838613
JX
546 bottom = find_unique((*ptr)->buf, menu_stuff);
547 top = bottom;
9f93e461
JX
548 }
549
550 if (top <= 0 || bottom <= 0 || top > menu_stuff->nr || bottom > top ||
551 (is_single && bottom != top)) {
552 clean_print_color(CLEAN_COLOR_ERROR);
901707ba 553 printf(_("Huh (%s)?\n"), (*ptr)->buf);
9f93e461
JX
554 clean_print_color(CLEAN_COLOR_RESET);
555 continue;
556 }
557
558 for (i = bottom; i <= top; i++)
559 (*chosen)[i-1] = choose;
560 }
561
562 strbuf_list_free(choice_list);
563
564 for (i = 0; i < menu_stuff->nr; i++)
565 nr += (*chosen)[i];
566 return nr;
567}
568
569/*
570 * Implement a git-add-interactive compatible UI, which is borrowed
5a7d41d8 571 * from add-interactive.c.
9f93e461
JX
572 *
573 * Return value:
574 *
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.
579 */
580static int *list_and_choose(struct menu_opts *opts, struct menu_stuff *stuff)
581{
582 struct strbuf choice = STRBUF_INIT;
583 int *chosen, *result;
584 int nr = 0;
585 int eof = 0;
586 int i;
587
b32fa95f 588 ALLOC_ARRAY(chosen, stuff->nr);
9f93e461
JX
589 /* set chosen as uninitialized */
590 for (i = 0; i < stuff->nr; i++)
591 chosen[i] = -1;
592
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));
599 }
600
601 /* chosen will be initialized by print_highlight_menu_stuff */
602 print_highlight_menu_stuff(stuff, &chosen);
603
604 if (opts->flags & MENU_OPTS_LIST_ONLY)
605 break;
606
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));
613 }
614
08d383f2 615 if (git_read_line_interactively(&choice) == EOF) {
9f93e461
JX
616 eof = 1;
617 break;
618 }
619
620 /* help for prompt */
621 if (!strcmp(choice.buf, "?")) {
622 prompt_help_cmd(opts->flags & MENU_OPTS_SINGLETON);
623 continue;
624 }
625
626 /* for a multiple-choice menu, press ENTER (empty) will return back */
627 if (!(opts->flags & MENU_OPTS_SINGLETON) && !choice.len)
628 break;
629
630 nr = parse_choice(stuff,
631 opts->flags & MENU_OPTS_SINGLETON,
632 choice,
633 &chosen);
634
635 if (opts->flags & MENU_OPTS_SINGLETON) {
636 if (nr)
637 break;
638 } else if (opts->flags & MENU_OPTS_IMMEDIATE) {
639 break;
640 }
641 }
642
643 if (eof) {
644 result = xmalloc(sizeof(int));
645 *result = EOF;
646 } else {
647 int j = 0;
648
649 /*
650 * recalculate nr, if return back from menu directly with
651 * default selections.
652 */
653 if (!nr) {
654 for (i = 0; i < stuff->nr; i++)
655 nr += chosen[i];
656 }
657
ca56dadb 658 CALLOC_ARRAY(result, st_add(nr, 1));
9f93e461
JX
659 for (i = 0; i < stuff->nr && j < nr; i++) {
660 if (chosen[i])
661 result[j++] = i;
662 }
663 result[j] = EOF;
664 }
665
666 free(chosen);
667 strbuf_release(&choice);
668 return result;
669}
670
671static int clean_cmd(void)
1b8fd467 672{
9f93e461
JX
673 return MENU_RETURN_NO_LOOP;
674}
675
d1239264
JX
676static int filter_by_patterns_cmd(void)
677{
ce93a4c6 678 struct dir_struct dir = DIR_INIT;
d1239264
JX
679 struct strbuf confirm = STRBUF_INIT;
680 struct strbuf **ignore_list;
681 struct string_list_item *item;
caa3d554 682 struct pattern_list *pl;
d1239264
JX
683 int changed = -1, i;
684
685 for (;;) {
686 if (!del_list.nr)
687 break;
688
689 if (changed)
690 pretty_print_dels();
691
692 clean_print_color(CLEAN_COLOR_PROMPT);
693 printf(_("Input ignore patterns>> "));
694 clean_print_color(CLEAN_COLOR_RESET);
08d383f2 695 if (git_read_line_interactively(&confirm) == EOF)
d1239264
JX
696 putchar('\n');
697
698 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
699 if (!confirm.len)
700 break;
701
65edd96a 702 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
d1239264
JX
703 ignore_list = strbuf_split_max(&confirm, ' ', 0);
704
705 for (i = 0; ignore_list[i]; i++) {
706 strbuf_trim(ignore_list[i]);
707 if (!ignore_list[i]->len)
708 continue;
709
65edd96a 710 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
d1239264
JX
711 }
712
713 changed = 0;
714 for_each_string_list_item(item, &del_list) {
715 int dtype = DT_UNKNOWN;
716
a0bba65b 717 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
d1239264
JX
718 *item->string = '\0';
719 changed++;
720 }
721 }
722
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);
729 }
730
731 strbuf_list_free(ignore_list);
eceba532 732 dir_clear(&dir);
d1239264
JX
733 }
734
735 strbuf_release(&confirm);
736 return 0;
737}
738
c1f1d24a
JX
739static int select_by_numbers_cmd(void)
740{
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;
746
747 menu_opts.header = NULL;
748 menu_opts.prompt = N_("Select items to delete");
749 menu_opts.flags = 0;
750
751 menu_stuff.type = MENU_STUFF_TYPE_STRING_LIST;
752 menu_stuff.stuff = &del_list;
753 menu_stuff.nr = del_list.nr;
754
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';
767 }
768 }
769
770 string_list_remove_empty_items(&del_list, 0);
771
772 free(chosen);
773 return 0;
774}
775
96a799b6
JX
776static int ask_each_cmd(void)
777{
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;
783
784 for_each_string_list_item(item, &del_list) {
785 /* Ctrl-D should stop removing files */
786 if (!eof) {
88910c99 787 qname = quote_path(item->string, NULL, &buf, 0);
d9130227
JNA
788 /* TRANSLATORS: Make sure to keep [y/N] as is */
789 printf(_("Remove %s [y/N]? "), qname);
08d383f2 790 if (git_read_line_interactively(&confirm) == EOF) {
96a799b6
JX
791 putchar('\n');
792 eof = 1;
793 }
794 }
795 if (!confirm.len || strncasecmp(confirm.buf, "yes", confirm.len)) {
796 *item->string = '\0';
797 changed++;
798 }
799 }
800
801 if (changed)
802 string_list_remove_empty_items(&del_list, 0);
803
804 strbuf_release(&buf);
805 strbuf_release(&confirm);
806 return MENU_RETURN_NO_LOOP;
807}
808
9f93e461
JX
809static int quit_cmd(void)
810{
811 string_list_clear(&del_list, 0);
901707ba 812 printf(_("Bye.\n"));
9f93e461
JX
813 return MENU_RETURN_NO_LOOP;
814}
815
816static int help_cmd(void)
817{
818 clean_print_color(CLEAN_COLOR_HELP);
819 printf_ln(_(
820 "clean - start cleaning\n"
d1239264 821 "filter by pattern - exclude items from deletion\n"
c1f1d24a 822 "select by numbers - select items to be deleted by numbers\n"
96a799b6 823 "ask each - confirm each deletion (like \"rm -i\")\n"
9f93e461
JX
824 "quit - stop cleaning\n"
825 "help - this screen\n"
826 "? - help for prompt selection"
827 ));
828 clean_print_color(CLEAN_COLOR_RESET);
829 return 0;
830}
17696002 831
9f93e461
JX
832static void interactive_main_loop(void)
833{
17696002 834 while (del_list.nr) {
9f93e461
JX
835 struct menu_opts menu_opts;
836 struct menu_stuff menu_stuff;
837 struct menu_item menus[] = {
838 {'c', "clean", 0, clean_cmd},
d1239264 839 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
c1f1d24a 840 {'s', "select by numbers", 0, select_by_numbers_cmd},
96a799b6 841 {'a', "ask each", 0, ask_each_cmd},
9f93e461
JX
842 {'q', "quit", 0, quit_cmd},
843 {'h', "help", 0, help_cmd},
844 };
845 int *chosen;
846
847 menu_opts.header = N_("*** Commands ***");
848 menu_opts.prompt = N_("What now");
849 menu_opts.flags = MENU_OPTS_SINGLETON;
850
851 menu_stuff.type = MENU_STUFF_TYPE_MENU_ITEM;
852 menu_stuff.stuff = menus;
853 menu_stuff.nr = sizeof(menus) / sizeof(struct menu_item);
854
7a9b0b80 855 clean_print_color(CLEAN_COLOR_HEADER);
1b8fd467
JX
856 printf_ln(Q_("Would remove the following item:",
857 "Would remove the following items:",
858 del_list.nr));
7a9b0b80 859 clean_print_color(CLEAN_COLOR_RESET);
17696002 860
1b8fd467
JX
861 pretty_print_dels();
862
9f93e461
JX
863 chosen = list_and_choose(&menu_opts, &menu_stuff);
864
865 if (*chosen != EOF) {
866 int ret;
867 ret = menus[*chosen].fn();
868 if (ret != MENU_RETURN_NO_LOOP) {
6a83d902 869 FREE_AND_NULL(chosen);
9f93e461
JX
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;
875 }
17696002
JX
876 continue;
877 }
9f93e461
JX
878 } else {
879 quit_cmd();
17696002 880 }
17696002 881
6a83d902 882 FREE_AND_NULL(chosen);
9f93e461
JX
883 break;
884 }
17696002
JX
885}
886
6b1db431
SL
887static void correct_untracked_entries(struct dir_struct *dir)
888{
889 int src, dst, ign;
890
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++;
896
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++];
903
904 /* entries[src] does not contain an ignored path, so we keep it */
905 dir->entries[dst++] = ent;
906
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++]);
911
912 /* compensate for the outer loop's loop control */
913 src--;
914 }
915 }
916 dir->nr = dst;
917}
918
113f10f2
SB
919int cmd_clean(int argc, const char **argv, const char *prefix)
920{
f538a91e
ZK
921 int i, res;
922 int dry_run = 0, remove_directories = 0, quiet = 0, ignored = 0;
12a4883f 923 int ignored_only = 0, force = 0, errors = 0, gone = 1;
a0f4afbe 924 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
396049e5 925 struct strbuf abs_path = STRBUF_INIT;
ce93a4c6 926 struct dir_struct dir = DIR_INIT;
893d8399 927 struct pathspec pathspec;
f285a2d7 928 struct strbuf buf = STRBUF_INIT;
bdab6a59 929 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
caa3d554 930 struct pattern_list *pl;
396049e5 931 struct string_list_item *item;
1fb32894 932 const char *qname;
113f10f2 933 struct option options[] = {
145f9c81 934 OPT__QUIET(&quiet, N_("do not print names of files removed")),
f538a91e 935 OPT__DRY_RUN(&dry_run, N_("dry run")),
26e90958 936 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
17696002 937 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
d5d09d47 938 OPT_BOOL('d', NULL, &remove_directories,
145f9c81 939 N_("remove whole directories")),
203c8533
DL
940 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
941 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
d5d09d47
SB
942 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
943 OPT_BOOL('X', NULL, &ignored_only,
145f9c81 944 N_("remove only ignored files")),
113f10f2
SB
945 OPT_END()
946 };
947
ef90d6d4 948 git_config(git_clean_config, NULL);
625db1b7 949
37782920
SB
950 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
951 0);
113f10f2 952
105ec9ae
JH
953 if (require_force != 0 && !force && !interactive && !dry_run)
954 die(_("clean.requireForce is true and -f not given: refusing to clean"));
113f10f2 955
a0f4afbe
JH
956 if (force > 1)
957 rm_flags = 0;
09487f2c
EN
958 else
959 dir.flags |= DIR_SKIP_NESTED_GIT;
a0f4afbe 960
7c4c97c0 961 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
113f10f2 962
f7f5c6c0 963 if (ignored && ignored_only)
f5f9e972 964 die(_("options '%s' and '%s' cannot be used together"), "-x", "-X");
f7f5c6c0
EN
965 if (!ignored)
966 setup_standard_excludes(&dir);
967 if (ignored_only)
968 dir.flags |= DIR_SHOW_IGNORED;
969
e86bbcf9
EN
970 if (argc) {
971 /*
972 * Remaining args implies pathspecs specified, and we should
973 * recurse within those.
974 */
975 remove_directories = 1;
976 }
977
7233f175
EN
978 if (remove_directories && !ignored_only) {
979 /*
980 * We need to know about ignored files too:
981 *
982 * If (ignored), then we will delete ignored files as well.
983 *
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.
988 *
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.
993 */
994 dir.flags |= DIR_SHOW_IGNORED_TOO;
995 if (!ignored)
996 dir.flags |= DIR_SHOW_IGNORED_TOO_MODE_MATCHING;
997
998 /*
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.
1006 */
1007 dir.flags |= DIR_KEEP_UNTRACKED_CONTENTS;
1008 }
6b1db431 1009
1e9e10e0
VD
1010 prepare_repo_settings(the_repository);
1011 the_repository->settings.command_requires_full_index = 0;
1012
07047d68 1013 if (repo_read_index(the_repository) < 0)
2da57add 1014 die(_("index file corrupt"));
c28b3d6e 1015
65edd96a 1016 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
07de4eba 1017 for (i = 0; i < exclude_list.nr; i++)
65edd96a 1018 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
07de4eba 1019
893d8399
NTND
1020 parse_pathspec(&pathspec, 0,
1021 PATHSPEC_PREFER_CWD,
1022 prefix, argv);
113f10f2 1023
0d32c183 1024 fill_directory(&dir, &the_index, &pathspec);
6b1db431 1025 correct_untracked_entries(&dir);
d871c869
JH
1026
1027 for (i = 0; i < dir.nr; i++) {
1028 struct dir_entry *ent = dir.entries[i];
113f10f2 1029 struct stat st;
396049e5 1030 const char *rel;
113f10f2 1031
fbc1ed62 1032 if (!index_name_is_other(&the_index, ent->name, ent->len))
2e70c017 1033 continue;
113f10f2 1034
838d6a92
DT
1035 if (lstat(ent->name, &st))
1036 die_errno("Cannot lstat '%s'", ent->name);
1037
3a7f0908 1038 if (S_ISDIR(st.st_mode) && !remove_directories)
1f2e1088
JK
1039 continue;
1040
1041 rel = relative_path(ent->name, prefix, &buf);
1042 string_list_append(&del_list, rel);
396049e5
JX
1043 }
1044
eceba532 1045 dir_clear(&dir);
6b1db431 1046
17696002
JX
1047 if (interactive && del_list.nr > 0)
1048 interactive_main_loop();
396049e5
JX
1049
1050 for_each_string_list_item(item, &del_list) {
1051 struct stat st;
1052
902b90cf 1053 strbuf_reset(&abs_path);
396049e5
JX
1054 if (prefix)
1055 strbuf_addstr(&abs_path, prefix);
1056
1057 strbuf_addstr(&abs_path, item->string);
1058
1059 /*
1060 * we might have removed this as part of earlier
1061 * recursive directory removal, so lstat() here could
1062 * fail with ENOENT.
1063 */
1064 if (lstat(abs_path.buf, &st))
1065 continue;
1066
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) {
88910c99 1071 qname = quote_path(item->string, NULL, &buf, 0);
396049e5
JX
1072 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1073 }
1074 } else {
1075 res = dry_run ? 0 : unlink(abs_path.buf);
f538a91e 1076 if (res) {
cccf97d6 1077 int saved_errno = errno;
88910c99 1078 qname = quote_path(item->string, NULL, &buf, 0);
cccf97d6
NTND
1079 errno = saved_errno;
1080 warning_errno(_(msg_warn_remove_failed), qname);
aa9c83c2 1081 errors++;
f538a91e 1082 } else if (!quiet) {
88910c99 1083 qname = quote_path(item->string, NULL, &buf, 0);
f538a91e 1084 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
aa9c83c2 1085 }
113f10f2
SB
1086 }
1087 }
1088
396049e5
JX
1089 strbuf_release(&abs_path);
1090 strbuf_release(&buf);
1091 string_list_clear(&del_list, 0);
07de4eba 1092 string_list_clear(&exclude_list, 0);
7615cf94 1093 clear_pathspec(&pathspec);
aa9c83c2 1094 return (errors != 0);
113f10f2 1095}