add -i: use `reset_color` consistently
[alt-git.git] / add-interactive.c
blob0f24992ca4a925af3b712eb196a165a24b68312a
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 #include "prompt.h"
14 static void init_color(struct repository *r, struct add_i_state *s,
15 const char *slot_name, char *dst,
16 const char *default_color)
18 char *key = xstrfmt("color.interactive.%s", slot_name);
19 const char *value;
21 if (!s->use_color)
22 dst[0] = '\0';
23 else if (repo_config_get_value(r, key, &value) ||
24 color_parse(value, dst))
25 strlcpy(dst, default_color, COLOR_MAXLEN);
27 free(key);
30 void init_add_i_state(struct add_i_state *s, struct repository *r)
32 const char *value;
34 s->r = r;
36 if (repo_config_get_value(r, "color.interactive", &value))
37 s->use_color = -1;
38 else
39 s->use_color =
40 git_config_colorbool("color.interactive", value);
41 s->use_color = want_color(s->use_color);
43 init_color(r, s, "header", s->header_color, GIT_COLOR_BOLD);
44 init_color(r, s, "help", s->help_color, GIT_COLOR_BOLD_RED);
45 init_color(r, s, "prompt", s->prompt_color, GIT_COLOR_BOLD_BLUE);
46 init_color(r, s, "error", s->error_color, GIT_COLOR_BOLD_RED);
47 init_color(r, s, "reset", s->reset_color, GIT_COLOR_RESET);
48 init_color(r, s, "fraginfo", s->fraginfo_color,
49 diff_get_color(s->use_color, DIFF_FRAGINFO));
50 init_color(r, s, "context", s->context_color,
51 diff_get_color(s->use_color, DIFF_CONTEXT));
52 init_color(r, s, "old", s->file_old_color,
53 diff_get_color(s->use_color, DIFF_FILE_OLD));
54 init_color(r, s, "new", s->file_new_color,
55 diff_get_color(s->use_color, DIFF_FILE_NEW));
57 FREE_AND_NULL(s->interactive_diff_filter);
58 git_config_get_string("interactive.difffilter",
59 &s->interactive_diff_filter);
61 FREE_AND_NULL(s->interactive_diff_algorithm);
62 git_config_get_string("diff.algorithm",
63 &s->interactive_diff_algorithm);
65 git_config_get_bool("interactive.singlekey", &s->use_single_key);
68 void clear_add_i_state(struct add_i_state *s)
70 FREE_AND_NULL(s->interactive_diff_filter);
71 FREE_AND_NULL(s->interactive_diff_algorithm);
72 memset(s, 0, sizeof(*s));
73 s->use_color = -1;
77 * A "prefix item list" is a list of items that are identified by a string, and
78 * a unique prefix (if any) is determined for each item.
80 * It is implemented in the form of a pair of `string_list`s, the first one
81 * duplicating the strings, with the `util` field pointing at a structure whose
82 * first field must be `size_t prefix_length`.
84 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
85 * will be set to zero if no valid, unique prefix could be found.
87 * The second `string_list` is called `sorted` and does _not_ duplicate the
88 * strings but simply reuses the first one's, with the `util` field pointing at
89 * the `string_item_list` of the first `string_list`. It will be populated and
90 * sorted by `find_unique_prefixes()`.
92 struct prefix_item_list {
93 struct string_list items;
94 struct string_list sorted;
95 int *selected; /* for multi-selections */
96 size_t min_length, max_length;
98 #define PREFIX_ITEM_LIST_INIT \
99 { STRING_LIST_INIT_DUP, STRING_LIST_INIT_NODUP, NULL, 1, 4 }
101 static void prefix_item_list_clear(struct prefix_item_list *list)
103 string_list_clear(&list->items, 1);
104 string_list_clear(&list->sorted, 0);
105 FREE_AND_NULL(list->selected);
108 static void extend_prefix_length(struct string_list_item *p,
109 const char *other_string, size_t max_length)
111 size_t *len = p->util;
113 if (!*len || memcmp(p->string, other_string, *len))
114 return;
116 for (;;) {
117 char c = p->string[*len];
120 * Is `p` a strict prefix of `other`? Or have we exhausted the
121 * maximal length of the prefix? Or is the current character a
122 * multi-byte UTF-8 one? If so, there is no valid, unique
123 * prefix.
125 if (!c || ++*len > max_length || !isascii(c)) {
126 *len = 0;
127 break;
130 if (c != other_string[*len - 1])
131 break;
135 static void find_unique_prefixes(struct prefix_item_list *list)
137 size_t i;
139 if (list->sorted.nr == list->items.nr)
140 return;
142 string_list_clear(&list->sorted, 0);
143 /* Avoid reallocating incrementally */
144 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
145 list->items.nr));
146 list->sorted.nr = list->sorted.alloc = list->items.nr;
148 for (i = 0; i < list->items.nr; i++) {
149 list->sorted.items[i].string = list->items.items[i].string;
150 list->sorted.items[i].util = list->items.items + i;
153 string_list_sort(&list->sorted);
155 for (i = 0; i < list->sorted.nr; i++) {
156 struct string_list_item *sorted_item = list->sorted.items + i;
157 struct string_list_item *item = sorted_item->util;
158 size_t *len = item->util;
160 *len = 0;
161 while (*len < list->min_length) {
162 char c = item->string[(*len)++];
164 if (!c || !isascii(c)) {
165 *len = 0;
166 break;
170 if (i > 0)
171 extend_prefix_length(item, sorted_item[-1].string,
172 list->max_length);
173 if (i + 1 < list->sorted.nr)
174 extend_prefix_length(item, sorted_item[1].string,
175 list->max_length);
179 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
181 int index = string_list_find_insert_index(&list->sorted, string, 1);
182 struct string_list_item *item;
184 if (list->items.nr != list->sorted.nr)
185 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
186 " vs %"PRIuMAX")",
187 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
189 if (index < 0)
190 item = list->sorted.items[-1 - index].util;
191 else if (index > 0 &&
192 starts_with(list->sorted.items[index - 1].string, string))
193 return -1;
194 else if (index + 1 < list->sorted.nr &&
195 starts_with(list->sorted.items[index + 1].string, string))
196 return -1;
197 else if (index < list->sorted.nr &&
198 starts_with(list->sorted.items[index].string, string))
199 item = list->sorted.items[index].util;
200 else
201 return -1;
202 return item - list->items.items;
205 struct list_options {
206 int columns;
207 const char *header;
208 void (*print_item)(int i, int selected, struct string_list_item *item,
209 void *print_item_data);
210 void *print_item_data;
213 static void list(struct add_i_state *s, struct string_list *list, int *selected,
214 struct list_options *opts)
216 int i, last_lf = 0;
218 if (!list->nr)
219 return;
221 if (opts->header)
222 color_fprintf_ln(stdout, s->header_color,
223 "%s", opts->header);
225 for (i = 0; i < list->nr; i++) {
226 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
227 opts->print_item_data);
229 if ((opts->columns) && ((i + 1) % (opts->columns))) {
230 putchar('\t');
231 last_lf = 0;
233 else {
234 putchar('\n');
235 last_lf = 1;
239 if (!last_lf)
240 putchar('\n');
242 struct list_and_choose_options {
243 struct list_options list_opts;
245 const char *prompt;
246 enum {
247 SINGLETON = (1<<0),
248 IMMEDIATE = (1<<1),
249 } flags;
250 void (*print_help)(struct add_i_state *s);
253 #define LIST_AND_CHOOSE_ERROR (-1)
254 #define LIST_AND_CHOOSE_QUIT (-2)
257 * Returns the selected index in singleton mode, the number of selected items
258 * otherwise.
260 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
261 * `LIST_AND_CHOOSE_QUIT` is returned.
263 static ssize_t list_and_choose(struct add_i_state *s,
264 struct prefix_item_list *items,
265 struct list_and_choose_options *opts)
267 int singleton = opts->flags & SINGLETON;
268 int immediate = opts->flags & IMMEDIATE;
270 struct strbuf input = STRBUF_INIT;
271 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
273 if (!singleton) {
274 free(items->selected);
275 CALLOC_ARRAY(items->selected, items->items.nr);
278 if (singleton && !immediate)
279 BUG("singleton requires immediate");
281 find_unique_prefixes(items);
283 for (;;) {
284 char *p;
286 strbuf_reset(&input);
288 list(s, &items->items, items->selected, &opts->list_opts);
290 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
291 fputs(singleton ? "> " : ">> ", stdout);
292 fflush(stdout);
294 if (git_read_line_interactively(&input) == EOF) {
295 putchar('\n');
296 if (immediate)
297 res = LIST_AND_CHOOSE_QUIT;
298 break;
301 if (!input.len)
302 break;
304 if (!strcmp(input.buf, "?")) {
305 opts->print_help(s);
306 continue;
309 p = input.buf;
310 for (;;) {
311 size_t sep = strcspn(p, " \t\r\n,");
312 int choose = 1;
313 /* `from` is inclusive, `to` is exclusive */
314 ssize_t from = -1, to = -1;
316 if (!sep) {
317 if (!*p)
318 break;
319 p++;
320 continue;
323 /* Input that begins with '-'; de-select */
324 if (*p == '-') {
325 choose = 0;
326 p++;
327 sep--;
330 if (sep == 1 && *p == '*') {
331 from = 0;
332 to = items->items.nr;
333 } else if (isdigit(*p)) {
334 char *endp;
336 * A range can be specified like 5-7 or 5-.
338 * Note: `from` is 0-based while the user input
339 * is 1-based, hence we have to decrement by
340 * one. We do not have to decrement `to` even
341 * if it is 0-based because it is an exclusive
342 * boundary.
344 from = strtoul(p, &endp, 10) - 1;
345 if (endp == p + sep)
346 to = from + 1;
347 else if (*endp == '-') {
348 if (isdigit(*(++endp)))
349 to = strtoul(endp, &endp, 10);
350 else
351 to = items->items.nr;
352 /* extra characters after the range? */
353 if (endp != p + sep)
354 from = -1;
358 if (p[sep])
359 p[sep++] = '\0';
360 if (from < 0) {
361 from = find_unique(p, items);
362 if (from >= 0)
363 to = from + 1;
366 if (from < 0 || from >= items->items.nr ||
367 (singleton && from + 1 != to)) {
368 color_fprintf_ln(stderr, s->error_color,
369 _("Huh (%s)?"), p);
370 break;
371 } else if (singleton) {
372 res = from;
373 break;
376 if (to > items->items.nr)
377 to = items->items.nr;
379 for (; from < to; from++)
380 if (items->selected[from] != choose) {
381 items->selected[from] = choose;
382 res += choose ? +1 : -1;
385 p += sep;
388 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
389 !strcmp(input.buf, "*"))
390 break;
393 strbuf_release(&input);
394 return res;
397 struct adddel {
398 uintmax_t add, del;
399 unsigned seen:1, unmerged:1, binary:1;
402 struct file_item {
403 size_t prefix_length;
404 struct adddel index, worktree;
407 static void add_file_item(struct string_list *files, const char *name)
409 struct file_item *item = xcalloc(sizeof(*item), 1);
411 string_list_append(files, name)->util = item;
414 struct pathname_entry {
415 struct hashmap_entry ent;
416 const char *name;
417 struct file_item *item;
420 static int pathname_entry_cmp(const void *unused_cmp_data,
421 const struct hashmap_entry *he1,
422 const struct hashmap_entry *he2,
423 const void *name)
425 const struct pathname_entry *e1 =
426 container_of(he1, const struct pathname_entry, ent);
427 const struct pathname_entry *e2 =
428 container_of(he2, const struct pathname_entry, ent);
430 return strcmp(e1->name, name ? (const char *)name : e2->name);
433 struct collection_status {
434 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
436 const char *reference;
438 unsigned skip_unseen:1;
439 size_t unmerged_count, binary_count;
440 struct string_list *files;
441 struct hashmap file_map;
444 static void collect_changes_cb(struct diff_queue_struct *q,
445 struct diff_options *options,
446 void *data)
448 struct collection_status *s = data;
449 struct diffstat_t stat = { 0 };
450 int i;
452 if (!q->nr)
453 return;
455 compute_diffstat(options, &stat, q);
457 for (i = 0; i < stat.nr; i++) {
458 const char *name = stat.files[i]->name;
459 int hash = strhash(name);
460 struct pathname_entry *entry;
461 struct file_item *file_item;
462 struct adddel *adddel, *other_adddel;
464 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
465 struct pathname_entry, ent);
466 if (!entry) {
467 if (s->skip_unseen)
468 continue;
470 add_file_item(s->files, name);
472 entry = xcalloc(sizeof(*entry), 1);
473 hashmap_entry_init(&entry->ent, hash);
474 entry->name = s->files->items[s->files->nr - 1].string;
475 entry->item = s->files->items[s->files->nr - 1].util;
476 hashmap_add(&s->file_map, &entry->ent);
479 file_item = entry->item;
480 adddel = s->mode == FROM_INDEX ?
481 &file_item->index : &file_item->worktree;
482 other_adddel = s->mode == FROM_INDEX ?
483 &file_item->worktree : &file_item->index;
484 adddel->seen = 1;
485 adddel->add = stat.files[i]->added;
486 adddel->del = stat.files[i]->deleted;
487 if (stat.files[i]->is_binary) {
488 if (!other_adddel->binary)
489 s->binary_count++;
490 adddel->binary = 1;
492 if (stat.files[i]->is_unmerged) {
493 if (!other_adddel->unmerged)
494 s->unmerged_count++;
495 adddel->unmerged = 1;
498 free_diffstat_info(&stat);
501 enum modified_files_filter {
502 NO_FILTER = 0,
503 WORKTREE_ONLY = 1,
504 INDEX_ONLY = 2,
507 static int get_modified_files(struct repository *r,
508 enum modified_files_filter filter,
509 struct prefix_item_list *files,
510 const struct pathspec *ps,
511 size_t *unmerged_count,
512 size_t *binary_count)
514 struct object_id head_oid;
515 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
516 &head_oid, NULL);
517 struct collection_status s = { 0 };
518 int i;
520 if (discard_index(r->index) < 0 ||
521 repo_read_index_preload(r, ps, 0) < 0)
522 return error(_("could not read index"));
524 prefix_item_list_clear(files);
525 s.files = &files->items;
526 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
528 for (i = 0; i < 2; i++) {
529 struct rev_info rev;
530 struct setup_revision_opt opt = { 0 };
532 if (filter == INDEX_ONLY)
533 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
534 else
535 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
536 s.skip_unseen = filter && i;
538 opt.def = is_initial ?
539 empty_tree_oid_hex() : oid_to_hex(&head_oid);
541 init_revisions(&rev, NULL);
542 setup_revisions(0, NULL, &rev, &opt);
544 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
545 rev.diffopt.format_callback = collect_changes_cb;
546 rev.diffopt.format_callback_data = &s;
548 if (ps)
549 copy_pathspec(&rev.prune_data, ps);
551 if (s.mode == FROM_INDEX)
552 run_diff_index(&rev, 1);
553 else {
554 rev.diffopt.flags.ignore_dirty_submodules = 1;
555 run_diff_files(&rev, 0);
558 if (ps)
559 clear_pathspec(&rev.prune_data);
561 hashmap_free_entries(&s.file_map, struct pathname_entry, ent);
562 if (unmerged_count)
563 *unmerged_count = s.unmerged_count;
564 if (binary_count)
565 *binary_count = s.binary_count;
567 /* While the diffs are ordered already, we ran *two* diffs... */
568 string_list_sort(&files->items);
570 return 0;
573 static void render_adddel(struct strbuf *buf,
574 struct adddel *ad, const char *no_changes)
576 if (ad->binary)
577 strbuf_addstr(buf, _("binary"));
578 else if (ad->seen)
579 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
580 (uintmax_t)ad->add, (uintmax_t)ad->del);
581 else
582 strbuf_addstr(buf, no_changes);
585 /* filters out prefixes which have special meaning to list_and_choose() */
586 static int is_valid_prefix(const char *prefix, size_t prefix_len)
588 return prefix_len && prefix &&
590 * We expect `prefix` to be NUL terminated, therefore this
591 * `strcspn()` call is okay, even if it might do much more
592 * work than strictly necessary.
594 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
595 *prefix != '-' && /* deselection */
596 !isdigit(*prefix) && /* selection */
597 (prefix_len != 1 ||
598 (*prefix != '*' && /* "all" wildcard */
599 *prefix != '?')); /* prompt help */
602 struct print_file_item_data {
603 const char *modified_fmt, *color, *reset;
604 struct strbuf buf, name, index, worktree;
605 unsigned only_names:1;
608 static void print_file_item(int i, int selected, struct string_list_item *item,
609 void *print_file_item_data)
611 struct file_item *c = item->util;
612 struct print_file_item_data *d = print_file_item_data;
613 const char *highlighted = NULL;
615 strbuf_reset(&d->index);
616 strbuf_reset(&d->worktree);
617 strbuf_reset(&d->buf);
619 /* Format the item with the prefix highlighted. */
620 if (c->prefix_length > 0 &&
621 is_valid_prefix(item->string, c->prefix_length)) {
622 strbuf_reset(&d->name);
623 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
624 (int)c->prefix_length, item->string, d->reset,
625 item->string + c->prefix_length);
626 highlighted = d->name.buf;
629 if (d->only_names) {
630 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
631 highlighted ? highlighted : item->string);
632 return;
635 render_adddel(&d->worktree, &c->worktree, _("nothing"));
636 render_adddel(&d->index, &c->index, _("unchanged"));
638 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
639 highlighted ? highlighted : item->string);
641 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
644 static int run_status(struct add_i_state *s, const struct pathspec *ps,
645 struct prefix_item_list *files,
646 struct list_and_choose_options *opts)
648 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
649 return -1;
651 list(s, &files->items, NULL, &opts->list_opts);
652 putchar('\n');
654 return 0;
657 static int run_update(struct add_i_state *s, const struct pathspec *ps,
658 struct prefix_item_list *files,
659 struct list_and_choose_options *opts)
661 int res = 0, fd;
662 size_t count, i;
663 struct lock_file index_lock;
665 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
666 return -1;
668 if (!files->items.nr) {
669 putchar('\n');
670 return 0;
673 opts->prompt = N_("Update");
674 count = list_and_choose(s, files, opts);
675 if (count <= 0) {
676 putchar('\n');
677 return 0;
680 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
681 if (fd < 0) {
682 putchar('\n');
683 return -1;
686 for (i = 0; i < files->items.nr; i++) {
687 const char *name = files->items.items[i].string;
688 if (files->selected[i] &&
689 add_file_to_index(s->r->index, name, 0) < 0) {
690 res = error(_("could not stage '%s'"), name);
691 break;
695 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
696 res = error(_("could not write index"));
698 if (!res)
699 printf(Q_("updated %d path\n",
700 "updated %d paths\n", count), (int)count);
702 putchar('\n');
703 return res;
706 static void revert_from_diff(struct diff_queue_struct *q,
707 struct diff_options *opt, void *data)
709 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
711 for (i = 0; i < q->nr; i++) {
712 struct diff_filespec *one = q->queue[i]->one;
713 struct cache_entry *ce;
715 if (!(one->mode && !is_null_oid(&one->oid))) {
716 remove_file_from_index(opt->repo->index, one->path);
717 printf(_("note: %s is untracked now.\n"), one->path);
718 } else {
719 ce = make_cache_entry(opt->repo->index, one->mode,
720 &one->oid, one->path, 0, 0);
721 if (!ce)
722 die(_("make_cache_entry failed for path '%s'"),
723 one->path);
724 add_index_entry(opt->repo->index, ce, add_flags);
729 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
730 struct prefix_item_list *files,
731 struct list_and_choose_options *opts)
733 int res = 0, fd;
734 size_t count, i, j;
736 struct object_id oid;
737 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
738 NULL);
739 struct lock_file index_lock;
740 const char **paths;
741 struct tree *tree;
742 struct diff_options diffopt = { NULL };
744 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
745 return -1;
747 if (!files->items.nr) {
748 putchar('\n');
749 return 0;
752 opts->prompt = N_("Revert");
753 count = list_and_choose(s, files, opts);
754 if (count <= 0)
755 goto finish_revert;
757 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
758 if (fd < 0) {
759 res = -1;
760 goto finish_revert;
763 if (is_initial)
764 oidcpy(&oid, s->r->hash_algo->empty_tree);
765 else {
766 tree = parse_tree_indirect(&oid);
767 if (!tree) {
768 res = error(_("Could not parse HEAD^{tree}"));
769 goto finish_revert;
771 oidcpy(&oid, &tree->object.oid);
774 ALLOC_ARRAY(paths, count + 1);
775 for (i = j = 0; i < files->items.nr; i++)
776 if (files->selected[i])
777 paths[j++] = files->items.items[i].string;
778 paths[j] = NULL;
780 parse_pathspec(&diffopt.pathspec, 0,
781 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
782 NULL, paths);
784 diffopt.output_format = DIFF_FORMAT_CALLBACK;
785 diffopt.format_callback = revert_from_diff;
786 diffopt.flags.override_submodule_config = 1;
787 diffopt.repo = s->r;
789 if (do_diff_cache(&oid, &diffopt))
790 res = -1;
791 else {
792 diffcore_std(&diffopt);
793 diff_flush(&diffopt);
795 free(paths);
796 clear_pathspec(&diffopt.pathspec);
798 if (!res && write_locked_index(s->r->index, &index_lock,
799 COMMIT_LOCK) < 0)
800 res = -1;
801 else
802 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
803 NULL, NULL, NULL);
805 if (!res)
806 printf(Q_("reverted %d path\n",
807 "reverted %d paths\n", count), (int)count);
809 finish_revert:
810 putchar('\n');
811 return res;
814 static int get_untracked_files(struct repository *r,
815 struct prefix_item_list *files,
816 const struct pathspec *ps)
818 struct dir_struct dir = { 0 };
819 size_t i;
820 struct strbuf buf = STRBUF_INIT;
822 if (repo_read_index(r) < 0)
823 return error(_("could not read index"));
825 prefix_item_list_clear(files);
826 setup_standard_excludes(&dir);
827 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
828 fill_directory(&dir, r->index, ps);
830 for (i = 0; i < dir.nr; i++) {
831 struct dir_entry *ent = dir.entries[i];
833 if (index_name_is_other(r->index, ent->name, ent->len)) {
834 strbuf_reset(&buf);
835 strbuf_add(&buf, ent->name, ent->len);
836 add_file_item(&files->items, buf.buf);
840 strbuf_release(&buf);
841 return 0;
844 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
845 struct prefix_item_list *files,
846 struct list_and_choose_options *opts)
848 struct print_file_item_data *d = opts->list_opts.print_item_data;
849 int res = 0, fd;
850 size_t count, i;
851 struct lock_file index_lock;
853 if (get_untracked_files(s->r, files, ps) < 0)
854 return -1;
856 if (!files->items.nr) {
857 printf(_("No untracked files.\n"));
858 goto finish_add_untracked;
861 opts->prompt = N_("Add untracked");
862 d->only_names = 1;
863 count = list_and_choose(s, files, opts);
864 d->only_names = 0;
865 if (count <= 0)
866 goto finish_add_untracked;
868 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
869 if (fd < 0) {
870 res = -1;
871 goto finish_add_untracked;
874 for (i = 0; i < files->items.nr; i++) {
875 const char *name = files->items.items[i].string;
876 if (files->selected[i] &&
877 add_file_to_index(s->r->index, name, 0) < 0) {
878 res = error(_("could not stage '%s'"), name);
879 break;
883 if (!res &&
884 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
885 res = error(_("could not write index"));
887 if (!res)
888 printf(Q_("added %d path\n",
889 "added %d paths\n", count), (int)count);
891 finish_add_untracked:
892 putchar('\n');
893 return res;
896 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
897 struct prefix_item_list *files,
898 struct list_and_choose_options *opts)
900 int res = 0;
901 ssize_t count, i, j;
902 size_t unmerged_count = 0, binary_count = 0;
904 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
905 &unmerged_count, &binary_count) < 0)
906 return -1;
908 if (unmerged_count || binary_count) {
909 for (i = j = 0; i < files->items.nr; i++) {
910 struct file_item *item = files->items.items[i].util;
912 if (item->index.binary || item->worktree.binary) {
913 free(item);
914 free(files->items.items[i].string);
915 } else if (item->index.unmerged ||
916 item->worktree.unmerged) {
917 color_fprintf_ln(stderr, s->error_color,
918 _("ignoring unmerged: %s"),
919 files->items.items[i].string);
920 free(item);
921 free(files->items.items[i].string);
922 } else
923 files->items.items[j++] = files->items.items[i];
925 files->items.nr = j;
928 if (!files->items.nr) {
929 if (binary_count)
930 fprintf(stderr, _("Only binary files changed.\n"));
931 else
932 fprintf(stderr, _("No changes.\n"));
933 return 0;
936 opts->prompt = N_("Patch update");
937 count = list_and_choose(s, files, opts);
938 if (count > 0) {
939 struct strvec args = STRVEC_INIT;
940 struct pathspec ps_selected = { 0 };
942 for (i = 0; i < files->items.nr; i++)
943 if (files->selected[i])
944 strvec_push(&args,
945 files->items.items[i].string);
946 parse_pathspec(&ps_selected,
947 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
948 PATHSPEC_LITERAL_PATH, "", args.v);
949 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
950 strvec_clear(&args);
951 clear_pathspec(&ps_selected);
954 return res;
957 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
958 struct prefix_item_list *files,
959 struct list_and_choose_options *opts)
961 int res = 0;
962 ssize_t count, i;
964 struct object_id oid;
965 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
966 NULL);
967 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
968 return -1;
970 if (!files->items.nr) {
971 putchar('\n');
972 return 0;
975 opts->prompt = N_("Review diff");
976 opts->flags = IMMEDIATE;
977 count = list_and_choose(s, files, opts);
978 opts->flags = 0;
979 if (count > 0) {
980 struct strvec args = STRVEC_INIT;
982 strvec_pushl(&args, "git", "diff", "-p", "--cached",
983 oid_to_hex(!is_initial ? &oid :
984 s->r->hash_algo->empty_tree),
985 "--", NULL);
986 for (i = 0; i < files->items.nr; i++)
987 if (files->selected[i])
988 strvec_push(&args,
989 files->items.items[i].string);
990 res = run_command_v_opt(args.v, 0);
991 strvec_clear(&args);
994 putchar('\n');
995 return res;
998 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
999 struct prefix_item_list *unused_files,
1000 struct list_and_choose_options *unused_opts)
1002 color_fprintf_ln(stdout, s->help_color, "status - %s",
1003 _("show paths with changes"));
1004 color_fprintf_ln(stdout, s->help_color, "update - %s",
1005 _("add working tree state to the staged set of changes"));
1006 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1007 _("revert staged set of changes back to the HEAD version"));
1008 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1009 _("pick hunks and update selectively"));
1010 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1011 _("view diff between HEAD and index"));
1012 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1013 _("add contents of untracked files to the staged set of changes"));
1015 return 0;
1018 static void choose_prompt_help(struct add_i_state *s)
1020 color_fprintf_ln(stdout, s->help_color, "%s",
1021 _("Prompt help:"));
1022 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1023 _("select a single item"));
1024 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1025 _("select a range of items"));
1026 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1027 _("select multiple ranges"));
1028 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1029 _("select item based on unique prefix"));
1030 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1031 _("unselect specified items"));
1032 color_fprintf_ln(stdout, s->help_color, "* - %s",
1033 _("choose all items"));
1034 color_fprintf_ln(stdout, s->help_color, " - %s",
1035 _("(empty) finish selecting"));
1038 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1039 struct prefix_item_list *files,
1040 struct list_and_choose_options *opts);
1042 struct command_item {
1043 size_t prefix_length;
1044 command_t command;
1047 struct print_command_item_data {
1048 const char *color, *reset;
1051 static void print_command_item(int i, int selected,
1052 struct string_list_item *item,
1053 void *print_command_item_data)
1055 struct print_command_item_data *d = print_command_item_data;
1056 struct command_item *util = item->util;
1058 if (!util->prefix_length ||
1059 !is_valid_prefix(item->string, util->prefix_length))
1060 printf(" %2d: %s", i + 1, item->string);
1061 else
1062 printf(" %2d: %s%.*s%s%s", i + 1,
1063 d->color, (int)util->prefix_length, item->string,
1064 d->reset, item->string + util->prefix_length);
1067 static void command_prompt_help(struct add_i_state *s)
1069 const char *help_color = s->help_color;
1070 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1071 color_fprintf_ln(stdout, help_color, "1 - %s",
1072 _("select a numbered item"));
1073 color_fprintf_ln(stdout, help_color, "foo - %s",
1074 _("select item based on unique prefix"));
1075 color_fprintf_ln(stdout, help_color, " - %s",
1076 _("(empty) select nothing"));
1079 int run_add_i(struct repository *r, const struct pathspec *ps)
1081 struct add_i_state s = { NULL };
1082 struct print_command_item_data data = { "[", "]" };
1083 struct list_and_choose_options main_loop_opts = {
1084 { 4, N_("*** Commands ***"), print_command_item, &data },
1085 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1087 struct {
1088 const char *string;
1089 command_t command;
1090 } command_list[] = {
1091 { "status", run_status },
1092 { "update", run_update },
1093 { "revert", run_revert },
1094 { "add untracked", run_add_untracked },
1095 { "patch", run_patch },
1096 { "diff", run_diff },
1097 { "quit", NULL },
1098 { "help", run_help },
1100 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1102 struct print_file_item_data print_file_item_data = {
1103 "%12s %12s %s", NULL, NULL,
1104 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1106 struct list_and_choose_options opts = {
1107 { 0, NULL, print_file_item, &print_file_item_data },
1108 NULL, 0, choose_prompt_help
1110 struct strbuf header = STRBUF_INIT;
1111 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1112 ssize_t i;
1113 int res = 0;
1115 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1116 struct command_item *util = xcalloc(sizeof(*util), 1);
1117 util->command = command_list[i].command;
1118 string_list_append(&commands.items, command_list[i].string)
1119 ->util = util;
1122 init_add_i_state(&s, r);
1125 * When color was asked for, use the prompt color for
1126 * highlighting, otherwise use square brackets.
1128 if (s.use_color) {
1129 data.color = s.prompt_color;
1130 data.reset = s.reset_color;
1132 print_file_item_data.color = data.color;
1133 print_file_item_data.reset = data.reset;
1135 strbuf_addstr(&header, " ");
1136 strbuf_addf(&header, print_file_item_data.modified_fmt,
1137 _("staged"), _("unstaged"), _("path"));
1138 opts.list_opts.header = header.buf;
1140 if (discard_index(r->index) < 0 ||
1141 repo_read_index(r) < 0 ||
1142 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1143 NULL, NULL, NULL) < 0)
1144 warning(_("could not refresh index"));
1146 res = run_status(&s, ps, &files, &opts);
1148 for (;;) {
1149 struct command_item *util;
1151 i = list_and_choose(&s, &commands, &main_loop_opts);
1152 if (i < 0 || i >= commands.items.nr)
1153 util = NULL;
1154 else
1155 util = commands.items.items[i].util;
1157 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1158 printf(_("Bye.\n"));
1159 res = 0;
1160 break;
1163 if (util)
1164 res = util->command(&s, ps, &files, &opts);
1167 prefix_item_list_clear(&files);
1168 strbuf_release(&print_file_item_data.buf);
1169 strbuf_release(&print_file_item_data.name);
1170 strbuf_release(&print_file_item_data.index);
1171 strbuf_release(&print_file_item_data.worktree);
1172 strbuf_release(&header);
1173 prefix_item_list_clear(&commands);
1174 clear_add_i_state(&s);
1176 return res;