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