connected: verify promisor-ness of partial clone
[git] / add-interactive.c
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "color.h"
4 #include "config.h"
5 #include "diffcore.h"
6 #include "revision.h"
7 #include "refs.h"
8 #include "string-list.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "run-command.h"
12
13 static void init_color(struct repository *r, struct add_i_state *s,
14                        const char *slot_name, char *dst,
15                        const char *default_color)
16 {
17         char *key = xstrfmt("color.interactive.%s", slot_name);
18         const char *value;
19
20         if (!s->use_color)
21                 dst[0] = '\0';
22         else if (repo_config_get_value(r, key, &value) ||
23                  color_parse(value, dst))
24                 strlcpy(dst, default_color, COLOR_MAXLEN);
25
26         free(key);
27 }
28
29 void init_add_i_state(struct add_i_state *s, struct repository *r)
30 {
31         const char *value;
32
33         s->r = r;
34
35         if (repo_config_get_value(r, "color.interactive", &value))
36                 s->use_color = -1;
37         else
38                 s->use_color =
39                         git_config_colorbool("color.interactive", value);
40         s->use_color = want_color(s->use_color);
41
42         init_color(r, s, "header", s->header_color, GIT_COLOR_BOLD);
43         init_color(r, s, "help", s->help_color, GIT_COLOR_BOLD_RED);
44         init_color(r, s, "prompt", s->prompt_color, GIT_COLOR_BOLD_BLUE);
45         init_color(r, s, "error", s->error_color, GIT_COLOR_BOLD_RED);
46         init_color(r, s, "reset", s->reset_color, GIT_COLOR_RESET);
47         init_color(r, s, "fraginfo", s->fraginfo_color,
48                    diff_get_color(s->use_color, DIFF_FRAGINFO));
49         init_color(r, s, "context", s->context_color,
50                 diff_get_color(s->use_color, DIFF_CONTEXT));
51         init_color(r, s, "old", s->file_old_color,
52                 diff_get_color(s->use_color, DIFF_FILE_OLD));
53         init_color(r, s, "new", s->file_new_color,
54                 diff_get_color(s->use_color, DIFF_FILE_NEW));
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, unmerged: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         size_t unmerged_count, binary_count;
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, *other_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                 other_adddel = s->mode == FROM_INDEX ?
461                         &file_item->worktree : &file_item->index;
462                 adddel->seen = 1;
463                 adddel->add = stat.files[i]->added;
464                 adddel->del = stat.files[i]->deleted;
465                 if (stat.files[i]->is_binary) {
466                         if (!other_adddel->binary)
467                                 s->binary_count++;
468                         adddel->binary = 1;
469                 }
470                 if (stat.files[i]->is_unmerged) {
471                         if (!other_adddel->unmerged)
472                                 s->unmerged_count++;
473                         adddel->unmerged = 1;
474                 }
475         }
476         free_diffstat_info(&stat);
477 }
478
479 enum modified_files_filter {
480         NO_FILTER = 0,
481         WORKTREE_ONLY = 1,
482         INDEX_ONLY = 2,
483 };
484
485 static int get_modified_files(struct repository *r,
486                               enum modified_files_filter filter,
487                               struct prefix_item_list *files,
488                               const struct pathspec *ps,
489                               size_t *unmerged_count,
490                               size_t *binary_count)
491 {
492         struct object_id head_oid;
493         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
494                                              &head_oid, NULL);
495         struct collection_status s = { 0 };
496         int i;
497
498         if (discard_index(r->index) < 0 ||
499             repo_read_index_preload(r, ps, 0) < 0)
500                 return error(_("could not read index"));
501
502         prefix_item_list_clear(files);
503         s.files = &files->items;
504         hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
505
506         for (i = 0; i < 2; i++) {
507                 struct rev_info rev;
508                 struct setup_revision_opt opt = { 0 };
509
510                 if (filter == INDEX_ONLY)
511                         s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
512                 else
513                         s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
514                 s.skip_unseen = filter && i;
515
516                 opt.def = is_initial ?
517                         empty_tree_oid_hex() : oid_to_hex(&head_oid);
518
519                 init_revisions(&rev, NULL);
520                 setup_revisions(0, NULL, &rev, &opt);
521
522                 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
523                 rev.diffopt.format_callback = collect_changes_cb;
524                 rev.diffopt.format_callback_data = &s;
525
526                 if (ps)
527                         copy_pathspec(&rev.prune_data, ps);
528
529                 if (s.mode == FROM_INDEX)
530                         run_diff_index(&rev, 1);
531                 else {
532                         rev.diffopt.flags.ignore_dirty_submodules = 1;
533                         run_diff_files(&rev, 0);
534                 }
535
536                 if (ps)
537                         clear_pathspec(&rev.prune_data);
538         }
539         hashmap_free_entries(&s.file_map, struct pathname_entry, ent);
540         if (unmerged_count)
541                 *unmerged_count = s.unmerged_count;
542         if (binary_count)
543                 *binary_count = s.binary_count;
544
545         /* While the diffs are ordered already, we ran *two* diffs... */
546         string_list_sort(&files->items);
547
548         return 0;
549 }
550
551 static void render_adddel(struct strbuf *buf,
552                                 struct adddel *ad, const char *no_changes)
553 {
554         if (ad->binary)
555                 strbuf_addstr(buf, _("binary"));
556         else if (ad->seen)
557                 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
558                             (uintmax_t)ad->add, (uintmax_t)ad->del);
559         else
560                 strbuf_addstr(buf, no_changes);
561 }
562
563 /* filters out prefixes which have special meaning to list_and_choose() */
564 static int is_valid_prefix(const char *prefix, size_t prefix_len)
565 {
566         return prefix_len && prefix &&
567                 /*
568                  * We expect `prefix` to be NUL terminated, therefore this
569                  * `strcspn()` call is okay, even if it might do much more
570                  * work than strictly necessary.
571                  */
572                 strcspn(prefix, " \t\r\n,") >= prefix_len &&    /* separators */
573                 *prefix != '-' &&                               /* deselection */
574                 !isdigit(*prefix) &&                            /* selection */
575                 (prefix_len != 1 ||
576                  (*prefix != '*' &&                             /* "all" wildcard */
577                   *prefix != '?'));                             /* prompt help */
578 }
579
580 struct print_file_item_data {
581         const char *modified_fmt, *color, *reset;
582         struct strbuf buf, name, index, worktree;
583         unsigned only_names:1;
584 };
585
586 static void print_file_item(int i, int selected, struct string_list_item *item,
587                             void *print_file_item_data)
588 {
589         struct file_item *c = item->util;
590         struct print_file_item_data *d = print_file_item_data;
591         const char *highlighted = NULL;
592
593         strbuf_reset(&d->index);
594         strbuf_reset(&d->worktree);
595         strbuf_reset(&d->buf);
596
597         /* Format the item with the prefix highlighted. */
598         if (c->prefix_length > 0 &&
599             is_valid_prefix(item->string, c->prefix_length)) {
600                 strbuf_reset(&d->name);
601                 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
602                             (int)c->prefix_length, item->string, d->reset,
603                             item->string + c->prefix_length);
604                 highlighted = d->name.buf;
605         }
606
607         if (d->only_names) {
608                 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
609                        highlighted ? highlighted : item->string);
610                 return;
611         }
612
613         render_adddel(&d->worktree, &c->worktree, _("nothing"));
614         render_adddel(&d->index, &c->index, _("unchanged"));
615
616         strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
617                     highlighted ? highlighted : item->string);
618
619         printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
620 }
621
622 static int run_status(struct add_i_state *s, const struct pathspec *ps,
623                       struct prefix_item_list *files,
624                       struct list_and_choose_options *opts)
625 {
626         if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
627                 return -1;
628
629         list(s, &files->items, NULL, &opts->list_opts);
630         putchar('\n');
631
632         return 0;
633 }
634
635 static int run_update(struct add_i_state *s, const struct pathspec *ps,
636                       struct prefix_item_list *files,
637                       struct list_and_choose_options *opts)
638 {
639         int res = 0, fd;
640         size_t count, i;
641         struct lock_file index_lock;
642
643         if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
644                 return -1;
645
646         if (!files->items.nr) {
647                 putchar('\n');
648                 return 0;
649         }
650
651         opts->prompt = N_("Update");
652         count = list_and_choose(s, files, opts);
653         if (count <= 0) {
654                 putchar('\n');
655                 return 0;
656         }
657
658         fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
659         if (fd < 0) {
660                 putchar('\n');
661                 return -1;
662         }
663
664         for (i = 0; i < files->items.nr; i++) {
665                 const char *name = files->items.items[i].string;
666                 if (files->selected[i] &&
667                     add_file_to_index(s->r->index, name, 0) < 0) {
668                         res = error(_("could not stage '%s'"), name);
669                         break;
670                 }
671         }
672
673         if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
674                 res = error(_("could not write index"));
675
676         if (!res)
677                 printf(Q_("updated %d path\n",
678                           "updated %d paths\n", count), (int)count);
679
680         putchar('\n');
681         return res;
682 }
683
684 static void revert_from_diff(struct diff_queue_struct *q,
685                              struct diff_options *opt, void *data)
686 {
687         int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
688
689         for (i = 0; i < q->nr; i++) {
690                 struct diff_filespec *one = q->queue[i]->one;
691                 struct cache_entry *ce;
692
693                 if (!(one->mode && !is_null_oid(&one->oid))) {
694                         remove_file_from_index(opt->repo->index, one->path);
695                         printf(_("note: %s is untracked now.\n"), one->path);
696                 } else {
697                         ce = make_cache_entry(opt->repo->index, one->mode,
698                                               &one->oid, one->path, 0, 0);
699                         if (!ce)
700                                 die(_("make_cache_entry failed for path '%s'"),
701                                     one->path);
702                         add_index_entry(opt->repo->index, ce, add_flags);
703                 }
704         }
705 }
706
707 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
708                       struct prefix_item_list *files,
709                       struct list_and_choose_options *opts)
710 {
711         int res = 0, fd;
712         size_t count, i, j;
713
714         struct object_id oid;
715         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
716                                              NULL);
717         struct lock_file index_lock;
718         const char **paths;
719         struct tree *tree;
720         struct diff_options diffopt = { NULL };
721
722         if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
723                 return -1;
724
725         if (!files->items.nr) {
726                 putchar('\n');
727                 return 0;
728         }
729
730         opts->prompt = N_("Revert");
731         count = list_and_choose(s, files, opts);
732         if (count <= 0)
733                 goto finish_revert;
734
735         fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
736         if (fd < 0) {
737                 res = -1;
738                 goto finish_revert;
739         }
740
741         if (is_initial)
742                 oidcpy(&oid, s->r->hash_algo->empty_tree);
743         else {
744                 tree = parse_tree_indirect(&oid);
745                 if (!tree) {
746                         res = error(_("Could not parse HEAD^{tree}"));
747                         goto finish_revert;
748                 }
749                 oidcpy(&oid, &tree->object.oid);
750         }
751
752         ALLOC_ARRAY(paths, count + 1);
753         for (i = j = 0; i < files->items.nr; i++)
754                 if (files->selected[i])
755                         paths[j++] = files->items.items[i].string;
756         paths[j] = NULL;
757
758         parse_pathspec(&diffopt.pathspec, 0,
759                        PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
760                        NULL, paths);
761
762         diffopt.output_format = DIFF_FORMAT_CALLBACK;
763         diffopt.format_callback = revert_from_diff;
764         diffopt.flags.override_submodule_config = 1;
765         diffopt.repo = s->r;
766
767         if (do_diff_cache(&oid, &diffopt))
768                 res = -1;
769         else {
770                 diffcore_std(&diffopt);
771                 diff_flush(&diffopt);
772         }
773         free(paths);
774         clear_pathspec(&diffopt.pathspec);
775
776         if (!res && write_locked_index(s->r->index, &index_lock,
777                                        COMMIT_LOCK) < 0)
778                 res = -1;
779         else
780                 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
781                                                    NULL, NULL, NULL);
782
783         if (!res)
784                 printf(Q_("reverted %d path\n",
785                           "reverted %d paths\n", count), (int)count);
786
787 finish_revert:
788         putchar('\n');
789         return res;
790 }
791
792 static int get_untracked_files(struct repository *r,
793                                struct prefix_item_list *files,
794                                const struct pathspec *ps)
795 {
796         struct dir_struct dir = { 0 };
797         size_t i;
798         struct strbuf buf = STRBUF_INIT;
799
800         if (repo_read_index(r) < 0)
801                 return error(_("could not read index"));
802
803         prefix_item_list_clear(files);
804         setup_standard_excludes(&dir);
805         add_pattern_list(&dir, EXC_CMDL, "--exclude option");
806         fill_directory(&dir, r->index, ps);
807
808         for (i = 0; i < dir.nr; i++) {
809                 struct dir_entry *ent = dir.entries[i];
810
811                 if (index_name_is_other(r->index, ent->name, ent->len)) {
812                         strbuf_reset(&buf);
813                         strbuf_add(&buf, ent->name, ent->len);
814                         add_file_item(&files->items, buf.buf);
815                 }
816         }
817
818         strbuf_release(&buf);
819         return 0;
820 }
821
822 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
823                       struct prefix_item_list *files,
824                       struct list_and_choose_options *opts)
825 {
826         struct print_file_item_data *d = opts->list_opts.print_item_data;
827         int res = 0, fd;
828         size_t count, i;
829         struct lock_file index_lock;
830
831         if (get_untracked_files(s->r, files, ps) < 0)
832                 return -1;
833
834         if (!files->items.nr) {
835                 printf(_("No untracked files.\n"));
836                 goto finish_add_untracked;
837         }
838
839         opts->prompt = N_("Add untracked");
840         d->only_names = 1;
841         count = list_and_choose(s, files, opts);
842         d->only_names = 0;
843         if (count <= 0)
844                 goto finish_add_untracked;
845
846         fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
847         if (fd < 0) {
848                 res = -1;
849                 goto finish_add_untracked;
850         }
851
852         for (i = 0; i < files->items.nr; i++) {
853                 const char *name = files->items.items[i].string;
854                 if (files->selected[i] &&
855                     add_file_to_index(s->r->index, name, 0) < 0) {
856                         res = error(_("could not stage '%s'"), name);
857                         break;
858                 }
859         }
860
861         if (!res &&
862             write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
863                 res = error(_("could not write index"));
864
865         if (!res)
866                 printf(Q_("added %d path\n",
867                           "added %d paths\n", count), (int)count);
868
869 finish_add_untracked:
870         putchar('\n');
871         return res;
872 }
873
874 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
875                      struct prefix_item_list *files,
876                      struct list_and_choose_options *opts)
877 {
878         int res = 0;
879         ssize_t count, i, j;
880         size_t unmerged_count = 0, binary_count = 0;
881
882         if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
883                                &unmerged_count, &binary_count) < 0)
884                 return -1;
885
886         if (unmerged_count || binary_count) {
887                 for (i = j = 0; i < files->items.nr; i++) {
888                         struct file_item *item = files->items.items[i].util;
889
890                         if (item->index.binary || item->worktree.binary) {
891                                 free(item);
892                                 free(files->items.items[i].string);
893                         } else if (item->index.unmerged ||
894                                  item->worktree.unmerged) {
895                                 color_fprintf_ln(stderr, s->error_color,
896                                                  _("ignoring unmerged: %s"),
897                                                  files->items.items[i].string);
898                                 free(item);
899                                 free(files->items.items[i].string);
900                         } else
901                                 files->items.items[j++] = files->items.items[i];
902                 }
903                 files->items.nr = j;
904         }
905
906         if (!files->items.nr) {
907                 if (binary_count)
908                         fprintf(stderr, _("Only binary files changed.\n"));
909                 else
910                         fprintf(stderr, _("No changes.\n"));
911                 return 0;
912         }
913
914         opts->prompt = N_("Patch update");
915         count = list_and_choose(s, files, opts);
916         if (count >= 0) {
917                 struct argv_array args = ARGV_ARRAY_INIT;
918                 struct pathspec ps_selected = { 0 };
919
920                 for (i = 0; i < files->items.nr; i++)
921                         if (files->selected[i])
922                                 argv_array_push(&args,
923                                                 files->items.items[i].string);
924                 parse_pathspec(&ps_selected,
925                                PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
926                                PATHSPEC_LITERAL_PATH, "", args.argv);
927                 res = run_add_p(s->r, &ps_selected);
928                 argv_array_clear(&args);
929                 clear_pathspec(&ps_selected);
930         }
931
932         return res;
933 }
934
935 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
936                     struct prefix_item_list *files,
937                     struct list_and_choose_options *opts)
938 {
939         int res = 0;
940         ssize_t count, i;
941
942         struct object_id oid;
943         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
944                                              NULL);
945         if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
946                 return -1;
947
948         if (!files->items.nr) {
949                 putchar('\n');
950                 return 0;
951         }
952
953         opts->prompt = N_("Review diff");
954         opts->flags = IMMEDIATE;
955         count = list_and_choose(s, files, opts);
956         opts->flags = 0;
957         if (count >= 0) {
958                 struct argv_array args = ARGV_ARRAY_INIT;
959
960                 argv_array_pushl(&args, "git", "diff", "-p", "--cached",
961                                  oid_to_hex(!is_initial ? &oid :
962                                             s->r->hash_algo->empty_tree),
963                                  "--", NULL);
964                 for (i = 0; i < files->items.nr; i++)
965                         if (files->selected[i])
966                                 argv_array_push(&args,
967                                                 files->items.items[i].string);
968                 res = run_command_v_opt(args.argv, 0);
969                 argv_array_clear(&args);
970         }
971
972         putchar('\n');
973         return res;
974 }
975
976 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
977                     struct prefix_item_list *unused_files,
978                     struct list_and_choose_options *unused_opts)
979 {
980         color_fprintf_ln(stdout, s->help_color, "status        - %s",
981                          _("show paths with changes"));
982         color_fprintf_ln(stdout, s->help_color, "update        - %s",
983                          _("add working tree state to the staged set of changes"));
984         color_fprintf_ln(stdout, s->help_color, "revert        - %s",
985                          _("revert staged set of changes back to the HEAD version"));
986         color_fprintf_ln(stdout, s->help_color, "patch         - %s",
987                          _("pick hunks and update selectively"));
988         color_fprintf_ln(stdout, s->help_color, "diff          - %s",
989                          _("view diff between HEAD and index"));
990         color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
991                          _("add contents of untracked files to the staged set of changes"));
992
993         return 0;
994 }
995
996 static void choose_prompt_help(struct add_i_state *s)
997 {
998         color_fprintf_ln(stdout, s->help_color, "%s",
999                          _("Prompt help:"));
1000         color_fprintf_ln(stdout, s->help_color, "1          - %s",
1001                          _("select a single item"));
1002         color_fprintf_ln(stdout, s->help_color, "3-5        - %s",
1003                          _("select a range of items"));
1004         color_fprintf_ln(stdout, s->help_color, "2-3,6-9    - %s",
1005                          _("select multiple ranges"));
1006         color_fprintf_ln(stdout, s->help_color, "foo        - %s",
1007                          _("select item based on unique prefix"));
1008         color_fprintf_ln(stdout, s->help_color, "-...       - %s",
1009                          _("unselect specified items"));
1010         color_fprintf_ln(stdout, s->help_color, "*          - %s",
1011                          _("choose all items"));
1012         color_fprintf_ln(stdout, s->help_color, "           - %s",
1013                          _("(empty) finish selecting"));
1014 }
1015
1016 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1017                          struct prefix_item_list *files,
1018                          struct list_and_choose_options *opts);
1019
1020 struct command_item {
1021         size_t prefix_length;
1022         command_t command;
1023 };
1024
1025 struct print_command_item_data {
1026         const char *color, *reset;
1027 };
1028
1029 static void print_command_item(int i, int selected,
1030                                struct string_list_item *item,
1031                                void *print_command_item_data)
1032 {
1033         struct print_command_item_data *d = print_command_item_data;
1034         struct command_item *util = item->util;
1035
1036         if (!util->prefix_length ||
1037             !is_valid_prefix(item->string, util->prefix_length))
1038                 printf(" %2d: %s", i + 1, item->string);
1039         else
1040                 printf(" %2d: %s%.*s%s%s", i + 1,
1041                        d->color, (int)util->prefix_length, item->string,
1042                        d->reset, item->string + util->prefix_length);
1043 }
1044
1045 static void command_prompt_help(struct add_i_state *s)
1046 {
1047         const char *help_color = s->help_color;
1048         color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1049         color_fprintf_ln(stdout, help_color, "1          - %s",
1050                          _("select a numbered item"));
1051         color_fprintf_ln(stdout, help_color, "foo        - %s",
1052                          _("select item based on unique prefix"));
1053         color_fprintf_ln(stdout, help_color, "           - %s",
1054                          _("(empty) select nothing"));
1055 }
1056
1057 int run_add_i(struct repository *r, const struct pathspec *ps)
1058 {
1059         struct add_i_state s = { NULL };
1060         struct print_command_item_data data = { "[", "]" };
1061         struct list_and_choose_options main_loop_opts = {
1062                 { 4, N_("*** Commands ***"), print_command_item, &data },
1063                 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1064         };
1065         struct {
1066                 const char *string;
1067                 command_t command;
1068         } command_list[] = {
1069                 { "status", run_status },
1070                 { "update", run_update },
1071                 { "revert", run_revert },
1072                 { "add untracked", run_add_untracked },
1073                 { "patch", run_patch },
1074                 { "diff", run_diff },
1075                 { "quit", NULL },
1076                 { "help", run_help },
1077         };
1078         struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1079
1080         struct print_file_item_data print_file_item_data = {
1081                 "%12s %12s %s", NULL, NULL,
1082                 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1083         };
1084         struct list_and_choose_options opts = {
1085                 { 0, NULL, print_file_item, &print_file_item_data },
1086                 NULL, 0, choose_prompt_help
1087         };
1088         struct strbuf header = STRBUF_INIT;
1089         struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1090         ssize_t i;
1091         int res = 0;
1092
1093         for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1094                 struct command_item *util = xcalloc(sizeof(*util), 1);
1095                 util->command = command_list[i].command;
1096                 string_list_append(&commands.items, command_list[i].string)
1097                         ->util = util;
1098         }
1099
1100         init_add_i_state(&s, r);
1101
1102         /*
1103          * When color was asked for, use the prompt color for
1104          * highlighting, otherwise use square brackets.
1105          */
1106         if (s.use_color) {
1107                 data.color = s.prompt_color;
1108                 data.reset = s.reset_color;
1109         }
1110         print_file_item_data.color = data.color;
1111         print_file_item_data.reset = data.reset;
1112
1113         strbuf_addstr(&header, "      ");
1114         strbuf_addf(&header, print_file_item_data.modified_fmt,
1115                     _("staged"), _("unstaged"), _("path"));
1116         opts.list_opts.header = header.buf;
1117
1118         if (discard_index(r->index) < 0 ||
1119             repo_read_index(r) < 0 ||
1120             repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1121                                          NULL, NULL, NULL) < 0)
1122                 warning(_("could not refresh index"));
1123
1124         res = run_status(&s, ps, &files, &opts);
1125
1126         for (;;) {
1127                 struct command_item *util;
1128
1129                 i = list_and_choose(&s, &commands, &main_loop_opts);
1130                 if (i < 0 || i >= commands.items.nr)
1131                         util = NULL;
1132                 else
1133                         util = commands.items.items[i].util;
1134
1135                 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1136                         printf(_("Bye.\n"));
1137                         res = 0;
1138                         break;
1139                 }
1140
1141                 if (util)
1142                         res = util->command(&s, ps, &files, &opts);
1143         }
1144
1145         prefix_item_list_clear(&files);
1146         strbuf_release(&print_file_item_data.buf);
1147         strbuf_release(&print_file_item_data.name);
1148         strbuf_release(&print_file_item_data.index);
1149         strbuf_release(&print_file_item_data.worktree);
1150         strbuf_release(&header);
1151         prefix_item_list_clear(&commands);
1152
1153         return res;
1154 }