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