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