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