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