Sync with 'master'
[alt-git.git] / add-interactive.c
blobb5d6cd689a1d5ebdd211b898d63ef5ce9137d2cc
1 #include "git-compat-util.h"
2 #include "add-interactive.h"
3 #include "color.h"
4 #include "config.h"
5 #include "diffcore.h"
6 #include "gettext.h"
7 #include "hash.h"
8 #include "hex.h"
9 #include "preload-index.h"
10 #include "read-cache-ll.h"
11 #include "repository.h"
12 #include "revision.h"
13 #include "refs.h"
14 #include "string-list.h"
15 #include "lockfile.h"
16 #include "dir.h"
17 #include "run-command.h"
18 #include "prompt.h"
19 #include "tree.h"
21 static void init_color(struct repository *r, struct add_i_state *s,
22 const char *section_and_slot, char *dst,
23 const char *default_color)
25 char *key = xstrfmt("color.%s", section_and_slot);
26 const char *value;
28 if (!s->use_color)
29 dst[0] = '\0';
30 else if (repo_config_get_value(r, key, &value) ||
31 color_parse(value, dst))
32 strlcpy(dst, default_color, COLOR_MAXLEN);
34 free(key);
37 void init_add_i_state(struct add_i_state *s, struct repository *r)
39 const char *value;
41 s->r = r;
43 if (repo_config_get_value(r, "color.interactive", &value))
44 s->use_color = -1;
45 else
46 s->use_color =
47 git_config_colorbool("color.interactive", value);
48 s->use_color = want_color(s->use_color);
50 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
51 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
52 init_color(r, s, "interactive.prompt", s->prompt_color,
53 GIT_COLOR_BOLD_BLUE);
54 init_color(r, s, "interactive.error", s->error_color,
55 GIT_COLOR_BOLD_RED);
57 init_color(r, s, "diff.frag", s->fraginfo_color,
58 diff_get_color(s->use_color, DIFF_FRAGINFO));
59 init_color(r, s, "diff.context", s->context_color, "fall back");
60 if (!strcmp(s->context_color, "fall back"))
61 init_color(r, s, "diff.plain", s->context_color,
62 diff_get_color(s->use_color, DIFF_CONTEXT));
63 init_color(r, s, "diff.old", s->file_old_color,
64 diff_get_color(s->use_color, DIFF_FILE_OLD));
65 init_color(r, s, "diff.new", s->file_new_color,
66 diff_get_color(s->use_color, DIFF_FILE_NEW));
68 strlcpy(s->reset_color,
69 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
71 FREE_AND_NULL(s->interactive_diff_filter);
72 git_config_get_string("interactive.difffilter",
73 &s->interactive_diff_filter);
75 FREE_AND_NULL(s->interactive_diff_algorithm);
76 git_config_get_string("diff.algorithm",
77 &s->interactive_diff_algorithm);
79 git_config_get_bool("interactive.singlekey", &s->use_single_key);
80 if (s->use_single_key)
81 setbuf(stdin, NULL);
84 void clear_add_i_state(struct add_i_state *s)
86 FREE_AND_NULL(s->interactive_diff_filter);
87 FREE_AND_NULL(s->interactive_diff_algorithm);
88 memset(s, 0, sizeof(*s));
89 s->use_color = -1;
93 * A "prefix item list" is a list of items that are identified by a string, and
94 * a unique prefix (if any) is determined for each item.
96 * It is implemented in the form of a pair of `string_list`s, the first one
97 * duplicating the strings, with the `util` field pointing at a structure whose
98 * first field must be `size_t prefix_length`.
100 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
101 * will be set to zero if no valid, unique prefix could be found.
103 * The second `string_list` is called `sorted` and does _not_ duplicate the
104 * strings but simply reuses the first one's, with the `util` field pointing at
105 * the `string_item_list` of the first `string_list`. It will be populated and
106 * sorted by `find_unique_prefixes()`.
108 struct prefix_item_list {
109 struct string_list items;
110 struct string_list sorted;
111 int *selected; /* for multi-selections */
112 size_t min_length, max_length;
114 #define PREFIX_ITEM_LIST_INIT { \
115 .items = STRING_LIST_INIT_DUP, \
116 .sorted = STRING_LIST_INIT_NODUP, \
117 .min_length = 1, \
118 .max_length = 4, \
121 static void prefix_item_list_clear(struct prefix_item_list *list)
123 string_list_clear(&list->items, 1);
124 string_list_clear(&list->sorted, 0);
125 FREE_AND_NULL(list->selected);
128 static void extend_prefix_length(struct string_list_item *p,
129 const char *other_string, size_t max_length)
131 size_t *len = p->util;
133 if (!*len || memcmp(p->string, other_string, *len))
134 return;
136 for (;;) {
137 char c = p->string[*len];
140 * Is `p` a strict prefix of `other`? Or have we exhausted the
141 * maximal length of the prefix? Or is the current character a
142 * multi-byte UTF-8 one? If so, there is no valid, unique
143 * prefix.
145 if (!c || ++*len > max_length || !isascii(c)) {
146 *len = 0;
147 break;
150 if (c != other_string[*len - 1])
151 break;
155 static void find_unique_prefixes(struct prefix_item_list *list)
157 size_t i;
159 if (list->sorted.nr == list->items.nr)
160 return;
162 string_list_clear(&list->sorted, 0);
163 /* Avoid reallocating incrementally */
164 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
165 list->items.nr));
166 list->sorted.nr = list->sorted.alloc = list->items.nr;
168 for (i = 0; i < list->items.nr; i++) {
169 list->sorted.items[i].string = list->items.items[i].string;
170 list->sorted.items[i].util = list->items.items + i;
173 string_list_sort(&list->sorted);
175 for (i = 0; i < list->sorted.nr; i++) {
176 struct string_list_item *sorted_item = list->sorted.items + i;
177 struct string_list_item *item = sorted_item->util;
178 size_t *len = item->util;
180 *len = 0;
181 while (*len < list->min_length) {
182 char c = item->string[(*len)++];
184 if (!c || !isascii(c)) {
185 *len = 0;
186 break;
190 if (i > 0)
191 extend_prefix_length(item, sorted_item[-1].string,
192 list->max_length);
193 if (i + 1 < list->sorted.nr)
194 extend_prefix_length(item, sorted_item[1].string,
195 list->max_length);
199 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
201 int index = string_list_find_insert_index(&list->sorted, string, 1);
202 struct string_list_item *item;
204 if (list->items.nr != list->sorted.nr)
205 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
206 " vs %"PRIuMAX")",
207 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
209 if (index < 0)
210 item = list->sorted.items[-1 - index].util;
211 else if (index > 0 &&
212 starts_with(list->sorted.items[index - 1].string, string))
213 return -1;
214 else if (index + 1 < list->sorted.nr &&
215 starts_with(list->sorted.items[index + 1].string, string))
216 return -1;
217 else if (index < list->sorted.nr &&
218 starts_with(list->sorted.items[index].string, string))
219 item = list->sorted.items[index].util;
220 else
221 return -1;
222 return item - list->items.items;
225 struct list_options {
226 int columns;
227 const char *header;
228 void (*print_item)(int i, int selected, struct string_list_item *item,
229 void *print_item_data);
230 void *print_item_data;
233 static void list(struct add_i_state *s, struct string_list *list, int *selected,
234 struct list_options *opts)
236 int i, last_lf = 0;
238 if (!list->nr)
239 return;
241 if (opts->header)
242 color_fprintf_ln(stdout, s->header_color,
243 "%s", opts->header);
245 for (i = 0; i < list->nr; i++) {
246 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
247 opts->print_item_data);
249 if ((opts->columns) && ((i + 1) % (opts->columns))) {
250 putchar('\t');
251 last_lf = 0;
253 else {
254 putchar('\n');
255 last_lf = 1;
259 if (!last_lf)
260 putchar('\n');
262 struct list_and_choose_options {
263 struct list_options list_opts;
265 const char *prompt;
266 enum {
267 SINGLETON = (1<<0),
268 IMMEDIATE = (1<<1),
269 } flags;
270 void (*print_help)(struct add_i_state *s);
273 #define LIST_AND_CHOOSE_ERROR (-1)
274 #define LIST_AND_CHOOSE_QUIT (-2)
277 * Returns the selected index in singleton mode, the number of selected items
278 * otherwise.
280 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
281 * `LIST_AND_CHOOSE_QUIT` is returned.
283 static ssize_t list_and_choose(struct add_i_state *s,
284 struct prefix_item_list *items,
285 struct list_and_choose_options *opts)
287 int singleton = opts->flags & SINGLETON;
288 int immediate = opts->flags & IMMEDIATE;
290 struct strbuf input = STRBUF_INIT;
291 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
293 if (!singleton) {
294 free(items->selected);
295 CALLOC_ARRAY(items->selected, items->items.nr);
298 if (singleton && !immediate)
299 BUG("singleton requires immediate");
301 find_unique_prefixes(items);
303 for (;;) {
304 char *p;
306 strbuf_reset(&input);
308 list(s, &items->items, items->selected, &opts->list_opts);
310 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
311 fputs(singleton ? "> " : ">> ", stdout);
312 fflush(stdout);
314 if (git_read_line_interactively(&input) == EOF) {
315 putchar('\n');
316 if (immediate)
317 res = LIST_AND_CHOOSE_QUIT;
318 break;
321 if (!input.len)
322 break;
324 if (!strcmp(input.buf, "?")) {
325 opts->print_help(s);
326 continue;
329 p = input.buf;
330 for (;;) {
331 size_t sep = strcspn(p, " \t\r\n,");
332 int choose = 1;
333 /* `from` is inclusive, `to` is exclusive */
334 ssize_t from = -1, to = -1;
336 if (!sep) {
337 if (!*p)
338 break;
339 p++;
340 continue;
343 /* Input that begins with '-'; de-select */
344 if (*p == '-') {
345 choose = 0;
346 p++;
347 sep--;
350 if (sep == 1 && *p == '*') {
351 from = 0;
352 to = items->items.nr;
353 } else if (isdigit(*p)) {
354 char *endp;
356 * A range can be specified like 5-7 or 5-.
358 * Note: `from` is 0-based while the user input
359 * is 1-based, hence we have to decrement by
360 * one. We do not have to decrement `to` even
361 * if it is 0-based because it is an exclusive
362 * boundary.
364 from = strtoul(p, &endp, 10) - 1;
365 if (endp == p + sep)
366 to = from + 1;
367 else if (*endp == '-') {
368 if (isdigit(*(++endp)))
369 to = strtoul(endp, &endp, 10);
370 else
371 to = items->items.nr;
372 /* extra characters after the range? */
373 if (endp != p + sep)
374 from = -1;
378 if (p[sep])
379 p[sep++] = '\0';
380 if (from < 0) {
381 from = find_unique(p, items);
382 if (from >= 0)
383 to = from + 1;
386 if (from < 0 || from >= items->items.nr ||
387 (singleton && from + 1 != to)) {
388 color_fprintf_ln(stderr, s->error_color,
389 _("Huh (%s)?"), p);
390 break;
391 } else if (singleton) {
392 res = from;
393 break;
396 if (to > items->items.nr)
397 to = items->items.nr;
399 for (; from < to; from++)
400 if (items->selected[from] != choose) {
401 items->selected[from] = choose;
402 res += choose ? +1 : -1;
405 p += sep;
408 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
409 !strcmp(input.buf, "*"))
410 break;
413 strbuf_release(&input);
414 return res;
417 struct adddel {
418 uintmax_t add, del;
419 unsigned seen:1, unmerged:1, binary:1;
422 struct file_item {
423 size_t prefix_length;
424 struct adddel index, worktree;
427 static void add_file_item(struct string_list *files, const char *name)
429 struct file_item *item = xcalloc(1, sizeof(*item));
431 string_list_append(files, name)->util = item;
434 struct pathname_entry {
435 struct hashmap_entry ent;
436 const char *name;
437 struct file_item *item;
440 static int pathname_entry_cmp(const void *cmp_data UNUSED,
441 const struct hashmap_entry *he1,
442 const struct hashmap_entry *he2,
443 const void *name)
445 const struct pathname_entry *e1 =
446 container_of(he1, const struct pathname_entry, ent);
447 const struct pathname_entry *e2 =
448 container_of(he2, const struct pathname_entry, ent);
450 return strcmp(e1->name, name ? (const char *)name : e2->name);
453 struct collection_status {
454 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
456 const char *reference;
458 unsigned skip_unseen:1;
459 size_t unmerged_count, binary_count;
460 struct string_list *files;
461 struct hashmap file_map;
464 static void collect_changes_cb(struct diff_queue_struct *q,
465 struct diff_options *options,
466 void *data)
468 struct collection_status *s = data;
469 struct diffstat_t stat = { 0 };
470 int i;
472 if (!q->nr)
473 return;
475 compute_diffstat(options, &stat, q);
477 for (i = 0; i < stat.nr; i++) {
478 const char *name = stat.files[i]->name;
479 int hash = strhash(name);
480 struct pathname_entry *entry;
481 struct file_item *file_item;
482 struct adddel *adddel, *other_adddel;
484 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
485 struct pathname_entry, ent);
486 if (!entry) {
487 if (s->skip_unseen)
488 continue;
490 add_file_item(s->files, name);
492 CALLOC_ARRAY(entry, 1);
493 hashmap_entry_init(&entry->ent, hash);
494 entry->name = s->files->items[s->files->nr - 1].string;
495 entry->item = s->files->items[s->files->nr - 1].util;
496 hashmap_add(&s->file_map, &entry->ent);
499 file_item = entry->item;
500 adddel = s->mode == FROM_INDEX ?
501 &file_item->index : &file_item->worktree;
502 other_adddel = s->mode == FROM_INDEX ?
503 &file_item->worktree : &file_item->index;
504 adddel->seen = 1;
505 adddel->add = stat.files[i]->added;
506 adddel->del = stat.files[i]->deleted;
507 if (stat.files[i]->is_binary) {
508 if (!other_adddel->binary)
509 s->binary_count++;
510 adddel->binary = 1;
512 if (stat.files[i]->is_unmerged) {
513 if (!other_adddel->unmerged)
514 s->unmerged_count++;
515 adddel->unmerged = 1;
518 free_diffstat_info(&stat);
521 enum modified_files_filter {
522 NO_FILTER = 0,
523 WORKTREE_ONLY = 1,
524 INDEX_ONLY = 2,
527 static int get_modified_files(struct repository *r,
528 enum modified_files_filter filter,
529 struct prefix_item_list *files,
530 const struct pathspec *ps,
531 size_t *unmerged_count,
532 size_t *binary_count)
534 struct object_id head_oid;
535 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
536 "HEAD", RESOLVE_REF_READING,
537 &head_oid, NULL);
538 struct collection_status s = { 0 };
539 int i;
541 discard_index(r->index);
542 if (repo_read_index_preload(r, ps, 0) < 0)
543 return error(_("could not read index"));
545 prefix_item_list_clear(files);
546 s.files = &files->items;
547 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
549 for (i = 0; i < 2; i++) {
550 struct rev_info rev;
551 struct setup_revision_opt opt = { 0 };
553 if (filter == INDEX_ONLY)
554 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
555 else
556 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
557 s.skip_unseen = filter && i;
559 opt.def = is_initial ?
560 empty_tree_oid_hex() : oid_to_hex(&head_oid);
562 repo_init_revisions(r, &rev, NULL);
563 setup_revisions(0, NULL, &rev, &opt);
565 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
566 rev.diffopt.format_callback = collect_changes_cb;
567 rev.diffopt.format_callback_data = &s;
569 if (ps)
570 copy_pathspec(&rev.prune_data, ps);
572 if (s.mode == FROM_INDEX)
573 run_diff_index(&rev, DIFF_INDEX_CACHED);
574 else {
575 rev.diffopt.flags.ignore_dirty_submodules = 1;
576 run_diff_files(&rev, 0);
579 release_revisions(&rev);
581 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
582 if (unmerged_count)
583 *unmerged_count = s.unmerged_count;
584 if (binary_count)
585 *binary_count = s.binary_count;
587 /* While the diffs are ordered already, we ran *two* diffs... */
588 string_list_sort(&files->items);
590 return 0;
593 static void render_adddel(struct strbuf *buf,
594 struct adddel *ad, const char *no_changes)
596 if (ad->binary)
597 strbuf_addstr(buf, _("binary"));
598 else if (ad->seen)
599 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
600 (uintmax_t)ad->add, (uintmax_t)ad->del);
601 else
602 strbuf_addstr(buf, no_changes);
605 /* filters out prefixes which have special meaning to list_and_choose() */
606 static int is_valid_prefix(const char *prefix, size_t prefix_len)
608 return prefix_len && prefix &&
610 * We expect `prefix` to be NUL terminated, therefore this
611 * `strcspn()` call is okay, even if it might do much more
612 * work than strictly necessary.
614 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
615 *prefix != '-' && /* deselection */
616 !isdigit(*prefix) && /* selection */
617 (prefix_len != 1 ||
618 (*prefix != '*' && /* "all" wildcard */
619 *prefix != '?')); /* prompt help */
622 struct print_file_item_data {
623 const char *modified_fmt, *color, *reset;
624 struct strbuf buf, name, index, worktree;
625 unsigned only_names:1;
628 static void print_file_item(int i, int selected, struct string_list_item *item,
629 void *print_file_item_data)
631 struct file_item *c = item->util;
632 struct print_file_item_data *d = print_file_item_data;
633 const char *highlighted = NULL;
635 strbuf_reset(&d->index);
636 strbuf_reset(&d->worktree);
637 strbuf_reset(&d->buf);
639 /* Format the item with the prefix highlighted. */
640 if (c->prefix_length > 0 &&
641 is_valid_prefix(item->string, c->prefix_length)) {
642 strbuf_reset(&d->name);
643 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
644 (int)c->prefix_length, item->string, d->reset,
645 item->string + c->prefix_length);
646 highlighted = d->name.buf;
649 if (d->only_names) {
650 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
651 highlighted ? highlighted : item->string);
652 return;
655 render_adddel(&d->worktree, &c->worktree, _("nothing"));
656 render_adddel(&d->index, &c->index, _("unchanged"));
658 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
659 highlighted ? highlighted : item->string);
661 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
664 static int run_status(struct add_i_state *s, const struct pathspec *ps,
665 struct prefix_item_list *files,
666 struct list_and_choose_options *opts)
668 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
669 return -1;
671 list(s, &files->items, NULL, &opts->list_opts);
672 putchar('\n');
674 return 0;
677 static int run_update(struct add_i_state *s, const struct pathspec *ps,
678 struct prefix_item_list *files,
679 struct list_and_choose_options *opts)
681 int res = 0, fd;
682 size_t count, i;
683 struct lock_file index_lock;
685 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
686 return -1;
688 if (!files->items.nr) {
689 putchar('\n');
690 return 0;
693 opts->prompt = N_("Update");
694 count = list_and_choose(s, files, opts);
695 if (count <= 0) {
696 putchar('\n');
697 return 0;
700 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
701 if (fd < 0) {
702 putchar('\n');
703 return -1;
706 for (i = 0; i < files->items.nr; i++) {
707 const char *name = files->items.items[i].string;
708 struct stat st;
710 if (!files->selected[i])
711 continue;
712 if (lstat(name, &st) && is_missing_file_error(errno)) {
713 if (remove_file_from_index(s->r->index, name) < 0) {
714 res = error(_("could not stage '%s'"), name);
715 break;
717 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
718 res = error(_("could not stage '%s'"), name);
719 break;
723 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
724 res = error(_("could not write index"));
726 if (!res)
727 printf(Q_("updated %d path\n",
728 "updated %d paths\n", count), (int)count);
730 putchar('\n');
731 return res;
734 static void revert_from_diff(struct diff_queue_struct *q,
735 struct diff_options *opt, void *data UNUSED)
737 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
739 for (i = 0; i < q->nr; i++) {
740 struct diff_filespec *one = q->queue[i]->one;
741 struct cache_entry *ce;
743 if (!(one->mode && !is_null_oid(&one->oid))) {
744 remove_file_from_index(opt->repo->index, one->path);
745 printf(_("note: %s is untracked now.\n"), one->path);
746 } else {
747 ce = make_cache_entry(opt->repo->index, one->mode,
748 &one->oid, one->path, 0, 0);
749 if (!ce)
750 die(_("make_cache_entry failed for path '%s'"),
751 one->path);
752 add_index_entry(opt->repo->index, ce, add_flags);
757 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
758 struct prefix_item_list *files,
759 struct list_and_choose_options *opts)
761 int res = 0, fd;
762 size_t count, i, j;
764 struct object_id oid;
765 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
766 "HEAD", RESOLVE_REF_READING,
767 &oid,
768 NULL);
769 struct lock_file index_lock;
770 const char **paths;
771 struct tree *tree;
772 struct diff_options diffopt = { NULL };
774 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
775 return -1;
777 if (!files->items.nr) {
778 putchar('\n');
779 return 0;
782 opts->prompt = N_("Revert");
783 count = list_and_choose(s, files, opts);
784 if (count <= 0)
785 goto finish_revert;
787 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
788 if (fd < 0) {
789 res = -1;
790 goto finish_revert;
793 if (is_initial)
794 oidcpy(&oid, s->r->hash_algo->empty_tree);
795 else {
796 tree = parse_tree_indirect(&oid);
797 if (!tree) {
798 res = error(_("Could not parse HEAD^{tree}"));
799 goto finish_revert;
801 oidcpy(&oid, &tree->object.oid);
804 ALLOC_ARRAY(paths, count + 1);
805 for (i = j = 0; i < files->items.nr; i++)
806 if (files->selected[i])
807 paths[j++] = files->items.items[i].string;
808 paths[j] = NULL;
810 parse_pathspec(&diffopt.pathspec, 0,
811 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
812 NULL, paths);
814 diffopt.output_format = DIFF_FORMAT_CALLBACK;
815 diffopt.format_callback = revert_from_diff;
816 diffopt.flags.override_submodule_config = 1;
817 diffopt.repo = s->r;
819 if (do_diff_cache(&oid, &diffopt)) {
820 diff_free(&diffopt);
821 res = -1;
822 } else {
823 diffcore_std(&diffopt);
824 diff_flush(&diffopt);
826 free(paths);
828 if (!res && write_locked_index(s->r->index, &index_lock,
829 COMMIT_LOCK) < 0)
830 res = -1;
831 else
832 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
833 NULL, NULL, NULL);
835 if (!res)
836 printf(Q_("reverted %d path\n",
837 "reverted %d paths\n", count), (int)count);
839 finish_revert:
840 putchar('\n');
841 return res;
844 static int get_untracked_files(struct repository *r,
845 struct prefix_item_list *files,
846 const struct pathspec *ps)
848 struct dir_struct dir = { 0 };
849 size_t i;
850 struct strbuf buf = STRBUF_INIT;
852 if (repo_read_index(r) < 0)
853 return error(_("could not read index"));
855 prefix_item_list_clear(files);
856 setup_standard_excludes(&dir);
857 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
858 fill_directory(&dir, r->index, ps);
860 for (i = 0; i < dir.nr; i++) {
861 struct dir_entry *ent = dir.entries[i];
863 if (index_name_is_other(r->index, ent->name, ent->len)) {
864 strbuf_reset(&buf);
865 strbuf_add(&buf, ent->name, ent->len);
866 add_file_item(&files->items, buf.buf);
870 strbuf_release(&buf);
871 dir_clear(&dir);
872 return 0;
875 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
876 struct prefix_item_list *files,
877 struct list_and_choose_options *opts)
879 struct print_file_item_data *d = opts->list_opts.print_item_data;
880 int res = 0, fd;
881 size_t count, i;
882 struct lock_file index_lock;
884 if (get_untracked_files(s->r, files, ps) < 0)
885 return -1;
887 if (!files->items.nr) {
888 printf(_("No untracked files.\n"));
889 goto finish_add_untracked;
892 opts->prompt = N_("Add untracked");
893 d->only_names = 1;
894 count = list_and_choose(s, files, opts);
895 d->only_names = 0;
896 if (count <= 0)
897 goto finish_add_untracked;
899 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
900 if (fd < 0) {
901 res = -1;
902 goto finish_add_untracked;
905 for (i = 0; i < files->items.nr; i++) {
906 const char *name = files->items.items[i].string;
907 if (files->selected[i] &&
908 add_file_to_index(s->r->index, name, 0) < 0) {
909 res = error(_("could not stage '%s'"), name);
910 break;
914 if (!res &&
915 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
916 res = error(_("could not write index"));
918 if (!res)
919 printf(Q_("added %d path\n",
920 "added %d paths\n", count), (int)count);
922 finish_add_untracked:
923 putchar('\n');
924 return res;
927 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
928 struct prefix_item_list *files,
929 struct list_and_choose_options *opts)
931 int res = 0;
932 ssize_t count, i, j;
933 size_t unmerged_count = 0, binary_count = 0;
935 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
936 &unmerged_count, &binary_count) < 0)
937 return -1;
939 if (unmerged_count || binary_count) {
940 for (i = j = 0; i < files->items.nr; i++) {
941 struct file_item *item = files->items.items[i].util;
943 if (item->index.binary || item->worktree.binary) {
944 free(item);
945 free(files->items.items[i].string);
946 } else if (item->index.unmerged ||
947 item->worktree.unmerged) {
948 color_fprintf_ln(stderr, s->error_color,
949 _("ignoring unmerged: %s"),
950 files->items.items[i].string);
951 free(item);
952 free(files->items.items[i].string);
953 } else
954 files->items.items[j++] = files->items.items[i];
956 files->items.nr = j;
959 if (!files->items.nr) {
960 if (binary_count)
961 fprintf(stderr, _("Only binary files changed.\n"));
962 else
963 fprintf(stderr, _("No changes.\n"));
964 return 0;
967 opts->prompt = N_("Patch update");
968 count = list_and_choose(s, files, opts);
969 if (count > 0) {
970 struct strvec args = STRVEC_INIT;
971 struct pathspec ps_selected = { 0 };
973 for (i = 0; i < files->items.nr; i++)
974 if (files->selected[i])
975 strvec_push(&args,
976 files->items.items[i].string);
977 parse_pathspec(&ps_selected,
978 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
979 PATHSPEC_LITERAL_PATH, "", args.v);
980 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
981 strvec_clear(&args);
982 clear_pathspec(&ps_selected);
985 return res;
988 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
989 struct prefix_item_list *files,
990 struct list_and_choose_options *opts)
992 int res = 0;
993 ssize_t count, i;
995 struct object_id oid;
996 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
997 "HEAD", RESOLVE_REF_READING,
998 &oid,
999 NULL);
1000 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
1001 return -1;
1003 if (!files->items.nr) {
1004 putchar('\n');
1005 return 0;
1008 opts->prompt = N_("Review diff");
1009 opts->flags = IMMEDIATE;
1010 count = list_and_choose(s, files, opts);
1011 opts->flags = 0;
1012 if (count > 0) {
1013 struct child_process cmd = CHILD_PROCESS_INIT;
1015 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
1016 oid_to_hex(!is_initial ? &oid :
1017 s->r->hash_algo->empty_tree),
1018 "--", NULL);
1019 for (i = 0; i < files->items.nr; i++)
1020 if (files->selected[i])
1021 strvec_push(&cmd.args,
1022 files->items.items[i].string);
1023 res = run_command(&cmd);
1026 putchar('\n');
1027 return res;
1030 static int run_help(struct add_i_state *s, const struct pathspec *ps UNUSED,
1031 struct prefix_item_list *files UNUSED,
1032 struct list_and_choose_options *opts UNUSED)
1034 color_fprintf_ln(stdout, s->help_color, "status - %s",
1035 _("show paths with changes"));
1036 color_fprintf_ln(stdout, s->help_color, "update - %s",
1037 _("add working tree state to the staged set of changes"));
1038 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1039 _("revert staged set of changes back to the HEAD version"));
1040 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1041 _("pick hunks and update selectively"));
1042 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1043 _("view diff between HEAD and index"));
1044 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1045 _("add contents of untracked files to the staged set of changes"));
1047 return 0;
1050 static void choose_prompt_help(struct add_i_state *s)
1052 color_fprintf_ln(stdout, s->help_color, "%s",
1053 _("Prompt help:"));
1054 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1055 _("select a single item"));
1056 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1057 _("select a range of items"));
1058 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1059 _("select multiple ranges"));
1060 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1061 _("select item based on unique prefix"));
1062 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1063 _("unselect specified items"));
1064 color_fprintf_ln(stdout, s->help_color, "* - %s",
1065 _("choose all items"));
1066 color_fprintf_ln(stdout, s->help_color, " - %s",
1067 _("(empty) finish selecting"));
1070 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1071 struct prefix_item_list *files,
1072 struct list_and_choose_options *opts);
1074 struct command_item {
1075 size_t prefix_length;
1076 command_t command;
1079 struct print_command_item_data {
1080 const char *color, *reset;
1083 static void print_command_item(int i, int selected UNUSED,
1084 struct string_list_item *item,
1085 void *print_command_item_data)
1087 struct print_command_item_data *d = print_command_item_data;
1088 struct command_item *util = item->util;
1090 if (!util->prefix_length ||
1091 !is_valid_prefix(item->string, util->prefix_length))
1092 printf(" %2d: %s", i + 1, item->string);
1093 else
1094 printf(" %2d: %s%.*s%s%s", i + 1,
1095 d->color, (int)util->prefix_length, item->string,
1096 d->reset, item->string + util->prefix_length);
1099 static void command_prompt_help(struct add_i_state *s)
1101 const char *help_color = s->help_color;
1102 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1103 color_fprintf_ln(stdout, help_color, "1 - %s",
1104 _("select a numbered item"));
1105 color_fprintf_ln(stdout, help_color, "foo - %s",
1106 _("select item based on unique prefix"));
1107 color_fprintf_ln(stdout, help_color, " - %s",
1108 _("(empty) select nothing"));
1111 int run_add_i(struct repository *r, const struct pathspec *ps)
1113 struct add_i_state s = { NULL };
1114 struct print_command_item_data data = { "[", "]" };
1115 struct list_and_choose_options main_loop_opts = {
1116 { 4, N_("*** Commands ***"), print_command_item, &data },
1117 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1119 struct {
1120 const char *string;
1121 command_t command;
1122 } command_list[] = {
1123 { "status", run_status },
1124 { "update", run_update },
1125 { "revert", run_revert },
1126 { "add untracked", run_add_untracked },
1127 { "patch", run_patch },
1128 { "diff", run_diff },
1129 { "quit", NULL },
1130 { "help", run_help },
1132 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1134 struct print_file_item_data print_file_item_data = {
1135 "%12s %12s %s", NULL, NULL,
1136 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1138 struct list_and_choose_options opts = {
1139 { 0, NULL, print_file_item, &print_file_item_data },
1140 NULL, 0, choose_prompt_help
1142 struct strbuf header = STRBUF_INIT;
1143 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1144 ssize_t i;
1145 int res = 0;
1147 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1148 struct command_item *util = xcalloc(1, sizeof(*util));
1149 util->command = command_list[i].command;
1150 string_list_append(&commands.items, command_list[i].string)
1151 ->util = util;
1154 init_add_i_state(&s, r);
1157 * When color was asked for, use the prompt color for
1158 * highlighting, otherwise use square brackets.
1160 if (s.use_color) {
1161 data.color = s.prompt_color;
1162 data.reset = s.reset_color;
1164 print_file_item_data.color = data.color;
1165 print_file_item_data.reset = data.reset;
1167 strbuf_addstr(&header, " ");
1168 strbuf_addf(&header, print_file_item_data.modified_fmt,
1169 _("staged"), _("unstaged"), _("path"));
1170 opts.list_opts.header = header.buf;
1172 discard_index(r->index);
1173 if (repo_read_index(r) < 0 ||
1174 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1175 NULL, NULL, NULL) < 0)
1176 warning(_("could not refresh index"));
1178 res = run_status(&s, ps, &files, &opts);
1180 for (;;) {
1181 struct command_item *util;
1183 i = list_and_choose(&s, &commands, &main_loop_opts);
1184 if (i < 0 || i >= commands.items.nr)
1185 util = NULL;
1186 else
1187 util = commands.items.items[i].util;
1189 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1190 printf(_("Bye.\n"));
1191 res = 0;
1192 break;
1195 if (util)
1196 res = util->command(&s, ps, &files, &opts);
1199 prefix_item_list_clear(&files);
1200 strbuf_release(&print_file_item_data.buf);
1201 strbuf_release(&print_file_item_data.name);
1202 strbuf_release(&print_file_item_data.index);
1203 strbuf_release(&print_file_item_data.worktree);
1204 strbuf_release(&header);
1205 prefix_item_list_clear(&commands);
1206 clear_add_i_state(&s);
1208 return res;