built-in add -i: support `?` (prompt help)
[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
10 struct add_i_state {
11         struct repository *r;
12         int use_color;
13         char header_color[COLOR_MAXLEN];
14         char help_color[COLOR_MAXLEN];
15 };
16
17 static void init_color(struct repository *r, struct add_i_state *s,
18                        const char *slot_name, char *dst,
19                        const char *default_color)
20 {
21         char *key = xstrfmt("color.interactive.%s", slot_name);
22         const char *value;
23
24         if (!s->use_color)
25                 dst[0] = '\0';
26         else if (repo_config_get_value(r, key, &value) ||
27                  color_parse(value, dst))
28                 strlcpy(dst, default_color, COLOR_MAXLEN);
29
30         free(key);
31 }
32
33 static void init_add_i_state(struct add_i_state *s, struct repository *r)
34 {
35         const char *value;
36
37         s->r = r;
38
39         if (repo_config_get_value(r, "color.interactive", &value))
40                 s->use_color = -1;
41         else
42                 s->use_color =
43                         git_config_colorbool("color.interactive", value);
44         s->use_color = want_color(s->use_color);
45
46         init_color(r, s, "header", s->header_color, GIT_COLOR_BOLD);
47         init_color(r, s, "help", s->help_color, GIT_COLOR_BOLD_RED);
48 }
49
50 /*
51  * A "prefix item list" is a list of items that are identified by a string, and
52  * a unique prefix (if any) is determined for each item.
53  *
54  * It is implemented in the form of a pair of `string_list`s, the first one
55  * duplicating the strings, with the `util` field pointing at a structure whose
56  * first field must be `size_t prefix_length`.
57  *
58  * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
59  * will be set to zero if no valid, unique prefix could be found.
60  *
61  * The second `string_list` is called `sorted` and does _not_ duplicate the
62  * strings but simply reuses the first one's, with the `util` field pointing at
63  * the `string_item_list` of the first `string_list`. It  will be populated and
64  * sorted by `find_unique_prefixes()`.
65  */
66 struct prefix_item_list {
67         struct string_list items;
68         struct string_list sorted;
69         size_t min_length, max_length;
70 };
71 #define PREFIX_ITEM_LIST_INIT \
72         { STRING_LIST_INIT_DUP, STRING_LIST_INIT_NODUP, 1, 4 }
73
74 static void prefix_item_list_clear(struct prefix_item_list *list)
75 {
76         string_list_clear(&list->items, 1);
77         string_list_clear(&list->sorted, 0);
78 }
79
80 static void extend_prefix_length(struct string_list_item *p,
81                                  const char *other_string, size_t max_length)
82 {
83         size_t *len = p->util;
84
85         if (!*len || memcmp(p->string, other_string, *len))
86                 return;
87
88         for (;;) {
89                 char c = p->string[*len];
90
91                 /*
92                  * Is `p` a strict prefix of `other`? Or have we exhausted the
93                  * maximal length of the prefix? Or is the current character a
94                  * multi-byte UTF-8 one? If so, there is no valid, unique
95                  * prefix.
96                  */
97                 if (!c || ++*len > max_length || !isascii(c)) {
98                         *len = 0;
99                         break;
100                 }
101
102                 if (c != other_string[*len - 1])
103                         break;
104         }
105 }
106
107 static void find_unique_prefixes(struct prefix_item_list *list)
108 {
109         size_t i;
110
111         if (list->sorted.nr == list->items.nr)
112                 return;
113
114         string_list_clear(&list->sorted, 0);
115         /* Avoid reallocating incrementally */
116         list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
117                                              list->items.nr));
118         list->sorted.nr = list->sorted.alloc = list->items.nr;
119
120         for (i = 0; i < list->items.nr; i++) {
121                 list->sorted.items[i].string = list->items.items[i].string;
122                 list->sorted.items[i].util = list->items.items + i;
123         }
124
125         string_list_sort(&list->sorted);
126
127         for (i = 0; i < list->sorted.nr; i++) {
128                 struct string_list_item *sorted_item = list->sorted.items + i;
129                 struct string_list_item *item = sorted_item->util;
130                 size_t *len = item->util;
131
132                 *len = 0;
133                 while (*len < list->min_length) {
134                         char c = item->string[(*len)++];
135
136                         if (!c || !isascii(c)) {
137                                 *len = 0;
138                                 break;
139                         }
140                 }
141
142                 if (i > 0)
143                         extend_prefix_length(item, sorted_item[-1].string,
144                                              list->max_length);
145                 if (i + 1 < list->sorted.nr)
146                         extend_prefix_length(item, sorted_item[1].string,
147                                              list->max_length);
148         }
149 }
150
151 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
152 {
153         int index = string_list_find_insert_index(&list->sorted, string, 1);
154         struct string_list_item *item;
155
156         if (list->items.nr != list->sorted.nr)
157                 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
158                     " vs %"PRIuMAX")",
159                     (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
160
161         if (index < 0)
162                 item = list->sorted.items[-1 - index].util;
163         else if (index > 0 &&
164                  starts_with(list->sorted.items[index - 1].string, string))
165                 return -1;
166         else if (index + 1 < list->sorted.nr &&
167                  starts_with(list->sorted.items[index + 1].string, string))
168                 return -1;
169         else if (index < list->sorted.nr)
170                 item = list->sorted.items[index].util;
171         else
172                 return -1;
173         return item - list->items.items;
174 }
175
176 struct list_options {
177         int columns;
178         const char *header;
179         void (*print_item)(int i, struct string_list_item *item, void *print_item_data);
180         void *print_item_data;
181 };
182
183 static void list(struct add_i_state *s, struct string_list *list,
184                  struct list_options *opts)
185 {
186         int i, last_lf = 0;
187
188         if (!list->nr)
189                 return;
190
191         if (opts->header)
192                 color_fprintf_ln(stdout, s->header_color,
193                                  "%s", opts->header);
194
195         for (i = 0; i < list->nr; i++) {
196                 opts->print_item(i, list->items + i, opts->print_item_data);
197
198                 if ((opts->columns) && ((i + 1) % (opts->columns))) {
199                         putchar('\t');
200                         last_lf = 0;
201                 }
202                 else {
203                         putchar('\n');
204                         last_lf = 1;
205                 }
206         }
207
208         if (!last_lf)
209                 putchar('\n');
210 }
211 struct list_and_choose_options {
212         struct list_options list_opts;
213
214         const char *prompt;
215         void (*print_help)(struct add_i_state *s);
216 };
217
218 #define LIST_AND_CHOOSE_ERROR (-1)
219 #define LIST_AND_CHOOSE_QUIT  (-2)
220
221 /*
222  * Returns the selected index.
223  *
224  * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
225  * `LIST_AND_CHOOSE_QUIT` is returned.
226  */
227 static ssize_t list_and_choose(struct add_i_state *s,
228                                struct prefix_item_list *items,
229                                struct list_and_choose_options *opts)
230 {
231         struct strbuf input = STRBUF_INIT;
232         ssize_t res = LIST_AND_CHOOSE_ERROR;
233
234         find_unique_prefixes(items);
235
236         for (;;) {
237                 char *p;
238
239                 strbuf_reset(&input);
240
241                 list(s, &items->items, &opts->list_opts);
242
243                 printf("%s%s", opts->prompt, "> ");
244                 fflush(stdout);
245
246                 if (strbuf_getline(&input, stdin) == EOF) {
247                         putchar('\n');
248                         res = LIST_AND_CHOOSE_QUIT;
249                         break;
250                 }
251                 strbuf_trim(&input);
252
253                 if (!input.len)
254                         break;
255
256                 if (!strcmp(input.buf, "?")) {
257                         opts->print_help(s);
258                         continue;
259                 }
260
261                 p = input.buf;
262                 for (;;) {
263                         size_t sep = strcspn(p, " \t\r\n,");
264                         ssize_t index = -1;
265
266                         if (!sep) {
267                                 if (!*p)
268                                         break;
269                                 p++;
270                                 continue;
271                         }
272
273                         if (isdigit(*p)) {
274                                 char *endp;
275                                 index = strtoul(p, &endp, 10) - 1;
276                                 if (endp != p + sep)
277                                         index = -1;
278                         }
279
280                         if (p[sep])
281                                 p[sep++] = '\0';
282                         if (index < 0)
283                                 index = find_unique(p, items);
284
285                         if (index < 0 || index >= items->items.nr)
286                                 printf(_("Huh (%s)?\n"), p);
287                         else {
288                                 res = index;
289                                 break;
290                         }
291
292                         p += sep;
293                 }
294
295                 if (res != LIST_AND_CHOOSE_ERROR)
296                         break;
297         }
298
299         strbuf_release(&input);
300         return res;
301 }
302
303 struct adddel {
304         uintmax_t add, del;
305         unsigned seen:1, binary:1;
306 };
307
308 struct file_item {
309         struct adddel index, worktree;
310 };
311
312 static void add_file_item(struct string_list *files, const char *name)
313 {
314         struct file_item *item = xcalloc(sizeof(*item), 1);
315
316         string_list_append(files, name)->util = item;
317 }
318
319 struct pathname_entry {
320         struct hashmap_entry ent;
321         const char *name;
322         struct file_item *item;
323 };
324
325 static int pathname_entry_cmp(const void *unused_cmp_data,
326                               const struct hashmap_entry *he1,
327                               const struct hashmap_entry *he2,
328                               const void *name)
329 {
330         const struct pathname_entry *e1 =
331                 container_of(he1, const struct pathname_entry, ent);
332         const struct pathname_entry *e2 =
333                 container_of(he2, const struct pathname_entry, ent);
334
335         return strcmp(e1->name, name ? (const char *)name : e2->name);
336 }
337
338 struct collection_status {
339         enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } phase;
340
341         const char *reference;
342
343         struct string_list *files;
344         struct hashmap file_map;
345 };
346
347 static void collect_changes_cb(struct diff_queue_struct *q,
348                                struct diff_options *options,
349                                void *data)
350 {
351         struct collection_status *s = data;
352         struct diffstat_t stat = { 0 };
353         int i;
354
355         if (!q->nr)
356                 return;
357
358         compute_diffstat(options, &stat, q);
359
360         for (i = 0; i < stat.nr; i++) {
361                 const char *name = stat.files[i]->name;
362                 int hash = strhash(name);
363                 struct pathname_entry *entry;
364                 struct file_item *file_item;
365                 struct adddel *adddel;
366
367                 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
368                                                     struct pathname_entry, ent);
369                 if (!entry) {
370                         add_file_item(s->files, name);
371
372                         entry = xcalloc(sizeof(*entry), 1);
373                         hashmap_entry_init(&entry->ent, hash);
374                         entry->name = s->files->items[s->files->nr - 1].string;
375                         entry->item = s->files->items[s->files->nr - 1].util;
376                         hashmap_add(&s->file_map, &entry->ent);
377                 }
378
379                 file_item = entry->item;
380                 adddel = s->phase == FROM_INDEX ?
381                         &file_item->index : &file_item->worktree;
382                 adddel->seen = 1;
383                 adddel->add = stat.files[i]->added;
384                 adddel->del = stat.files[i]->deleted;
385                 if (stat.files[i]->is_binary)
386                         adddel->binary = 1;
387         }
388         free_diffstat_info(&stat);
389 }
390
391 static int get_modified_files(struct repository *r, struct string_list *files,
392                               const struct pathspec *ps)
393 {
394         struct object_id head_oid;
395         int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
396                                              &head_oid, NULL);
397         struct collection_status s = { FROM_WORKTREE };
398
399         if (discard_index(r->index) < 0 ||
400             repo_read_index_preload(r, ps, 0) < 0)
401                 return error(_("could not read index"));
402
403         string_list_clear(files, 1);
404         s.files = files;
405         hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
406
407         for (s.phase = FROM_WORKTREE; s.phase <= FROM_INDEX; s.phase++) {
408                 struct rev_info rev;
409                 struct setup_revision_opt opt = { 0 };
410
411                 opt.def = is_initial ?
412                         empty_tree_oid_hex() : oid_to_hex(&head_oid);
413
414                 init_revisions(&rev, NULL);
415                 setup_revisions(0, NULL, &rev, &opt);
416
417                 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
418                 rev.diffopt.format_callback = collect_changes_cb;
419                 rev.diffopt.format_callback_data = &s;
420
421                 if (ps)
422                         copy_pathspec(&rev.prune_data, ps);
423
424                 if (s.phase == FROM_INDEX)
425                         run_diff_index(&rev, 1);
426                 else {
427                         rev.diffopt.flags.ignore_dirty_submodules = 1;
428                         run_diff_files(&rev, 0);
429                 }
430         }
431         hashmap_free_entries(&s.file_map, struct pathname_entry, ent);
432
433         /* While the diffs are ordered already, we ran *two* diffs... */
434         string_list_sort(files);
435
436         return 0;
437 }
438
439 static void render_adddel(struct strbuf *buf,
440                                 struct adddel *ad, const char *no_changes)
441 {
442         if (ad->binary)
443                 strbuf_addstr(buf, _("binary"));
444         else if (ad->seen)
445                 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
446                             (uintmax_t)ad->add, (uintmax_t)ad->del);
447         else
448                 strbuf_addstr(buf, no_changes);
449 }
450
451 /* filters out prefixes which have special meaning to list_and_choose() */
452 static int is_valid_prefix(const char *prefix, size_t prefix_len)
453 {
454         return prefix_len && prefix &&
455                 /*
456                  * We expect `prefix` to be NUL terminated, therefore this
457                  * `strcspn()` call is okay, even if it might do much more
458                  * work than strictly necessary.
459                  */
460                 strcspn(prefix, " \t\r\n,") >= prefix_len &&    /* separators */
461                 *prefix != '-' &&                               /* deselection */
462                 !isdigit(*prefix) &&                            /* selection */
463                 (prefix_len != 1 ||
464                  (*prefix != '*' &&                             /* "all" wildcard */
465                   *prefix != '?'));                             /* prompt help */
466 }
467
468 struct print_file_item_data {
469         const char *modified_fmt;
470         struct strbuf buf, index, worktree;
471 };
472
473 static void print_file_item(int i, struct string_list_item *item,
474                             void *print_file_item_data)
475 {
476         struct file_item *c = item->util;
477         struct print_file_item_data *d = print_file_item_data;
478
479         strbuf_reset(&d->index);
480         strbuf_reset(&d->worktree);
481         strbuf_reset(&d->buf);
482
483         render_adddel(&d->worktree, &c->worktree, _("nothing"));
484         render_adddel(&d->index, &c->index, _("unchanged"));
485         strbuf_addf(&d->buf, d->modified_fmt,
486                     d->index.buf, d->worktree.buf, item->string);
487
488         printf(" %2d: %s", i + 1, d->buf.buf);
489 }
490
491 static int run_status(struct add_i_state *s, const struct pathspec *ps,
492                       struct string_list *files, struct list_options *opts)
493 {
494         if (get_modified_files(s->r, files, ps) < 0)
495                 return -1;
496
497         list(s, files, opts);
498         putchar('\n');
499
500         return 0;
501 }
502
503 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
504                          struct string_list *files,
505                          struct list_options *opts);
506
507 struct command_item {
508         size_t prefix_length;
509         command_t command;
510 };
511
512 static void print_command_item(int i, struct string_list_item *item,
513                                void *print_command_item_data)
514 {
515         struct command_item *util = item->util;
516
517         if (!util->prefix_length ||
518             !is_valid_prefix(item->string, util->prefix_length))
519                 printf(" %2d: %s", i + 1, item->string);
520         else
521                 printf(" %2d: [%.*s]%s", i + 1,
522                        (int)util->prefix_length, item->string,
523                        item->string + util->prefix_length);
524 }
525
526 static void command_prompt_help(struct add_i_state *s)
527 {
528         const char *help_color = s->help_color;
529         color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
530         color_fprintf_ln(stdout, help_color, "1          - %s",
531                          _("select a numbered item"));
532         color_fprintf_ln(stdout, help_color, "foo        - %s",
533                          _("select item based on unique prefix"));
534         color_fprintf_ln(stdout, help_color, "           - %s",
535                          _("(empty) select nothing"));
536 }
537
538 int run_add_i(struct repository *r, const struct pathspec *ps)
539 {
540         struct add_i_state s = { NULL };
541         struct list_and_choose_options main_loop_opts = {
542                 { 4, N_("*** Commands ***"), print_command_item, NULL },
543                 N_("What now"), command_prompt_help
544         };
545         struct {
546                 const char *string;
547                 command_t command;
548         } command_list[] = {
549                 { "status", run_status },
550         };
551         struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
552
553         struct print_file_item_data print_file_item_data = {
554                 "%12s %12s %s", STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
555         };
556         struct list_options opts = {
557                 0, NULL, print_file_item, &print_file_item_data
558         };
559         struct strbuf header = STRBUF_INIT;
560         struct string_list files = STRING_LIST_INIT_DUP;
561         ssize_t i;
562         int res = 0;
563
564         for (i = 0; i < ARRAY_SIZE(command_list); i++) {
565                 struct command_item *util = xcalloc(sizeof(*util), 1);
566                 util->command = command_list[i].command;
567                 string_list_append(&commands.items, command_list[i].string)
568                         ->util = util;
569         }
570
571         init_add_i_state(&s, r);
572
573         strbuf_addstr(&header, "      ");
574         strbuf_addf(&header, print_file_item_data.modified_fmt,
575                     _("staged"), _("unstaged"), _("path"));
576         opts.header = header.buf;
577
578         if (discard_index(r->index) < 0 ||
579             repo_read_index(r) < 0 ||
580             repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
581                                          NULL, NULL, NULL) < 0)
582                 warning(_("could not refresh index"));
583
584         res = run_status(&s, ps, &files, &opts);
585
586         for (;;) {
587                 i = list_and_choose(&s, &commands, &main_loop_opts);
588                 if (i == LIST_AND_CHOOSE_QUIT) {
589                         printf(_("Bye.\n"));
590                         res = 0;
591                         break;
592                 }
593                 if (i != LIST_AND_CHOOSE_ERROR) {
594                         struct command_item *util =
595                                 commands.items.items[i].util;
596                         res = util->command(&s, ps, &files, &opts);
597                 }
598         }
599
600         string_list_clear(&files, 1);
601         strbuf_release(&print_file_item_data.buf);
602         strbuf_release(&print_file_item_data.index);
603         strbuf_release(&print_file_item_data.worktree);
604         strbuf_release(&header);
605         prefix_item_list_clear(&commands);
606
607         return res;
608 }