Merge branch 'tb/pseudo-merge-reachability-bitmap'
[alt-git.git] / add-interactive.c
blob49042b30261cc507d1094a007617764c1266eaed
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "add-interactive.h"
5 #include "color.h"
6 #include "config.h"
7 #include "diffcore.h"
8 #include "gettext.h"
9 #include "hash.h"
10 #include "hex.h"
11 #include "preload-index.h"
12 #include "read-cache-ll.h"
13 #include "repository.h"
14 #include "revision.h"
15 #include "refs.h"
16 #include "string-list.h"
17 #include "lockfile.h"
18 #include "dir.h"
19 #include "run-command.h"
20 #include "prompt.h"
21 #include "tree.h"
23 static void init_color(struct repository *r, struct add_i_state *s,
24 const char *section_and_slot, char *dst,
25 const char *default_color)
27 char *key = xstrfmt("color.%s", section_and_slot);
28 const char *value;
30 if (!s->use_color)
31 dst[0] = '\0';
32 else if (repo_config_get_value(r, key, &value) ||
33 color_parse(value, dst))
34 strlcpy(dst, default_color, COLOR_MAXLEN);
36 free(key);
39 void init_add_i_state(struct add_i_state *s, struct repository *r)
41 const char *value;
43 s->r = r;
45 if (repo_config_get_value(r, "color.interactive", &value))
46 s->use_color = -1;
47 else
48 s->use_color =
49 git_config_colorbool("color.interactive", value);
50 s->use_color = want_color(s->use_color);
52 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
53 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
54 init_color(r, s, "interactive.prompt", s->prompt_color,
55 GIT_COLOR_BOLD_BLUE);
56 init_color(r, s, "interactive.error", s->error_color,
57 GIT_COLOR_BOLD_RED);
59 init_color(r, s, "diff.frag", s->fraginfo_color,
60 diff_get_color(s->use_color, DIFF_FRAGINFO));
61 init_color(r, s, "diff.context", s->context_color, "fall back");
62 if (!strcmp(s->context_color, "fall back"))
63 init_color(r, s, "diff.plain", s->context_color,
64 diff_get_color(s->use_color, DIFF_CONTEXT));
65 init_color(r, s, "diff.old", s->file_old_color,
66 diff_get_color(s->use_color, DIFF_FILE_OLD));
67 init_color(r, s, "diff.new", s->file_new_color,
68 diff_get_color(s->use_color, DIFF_FILE_NEW));
70 strlcpy(s->reset_color,
71 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
73 FREE_AND_NULL(s->interactive_diff_filter);
74 git_config_get_string("interactive.difffilter",
75 &s->interactive_diff_filter);
77 FREE_AND_NULL(s->interactive_diff_algorithm);
78 git_config_get_string("diff.algorithm",
79 &s->interactive_diff_algorithm);
81 git_config_get_bool("interactive.singlekey", &s->use_single_key);
82 if (s->use_single_key)
83 setbuf(stdin, NULL);
86 void clear_add_i_state(struct add_i_state *s)
88 FREE_AND_NULL(s->interactive_diff_filter);
89 FREE_AND_NULL(s->interactive_diff_algorithm);
90 memset(s, 0, sizeof(*s));
91 s->use_color = -1;
95 * A "prefix item list" is a list of items that are identified by a string, and
96 * a unique prefix (if any) is determined for each item.
98 * It is implemented in the form of a pair of `string_list`s, the first one
99 * duplicating the strings, with the `util` field pointing at a structure whose
100 * first field must be `size_t prefix_length`.
102 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
103 * will be set to zero if no valid, unique prefix could be found.
105 * The second `string_list` is called `sorted` and does _not_ duplicate the
106 * strings but simply reuses the first one's, with the `util` field pointing at
107 * the `string_item_list` of the first `string_list`. It will be populated and
108 * sorted by `find_unique_prefixes()`.
110 struct prefix_item_list {
111 struct string_list items;
112 struct string_list sorted;
113 int *selected; /* for multi-selections */
114 size_t min_length, max_length;
116 #define PREFIX_ITEM_LIST_INIT { \
117 .items = STRING_LIST_INIT_DUP, \
118 .sorted = STRING_LIST_INIT_NODUP, \
119 .min_length = 1, \
120 .max_length = 4, \
123 static void prefix_item_list_clear(struct prefix_item_list *list)
125 string_list_clear(&list->items, 1);
126 string_list_clear(&list->sorted, 0);
127 FREE_AND_NULL(list->selected);
130 static void extend_prefix_length(struct string_list_item *p,
131 const char *other_string, size_t max_length)
133 size_t *len = p->util;
135 if (!*len || memcmp(p->string, other_string, *len))
136 return;
138 for (;;) {
139 char c = p->string[*len];
142 * Is `p` a strict prefix of `other`? Or have we exhausted the
143 * maximal length of the prefix? Or is the current character a
144 * multi-byte UTF-8 one? If so, there is no valid, unique
145 * prefix.
147 if (!c || ++*len > max_length || !isascii(c)) {
148 *len = 0;
149 break;
152 if (c != other_string[*len - 1])
153 break;
157 static void find_unique_prefixes(struct prefix_item_list *list)
159 size_t i;
161 if (list->sorted.nr == list->items.nr)
162 return;
164 string_list_clear(&list->sorted, 0);
165 /* Avoid reallocating incrementally */
166 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
167 list->items.nr));
168 list->sorted.nr = list->sorted.alloc = list->items.nr;
170 for (i = 0; i < list->items.nr; i++) {
171 list->sorted.items[i].string = list->items.items[i].string;
172 list->sorted.items[i].util = list->items.items + i;
175 string_list_sort(&list->sorted);
177 for (i = 0; i < list->sorted.nr; i++) {
178 struct string_list_item *sorted_item = list->sorted.items + i;
179 struct string_list_item *item = sorted_item->util;
180 size_t *len = item->util;
182 *len = 0;
183 while (*len < list->min_length) {
184 char c = item->string[(*len)++];
186 if (!c || !isascii(c)) {
187 *len = 0;
188 break;
192 if (i > 0)
193 extend_prefix_length(item, sorted_item[-1].string,
194 list->max_length);
195 if (i + 1 < list->sorted.nr)
196 extend_prefix_length(item, sorted_item[1].string,
197 list->max_length);
201 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
203 int index = string_list_find_insert_index(&list->sorted, string, 1);
204 struct string_list_item *item;
206 if (list->items.nr != list->sorted.nr)
207 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
208 " vs %"PRIuMAX")",
209 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
211 if (index < 0)
212 item = list->sorted.items[-1 - index].util;
213 else if (index > 0 &&
214 starts_with(list->sorted.items[index - 1].string, string))
215 return -1;
216 else if (index + 1 < list->sorted.nr &&
217 starts_with(list->sorted.items[index + 1].string, string))
218 return -1;
219 else if (index < list->sorted.nr &&
220 starts_with(list->sorted.items[index].string, string))
221 item = list->sorted.items[index].util;
222 else
223 return -1;
224 return item - list->items.items;
227 struct list_options {
228 int columns;
229 const char *header;
230 void (*print_item)(int i, int selected, struct string_list_item *item,
231 void *print_item_data);
232 void *print_item_data;
235 static void list(struct add_i_state *s, struct string_list *list, int *selected,
236 struct list_options *opts)
238 int i, last_lf = 0;
240 if (!list->nr)
241 return;
243 if (opts->header)
244 color_fprintf_ln(stdout, s->header_color,
245 "%s", opts->header);
247 for (i = 0; i < list->nr; i++) {
248 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
249 opts->print_item_data);
251 if ((opts->columns) && ((i + 1) % (opts->columns))) {
252 putchar('\t');
253 last_lf = 0;
255 else {
256 putchar('\n');
257 last_lf = 1;
261 if (!last_lf)
262 putchar('\n');
264 struct list_and_choose_options {
265 struct list_options list_opts;
267 const char *prompt;
268 enum {
269 SINGLETON = (1<<0),
270 IMMEDIATE = (1<<1),
271 } flags;
272 void (*print_help)(struct add_i_state *s);
275 #define LIST_AND_CHOOSE_ERROR (-1)
276 #define LIST_AND_CHOOSE_QUIT (-2)
279 * Returns the selected index in singleton mode, the number of selected items
280 * otherwise.
282 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
283 * `LIST_AND_CHOOSE_QUIT` is returned.
285 static ssize_t list_and_choose(struct add_i_state *s,
286 struct prefix_item_list *items,
287 struct list_and_choose_options *opts)
289 int singleton = opts->flags & SINGLETON;
290 int immediate = opts->flags & IMMEDIATE;
292 struct strbuf input = STRBUF_INIT;
293 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
295 if (!singleton) {
296 free(items->selected);
297 CALLOC_ARRAY(items->selected, items->items.nr);
300 if (singleton && !immediate)
301 BUG("singleton requires immediate");
303 find_unique_prefixes(items);
305 for (;;) {
306 char *p;
308 strbuf_reset(&input);
310 list(s, &items->items, items->selected, &opts->list_opts);
312 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
313 fputs(singleton ? "> " : ">> ", stdout);
314 fflush(stdout);
316 if (git_read_line_interactively(&input) == EOF) {
317 putchar('\n');
318 if (immediate)
319 res = LIST_AND_CHOOSE_QUIT;
320 break;
323 if (!input.len)
324 break;
326 if (!strcmp(input.buf, "?")) {
327 opts->print_help(s);
328 continue;
331 p = input.buf;
332 for (;;) {
333 size_t sep = strcspn(p, " \t\r\n,");
334 int choose = 1;
335 /* `from` is inclusive, `to` is exclusive */
336 ssize_t from = -1, to = -1;
338 if (!sep) {
339 if (!*p)
340 break;
341 p++;
342 continue;
345 /* Input that begins with '-'; de-select */
346 if (*p == '-') {
347 choose = 0;
348 p++;
349 sep--;
352 if (sep == 1 && *p == '*') {
353 from = 0;
354 to = items->items.nr;
355 } else if (isdigit(*p)) {
356 char *endp;
358 * A range can be specified like 5-7 or 5-.
360 * Note: `from` is 0-based while the user input
361 * is 1-based, hence we have to decrement by
362 * one. We do not have to decrement `to` even
363 * if it is 0-based because it is an exclusive
364 * boundary.
366 from = strtoul(p, &endp, 10) - 1;
367 if (endp == p + sep)
368 to = from + 1;
369 else if (*endp == '-') {
370 if (isdigit(*(++endp)))
371 to = strtoul(endp, &endp, 10);
372 else
373 to = items->items.nr;
374 /* extra characters after the range? */
375 if (endp != p + sep)
376 from = -1;
380 if (p[sep])
381 p[sep++] = '\0';
382 if (from < 0) {
383 from = find_unique(p, items);
384 if (from >= 0)
385 to = from + 1;
388 if (from < 0 || from >= items->items.nr ||
389 (singleton && from + 1 != to)) {
390 color_fprintf_ln(stderr, s->error_color,
391 _("Huh (%s)?"), p);
392 break;
393 } else if (singleton) {
394 res = from;
395 break;
398 if (to > items->items.nr)
399 to = items->items.nr;
401 for (; from < to; from++)
402 if (items->selected[from] != choose) {
403 items->selected[from] = choose;
404 res += choose ? +1 : -1;
407 p += sep;
410 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
411 !strcmp(input.buf, "*"))
412 break;
415 strbuf_release(&input);
416 return res;
419 struct adddel {
420 uintmax_t add, del;
421 unsigned seen:1, unmerged:1, binary:1;
424 struct file_item {
425 size_t prefix_length;
426 struct adddel index, worktree;
429 static void add_file_item(struct string_list *files, const char *name)
431 struct file_item *item = xcalloc(1, sizeof(*item));
433 string_list_append(files, name)->util = item;
436 struct pathname_entry {
437 struct hashmap_entry ent;
438 const char *name;
439 struct file_item *item;
442 static int pathname_entry_cmp(const void *cmp_data UNUSED,
443 const struct hashmap_entry *he1,
444 const struct hashmap_entry *he2,
445 const void *name)
447 const struct pathname_entry *e1 =
448 container_of(he1, const struct pathname_entry, ent);
449 const struct pathname_entry *e2 =
450 container_of(he2, const struct pathname_entry, ent);
452 return strcmp(e1->name, name ? (const char *)name : e2->name);
455 struct collection_status {
456 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
458 const char *reference;
460 unsigned skip_unseen:1;
461 size_t unmerged_count, binary_count;
462 struct string_list *files;
463 struct hashmap file_map;
466 static void collect_changes_cb(struct diff_queue_struct *q,
467 struct diff_options *options,
468 void *data)
470 struct collection_status *s = data;
471 struct diffstat_t stat = { 0 };
472 int i;
474 if (!q->nr)
475 return;
477 compute_diffstat(options, &stat, q);
479 for (i = 0; i < stat.nr; i++) {
480 const char *name = stat.files[i]->name;
481 int hash = strhash(name);
482 struct pathname_entry *entry;
483 struct file_item *file_item;
484 struct adddel *adddel, *other_adddel;
486 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
487 struct pathname_entry, ent);
488 if (!entry) {
489 if (s->skip_unseen)
490 continue;
492 add_file_item(s->files, name);
494 CALLOC_ARRAY(entry, 1);
495 hashmap_entry_init(&entry->ent, hash);
496 entry->name = s->files->items[s->files->nr - 1].string;
497 entry->item = s->files->items[s->files->nr - 1].util;
498 hashmap_add(&s->file_map, &entry->ent);
501 file_item = entry->item;
502 adddel = s->mode == FROM_INDEX ?
503 &file_item->index : &file_item->worktree;
504 other_adddel = s->mode == FROM_INDEX ?
505 &file_item->worktree : &file_item->index;
506 adddel->seen = 1;
507 adddel->add = stat.files[i]->added;
508 adddel->del = stat.files[i]->deleted;
509 if (stat.files[i]->is_binary) {
510 if (!other_adddel->binary)
511 s->binary_count++;
512 adddel->binary = 1;
514 if (stat.files[i]->is_unmerged) {
515 if (!other_adddel->unmerged)
516 s->unmerged_count++;
517 adddel->unmerged = 1;
520 free_diffstat_info(&stat);
523 enum modified_files_filter {
524 NO_FILTER = 0,
525 WORKTREE_ONLY = 1,
526 INDEX_ONLY = 2,
529 static int get_modified_files(struct repository *r,
530 enum modified_files_filter filter,
531 struct prefix_item_list *files,
532 const struct pathspec *ps,
533 size_t *unmerged_count,
534 size_t *binary_count)
536 struct object_id head_oid;
537 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
538 "HEAD", RESOLVE_REF_READING,
539 &head_oid, NULL);
540 struct collection_status s = { 0 };
541 int i;
543 discard_index(r->index);
544 if (repo_read_index_preload(r, ps, 0) < 0)
545 return error(_("could not read index"));
547 prefix_item_list_clear(files);
548 s.files = &files->items;
549 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
551 for (i = 0; i < 2; i++) {
552 struct rev_info rev;
553 struct setup_revision_opt opt = { 0 };
555 if (filter == INDEX_ONLY)
556 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
557 else
558 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
559 s.skip_unseen = filter && i;
561 opt.def = is_initial ?
562 empty_tree_oid_hex(the_repository->hash_algo) : oid_to_hex(&head_oid);
564 repo_init_revisions(r, &rev, NULL);
565 setup_revisions(0, NULL, &rev, &opt);
567 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
568 rev.diffopt.format_callback = collect_changes_cb;
569 rev.diffopt.format_callback_data = &s;
571 if (ps)
572 copy_pathspec(&rev.prune_data, ps);
574 if (s.mode == FROM_INDEX)
575 run_diff_index(&rev, DIFF_INDEX_CACHED);
576 else {
577 rev.diffopt.flags.ignore_dirty_submodules = 1;
578 run_diff_files(&rev, 0);
581 release_revisions(&rev);
583 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
584 if (unmerged_count)
585 *unmerged_count = s.unmerged_count;
586 if (binary_count)
587 *binary_count = s.binary_count;
589 /* While the diffs are ordered already, we ran *two* diffs... */
590 string_list_sort(&files->items);
592 return 0;
595 static void render_adddel(struct strbuf *buf,
596 struct adddel *ad, const char *no_changes)
598 if (ad->binary)
599 strbuf_addstr(buf, _("binary"));
600 else if (ad->seen)
601 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
602 (uintmax_t)ad->add, (uintmax_t)ad->del);
603 else
604 strbuf_addstr(buf, no_changes);
607 /* filters out prefixes which have special meaning to list_and_choose() */
608 static int is_valid_prefix(const char *prefix, size_t prefix_len)
610 return prefix_len && prefix &&
612 * We expect `prefix` to be NUL terminated, therefore this
613 * `strcspn()` call is okay, even if it might do much more
614 * work than strictly necessary.
616 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
617 *prefix != '-' && /* deselection */
618 !isdigit(*prefix) && /* selection */
619 (prefix_len != 1 ||
620 (*prefix != '*' && /* "all" wildcard */
621 *prefix != '?')); /* prompt help */
624 struct print_file_item_data {
625 const char *modified_fmt, *color, *reset;
626 struct strbuf buf, name, index, worktree;
627 unsigned only_names:1;
630 static void print_file_item(int i, int selected, struct string_list_item *item,
631 void *print_file_item_data)
633 struct file_item *c = item->util;
634 struct print_file_item_data *d = print_file_item_data;
635 const char *highlighted = NULL;
637 strbuf_reset(&d->index);
638 strbuf_reset(&d->worktree);
639 strbuf_reset(&d->buf);
641 /* Format the item with the prefix highlighted. */
642 if (c->prefix_length > 0 &&
643 is_valid_prefix(item->string, c->prefix_length)) {
644 strbuf_reset(&d->name);
645 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
646 (int)c->prefix_length, item->string, d->reset,
647 item->string + c->prefix_length);
648 highlighted = d->name.buf;
651 if (d->only_names) {
652 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
653 highlighted ? highlighted : item->string);
654 return;
657 render_adddel(&d->worktree, &c->worktree, _("nothing"));
658 render_adddel(&d->index, &c->index, _("unchanged"));
660 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
661 highlighted ? highlighted : item->string);
663 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
666 static int run_status(struct add_i_state *s, const struct pathspec *ps,
667 struct prefix_item_list *files,
668 struct list_and_choose_options *opts)
670 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
671 return -1;
673 list(s, &files->items, NULL, &opts->list_opts);
674 putchar('\n');
676 return 0;
679 static int run_update(struct add_i_state *s, const struct pathspec *ps,
680 struct prefix_item_list *files,
681 struct list_and_choose_options *opts)
683 int res = 0, fd;
684 size_t count, i;
685 struct lock_file index_lock;
687 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
688 return -1;
690 if (!files->items.nr) {
691 putchar('\n');
692 return 0;
695 opts->prompt = N_("Update");
696 count = list_and_choose(s, files, opts);
697 if (count <= 0) {
698 putchar('\n');
699 return 0;
702 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
703 if (fd < 0) {
704 putchar('\n');
705 return -1;
708 for (i = 0; i < files->items.nr; i++) {
709 const char *name = files->items.items[i].string;
710 struct stat st;
712 if (!files->selected[i])
713 continue;
714 if (lstat(name, &st) && is_missing_file_error(errno)) {
715 if (remove_file_from_index(s->r->index, name) < 0) {
716 res = error(_("could not stage '%s'"), name);
717 break;
719 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
720 res = error(_("could not stage '%s'"), name);
721 break;
725 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
726 res = error(_("could not write index"));
728 if (!res)
729 printf(Q_("updated %d path\n",
730 "updated %d paths\n", count), (int)count);
732 putchar('\n');
733 return res;
736 static void revert_from_diff(struct diff_queue_struct *q,
737 struct diff_options *opt, void *data UNUSED)
739 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
741 for (i = 0; i < q->nr; i++) {
742 struct diff_filespec *one = q->queue[i]->one;
743 struct cache_entry *ce;
745 if (!(one->mode && !is_null_oid(&one->oid))) {
746 remove_file_from_index(opt->repo->index, one->path);
747 printf(_("note: %s is untracked now.\n"), one->path);
748 } else {
749 ce = make_cache_entry(opt->repo->index, one->mode,
750 &one->oid, one->path, 0, 0);
751 if (!ce)
752 die(_("make_cache_entry failed for path '%s'"),
753 one->path);
754 add_index_entry(opt->repo->index, ce, add_flags);
759 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
760 struct prefix_item_list *files,
761 struct list_and_choose_options *opts)
763 int res = 0, fd;
764 size_t count, i, j;
766 struct object_id oid;
767 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
768 "HEAD", RESOLVE_REF_READING,
769 &oid,
770 NULL);
771 struct lock_file index_lock;
772 const char **paths;
773 struct tree *tree;
774 struct diff_options diffopt = { NULL };
776 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
777 return -1;
779 if (!files->items.nr) {
780 putchar('\n');
781 return 0;
784 opts->prompt = N_("Revert");
785 count = list_and_choose(s, files, opts);
786 if (count <= 0)
787 goto finish_revert;
789 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
790 if (fd < 0) {
791 res = -1;
792 goto finish_revert;
795 if (is_initial)
796 oidcpy(&oid, s->r->hash_algo->empty_tree);
797 else {
798 tree = parse_tree_indirect(&oid);
799 if (!tree) {
800 res = error(_("Could not parse HEAD^{tree}"));
801 goto finish_revert;
803 oidcpy(&oid, &tree->object.oid);
806 ALLOC_ARRAY(paths, count + 1);
807 for (i = j = 0; i < files->items.nr; i++)
808 if (files->selected[i])
809 paths[j++] = files->items.items[i].string;
810 paths[j] = NULL;
812 parse_pathspec(&diffopt.pathspec, 0,
813 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
814 NULL, paths);
816 diffopt.output_format = DIFF_FORMAT_CALLBACK;
817 diffopt.format_callback = revert_from_diff;
818 diffopt.flags.override_submodule_config = 1;
819 diffopt.repo = s->r;
821 if (do_diff_cache(&oid, &diffopt)) {
822 diff_free(&diffopt);
823 res = -1;
824 } else {
825 diffcore_std(&diffopt);
826 diff_flush(&diffopt);
828 free(paths);
830 if (!res && write_locked_index(s->r->index, &index_lock,
831 COMMIT_LOCK) < 0)
832 res = -1;
833 else
834 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
835 NULL, NULL, NULL);
837 if (!res)
838 printf(Q_("reverted %d path\n",
839 "reverted %d paths\n", count), (int)count);
841 finish_revert:
842 putchar('\n');
843 return res;
846 static int get_untracked_files(struct repository *r,
847 struct prefix_item_list *files,
848 const struct pathspec *ps)
850 struct dir_struct dir = { 0 };
851 size_t i;
852 struct strbuf buf = STRBUF_INIT;
854 if (repo_read_index(r) < 0)
855 return error(_("could not read index"));
857 prefix_item_list_clear(files);
858 setup_standard_excludes(&dir);
859 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
860 fill_directory(&dir, r->index, ps);
862 for (i = 0; i < dir.nr; i++) {
863 struct dir_entry *ent = dir.entries[i];
865 if (index_name_is_other(r->index, ent->name, ent->len)) {
866 strbuf_reset(&buf);
867 strbuf_add(&buf, ent->name, ent->len);
868 add_file_item(&files->items, buf.buf);
872 strbuf_release(&buf);
873 dir_clear(&dir);
874 return 0;
877 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
878 struct prefix_item_list *files,
879 struct list_and_choose_options *opts)
881 struct print_file_item_data *d = opts->list_opts.print_item_data;
882 int res = 0, fd;
883 size_t count, i;
884 struct lock_file index_lock;
886 if (get_untracked_files(s->r, files, ps) < 0)
887 return -1;
889 if (!files->items.nr) {
890 printf(_("No untracked files.\n"));
891 goto finish_add_untracked;
894 opts->prompt = N_("Add untracked");
895 d->only_names = 1;
896 count = list_and_choose(s, files, opts);
897 d->only_names = 0;
898 if (count <= 0)
899 goto finish_add_untracked;
901 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
902 if (fd < 0) {
903 res = -1;
904 goto finish_add_untracked;
907 for (i = 0; i < files->items.nr; i++) {
908 const char *name = files->items.items[i].string;
909 if (files->selected[i] &&
910 add_file_to_index(s->r->index, name, 0) < 0) {
911 res = error(_("could not stage '%s'"), name);
912 break;
916 if (!res &&
917 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
918 res = error(_("could not write index"));
920 if (!res)
921 printf(Q_("added %d path\n",
922 "added %d paths\n", count), (int)count);
924 finish_add_untracked:
925 putchar('\n');
926 return res;
929 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
930 struct prefix_item_list *files,
931 struct list_and_choose_options *opts)
933 int res = 0;
934 ssize_t count, i, j;
935 size_t unmerged_count = 0, binary_count = 0;
937 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
938 &unmerged_count, &binary_count) < 0)
939 return -1;
941 if (unmerged_count || binary_count) {
942 for (i = j = 0; i < files->items.nr; i++) {
943 struct file_item *item = files->items.items[i].util;
945 if (item->index.binary || item->worktree.binary) {
946 free(item);
947 free(files->items.items[i].string);
948 } else if (item->index.unmerged ||
949 item->worktree.unmerged) {
950 color_fprintf_ln(stderr, s->error_color,
951 _("ignoring unmerged: %s"),
952 files->items.items[i].string);
953 free(item);
954 free(files->items.items[i].string);
955 } else
956 files->items.items[j++] = files->items.items[i];
958 files->items.nr = j;
961 if (!files->items.nr) {
962 if (binary_count)
963 fprintf(stderr, _("Only binary files changed.\n"));
964 else
965 fprintf(stderr, _("No changes.\n"));
966 return 0;
969 opts->prompt = N_("Patch update");
970 count = list_and_choose(s, files, opts);
971 if (count > 0) {
972 struct strvec args = STRVEC_INIT;
973 struct pathspec ps_selected = { 0 };
975 for (i = 0; i < files->items.nr; i++)
976 if (files->selected[i])
977 strvec_push(&args,
978 files->items.items[i].string);
979 parse_pathspec(&ps_selected,
980 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
981 PATHSPEC_LITERAL_PATH, "", args.v);
982 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
983 strvec_clear(&args);
984 clear_pathspec(&ps_selected);
987 return res;
990 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
991 struct prefix_item_list *files,
992 struct list_and_choose_options *opts)
994 int res = 0;
995 ssize_t count, i;
997 struct object_id oid;
998 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
999 "HEAD", RESOLVE_REF_READING,
1000 &oid,
1001 NULL);
1002 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
1003 return -1;
1005 if (!files->items.nr) {
1006 putchar('\n');
1007 return 0;
1010 opts->prompt = N_("Review diff");
1011 opts->flags = IMMEDIATE;
1012 count = list_and_choose(s, files, opts);
1013 opts->flags = 0;
1014 if (count > 0) {
1015 struct child_process cmd = CHILD_PROCESS_INIT;
1017 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
1018 oid_to_hex(!is_initial ? &oid :
1019 s->r->hash_algo->empty_tree),
1020 "--", NULL);
1021 for (i = 0; i < files->items.nr; i++)
1022 if (files->selected[i])
1023 strvec_push(&cmd.args,
1024 files->items.items[i].string);
1025 res = run_command(&cmd);
1028 putchar('\n');
1029 return res;
1032 static int run_help(struct add_i_state *s, const struct pathspec *ps UNUSED,
1033 struct prefix_item_list *files UNUSED,
1034 struct list_and_choose_options *opts UNUSED)
1036 color_fprintf_ln(stdout, s->help_color, "status - %s",
1037 _("show paths with changes"));
1038 color_fprintf_ln(stdout, s->help_color, "update - %s",
1039 _("add working tree state to the staged set of changes"));
1040 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1041 _("revert staged set of changes back to the HEAD version"));
1042 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1043 _("pick hunks and update selectively"));
1044 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1045 _("view diff between HEAD and index"));
1046 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1047 _("add contents of untracked files to the staged set of changes"));
1049 return 0;
1052 static void choose_prompt_help(struct add_i_state *s)
1054 color_fprintf_ln(stdout, s->help_color, "%s",
1055 _("Prompt help:"));
1056 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1057 _("select a single item"));
1058 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1059 _("select a range of items"));
1060 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1061 _("select multiple ranges"));
1062 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1063 _("select item based on unique prefix"));
1064 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1065 _("unselect specified items"));
1066 color_fprintf_ln(stdout, s->help_color, "* - %s",
1067 _("choose all items"));
1068 color_fprintf_ln(stdout, s->help_color, " - %s",
1069 _("(empty) finish selecting"));
1072 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1073 struct prefix_item_list *files,
1074 struct list_and_choose_options *opts);
1076 struct command_item {
1077 size_t prefix_length;
1078 command_t command;
1081 struct print_command_item_data {
1082 const char *color, *reset;
1085 static void print_command_item(int i, int selected UNUSED,
1086 struct string_list_item *item,
1087 void *print_command_item_data)
1089 struct print_command_item_data *d = print_command_item_data;
1090 struct command_item *util = item->util;
1092 if (!util->prefix_length ||
1093 !is_valid_prefix(item->string, util->prefix_length))
1094 printf(" %2d: %s", i + 1, item->string);
1095 else
1096 printf(" %2d: %s%.*s%s%s", i + 1,
1097 d->color, (int)util->prefix_length, item->string,
1098 d->reset, item->string + util->prefix_length);
1101 static void command_prompt_help(struct add_i_state *s)
1103 const char *help_color = s->help_color;
1104 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1105 color_fprintf_ln(stdout, help_color, "1 - %s",
1106 _("select a numbered item"));
1107 color_fprintf_ln(stdout, help_color, "foo - %s",
1108 _("select item based on unique prefix"));
1109 color_fprintf_ln(stdout, help_color, " - %s",
1110 _("(empty) select nothing"));
1113 int run_add_i(struct repository *r, const struct pathspec *ps)
1115 struct add_i_state s = { NULL };
1116 struct print_command_item_data data = { "[", "]" };
1117 struct list_and_choose_options main_loop_opts = {
1118 { 4, N_("*** Commands ***"), print_command_item, &data },
1119 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1121 struct {
1122 const char *string;
1123 command_t command;
1124 } command_list[] = {
1125 { "status", run_status },
1126 { "update", run_update },
1127 { "revert", run_revert },
1128 { "add untracked", run_add_untracked },
1129 { "patch", run_patch },
1130 { "diff", run_diff },
1131 { "quit", NULL },
1132 { "help", run_help },
1134 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1136 struct print_file_item_data print_file_item_data = {
1137 "%12s %12s %s", NULL, NULL,
1138 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1140 struct list_and_choose_options opts = {
1141 { 0, NULL, print_file_item, &print_file_item_data },
1142 NULL, 0, choose_prompt_help
1144 struct strbuf header = STRBUF_INIT;
1145 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1146 ssize_t i;
1147 int res = 0;
1149 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1150 struct command_item *util = xcalloc(1, sizeof(*util));
1151 util->command = command_list[i].command;
1152 string_list_append(&commands.items, command_list[i].string)
1153 ->util = util;
1156 init_add_i_state(&s, r);
1159 * When color was asked for, use the prompt color for
1160 * highlighting, otherwise use square brackets.
1162 if (s.use_color) {
1163 data.color = s.prompt_color;
1164 data.reset = s.reset_color;
1166 print_file_item_data.color = data.color;
1167 print_file_item_data.reset = data.reset;
1169 strbuf_addstr(&header, " ");
1170 strbuf_addf(&header, print_file_item_data.modified_fmt,
1171 _("staged"), _("unstaged"), _("path"));
1172 opts.list_opts.header = header.buf;
1174 discard_index(r->index);
1175 if (repo_read_index(r) < 0 ||
1176 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1177 NULL, NULL, NULL) < 0)
1178 warning(_("could not refresh index"));
1180 res = run_status(&s, ps, &files, &opts);
1182 for (;;) {
1183 struct command_item *util;
1185 i = list_and_choose(&s, &commands, &main_loop_opts);
1186 if (i < 0 || i >= commands.items.nr)
1187 util = NULL;
1188 else
1189 util = commands.items.items[i].util;
1191 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1192 printf(_("Bye.\n"));
1193 res = 0;
1194 break;
1197 if (util)
1198 res = util->command(&s, ps, &files, &opts);
1201 prefix_item_list_clear(&files);
1202 strbuf_release(&print_file_item_data.buf);
1203 strbuf_release(&print_file_item_data.name);
1204 strbuf_release(&print_file_item_data.index);
1205 strbuf_release(&print_file_item_data.worktree);
1206 strbuf_release(&header);
1207 prefix_item_list_clear(&commands);
1208 clear_add_i_state(&s);
1210 return res;