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