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