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