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