]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/clean.c
cache.h: remove this no-longer-used header
[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"
08c46a49 16#include "read-cache-ll.h"
d1cbe1e6 17#include "repository.h"
e38da487 18#include "setup.h"
07de4eba 19#include "string-list.h"
1fb32894 20#include "quote.h"
1b8fd467 21#include "column.h"
7a9b0b80 22#include "color.h"
893d8399 23#include "pathspec.h"
3ac68a93 24#include "help.h"
08d383f2 25#include "prompt.h"
113f10f2 26
625db1b7 27static int force = -1; /* unset */
17696002 28static int interactive;
396049e5 29static struct string_list del_list = STRING_LIST_INIT_DUP;
1b8fd467 30static unsigned int colopts;
113f10f2
SB
31
32static const char *const builtin_clean_usage[] = {
463ea0cf 33 N_("git clean [-d] [-f] [-i] [-n] [-q] [-e <pattern>] [-x | -X] [--] [<pathspec>...]"),
113f10f2
SB
34 NULL
35};
36
f538a91e
ZK
37static const char *msg_remove = N_("Removing %s\n");
38static const char *msg_would_remove = N_("Would remove %s\n");
39static const char *msg_skip_git_dir = N_("Skipping repository %s\n");
40static const char *msg_would_skip_git_dir = N_("Would skip repository %s\n");
41static const char *msg_warn_remove_failed = N_("failed to remove %s");
b09364c4 42static const char *msg_warn_lstat_failed = N_("could not lstat %s\n");
c65744e7
EN
43static const char *msg_skip_cwd = N_("Refusing to remove current working directory\n");
44static const char *msg_would_skip_cwd = N_("Would refuse to remove current working directory\n");
f538a91e 45
7a9b0b80
JX
46enum 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,
78273520 52 CLEAN_COLOR_ERROR = 5
7a9b0b80
JX
53};
54
a73b3680
NTND
55static 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
512f41cf
JH
64static int clean_use_color = -1;
65static 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
9f93e461
JX
74#define MENU_OPTS_SINGLETON 01
75#define MENU_OPTS_IMMEDIATE 02
76#define MENU_OPTS_LIST_ONLY 04
77
78struct menu_opts {
79 const char *header;
80 const char *prompt;
81 int flags;
82};
83
84#define MENU_RETURN_NO_LOOP 10
85
86struct menu_item {
87 char hotkey;
88 const char *title;
89 int selected;
8687f777 90 int (*fn)(void);
9f93e461
JX
91};
92
93enum menu_stuff_type {
94 MENU_STUFF_TYPE_STRING_LIST = 1,
95 MENU_STUFF_TYPE_MENU_ITEM
96};
97
98struct menu_stuff {
99 enum menu_stuff_type type;
100 int nr;
101 void *stuff;
102};
103
3ac68a93
NTND
104define_list_config_array(color_interactive_slots);
105
ef90d6d4 106static int git_clean_config(const char *var, const char *value, void *cb)
113f10f2 107{
e3f1da98
RS
108 const char *slot_name;
109
59556548 110 if (starts_with(var, "column."))
1b8fd467
JX
111 return git_column_config(var, value, "clean", &colopts);
112
7a9b0b80
JX
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 }
e3f1da98 119 if (skip_prefix(var, "color.interactive.", &slot_name)) {
a73b3680 120 int slot = LOOKUP_CONFIG(color_interactive_slots, slot_name);
7a9b0b80
JX
121 if (slot < 0)
122 return 0;
123 if (!value)
124 return config_error_nonbool(var);
f6c5a296 125 return color_parse(value, clean_colors[slot]);
7a9b0b80
JX
126 }
127
1b8fd467 128 if (!strcmp(var, "clean.requireforce")) {
113f10f2 129 force = !git_config_bool(var, value);
1b8fd467
JX
130 return 0;
131 }
7a9b0b80 132
33c643bb
JK
133 /* inspect the color.ui config variable and others */
134 return git_color_default_config(var, value, cb);
7a9b0b80
JX
135}
136
137static 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
144static void clean_print_color(enum color_clean ix)
145{
146 printf("%s", clean_get_color(ix));
113f10f2
SB
147}
148
07de4eba
JH
149static int exclude_cb(const struct option *opt, const char *arg, int unset)
150{
151 struct string_list *exclude_list = opt->value;
517fe807 152 BUG_ON_OPT_NEG(unset);
07de4eba
JH
153 string_list_append(exclude_list, arg);
154 return 0;
155}
156
f538a91e
ZK
157static 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;
c65744e7
EN
162 struct strbuf realpath = STRBUF_INIT;
163 struct strbuf real_ocwd = STRBUF_INIT;
f538a91e 164 struct dirent *e;
e666b89d 165 int res = 0, ret = 0, gone = 1, original_len = path->len, len;
f538a91e
ZK
166 struct string_list dels = STRING_LIST_INIT_DUP;
167
168 *dir_gone = 1;
169
ca8b5390
EN
170 if ((force_flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
171 is_nonbare_repository_dir(path)) {
f538a91e 172 if (!quiet) {
88910c99 173 quote_path(path->buf, prefix, &quoted, 0);
f538a91e
ZK
174 printf(dry_run ? _(msg_would_skip_git_dir) : _(msg_skip_git_dir),
175 quoted.buf);
176 }
177
178 *dir_gone = 0;
25a8f80a 179 goto out;
f538a91e
ZK
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) {
cccf97d6 187 int saved_errno = errno;
88910c99 188 quote_path(path->buf, prefix, &quoted, 0);
cccf97d6
NTND
189 errno = saved_errno;
190 warning_errno(_(msg_warn_remove_failed), quoted.buf);
f538a91e
ZK
191 *dir_gone = 0;
192 }
25a8f80a
RS
193 ret = res;
194 goto out;
f538a91e
ZK
195 }
196
00b6c178 197 strbuf_complete(path, '/');
f538a91e
ZK
198
199 len = path->len;
b548f0f1 200 while ((e = readdir_skip_dot_and_dotdot(dir)) != NULL) {
f538a91e 201 struct stat st;
f538a91e
ZK
202
203 strbuf_setlen(path, len);
204 strbuf_addstr(path, e->d_name);
205 if (lstat(path->buf, &st))
b09364c4 206 warning_errno(_(msg_warn_lstat_failed), path->buf);
f538a91e
ZK
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) {
88910c99 211 quote_path(path->buf, prefix, &quoted, 0);
f538a91e
ZK
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) {
88910c99 219 quote_path(path->buf, prefix, &quoted, 0);
f538a91e
ZK
220 string_list_append(&dels, quoted.buf);
221 } else {
cccf97d6 222 int saved_errno = errno;
88910c99 223 quote_path(path->buf, prefix, &quoted, 0);
cccf97d6
NTND
224 errno = saved_errno;
225 warning_errno(_(msg_warn_remove_failed), quoted.buf);
f538a91e
ZK
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) {
c65744e7
EN
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));
f538a91e 259 *dir_gone = 0;
c65744e7
EN
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 }
f538a91e
ZK
272 }
273 }
274
275 if (!*dir_gone && !quiet) {
e666b89d 276 int i;
f538a91e
ZK
277 for (i = 0; i < dels.nr; i++)
278 printf(dry_run ? _(msg_would_remove) : _(msg_remove), dels.items[i].string);
279 }
25a8f80a 280out:
c65744e7
EN
281 strbuf_release(&realpath);
282 strbuf_release(&real_ocwd);
25a8f80a 283 strbuf_release(&quoted);
f538a91e
ZK
284 string_list_clear(&dels, 0);
285 return ret;
286}
287
1b8fd467 288static void pretty_print_dels(void)
17696002 289{
1b8fd467 290 struct string_list list = STRING_LIST_INIT_DUP;
17696002 291 struct string_list_item *item;
1b8fd467 292 struct strbuf buf = STRBUF_INIT;
17696002 293 const char *qname;
1b8fd467
JX
294 struct column_options copts;
295
296 for_each_string_list_item(item, &del_list) {
88910c99 297 qname = quote_path(item->string, NULL, &buf, 0);
1b8fd467
JX
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);
1b8fd467
JX
310 strbuf_release(&buf);
311 string_list_clear(&list, 0);
312}
313
9f93e461
JX
314static 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
326static void prompt_help_cmd(int singleton)
327{
328 clean_print_color(CLEAN_COLOR_HELP);
901707ba 329 printf(singleton ?
9f93e461
JX
330 _("Prompt help:\n"
331 "1 - select a numbered item\n"
332 "foo - select item based on unique prefix\n"
901707ba 333 " - (empty) select nothing\n") :
9f93e461
JX
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"
901707ba 341 " - (empty) finish selecting\n"));
9f93e461
JX
342 clean_print_color(CLEAN_COLOR_RESET);
343}
344
345/*
346 * display menu stuff with number prefix and hotkey highlight
347 */
348static 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;
9f93e461
JX
352 struct menu_item *menu_item;
353 struct string_list_item *string_list_item;
354 int i;
355
356 switch (stuff->type) {
357 default:
bef111d0 358 die("Bad type of menu_stuff when print menu");
9f93e461
JX
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);
9f93e461
JX
400 string_list_clear(&menu_list, 0);
401}
402
60838613
JX
403static 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
9f93e461
JX
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 */
473static 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;
9f93e461
JX
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 {
60838613
JX
542 bottom = find_unique((*ptr)->buf, menu_stuff);
543 top = bottom;
9f93e461
JX
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);
901707ba 549 printf(_("Huh (%s)?\n"), (*ptr)->buf);
9f93e461
JX
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
5a7d41d8 567 * from add-interactive.c.
9f93e461
JX
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 */
576static 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
b32fa95f 584 ALLOC_ARRAY(chosen, stuff->nr);
9f93e461
JX
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
08d383f2 611 if (git_read_line_interactively(&choice) == EOF) {
9f93e461
JX
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
ca56dadb 654 CALLOC_ARRAY(result, st_add(nr, 1));
9f93e461
JX
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
667static int clean_cmd(void)
1b8fd467 668{
9f93e461
JX
669 return MENU_RETURN_NO_LOOP;
670}
671
d1239264
JX
672static int filter_by_patterns_cmd(void)
673{
ce93a4c6 674 struct dir_struct dir = DIR_INIT;
d1239264
JX
675 struct strbuf confirm = STRBUF_INIT;
676 struct strbuf **ignore_list;
677 struct string_list_item *item;
caa3d554 678 struct pattern_list *pl;
d1239264
JX
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);
08d383f2 691 if (git_read_line_interactively(&confirm) == EOF)
d1239264
JX
692 putchar('\n');
693
694 /* quit filter_by_pattern mode if press ENTER or Ctrl-D */
695 if (!confirm.len)
696 break;
697
65edd96a 698 pl = add_pattern_list(&dir, EXC_CMDL, "manual exclude");
d1239264
JX
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
65edd96a 706 add_pattern(ignore_list[i]->buf, "", 0, pl, -(i+1));
d1239264
JX
707 }
708
709 changed = 0;
710 for_each_string_list_item(item, &del_list) {
711 int dtype = DT_UNKNOWN;
712
a0bba65b 713 if (is_excluded(&dir, &the_index, item->string, &dtype)) {
d1239264
JX
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);
eceba532 728 dir_clear(&dir);
d1239264
JX
729 }
730
731 strbuf_release(&confirm);
732 return 0;
733}
734
c1f1d24a
JX
735static 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
96a799b6
JX
772static 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) {
88910c99 783 qname = quote_path(item->string, NULL, &buf, 0);
d9130227
JNA
784 /* TRANSLATORS: Make sure to keep [y/N] as is */
785 printf(_("Remove %s [y/N]? "), qname);
08d383f2 786 if (git_read_line_interactively(&confirm) == EOF) {
96a799b6
JX
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
9f93e461
JX
805static int quit_cmd(void)
806{
807 string_list_clear(&del_list, 0);
901707ba 808 printf(_("Bye.\n"));
9f93e461
JX
809 return MENU_RETURN_NO_LOOP;
810}
811
812static int help_cmd(void)
813{
814 clean_print_color(CLEAN_COLOR_HELP);
815 printf_ln(_(
816 "clean - start cleaning\n"
d1239264 817 "filter by pattern - exclude items from deletion\n"
c1f1d24a 818 "select by numbers - select items to be deleted by numbers\n"
96a799b6 819 "ask each - confirm each deletion (like \"rm -i\")\n"
9f93e461
JX
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}
17696002 827
9f93e461
JX
828static void interactive_main_loop(void)
829{
17696002 830 while (del_list.nr) {
9f93e461
JX
831 struct menu_opts menu_opts;
832 struct menu_stuff menu_stuff;
833 struct menu_item menus[] = {
834 {'c', "clean", 0, clean_cmd},
d1239264 835 {'f', "filter by pattern", 0, filter_by_patterns_cmd},
c1f1d24a 836 {'s', "select by numbers", 0, select_by_numbers_cmd},
96a799b6 837 {'a', "ask each", 0, ask_each_cmd},
9f93e461
JX
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
7a9b0b80 851 clean_print_color(CLEAN_COLOR_HEADER);
1b8fd467
JX
852 printf_ln(Q_("Would remove the following item:",
853 "Would remove the following items:",
854 del_list.nr));
7a9b0b80 855 clean_print_color(CLEAN_COLOR_RESET);
17696002 856
1b8fd467
JX
857 pretty_print_dels();
858
9f93e461
JX
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) {
6a83d902 865 FREE_AND_NULL(chosen);
9f93e461
JX
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 }
17696002
JX
872 continue;
873 }
9f93e461
JX
874 } else {
875 quit_cmd();
17696002 876 }
17696002 877
6a83d902 878 FREE_AND_NULL(chosen);
9f93e461
JX
879 break;
880 }
17696002
JX
881}
882
6b1db431
SL
883static 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
113f10f2
SB
915int cmd_clean(int argc, const char **argv, const char *prefix)
916{
f538a91e
ZK
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;
a0f4afbe 920 int rm_flags = REMOVE_DIR_KEEP_NESTED_GIT;
396049e5 921 struct strbuf abs_path = STRBUF_INIT;
ce93a4c6 922 struct dir_struct dir = DIR_INIT;
893d8399 923 struct pathspec pathspec;
f285a2d7 924 struct strbuf buf = STRBUF_INIT;
bdab6a59 925 struct string_list exclude_list = STRING_LIST_INIT_NODUP;
caa3d554 926 struct pattern_list *pl;
396049e5 927 struct string_list_item *item;
1fb32894 928 const char *qname;
113f10f2 929 struct option options[] = {
145f9c81 930 OPT__QUIET(&quiet, N_("do not print names of files removed")),
f538a91e 931 OPT__DRY_RUN(&dry_run, N_("dry run")),
26e90958 932 OPT__FORCE(&force, N_("force"), PARSE_OPT_NOCOMPLETE),
17696002 933 OPT_BOOL('i', "interactive", &interactive, N_("interactive cleaning")),
d5d09d47 934 OPT_BOOL('d', NULL, &remove_directories,
145f9c81 935 N_("remove whole directories")),
203c8533
DL
936 OPT_CALLBACK_F('e', "exclude", &exclude_list, N_("pattern"),
937 N_("add <pattern> to ignore rules"), PARSE_OPT_NONEG, exclude_cb),
d5d09d47
SB
938 OPT_BOOL('x', NULL, &ignored, N_("remove ignored files, too")),
939 OPT_BOOL('X', NULL, &ignored_only,
145f9c81 940 N_("remove only ignored files")),
113f10f2
SB
941 OPT_END()
942 };
943
ef90d6d4 944 git_config(git_clean_config, NULL);
625db1b7
JH
945 if (force < 0)
946 force = 0;
947 else
948 config_set = 1;
949
37782920
SB
950 argc = parse_options(argc, argv, prefix, options, builtin_clean_usage,
951 0);
113f10f2 952
17696002 953 if (!interactive && !dry_run && !force) {
a66f9b2a 954 if (config_set)
235e8d59 955 die(_("clean.requireForce set to true and neither -i, -n, nor -f given; "
a66f9b2a
ÆAB
956 "refusing to clean"));
957 else
235e8d59
JL
958 die(_("clean.requireForce defaults to true and neither -i, -n, nor -f given;"
959 " refusing to clean"));
a66f9b2a 960 }
113f10f2 961
a0f4afbe
JH
962 if (force > 1)
963 rm_flags = 0;
09487f2c
EN
964 else
965 dir.flags |= DIR_SKIP_NESTED_GIT;
a0f4afbe 966
7c4c97c0 967 dir.flags |= DIR_SHOW_OTHER_DIRECTORIES;
113f10f2 968
f7f5c6c0
EN
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
e86bbcf9
EN
976 if (argc) {
977 /*
978 * Remaining args implies pathspecs specified, and we should
979 * recurse within those.
980 */
981 remove_directories = 1;
982 }
983
7233f175
EN
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 }
6b1db431 1015
1e9e10e0
VD
1016 prepare_repo_settings(the_repository);
1017 the_repository->settings.command_requires_full_index = 0;
1018
07047d68 1019 if (repo_read_index(the_repository) < 0)
2da57add 1020 die(_("index file corrupt"));
c28b3d6e 1021
65edd96a 1022 pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
07de4eba 1023 for (i = 0; i < exclude_list.nr; i++)
65edd96a 1024 add_pattern(exclude_list.items[i].string, "", 0, pl, -(i+1));
07de4eba 1025
893d8399
NTND
1026 parse_pathspec(&pathspec, 0,
1027 PATHSPEC_PREFER_CWD,
1028 prefix, argv);
113f10f2 1029
0d32c183 1030 fill_directory(&dir, &the_index, &pathspec);
6b1db431 1031 correct_untracked_entries(&dir);
d871c869
JH
1032
1033 for (i = 0; i < dir.nr; i++) {
1034 struct dir_entry *ent = dir.entries[i];
113f10f2 1035 struct stat st;
396049e5 1036 const char *rel;
113f10f2 1037
fbc1ed62 1038 if (!index_name_is_other(&the_index, ent->name, ent->len))
2e70c017 1039 continue;
113f10f2 1040
838d6a92
DT
1041 if (lstat(ent->name, &st))
1042 die_errno("Cannot lstat '%s'", ent->name);
1043
3a7f0908 1044 if (S_ISDIR(st.st_mode) && !remove_directories)
1f2e1088
JK
1045 continue;
1046
1047 rel = relative_path(ent->name, prefix, &buf);
1048 string_list_append(&del_list, rel);
396049e5
JX
1049 }
1050
eceba532 1051 dir_clear(&dir);
6b1db431 1052
17696002
JX
1053 if (interactive && del_list.nr > 0)
1054 interactive_main_loop();
396049e5
JX
1055
1056 for_each_string_list_item(item, &del_list) {
1057 struct stat st;
1058
902b90cf 1059 strbuf_reset(&abs_path);
396049e5
JX
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) {
88910c99 1077 qname = quote_path(item->string, NULL, &buf, 0);
396049e5
JX
1078 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
1079 }
1080 } else {
1081 res = dry_run ? 0 : unlink(abs_path.buf);
f538a91e 1082 if (res) {
cccf97d6 1083 int saved_errno = errno;
88910c99 1084 qname = quote_path(item->string, NULL, &buf, 0);
cccf97d6
NTND
1085 errno = saved_errno;
1086 warning_errno(_(msg_warn_remove_failed), qname);
aa9c83c2 1087 errors++;
f538a91e 1088 } else if (!quiet) {
88910c99 1089 qname = quote_path(item->string, NULL, &buf, 0);
f538a91e 1090 printf(dry_run ? _(msg_would_remove) : _(msg_remove), qname);
aa9c83c2 1091 }
113f10f2
SB
1092 }
1093 }
1094
396049e5
JX
1095 strbuf_release(&abs_path);
1096 strbuf_release(&buf);
1097 string_list_clear(&del_list, 0);
07de4eba 1098 string_list_clear(&exclude_list, 0);
7615cf94 1099 clear_pathspec(&pathspec);
aa9c83c2 1100 return (errors != 0);
113f10f2 1101}