worktree: teach `list` to annotate prunable worktree
[git] / add-interactive.c
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "color.h"
4 #include "config.h"
5 #include "diffcore.h"
6 #include "revision.h"
7 #include "refs.h"
8 #include "string-list.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "prompt.h"
13
14 static void init_color(struct repository *r, struct add_i_state *s,
15                        const char *section_and_slot, char *dst,
16                        const char *default_color)
17 {
18         char *key = xstrfmt("color.%s", section_and_slot);
19         const char *value;
20
21         if (!s->use_color)
22                 dst[0] = '\0';
23         else if (repo_config_get_value(r, key, &value) ||
24                  color_parse(value, dst))
25                 strlcpy(dst, default_color, COLOR_MAXLEN);
26
27         free(key);
28 }
29
30 void init_add_i_state(struct add_i_state *s, struct repository *r)
31 {
32         const char *value;
33
34         s->r = r;
35
36         if (repo_config_get_value(r, "color.interactive", &value))
37                 s->use_color = -1;
38         else
39                 s->use_color =
40                         git_config_colorbool("color.interactive", value);
41         s->use_color = want_color(s->use_color);
42
43         init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
44         init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
45         init_color(r, s, "interactive.prompt", s->prompt_color,
46                    GIT_COLOR_BOLD_BLUE);
47         init_color(r, s, "interactive.error", s->error_color,
48                    GIT_COLOR_BOLD_RED);
49
50         init_color(r, s, "diff.frag", s->fraginfo_color,
51                    diff_get_color(s->use_color, DIFF_FRAGINFO));
52         init_color(r, s, "diff.context", s->context_color, "fall back");
53         if (!strcmp(s->context_color, "fall back"))
54                 init_color(r, s, "diff.plain", s->context_color,
55                            diff_get_color(s->use_color, DIFF_CONTEXT));
56         init_color(r, s, "diff.old", s->file_old_color,
57                 diff_get_color(s->use_color, DIFF_FILE_OLD));
58         init_color(r, s, "diff.new", s->file_new_color,
59                 diff_get_color(s->use_color, DIFF_FILE_NEW));
60
61         strlcpy(s->reset_color,
62                 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
63
64         FREE_AND_NULL(s->interactive_diff_filter);
65         git_config_get_string("interactive.difffilter",
66                               &s->interactive_diff_filter);
67
68         FREE_AND_NULL(s->interactive_diff_algorithm);
69         git_config_get_string("diff.algorithm",
70                               &s->interactive_diff_algorithm);
71
72         git_config_get_bool("interactive.singlekey", &s->use_single_key);
73 }
74
75 void clear_add_i_state(struct add_i_state *s)
76 {
77         FREE_AND_NULL(s->interactive_diff_filter);
78         FREE_AND_NULL(s->interactive_diff_algorithm);
79         memset(s, 0, sizeof(*s));
80         s->use_color = -1;
81 }
82
83 /*
84  * A "prefix item list" is a list of items that are identified by a string, and
85  * a unique prefix (if any) is determined for each item.
86  *
87  * It is implemented in the form of a pair of `string_list`s, the first one
88  * duplicating the strings, with the `util` field pointing at a structure whose
89  * first field must be `size_t prefix_length`.
90  *
91  * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
92  * will be set to zero if no valid, unique prefix could be found.
93  *
94  * The second `string_list` is called `sorted` and does _not_ duplicate the
95  * strings but simply reuses the first one's, with the `util` field pointing at
96  * the `string_item_list` of the first `string_list`. It  will be populated and
97  * sorted by `find_unique_prefixes()`.
98  */
99 struct prefix_item_list {
100         struct string_list items;
101         struct string_list sorted;
102         int *selected; /* for multi-selections */
103         size_t min_length, max_length;
104 };
105 #define PREFIX_ITEM_LIST_INIT \
106         { STRING_LIST_INIT_DUP, STRING_LIST_INIT_NODUP, NULL, 1, 4 }
107
108 static void prefix_item_list_clear(struct prefix_item_list *list)
109 {
110         string_list_clear(&list->items, 1);
111         string_list_clear(&list->sorted, 0);
112         FREE_AND_NULL(list->selected);
113 }
114
115 static void extend_prefix_length(struct string_list_item *p,
116                                  const char *other_string, size_t max_length)
117 {
118         size_t *len = p->util;
119
120         if (!*len || memcmp(p->string, other_string, *len))
121                 return;
122
123         for (;;) {
124                 char c = p->string[*len];
125
126                 /*
127                  * Is `p` a strict prefix of `other`? Or have we exhausted the
128                  * maximal length of the prefix? Or is the current character a
129                  * multi-byte UTF-8 one? If so, there is no valid, unique
130                  * prefix.
131                  */
132                 if (!c || ++*len > max_length || !isascii(c)) {
133                         *len = 0;
134                         break;
135                 }
136
137                 if (c != other_string[*len - 1])
138                         break;
139         }
140 }
141
142 static void find_unique_prefixes(struct prefix_item_list *list)
143 {
144         size_t i;
145
146         if (list->sorted.nr == list->items.nr)
147                 return;
148
149         string_list_clear(&list->sorted, 0);
150         /* Avoid reallocating incrementally */
151         list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
152                                              list->items.nr));
153         list->sorted.nr = list->sorted.alloc = list->items.nr;
154
155         for (i = 0; i < list->items.nr; i++) {
156                 list->sorted.items[i].string = list->items.items[i].string;
157                 list->sorted.items[i].util = list->items.items + i;
158         }
159
160         string_list_sort(&list->sorted);
161
162         for (i = 0; i < list->sorted.nr; i++) {
163                 struct string_list_item *sorted_item = list->sorted.items + i;
164                 struct string_list_item *item = sorted_item->util;
165                 size_t *len = item->util;
166
167                 *len = 0;
168                 while (*len < list->min_length) {
169                         char c = item->string[(*len)++];
170
171                         if (!c || !isascii(c)) {
172                                 *len = 0;
173                                 break;
174                         }
175                 }
176
177                 if (i > 0)
178                         extend_prefix_length(item, sorted_item[-1].string,
179                                              list->max_length);
180                 if (i + 1 < list->sorted.nr)
181                         extend_prefix_length(item, sorted_item[1].string,
182                                              list->max_length);
183         }
184 }
185
186 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
187 {
188         int index = string_list_find_insert_index(&list->sorted, string, 1);
189         struct string_list_item *item;
190
191         if (list->items.nr != list->sorted.nr)
192                 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
193                     " vs %"PRIuMAX")",
194                     (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
195
196         if (index < 0)
197                 item = list->sorted.items[-1 - index].util;
198         else if (index > 0 &&
199                  starts_with(list->sorted.items[index - 1].string, string))
200                 return -1;
201         else if (index + 1 < list->sorted.nr &&
202                  starts_with(list->sorted.items[index + 1].string, string))
203                 return -1;
204         else if (index < list->sorted.nr &&
205                  starts_with(list->sorted.items[index].string, string))
206                 item = list->sorted.items[index].util;
207         else
208                 return -1;
209         return item - list->items.items;
210 }
211
212 struct list_options {
213         int columns;
214         const char *header;
215         void (*print_item)(int i, int selected, struct string_list_item *item,
216                            void *print_item_data);
217         void *print_item_data;
218 };
219
220 static void list(struct add_i_state *s, struct string_list *list, int *selected,
221                  struct list_options *opts)
222 {
223         int i, last_lf = 0;
224
225         if (!list->nr)
226                 return;
227
228         if (opts->header)
229                 color_fprintf_ln(stdout, s->header_color,
230                                  "%s", opts->header);
231
232         for (i = 0; i < list->nr; i++) {
233                 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
234                                  opts->print_item_data);
235
236                 if ((opts->columns) && ((i + 1) % (opts->columns))) {
237                         putchar('\t');
238                         last_lf = 0;
239                 }
240                 else {
241                         putchar('\n');
242                         last_lf = 1;
243                 }
244         }
245
246         if (!last_lf)
247                 putchar('\n');
248 }
249 struct list_and_choose_options {
250         struct list_options list_opts;
251
252         const char *prompt;
253         enum {
254                 SINGLETON = (1<<0),
255                 IMMEDIATE = (1<<1),
256         } flags;
257         void (*print_help)(struct add_i_state *s);
258 };
259
260 #define LIST_AND_CHOOSE_ERROR (-1)
261 #define LIST_AND_CHOOSE_QUIT  (-2)
262
263 /*
264  * Returns the selected index in singleton mode, the number of selected items
265  * otherwise.
266  *
267  * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
268  * `LIST_AND_CHOOSE_QUIT` is returned.
269  */
270 static ssize_t list_and_choose(struct add_i_state *s,
271                                struct prefix_item_list *items,
272                                struct list_and_choose_options *opts)
273 {
274         int singleton = opts->flags & SINGLETON;
275         int immediate = opts->flags & IMMEDIATE;
276
277         struct strbuf input = STRBUF_INIT;
278         ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
279
280         if (!singleton) {
281                 free(items->selected);
282                 CALLOC_ARRAY(items->selected, items->items.nr);
283         }
284
285         if (singleton && !immediate)
286                 BUG("singleton requires immediate");
287
288         find_unique_prefixes(items);
289
290         for (;;) {
291                 char *p;
292
293                 strbuf_reset(&input);
294
295                 list(s, &items->items, items->selected, &opts->list_opts);
296
297                 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
298                 fputs(singleton ? "> " : ">> ", stdout);
299                 fflush(stdout);
300
301                 if (git_read_line_interactively(&input) == EOF) {
302                         putchar('\n');
303                         if (immediate)
304                                 res = LIST_AND_CHOOSE_QUIT;
305                         break;
306                 }
307
308                 if (!input.len)
309                         break;
310
311                 if (!strcmp(input.buf, "?")) {
312                         opts->print_help(s);
313                         continue;
314                 }
315
316                 p = input.buf;
317                 for (;;) {
318                         size_t sep = strcspn(p, " \t\r\n,");
319                         int choose = 1;
320                         /* `from` is inclusive, `to` is exclusive */
321                         ssize_t from = -1, to = -1;
322
323                         if (!sep) {
324                                 if (!*p)
325                                         break;
326                                 p++;
327                                 continue;
328                         }
329
330                         /* Input that begins with '-'; de-select */
331                         if (*p == '-') {
332                                 choose = 0;
333                                 p++;
334                                 sep--;
335                         }
336
337                         if (sep == 1 && *p == '*') {
338                                 from = 0;
339                                 to = items->items.nr;
340                         } else if (isdigit(*p)) {
341                                 char *endp;
342                                 /*
343                                  * A range can be specified like 5-7 or 5-.
344                                  *
345                                  * Note: `from` is 0-based while the user input
346                                  * is 1-based, hence we have to decrement by
347                                  * one. We do not have to decrement `to` even
348                                  * if it is 0-based because it is an exclusive
349                                  * boundary.
350                                  */
351                                 from = strtoul(p, &endp, 10) - 1;
352                                 if (endp == p + sep)
353                                         to = from + 1;
354                                 else if (*endp == '-') {
355                                         if (isdigit(*(++endp)))
356                                                 to = strtoul(endp, &endp, 10);
357                                         else
358                                                 to = items->items.nr;
359                                         /* extra characters after the range? */
360                                         if (endp != p + sep)
361                                                 from = -1;
362                                 }
363                         }
364
365                         if (p[sep])
366                                 p[sep++] = '\0';
367                         if (from < 0) {
368                                 from = find_unique(p, items);
369                                 if (from >= 0)
370                                         to = from + 1;
371                         }
372
373                         if (from < 0 || from >= items->items.nr ||
374                             (singleton && from + 1 != to)) {
375                                 color_fprintf_ln(stderr, s->error_color,
376                                                  _("Huh (%s)?"), p);
377                                 break;
378                         } else if (singleton) {
379                                 res = from;
380                                 break;
381                         }
382
383                         if (to > items->items.nr)
384                                 to = items->items.nr;
385
386                         for (; from < to; from++)
387                                 if (items->selected[from] != choose) {
388                                         items->selected[from] = choose;
389                                         res += choose ? +1 : -1;
390                                 }
391
392                         p += sep;
393                 }
394
395                 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
396                     !strcmp(input.buf, "*"))
397                         break;
398         }
399
400         strbuf_release(&input);
401         return res;
402 }
403
404 struct adddel {
405         uintmax_t add, del;
406         unsigned seen:1, unmerged:1, binary:1;
407 };
408
409 struct file_item {
410         size_t prefix_length;
411         struct adddel index, worktree;
412 };
413
414 static void add_file_item(struct string_list *files, const char *name)
415 {
416         struct file_item *item = xcalloc(sizeof(*item), 1);
417
418         string_list_append(files, name)->util = item;
419 }
420
421 struct pathname_entry {
422         struct hashmap_entry ent;
423         const char *name;
424         struct file_item *item;
425 };
426
427 static int pathname_entry_cmp(const void *unused_cmp_data,
428                               const struct hashmap_entry *he1,
429                               const struct hashmap_entry *he2,
430                               const void *name)
431 {
432         const struct pathname_entry *e1 =
433                 container_of(he1, const struct pathname_entry, ent);
434         const struct pathname_entry *e2 =
435                 container_of(he2, const struct pathname_entry, ent);
436
437         return strcmp(e1->name, name ? (const char *)name : e2->name);
438 }
439
440 struct collection_status {
441         enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
442
443         const char *reference;
444
445         unsigned skip_unseen:1;
446         size_t unmerged_count, binary_count;
447         struct string_list *files;
448         struct hashmap file_map;
449 };
450
451 static void collect_changes_cb(struct diff_queue_struct *q,
452                                struct diff_options *options,
453                                void *data)
454 {
455         struct collection_status *s = data;
456         struct diffstat_t stat = { 0 };
457         int i;
458
459         if (!q->nr)
460                 return;
461
462         compute_diffstat(options, &stat, q);
463
464         for (i = 0; i < stat.nr; i++) {
465                 const char *name = stat.files[i]->name;
466                 int hash = strhash(name);
467                 struct pathname_entry *entry;
468                 struct file_item *file_item;
469                 struct adddel *adddel, *other_adddel;
470
471                 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
472                                                     struct pathname_entry, ent);
473                 if (!entry) {
474                         if (s->skip_unseen)
475                                 continue;
476
477                         add_file_item(s->files, name);
478
479                         entry = xcalloc(sizeof(*entry), 1);
480                         hashmap_entry_init(&entry->ent, hash);
481                         entry->name = s->files->items[s->files->nr - 1].string;
482                         entry->item = s->files->items[s->files->nr - 1].util;
483                         hashmap_add(&s->file_map, &entry->ent);
484                 }
485
486                 file_item = entry->item;
487                 adddel = s->mode == FROM_INDEX ?
488                         &file_item->index : &file_item->worktree;
489                 other_adddel = s->mode == FROM_INDEX ?
490                         &file_item->worktree : &file_item->index;
491                 adddel->seen = 1;
492                 adddel->add = stat.files[i]->added;
493                 adddel->del = stat.files[i]->deleted;
494                 if (stat.files[i]->is_binary) {
495                         if (!other_adddel->binary)
496                                 s->binary_count++;
497                         adddel->binary = 1;
498                 }
499                 if (stat.files[i]->is_unmerged) {
500                         if (!other_adddel->unmerged)
501                                 s->unmerged_count++;
502                         adddel->unmerged = 1;
503                 }
504         }
505         free_diffstat_info(&stat);
506 }
507
508 enum modified_files_filter {
509         NO_FILTER = 0,
510         WORKTREE_ONLY = 1,
511         INDEX_ONLY = 2,
512 };
513
514 static int get_modified_files(struct repository *r,
515                               enum modified_files_filter filter,
516                               struct prefix_item_list *files,
517                               const struct pathspec *ps,
518                               size_t *unmerged_count,
519                               size_t *binary_count)
520 {
521         struct object_id head_oid;
522         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
523                                              &head_oid, NULL);
524         struct collection_status s = { 0 };
525         int i;
526
527         if (discard_index(r->index) < 0 ||
528             repo_read_index_preload(r, ps, 0) < 0)
529                 return error(_("could not read index"));
530
531         prefix_item_list_clear(files);
532         s.files = &files->items;
533         hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
534
535         for (i = 0; i < 2; i++) {
536                 struct rev_info rev;
537                 struct setup_revision_opt opt = { 0 };
538
539                 if (filter == INDEX_ONLY)
540                         s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
541                 else
542                         s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
543                 s.skip_unseen = filter && i;
544
545                 opt.def = is_initial ?
546                         empty_tree_oid_hex() : oid_to_hex(&head_oid);
547
548                 init_revisions(&rev, NULL);
549                 setup_revisions(0, NULL, &rev, &opt);
550
551                 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
552                 rev.diffopt.format_callback = collect_changes_cb;
553                 rev.diffopt.format_callback_data = &s;
554
555                 if (ps)
556                         copy_pathspec(&rev.prune_data, ps);
557
558                 if (s.mode == FROM_INDEX)
559                         run_diff_index(&rev, 1);
560                 else {
561                         rev.diffopt.flags.ignore_dirty_submodules = 1;
562                         run_diff_files(&rev, 0);
563                 }
564
565                 if (ps)
566                         clear_pathspec(&rev.prune_data);
567         }
568         hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
569         if (unmerged_count)
570                 *unmerged_count = s.unmerged_count;
571         if (binary_count)
572                 *binary_count = s.binary_count;
573
574         /* While the diffs are ordered already, we ran *two* diffs... */
575         string_list_sort(&files->items);
576
577         return 0;
578 }
579
580 static void render_adddel(struct strbuf *buf,
581                                 struct adddel *ad, const char *no_changes)
582 {
583         if (ad->binary)
584                 strbuf_addstr(buf, _("binary"));
585         else if (ad->seen)
586                 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
587                             (uintmax_t)ad->add, (uintmax_t)ad->del);
588         else
589                 strbuf_addstr(buf, no_changes);
590 }
591
592 /* filters out prefixes which have special meaning to list_and_choose() */
593 static int is_valid_prefix(const char *prefix, size_t prefix_len)
594 {
595         return prefix_len && prefix &&
596                 /*
597                  * We expect `prefix` to be NUL terminated, therefore this
598                  * `strcspn()` call is okay, even if it might do much more
599                  * work than strictly necessary.
600                  */
601                 strcspn(prefix, " \t\r\n,") >= prefix_len &&    /* separators */
602                 *prefix != '-' &&                               /* deselection */
603                 !isdigit(*prefix) &&                            /* selection */
604                 (prefix_len != 1 ||
605                  (*prefix != '*' &&                             /* "all" wildcard */
606                   *prefix != '?'));                             /* prompt help */
607 }
608
609 struct print_file_item_data {
610         const char *modified_fmt, *color, *reset;
611         struct strbuf buf, name, index, worktree;
612         unsigned only_names:1;
613 };
614
615 static void print_file_item(int i, int selected, struct string_list_item *item,
616                             void *print_file_item_data)
617 {
618         struct file_item *c = item->util;
619         struct print_file_item_data *d = print_file_item_data;
620         const char *highlighted = NULL;
621
622         strbuf_reset(&d->index);
623         strbuf_reset(&d->worktree);
624         strbuf_reset(&d->buf);
625
626         /* Format the item with the prefix highlighted. */
627         if (c->prefix_length > 0 &&
628             is_valid_prefix(item->string, c->prefix_length)) {
629                 strbuf_reset(&d->name);
630                 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
631                             (int)c->prefix_length, item->string, d->reset,
632                             item->string + c->prefix_length);
633                 highlighted = d->name.buf;
634         }
635
636         if (d->only_names) {
637                 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
638                        highlighted ? highlighted : item->string);
639                 return;
640         }
641
642         render_adddel(&d->worktree, &c->worktree, _("nothing"));
643         render_adddel(&d->index, &c->index, _("unchanged"));
644
645         strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
646                     highlighted ? highlighted : item->string);
647
648         printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
649 }
650
651 static int run_status(struct add_i_state *s, const struct pathspec *ps,
652                       struct prefix_item_list *files,
653                       struct list_and_choose_options *opts)
654 {
655         if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
656                 return -1;
657
658         list(s, &files->items, NULL, &opts->list_opts);
659         putchar('\n');
660
661         return 0;
662 }
663
664 static int run_update(struct add_i_state *s, const struct pathspec *ps,
665                       struct prefix_item_list *files,
666                       struct list_and_choose_options *opts)
667 {
668         int res = 0, fd;
669         size_t count, i;
670         struct lock_file index_lock;
671
672         if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
673                 return -1;
674
675         if (!files->items.nr) {
676                 putchar('\n');
677                 return 0;
678         }
679
680         opts->prompt = N_("Update");
681         count = list_and_choose(s, files, opts);
682         if (count <= 0) {
683                 putchar('\n');
684                 return 0;
685         }
686
687         fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
688         if (fd < 0) {
689                 putchar('\n');
690                 return -1;
691         }
692
693         for (i = 0; i < files->items.nr; i++) {
694                 const char *name = files->items.items[i].string;
695                 if (files->selected[i] &&
696                     add_file_to_index(s->r->index, name, 0) < 0) {
697                         res = error(_("could not stage '%s'"), name);
698                         break;
699                 }
700         }
701
702         if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
703                 res = error(_("could not write index"));
704
705         if (!res)
706                 printf(Q_("updated %d path\n",
707                           "updated %d paths\n", count), (int)count);
708
709         putchar('\n');
710         return res;
711 }
712
713 static void revert_from_diff(struct diff_queue_struct *q,
714                              struct diff_options *opt, void *data)
715 {
716         int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
717
718         for (i = 0; i < q->nr; i++) {
719                 struct diff_filespec *one = q->queue[i]->one;
720                 struct cache_entry *ce;
721
722                 if (!(one->mode && !is_null_oid(&one->oid))) {
723                         remove_file_from_index(opt->repo->index, one->path);
724                         printf(_("note: %s is untracked now.\n"), one->path);
725                 } else {
726                         ce = make_cache_entry(opt->repo->index, one->mode,
727                                               &one->oid, one->path, 0, 0);
728                         if (!ce)
729                                 die(_("make_cache_entry failed for path '%s'"),
730                                     one->path);
731                         add_index_entry(opt->repo->index, ce, add_flags);
732                 }
733         }
734 }
735
736 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
737                       struct prefix_item_list *files,
738                       struct list_and_choose_options *opts)
739 {
740         int res = 0, fd;
741         size_t count, i, j;
742
743         struct object_id oid;
744         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
745                                              NULL);
746         struct lock_file index_lock;
747         const char **paths;
748         struct tree *tree;
749         struct diff_options diffopt = { NULL };
750
751         if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
752                 return -1;
753
754         if (!files->items.nr) {
755                 putchar('\n');
756                 return 0;
757         }
758
759         opts->prompt = N_("Revert");
760         count = list_and_choose(s, files, opts);
761         if (count <= 0)
762                 goto finish_revert;
763
764         fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
765         if (fd < 0) {
766                 res = -1;
767                 goto finish_revert;
768         }
769
770         if (is_initial)
771                 oidcpy(&oid, s->r->hash_algo->empty_tree);
772         else {
773                 tree = parse_tree_indirect(&oid);
774                 if (!tree) {
775                         res = error(_("Could not parse HEAD^{tree}"));
776                         goto finish_revert;
777                 }
778                 oidcpy(&oid, &tree->object.oid);
779         }
780
781         ALLOC_ARRAY(paths, count + 1);
782         for (i = j = 0; i < files->items.nr; i++)
783                 if (files->selected[i])
784                         paths[j++] = files->items.items[i].string;
785         paths[j] = NULL;
786
787         parse_pathspec(&diffopt.pathspec, 0,
788                        PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
789                        NULL, paths);
790
791         diffopt.output_format = DIFF_FORMAT_CALLBACK;
792         diffopt.format_callback = revert_from_diff;
793         diffopt.flags.override_submodule_config = 1;
794         diffopt.repo = s->r;
795
796         if (do_diff_cache(&oid, &diffopt))
797                 res = -1;
798         else {
799                 diffcore_std(&diffopt);
800                 diff_flush(&diffopt);
801         }
802         free(paths);
803         clear_pathspec(&diffopt.pathspec);
804
805         if (!res && write_locked_index(s->r->index, &index_lock,
806                                        COMMIT_LOCK) < 0)
807                 res = -1;
808         else
809                 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
810                                                    NULL, NULL, NULL);
811
812         if (!res)
813                 printf(Q_("reverted %d path\n",
814                           "reverted %d paths\n", count), (int)count);
815
816 finish_revert:
817         putchar('\n');
818         return res;
819 }
820
821 static int get_untracked_files(struct repository *r,
822                                struct prefix_item_list *files,
823                                const struct pathspec *ps)
824 {
825         struct dir_struct dir = { 0 };
826         size_t i;
827         struct strbuf buf = STRBUF_INIT;
828
829         if (repo_read_index(r) < 0)
830                 return error(_("could not read index"));
831
832         prefix_item_list_clear(files);
833         setup_standard_excludes(&dir);
834         add_pattern_list(&dir, EXC_CMDL, "--exclude option");
835         fill_directory(&dir, r->index, ps);
836
837         for (i = 0; i < dir.nr; i++) {
838                 struct dir_entry *ent = dir.entries[i];
839
840                 if (index_name_is_other(r->index, ent->name, ent->len)) {
841                         strbuf_reset(&buf);
842                         strbuf_add(&buf, ent->name, ent->len);
843                         add_file_item(&files->items, buf.buf);
844                 }
845         }
846
847         strbuf_release(&buf);
848         return 0;
849 }
850
851 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
852                       struct prefix_item_list *files,
853                       struct list_and_choose_options *opts)
854 {
855         struct print_file_item_data *d = opts->list_opts.print_item_data;
856         int res = 0, fd;
857         size_t count, i;
858         struct lock_file index_lock;
859
860         if (get_untracked_files(s->r, files, ps) < 0)
861                 return -1;
862
863         if (!files->items.nr) {
864                 printf(_("No untracked files.\n"));
865                 goto finish_add_untracked;
866         }
867
868         opts->prompt = N_("Add untracked");
869         d->only_names = 1;
870         count = list_and_choose(s, files, opts);
871         d->only_names = 0;
872         if (count <= 0)
873                 goto finish_add_untracked;
874
875         fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
876         if (fd < 0) {
877                 res = -1;
878                 goto finish_add_untracked;
879         }
880
881         for (i = 0; i < files->items.nr; i++) {
882                 const char *name = files->items.items[i].string;
883                 if (files->selected[i] &&
884                     add_file_to_index(s->r->index, name, 0) < 0) {
885                         res = error(_("could not stage '%s'"), name);
886                         break;
887                 }
888         }
889
890         if (!res &&
891             write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
892                 res = error(_("could not write index"));
893
894         if (!res)
895                 printf(Q_("added %d path\n",
896                           "added %d paths\n", count), (int)count);
897
898 finish_add_untracked:
899         putchar('\n');
900         return res;
901 }
902
903 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
904                      struct prefix_item_list *files,
905                      struct list_and_choose_options *opts)
906 {
907         int res = 0;
908         ssize_t count, i, j;
909         size_t unmerged_count = 0, binary_count = 0;
910
911         if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
912                                &unmerged_count, &binary_count) < 0)
913                 return -1;
914
915         if (unmerged_count || binary_count) {
916                 for (i = j = 0; i < files->items.nr; i++) {
917                         struct file_item *item = files->items.items[i].util;
918
919                         if (item->index.binary || item->worktree.binary) {
920                                 free(item);
921                                 free(files->items.items[i].string);
922                         } else if (item->index.unmerged ||
923                                  item->worktree.unmerged) {
924                                 color_fprintf_ln(stderr, s->error_color,
925                                                  _("ignoring unmerged: %s"),
926                                                  files->items.items[i].string);
927                                 free(item);
928                                 free(files->items.items[i].string);
929                         } else
930                                 files->items.items[j++] = files->items.items[i];
931                 }
932                 files->items.nr = j;
933         }
934
935         if (!files->items.nr) {
936                 if (binary_count)
937                         fprintf(stderr, _("Only binary files changed.\n"));
938                 else
939                         fprintf(stderr, _("No changes.\n"));
940                 return 0;
941         }
942
943         opts->prompt = N_("Patch update");
944         count = list_and_choose(s, files, opts);
945         if (count > 0) {
946                 struct strvec args = STRVEC_INIT;
947                 struct pathspec ps_selected = { 0 };
948
949                 for (i = 0; i < files->items.nr; i++)
950                         if (files->selected[i])
951                                 strvec_push(&args,
952                                             files->items.items[i].string);
953                 parse_pathspec(&ps_selected,
954                                PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
955                                PATHSPEC_LITERAL_PATH, "", args.v);
956                 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
957                 strvec_clear(&args);
958                 clear_pathspec(&ps_selected);
959         }
960
961         return res;
962 }
963
964 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
965                     struct prefix_item_list *files,
966                     struct list_and_choose_options *opts)
967 {
968         int res = 0;
969         ssize_t count, i;
970
971         struct object_id oid;
972         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
973                                              NULL);
974         if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
975                 return -1;
976
977         if (!files->items.nr) {
978                 putchar('\n');
979                 return 0;
980         }
981
982         opts->prompt = N_("Review diff");
983         opts->flags = IMMEDIATE;
984         count = list_and_choose(s, files, opts);
985         opts->flags = 0;
986         if (count > 0) {
987                 struct strvec args = STRVEC_INIT;
988
989                 strvec_pushl(&args, "git", "diff", "-p", "--cached",
990                              oid_to_hex(!is_initial ? &oid :
991                                         s->r->hash_algo->empty_tree),
992                              "--", NULL);
993                 for (i = 0; i < files->items.nr; i++)
994                         if (files->selected[i])
995                                 strvec_push(&args,
996                                             files->items.items[i].string);
997                 res = run_command_v_opt(args.v, 0);
998                 strvec_clear(&args);
999         }
1000
1001         putchar('\n');
1002         return res;
1003 }
1004
1005 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1006                     struct prefix_item_list *unused_files,
1007                     struct list_and_choose_options *unused_opts)
1008 {
1009         color_fprintf_ln(stdout, s->help_color, "status        - %s",
1010                          _("show paths with changes"));
1011         color_fprintf_ln(stdout, s->help_color, "update        - %s",
1012                          _("add working tree state to the staged set of changes"));
1013         color_fprintf_ln(stdout, s->help_color, "revert        - %s",
1014                          _("revert staged set of changes back to the HEAD version"));
1015         color_fprintf_ln(stdout, s->help_color, "patch         - %s",
1016                          _("pick hunks and update selectively"));
1017         color_fprintf_ln(stdout, s->help_color, "diff          - %s",
1018                          _("view diff between HEAD and index"));
1019         color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1020                          _("add contents of untracked files to the staged set of changes"));
1021
1022         return 0;
1023 }
1024
1025 static void choose_prompt_help(struct add_i_state *s)
1026 {
1027         color_fprintf_ln(stdout, s->help_color, "%s",
1028                          _("Prompt help:"));
1029         color_fprintf_ln(stdout, s->help_color, "1          - %s",
1030                          _("select a single item"));
1031         color_fprintf_ln(stdout, s->help_color, "3-5        - %s",
1032                          _("select a range of items"));
1033         color_fprintf_ln(stdout, s->help_color, "2-3,6-9    - %s",
1034                          _("select multiple ranges"));
1035         color_fprintf_ln(stdout, s->help_color, "foo        - %s",
1036                          _("select item based on unique prefix"));
1037         color_fprintf_ln(stdout, s->help_color, "-...       - %s",
1038                          _("unselect specified items"));
1039         color_fprintf_ln(stdout, s->help_color, "*          - %s",
1040                          _("choose all items"));
1041         color_fprintf_ln(stdout, s->help_color, "           - %s",
1042                          _("(empty) finish selecting"));
1043 }
1044
1045 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1046                          struct prefix_item_list *files,
1047                          struct list_and_choose_options *opts);
1048
1049 struct command_item {
1050         size_t prefix_length;
1051         command_t command;
1052 };
1053
1054 struct print_command_item_data {
1055         const char *color, *reset;
1056 };
1057
1058 static void print_command_item(int i, int selected,
1059                                struct string_list_item *item,
1060                                void *print_command_item_data)
1061 {
1062         struct print_command_item_data *d = print_command_item_data;
1063         struct command_item *util = item->util;
1064
1065         if (!util->prefix_length ||
1066             !is_valid_prefix(item->string, util->prefix_length))
1067                 printf(" %2d: %s", i + 1, item->string);
1068         else
1069                 printf(" %2d: %s%.*s%s%s", i + 1,
1070                        d->color, (int)util->prefix_length, item->string,
1071                        d->reset, item->string + util->prefix_length);
1072 }
1073
1074 static void command_prompt_help(struct add_i_state *s)
1075 {
1076         const char *help_color = s->help_color;
1077         color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1078         color_fprintf_ln(stdout, help_color, "1          - %s",
1079                          _("select a numbered item"));
1080         color_fprintf_ln(stdout, help_color, "foo        - %s",
1081                          _("select item based on unique prefix"));
1082         color_fprintf_ln(stdout, help_color, "           - %s",
1083                          _("(empty) select nothing"));
1084 }
1085
1086 int run_add_i(struct repository *r, const struct pathspec *ps)
1087 {
1088         struct add_i_state s = { NULL };
1089         struct print_command_item_data data = { "[", "]" };
1090         struct list_and_choose_options main_loop_opts = {
1091                 { 4, N_("*** Commands ***"), print_command_item, &data },
1092                 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1093         };
1094         struct {
1095                 const char *string;
1096                 command_t command;
1097         } command_list[] = {
1098                 { "status", run_status },
1099                 { "update", run_update },
1100                 { "revert", run_revert },
1101                 { "add untracked", run_add_untracked },
1102                 { "patch", run_patch },
1103                 { "diff", run_diff },
1104                 { "quit", NULL },
1105                 { "help", run_help },
1106         };
1107         struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1108
1109         struct print_file_item_data print_file_item_data = {
1110                 "%12s %12s %s", NULL, NULL,
1111                 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1112         };
1113         struct list_and_choose_options opts = {
1114                 { 0, NULL, print_file_item, &print_file_item_data },
1115                 NULL, 0, choose_prompt_help
1116         };
1117         struct strbuf header = STRBUF_INIT;
1118         struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1119         ssize_t i;
1120         int res = 0;
1121
1122         for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1123                 struct command_item *util = xcalloc(sizeof(*util), 1);
1124                 util->command = command_list[i].command;
1125                 string_list_append(&commands.items, command_list[i].string)
1126                         ->util = util;
1127         }
1128
1129         init_add_i_state(&s, r);
1130
1131         /*
1132          * When color was asked for, use the prompt color for
1133          * highlighting, otherwise use square brackets.
1134          */
1135         if (s.use_color) {
1136                 data.color = s.prompt_color;
1137                 data.reset = s.reset_color;
1138         }
1139         print_file_item_data.color = data.color;
1140         print_file_item_data.reset = data.reset;
1141
1142         strbuf_addstr(&header, "     ");
1143         strbuf_addf(&header, print_file_item_data.modified_fmt,
1144                     _("staged"), _("unstaged"), _("path"));
1145         opts.list_opts.header = header.buf;
1146
1147         if (discard_index(r->index) < 0 ||
1148             repo_read_index(r) < 0 ||
1149             repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1150                                          NULL, NULL, NULL) < 0)
1151                 warning(_("could not refresh index"));
1152
1153         res = run_status(&s, ps, &files, &opts);
1154
1155         for (;;) {
1156                 struct command_item *util;
1157
1158                 i = list_and_choose(&s, &commands, &main_loop_opts);
1159                 if (i < 0 || i >= commands.items.nr)
1160                         util = NULL;
1161                 else
1162                         util = commands.items.items[i].util;
1163
1164                 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1165                         printf(_("Bye.\n"));
1166                         res = 0;
1167                         break;
1168                 }
1169
1170                 if (util)
1171                         res = util->command(&s, ps, &files, &opts);
1172         }
1173
1174         prefix_item_list_clear(&files);
1175         strbuf_release(&print_file_item_data.buf);
1176         strbuf_release(&print_file_item_data.name);
1177         strbuf_release(&print_file_item_data.index);
1178         strbuf_release(&print_file_item_data.worktree);
1179         strbuf_release(&header);
1180         prefix_item_list_clear(&commands);
1181         clear_add_i_state(&s);
1182
1183         return res;
1184 }