2 #include "add-interactive.h"
8 #include "string-list.h"
14 char header_color[COLOR_MAXLEN];
15 char help_color[COLOR_MAXLEN];
16 char prompt_color[COLOR_MAXLEN];
17 char error_color[COLOR_MAXLEN];
18 char reset_color[COLOR_MAXLEN];
21 static void init_color(struct repository *r, struct add_i_state *s,
22 const char *slot_name, char *dst,
23 const char *default_color)
25 char *key = xstrfmt("color.interactive.%s", slot_name);
30 else if (repo_config_get_value(r, key, &value) ||
31 color_parse(value, dst))
32 strlcpy(dst, default_color, COLOR_MAXLEN);
37 static void init_add_i_state(struct add_i_state *s, struct repository *r)
43 if (repo_config_get_value(r, "color.interactive", &value))
47 git_config_colorbool("color.interactive", value);
48 s->use_color = want_color(s->use_color);
50 init_color(r, s, "header", s->header_color, GIT_COLOR_BOLD);
51 init_color(r, s, "help", s->help_color, GIT_COLOR_BOLD_RED);
52 init_color(r, s, "prompt", s->prompt_color, GIT_COLOR_BOLD_BLUE);
53 init_color(r, s, "error", s->error_color, GIT_COLOR_BOLD_RED);
54 init_color(r, s, "reset", s->reset_color, GIT_COLOR_RESET);
58 * A "prefix item list" is a list of items that are identified by a string, and
59 * a unique prefix (if any) is determined for each item.
61 * It is implemented in the form of a pair of `string_list`s, the first one
62 * duplicating the strings, with the `util` field pointing at a structure whose
63 * first field must be `size_t prefix_length`.
65 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
66 * will be set to zero if no valid, unique prefix could be found.
68 * The second `string_list` is called `sorted` and does _not_ duplicate the
69 * strings but simply reuses the first one's, with the `util` field pointing at
70 * the `string_item_list` of the first `string_list`. It will be populated and
71 * sorted by `find_unique_prefixes()`.
73 struct prefix_item_list {
74 struct string_list items;
75 struct string_list sorted;
76 int *selected; /* for multi-selections */
77 size_t min_length, max_length;
79 #define PREFIX_ITEM_LIST_INIT \
80 { STRING_LIST_INIT_DUP, STRING_LIST_INIT_NODUP, NULL, 1, 4 }
82 static void prefix_item_list_clear(struct prefix_item_list *list)
84 string_list_clear(&list->items, 1);
85 string_list_clear(&list->sorted, 0);
86 FREE_AND_NULL(list->selected);
89 static void extend_prefix_length(struct string_list_item *p,
90 const char *other_string, size_t max_length)
92 size_t *len = p->util;
94 if (!*len || memcmp(p->string, other_string, *len))
98 char c = p->string[*len];
101 * Is `p` a strict prefix of `other`? Or have we exhausted the
102 * maximal length of the prefix? Or is the current character a
103 * multi-byte UTF-8 one? If so, there is no valid, unique
106 if (!c || ++*len > max_length || !isascii(c)) {
111 if (c != other_string[*len - 1])
116 static void find_unique_prefixes(struct prefix_item_list *list)
120 if (list->sorted.nr == list->items.nr)
123 string_list_clear(&list->sorted, 0);
124 /* Avoid reallocating incrementally */
125 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
127 list->sorted.nr = list->sorted.alloc = list->items.nr;
129 for (i = 0; i < list->items.nr; i++) {
130 list->sorted.items[i].string = list->items.items[i].string;
131 list->sorted.items[i].util = list->items.items + i;
134 string_list_sort(&list->sorted);
136 for (i = 0; i < list->sorted.nr; i++) {
137 struct string_list_item *sorted_item = list->sorted.items + i;
138 struct string_list_item *item = sorted_item->util;
139 size_t *len = item->util;
142 while (*len < list->min_length) {
143 char c = item->string[(*len)++];
145 if (!c || !isascii(c)) {
152 extend_prefix_length(item, sorted_item[-1].string,
154 if (i + 1 < list->sorted.nr)
155 extend_prefix_length(item, sorted_item[1].string,
160 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
162 int index = string_list_find_insert_index(&list->sorted, string, 1);
163 struct string_list_item *item;
165 if (list->items.nr != list->sorted.nr)
166 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
168 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
171 item = list->sorted.items[-1 - index].util;
172 else if (index > 0 &&
173 starts_with(list->sorted.items[index - 1].string, string))
175 else if (index + 1 < list->sorted.nr &&
176 starts_with(list->sorted.items[index + 1].string, string))
178 else if (index < list->sorted.nr)
179 item = list->sorted.items[index].util;
182 return item - list->items.items;
185 struct list_options {
188 void (*print_item)(int i, int selected, struct string_list_item *item,
189 void *print_item_data);
190 void *print_item_data;
193 static void list(struct add_i_state *s, struct string_list *list, int *selected,
194 struct list_options *opts)
202 color_fprintf_ln(stdout, s->header_color,
205 for (i = 0; i < list->nr; i++) {
206 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
207 opts->print_item_data);
209 if ((opts->columns) && ((i + 1) % (opts->columns))) {
222 struct list_and_choose_options {
223 struct list_options list_opts;
230 void (*print_help)(struct add_i_state *s);
233 #define LIST_AND_CHOOSE_ERROR (-1)
234 #define LIST_AND_CHOOSE_QUIT (-2)
237 * Returns the selected index in singleton mode, the number of selected items
240 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
241 * `LIST_AND_CHOOSE_QUIT` is returned.
243 static ssize_t list_and_choose(struct add_i_state *s,
244 struct prefix_item_list *items,
245 struct list_and_choose_options *opts)
247 int singleton = opts->flags & SINGLETON;
248 int immediate = opts->flags & IMMEDIATE;
250 struct strbuf input = STRBUF_INIT;
251 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
254 free(items->selected);
255 CALLOC_ARRAY(items->selected, items->items.nr);
258 if (singleton && !immediate)
259 BUG("singleton requires immediate");
261 find_unique_prefixes(items);
266 strbuf_reset(&input);
268 list(s, &items->items, items->selected, &opts->list_opts);
270 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
271 fputs(singleton ? "> " : ">> ", stdout);
274 if (strbuf_getline(&input, stdin) == EOF) {
277 res = LIST_AND_CHOOSE_QUIT;
285 if (!strcmp(input.buf, "?")) {
292 size_t sep = strcspn(p, " \t\r\n,");
294 /* `from` is inclusive, `to` is exclusive */
295 ssize_t from = -1, to = -1;
304 /* Input that begins with '-'; de-select */
311 if (sep == 1 && *p == '*') {
313 to = items->items.nr;
314 } else if (isdigit(*p)) {
317 * A range can be specified like 5-7 or 5-.
319 * Note: `from` is 0-based while the user input
320 * is 1-based, hence we have to decrement by
321 * one. We do not have to decrement `to` even
322 * if it is 0-based because it is an exclusive
325 from = strtoul(p, &endp, 10) - 1;
328 else if (*endp == '-') {
329 to = strtoul(++endp, &endp, 10);
330 /* extra characters after the range? */
339 from = find_unique(p, items);
344 if (from < 0 || from >= items->items.nr ||
345 (singleton && from + 1 != to)) {
346 color_fprintf_ln(stdout, s->error_color,
349 } else if (singleton) {
354 if (to > items->items.nr)
355 to = items->items.nr;
357 for (; from < to; from++)
358 if (items->selected[from] != choose) {
359 items->selected[from] = choose;
360 res += choose ? +1 : -1;
366 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
367 !strcmp(input.buf, "*"))
371 strbuf_release(&input);
377 unsigned seen:1, binary:1;
381 size_t prefix_length;
382 struct adddel index, worktree;
385 static void add_file_item(struct string_list *files, const char *name)
387 struct file_item *item = xcalloc(sizeof(*item), 1);
389 string_list_append(files, name)->util = item;
392 struct pathname_entry {
393 struct hashmap_entry ent;
395 struct file_item *item;
398 static int pathname_entry_cmp(const void *unused_cmp_data,
399 const struct hashmap_entry *he1,
400 const struct hashmap_entry *he2,
403 const struct pathname_entry *e1 =
404 container_of(he1, const struct pathname_entry, ent);
405 const struct pathname_entry *e2 =
406 container_of(he2, const struct pathname_entry, ent);
408 return strcmp(e1->name, name ? (const char *)name : e2->name);
411 struct collection_status {
412 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
414 const char *reference;
416 unsigned skip_unseen:1;
417 struct string_list *files;
418 struct hashmap file_map;
421 static void collect_changes_cb(struct diff_queue_struct *q,
422 struct diff_options *options,
425 struct collection_status *s = data;
426 struct diffstat_t stat = { 0 };
432 compute_diffstat(options, &stat, q);
434 for (i = 0; i < stat.nr; i++) {
435 const char *name = stat.files[i]->name;
436 int hash = strhash(name);
437 struct pathname_entry *entry;
438 struct file_item *file_item;
439 struct adddel *adddel;
441 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
442 struct pathname_entry, ent);
447 add_file_item(s->files, name);
449 entry = xcalloc(sizeof(*entry), 1);
450 hashmap_entry_init(&entry->ent, hash);
451 entry->name = s->files->items[s->files->nr - 1].string;
452 entry->item = s->files->items[s->files->nr - 1].util;
453 hashmap_add(&s->file_map, &entry->ent);
456 file_item = entry->item;
457 adddel = s->mode == FROM_INDEX ?
458 &file_item->index : &file_item->worktree;
460 adddel->add = stat.files[i]->added;
461 adddel->del = stat.files[i]->deleted;
462 if (stat.files[i]->is_binary)
465 free_diffstat_info(&stat);
468 enum modified_files_filter {
474 static int get_modified_files(struct repository *r,
475 enum modified_files_filter filter,
476 struct prefix_item_list *files,
477 const struct pathspec *ps)
479 struct object_id head_oid;
480 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
482 struct collection_status s = { 0 };
485 if (discard_index(r->index) < 0 ||
486 repo_read_index_preload(r, ps, 0) < 0)
487 return error(_("could not read index"));
489 prefix_item_list_clear(files);
490 s.files = &files->items;
491 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
493 for (i = 0; i < 2; i++) {
495 struct setup_revision_opt opt = { 0 };
497 if (filter == INDEX_ONLY)
498 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
500 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
501 s.skip_unseen = filter && i;
503 opt.def = is_initial ?
504 empty_tree_oid_hex() : oid_to_hex(&head_oid);
506 init_revisions(&rev, NULL);
507 setup_revisions(0, NULL, &rev, &opt);
509 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
510 rev.diffopt.format_callback = collect_changes_cb;
511 rev.diffopt.format_callback_data = &s;
514 copy_pathspec(&rev.prune_data, ps);
516 if (s.mode == FROM_INDEX)
517 run_diff_index(&rev, 1);
519 rev.diffopt.flags.ignore_dirty_submodules = 1;
520 run_diff_files(&rev, 0);
524 clear_pathspec(&rev.prune_data);
526 hashmap_free_entries(&s.file_map, struct pathname_entry, ent);
528 /* While the diffs are ordered already, we ran *two* diffs... */
529 string_list_sort(&files->items);
534 static void render_adddel(struct strbuf *buf,
535 struct adddel *ad, const char *no_changes)
538 strbuf_addstr(buf, _("binary"));
540 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
541 (uintmax_t)ad->add, (uintmax_t)ad->del);
543 strbuf_addstr(buf, no_changes);
546 /* filters out prefixes which have special meaning to list_and_choose() */
547 static int is_valid_prefix(const char *prefix, size_t prefix_len)
549 return prefix_len && prefix &&
551 * We expect `prefix` to be NUL terminated, therefore this
552 * `strcspn()` call is okay, even if it might do much more
553 * work than strictly necessary.
555 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
556 *prefix != '-' && /* deselection */
557 !isdigit(*prefix) && /* selection */
559 (*prefix != '*' && /* "all" wildcard */
560 *prefix != '?')); /* prompt help */
563 struct print_file_item_data {
564 const char *modified_fmt, *color, *reset;
565 struct strbuf buf, name, index, worktree;
568 static void print_file_item(int i, int selected, struct string_list_item *item,
569 void *print_file_item_data)
571 struct file_item *c = item->util;
572 struct print_file_item_data *d = print_file_item_data;
573 const char *highlighted = NULL;
575 strbuf_reset(&d->index);
576 strbuf_reset(&d->worktree);
577 strbuf_reset(&d->buf);
579 /* Format the item with the prefix highlighted. */
580 if (c->prefix_length > 0 &&
581 is_valid_prefix(item->string, c->prefix_length)) {
582 strbuf_reset(&d->name);
583 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
584 (int)c->prefix_length, item->string, d->reset,
585 item->string + c->prefix_length);
586 highlighted = d->name.buf;
589 render_adddel(&d->worktree, &c->worktree, _("nothing"));
590 render_adddel(&d->index, &c->index, _("unchanged"));
592 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
593 highlighted ? highlighted : item->string);
595 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
598 static int run_status(struct add_i_state *s, const struct pathspec *ps,
599 struct prefix_item_list *files,
600 struct list_and_choose_options *opts)
602 if (get_modified_files(s->r, NO_FILTER, files, ps) < 0)
605 list(s, &files->items, NULL, &opts->list_opts);
611 static int run_update(struct add_i_state *s, const struct pathspec *ps,
612 struct prefix_item_list *files,
613 struct list_and_choose_options *opts)
617 struct lock_file index_lock;
619 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps) < 0)
622 if (!files->items.nr) {
627 opts->prompt = N_("Update");
628 count = list_and_choose(s, files, opts);
634 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
640 for (i = 0; i < files->items.nr; i++) {
641 const char *name = files->items.items[i].string;
642 if (files->selected[i] &&
643 add_file_to_index(s->r->index, name, 0) < 0) {
644 res = error(_("could not stage '%s'"), name);
649 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
650 res = error(_("could not write index"));
653 printf(Q_("updated %d path\n",
654 "updated %d paths\n", count), (int)count);
660 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
661 struct prefix_item_list *unused_files,
662 struct list_and_choose_options *unused_opts)
664 color_fprintf_ln(stdout, s->help_color, "status - %s",
665 _("show paths with changes"));
666 color_fprintf_ln(stdout, s->help_color, "update - %s",
667 _("add working tree state to the staged set of changes"));
668 color_fprintf_ln(stdout, s->help_color, "revert - %s",
669 _("revert staged set of changes back to the HEAD version"));
670 color_fprintf_ln(stdout, s->help_color, "patch - %s",
671 _("pick hunks and update selectively"));
672 color_fprintf_ln(stdout, s->help_color, "diff - %s",
673 _("view diff between HEAD and index"));
674 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
675 _("add contents of untracked files to the staged set of changes"));
680 static void choose_prompt_help(struct add_i_state *s)
682 color_fprintf_ln(stdout, s->help_color, "%s",
684 color_fprintf_ln(stdout, s->help_color, "1 - %s",
685 _("select a single item"));
686 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
687 _("select a range of items"));
688 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
689 _("select multiple ranges"));
690 color_fprintf_ln(stdout, s->help_color, "foo - %s",
691 _("select item based on unique prefix"));
692 color_fprintf_ln(stdout, s->help_color, "-... - %s",
693 _("unselect specified items"));
694 color_fprintf_ln(stdout, s->help_color, "* - %s",
695 _("choose all items"));
696 color_fprintf_ln(stdout, s->help_color, " - %s",
697 _("(empty) finish selecting"));
700 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
701 struct prefix_item_list *files,
702 struct list_and_choose_options *opts);
704 struct command_item {
705 size_t prefix_length;
709 struct print_command_item_data {
710 const char *color, *reset;
713 static void print_command_item(int i, int selected,
714 struct string_list_item *item,
715 void *print_command_item_data)
717 struct print_command_item_data *d = print_command_item_data;
718 struct command_item *util = item->util;
720 if (!util->prefix_length ||
721 !is_valid_prefix(item->string, util->prefix_length))
722 printf(" %2d: %s", i + 1, item->string);
724 printf(" %2d: %s%.*s%s%s", i + 1,
725 d->color, (int)util->prefix_length, item->string,
726 d->reset, item->string + util->prefix_length);
729 static void command_prompt_help(struct add_i_state *s)
731 const char *help_color = s->help_color;
732 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
733 color_fprintf_ln(stdout, help_color, "1 - %s",
734 _("select a numbered item"));
735 color_fprintf_ln(stdout, help_color, "foo - %s",
736 _("select item based on unique prefix"));
737 color_fprintf_ln(stdout, help_color, " - %s",
738 _("(empty) select nothing"));
741 int run_add_i(struct repository *r, const struct pathspec *ps)
743 struct add_i_state s = { NULL };
744 struct print_command_item_data data = { "[", "]" };
745 struct list_and_choose_options main_loop_opts = {
746 { 4, N_("*** Commands ***"), print_command_item, &data },
747 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
753 { "status", run_status },
754 { "update", run_update },
755 { "help", run_help },
757 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
759 struct print_file_item_data print_file_item_data = {
760 "%12s %12s %s", NULL, NULL,
761 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
763 struct list_and_choose_options opts = {
764 { 0, NULL, print_file_item, &print_file_item_data },
765 NULL, 0, choose_prompt_help
767 struct strbuf header = STRBUF_INIT;
768 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
772 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
773 struct command_item *util = xcalloc(sizeof(*util), 1);
774 util->command = command_list[i].command;
775 string_list_append(&commands.items, command_list[i].string)
779 init_add_i_state(&s, r);
782 * When color was asked for, use the prompt color for
783 * highlighting, otherwise use square brackets.
786 data.color = s.prompt_color;
787 data.reset = s.reset_color;
789 print_file_item_data.color = data.color;
790 print_file_item_data.reset = data.reset;
792 strbuf_addstr(&header, " ");
793 strbuf_addf(&header, print_file_item_data.modified_fmt,
794 _("staged"), _("unstaged"), _("path"));
795 opts.list_opts.header = header.buf;
797 if (discard_index(r->index) < 0 ||
798 repo_read_index(r) < 0 ||
799 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
800 NULL, NULL, NULL) < 0)
801 warning(_("could not refresh index"));
803 res = run_status(&s, ps, &files, &opts);
806 i = list_and_choose(&s, &commands, &main_loop_opts);
807 if (i == LIST_AND_CHOOSE_QUIT) {
812 if (i != LIST_AND_CHOOSE_ERROR) {
813 struct command_item *util =
814 commands.items.items[i].util;
815 res = util->command(&s, ps, &files, &opts);
819 prefix_item_list_clear(&files);
820 strbuf_release(&print_file_item_data.buf);
821 strbuf_release(&print_file_item_data.name);
822 strbuf_release(&print_file_item_data.index);
823 strbuf_release(&print_file_item_data.worktree);
824 strbuf_release(&header);
825 prefix_item_list_clear(&commands);