read-cache*.h: move declarations for read-cache.c functions from cache.h
[alt-git.git] / add-interactive.c
bloba9671e33491fb17b266af4c4e16f0346bd23c977
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "color.h"
4 #include "config.h"
5 #include "diffcore.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "preload-index.h"
9 #include "read-cache-ll.h"
10 #include "revision.h"
11 #include "refs.h"
12 #include "string-list.h"
13 #include "lockfile.h"
14 #include "dir.h"
15 #include "run-command.h"
16 #include "prompt.h"
17 #include "tree.h"
19 static void init_color(struct repository *r, struct add_i_state *s,
20 const char *section_and_slot, char *dst,
21 const char *default_color)
23 char *key = xstrfmt("color.%s", section_and_slot);
24 const char *value;
26 if (!s->use_color)
27 dst[0] = '\0';
28 else if (repo_config_get_value(r, key, &value) ||
29 color_parse(value, dst))
30 strlcpy(dst, default_color, COLOR_MAXLEN);
32 free(key);
35 void init_add_i_state(struct add_i_state *s, struct repository *r)
37 const char *value;
39 s->r = r;
41 if (repo_config_get_value(r, "color.interactive", &value))
42 s->use_color = -1;
43 else
44 s->use_color =
45 git_config_colorbool("color.interactive", value);
46 s->use_color = want_color(s->use_color);
48 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
49 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
50 init_color(r, s, "interactive.prompt", s->prompt_color,
51 GIT_COLOR_BOLD_BLUE);
52 init_color(r, s, "interactive.error", s->error_color,
53 GIT_COLOR_BOLD_RED);
55 init_color(r, s, "diff.frag", s->fraginfo_color,
56 diff_get_color(s->use_color, DIFF_FRAGINFO));
57 init_color(r, s, "diff.context", s->context_color, "fall back");
58 if (!strcmp(s->context_color, "fall back"))
59 init_color(r, s, "diff.plain", s->context_color,
60 diff_get_color(s->use_color, DIFF_CONTEXT));
61 init_color(r, s, "diff.old", s->file_old_color,
62 diff_get_color(s->use_color, DIFF_FILE_OLD));
63 init_color(r, s, "diff.new", s->file_new_color,
64 diff_get_color(s->use_color, DIFF_FILE_NEW));
66 strlcpy(s->reset_color,
67 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
69 FREE_AND_NULL(s->interactive_diff_filter);
70 git_config_get_string("interactive.difffilter",
71 &s->interactive_diff_filter);
73 FREE_AND_NULL(s->interactive_diff_algorithm);
74 git_config_get_string("diff.algorithm",
75 &s->interactive_diff_algorithm);
77 git_config_get_bool("interactive.singlekey", &s->use_single_key);
78 if (s->use_single_key)
79 setbuf(stdin, NULL);
82 void clear_add_i_state(struct add_i_state *s)
84 FREE_AND_NULL(s->interactive_diff_filter);
85 FREE_AND_NULL(s->interactive_diff_algorithm);
86 memset(s, 0, sizeof(*s));
87 s->use_color = -1;
91 * A "prefix item list" is a list of items that are identified by a string, and
92 * a unique prefix (if any) is determined for each item.
94 * It is implemented in the form of a pair of `string_list`s, the first one
95 * duplicating the strings, with the `util` field pointing at a structure whose
96 * first field must be `size_t prefix_length`.
98 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
99 * will be set to zero if no valid, unique prefix could be found.
101 * The second `string_list` is called `sorted` and does _not_ duplicate the
102 * strings but simply reuses the first one's, with the `util` field pointing at
103 * the `string_item_list` of the first `string_list`. It will be populated and
104 * sorted by `find_unique_prefixes()`.
106 struct prefix_item_list {
107 struct string_list items;
108 struct string_list sorted;
109 int *selected; /* for multi-selections */
110 size_t min_length, max_length;
112 #define PREFIX_ITEM_LIST_INIT { \
113 .items = STRING_LIST_INIT_DUP, \
114 .sorted = STRING_LIST_INIT_NODUP, \
115 .min_length = 1, \
116 .max_length = 4, \
119 static void prefix_item_list_clear(struct prefix_item_list *list)
121 string_list_clear(&list->items, 1);
122 string_list_clear(&list->sorted, 0);
123 FREE_AND_NULL(list->selected);
126 static void extend_prefix_length(struct string_list_item *p,
127 const char *other_string, size_t max_length)
129 size_t *len = p->util;
131 if (!*len || memcmp(p->string, other_string, *len))
132 return;
134 for (;;) {
135 char c = p->string[*len];
138 * Is `p` a strict prefix of `other`? Or have we exhausted the
139 * maximal length of the prefix? Or is the current character a
140 * multi-byte UTF-8 one? If so, there is no valid, unique
141 * prefix.
143 if (!c || ++*len > max_length || !isascii(c)) {
144 *len = 0;
145 break;
148 if (c != other_string[*len - 1])
149 break;
153 static void find_unique_prefixes(struct prefix_item_list *list)
155 size_t i;
157 if (list->sorted.nr == list->items.nr)
158 return;
160 string_list_clear(&list->sorted, 0);
161 /* Avoid reallocating incrementally */
162 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
163 list->items.nr));
164 list->sorted.nr = list->sorted.alloc = list->items.nr;
166 for (i = 0; i < list->items.nr; i++) {
167 list->sorted.items[i].string = list->items.items[i].string;
168 list->sorted.items[i].util = list->items.items + i;
171 string_list_sort(&list->sorted);
173 for (i = 0; i < list->sorted.nr; i++) {
174 struct string_list_item *sorted_item = list->sorted.items + i;
175 struct string_list_item *item = sorted_item->util;
176 size_t *len = item->util;
178 *len = 0;
179 while (*len < list->min_length) {
180 char c = item->string[(*len)++];
182 if (!c || !isascii(c)) {
183 *len = 0;
184 break;
188 if (i > 0)
189 extend_prefix_length(item, sorted_item[-1].string,
190 list->max_length);
191 if (i + 1 < list->sorted.nr)
192 extend_prefix_length(item, sorted_item[1].string,
193 list->max_length);
197 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
199 int index = string_list_find_insert_index(&list->sorted, string, 1);
200 struct string_list_item *item;
202 if (list->items.nr != list->sorted.nr)
203 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
204 " vs %"PRIuMAX")",
205 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
207 if (index < 0)
208 item = list->sorted.items[-1 - index].util;
209 else if (index > 0 &&
210 starts_with(list->sorted.items[index - 1].string, string))
211 return -1;
212 else if (index + 1 < list->sorted.nr &&
213 starts_with(list->sorted.items[index + 1].string, string))
214 return -1;
215 else if (index < list->sorted.nr &&
216 starts_with(list->sorted.items[index].string, string))
217 item = list->sorted.items[index].util;
218 else
219 return -1;
220 return item - list->items.items;
223 struct list_options {
224 int columns;
225 const char *header;
226 void (*print_item)(int i, int selected, struct string_list_item *item,
227 void *print_item_data);
228 void *print_item_data;
231 static void list(struct add_i_state *s, struct string_list *list, int *selected,
232 struct list_options *opts)
234 int i, last_lf = 0;
236 if (!list->nr)
237 return;
239 if (opts->header)
240 color_fprintf_ln(stdout, s->header_color,
241 "%s", opts->header);
243 for (i = 0; i < list->nr; i++) {
244 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
245 opts->print_item_data);
247 if ((opts->columns) && ((i + 1) % (opts->columns))) {
248 putchar('\t');
249 last_lf = 0;
251 else {
252 putchar('\n');
253 last_lf = 1;
257 if (!last_lf)
258 putchar('\n');
260 struct list_and_choose_options {
261 struct list_options list_opts;
263 const char *prompt;
264 enum {
265 SINGLETON = (1<<0),
266 IMMEDIATE = (1<<1),
267 } flags;
268 void (*print_help)(struct add_i_state *s);
271 #define LIST_AND_CHOOSE_ERROR (-1)
272 #define LIST_AND_CHOOSE_QUIT (-2)
275 * Returns the selected index in singleton mode, the number of selected items
276 * otherwise.
278 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
279 * `LIST_AND_CHOOSE_QUIT` is returned.
281 static ssize_t list_and_choose(struct add_i_state *s,
282 struct prefix_item_list *items,
283 struct list_and_choose_options *opts)
285 int singleton = opts->flags & SINGLETON;
286 int immediate = opts->flags & IMMEDIATE;
288 struct strbuf input = STRBUF_INIT;
289 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
291 if (!singleton) {
292 free(items->selected);
293 CALLOC_ARRAY(items->selected, items->items.nr);
296 if (singleton && !immediate)
297 BUG("singleton requires immediate");
299 find_unique_prefixes(items);
301 for (;;) {
302 char *p;
304 strbuf_reset(&input);
306 list(s, &items->items, items->selected, &opts->list_opts);
308 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
309 fputs(singleton ? "> " : ">> ", stdout);
310 fflush(stdout);
312 if (git_read_line_interactively(&input) == EOF) {
313 putchar('\n');
314 if (immediate)
315 res = LIST_AND_CHOOSE_QUIT;
316 break;
319 if (!input.len)
320 break;
322 if (!strcmp(input.buf, "?")) {
323 opts->print_help(s);
324 continue;
327 p = input.buf;
328 for (;;) {
329 size_t sep = strcspn(p, " \t\r\n,");
330 int choose = 1;
331 /* `from` is inclusive, `to` is exclusive */
332 ssize_t from = -1, to = -1;
334 if (!sep) {
335 if (!*p)
336 break;
337 p++;
338 continue;
341 /* Input that begins with '-'; de-select */
342 if (*p == '-') {
343 choose = 0;
344 p++;
345 sep--;
348 if (sep == 1 && *p == '*') {
349 from = 0;
350 to = items->items.nr;
351 } else if (isdigit(*p)) {
352 char *endp;
354 * A range can be specified like 5-7 or 5-.
356 * Note: `from` is 0-based while the user input
357 * is 1-based, hence we have to decrement by
358 * one. We do not have to decrement `to` even
359 * if it is 0-based because it is an exclusive
360 * boundary.
362 from = strtoul(p, &endp, 10) - 1;
363 if (endp == p + sep)
364 to = from + 1;
365 else if (*endp == '-') {
366 if (isdigit(*(++endp)))
367 to = strtoul(endp, &endp, 10);
368 else
369 to = items->items.nr;
370 /* extra characters after the range? */
371 if (endp != p + sep)
372 from = -1;
376 if (p[sep])
377 p[sep++] = '\0';
378 if (from < 0) {
379 from = find_unique(p, items);
380 if (from >= 0)
381 to = from + 1;
384 if (from < 0 || from >= items->items.nr ||
385 (singleton && from + 1 != to)) {
386 color_fprintf_ln(stderr, s->error_color,
387 _("Huh (%s)?"), p);
388 break;
389 } else if (singleton) {
390 res = from;
391 break;
394 if (to > items->items.nr)
395 to = items->items.nr;
397 for (; from < to; from++)
398 if (items->selected[from] != choose) {
399 items->selected[from] = choose;
400 res += choose ? +1 : -1;
403 p += sep;
406 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
407 !strcmp(input.buf, "*"))
408 break;
411 strbuf_release(&input);
412 return res;
415 struct adddel {
416 uintmax_t add, del;
417 unsigned seen:1, unmerged:1, binary:1;
420 struct file_item {
421 size_t prefix_length;
422 struct adddel index, worktree;
425 static void add_file_item(struct string_list *files, const char *name)
427 struct file_item *item = xcalloc(1, sizeof(*item));
429 string_list_append(files, name)->util = item;
432 struct pathname_entry {
433 struct hashmap_entry ent;
434 const char *name;
435 struct file_item *item;
438 static int pathname_entry_cmp(const void *cmp_data UNUSED,
439 const struct hashmap_entry *he1,
440 const struct hashmap_entry *he2,
441 const void *name)
443 const struct pathname_entry *e1 =
444 container_of(he1, const struct pathname_entry, ent);
445 const struct pathname_entry *e2 =
446 container_of(he2, const struct pathname_entry, ent);
448 return strcmp(e1->name, name ? (const char *)name : e2->name);
451 struct collection_status {
452 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
454 const char *reference;
456 unsigned skip_unseen:1;
457 size_t unmerged_count, binary_count;
458 struct string_list *files;
459 struct hashmap file_map;
462 static void collect_changes_cb(struct diff_queue_struct *q,
463 struct diff_options *options,
464 void *data)
466 struct collection_status *s = data;
467 struct diffstat_t stat = { 0 };
468 int i;
470 if (!q->nr)
471 return;
473 compute_diffstat(options, &stat, q);
475 for (i = 0; i < stat.nr; i++) {
476 const char *name = stat.files[i]->name;
477 int hash = strhash(name);
478 struct pathname_entry *entry;
479 struct file_item *file_item;
480 struct adddel *adddel, *other_adddel;
482 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
483 struct pathname_entry, ent);
484 if (!entry) {
485 if (s->skip_unseen)
486 continue;
488 add_file_item(s->files, name);
490 CALLOC_ARRAY(entry, 1);
491 hashmap_entry_init(&entry->ent, hash);
492 entry->name = s->files->items[s->files->nr - 1].string;
493 entry->item = s->files->items[s->files->nr - 1].util;
494 hashmap_add(&s->file_map, &entry->ent);
497 file_item = entry->item;
498 adddel = s->mode == FROM_INDEX ?
499 &file_item->index : &file_item->worktree;
500 other_adddel = s->mode == FROM_INDEX ?
501 &file_item->worktree : &file_item->index;
502 adddel->seen = 1;
503 adddel->add = stat.files[i]->added;
504 adddel->del = stat.files[i]->deleted;
505 if (stat.files[i]->is_binary) {
506 if (!other_adddel->binary)
507 s->binary_count++;
508 adddel->binary = 1;
510 if (stat.files[i]->is_unmerged) {
511 if (!other_adddel->unmerged)
512 s->unmerged_count++;
513 adddel->unmerged = 1;
516 free_diffstat_info(&stat);
519 enum modified_files_filter {
520 NO_FILTER = 0,
521 WORKTREE_ONLY = 1,
522 INDEX_ONLY = 2,
525 static int get_modified_files(struct repository *r,
526 enum modified_files_filter filter,
527 struct prefix_item_list *files,
528 const struct pathspec *ps,
529 size_t *unmerged_count,
530 size_t *binary_count)
532 struct object_id head_oid;
533 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
534 &head_oid, NULL);
535 struct collection_status s = { 0 };
536 int i;
538 discard_index(r->index);
539 if (repo_read_index_preload(r, ps, 0) < 0)
540 return error(_("could not read index"));
542 prefix_item_list_clear(files);
543 s.files = &files->items;
544 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
546 for (i = 0; i < 2; i++) {
547 struct rev_info rev;
548 struct setup_revision_opt opt = { 0 };
550 if (filter == INDEX_ONLY)
551 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
552 else
553 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
554 s.skip_unseen = filter && i;
556 opt.def = is_initial ?
557 empty_tree_oid_hex() : oid_to_hex(&head_oid);
559 repo_init_revisions(r, &rev, NULL);
560 setup_revisions(0, NULL, &rev, &opt);
562 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
563 rev.diffopt.format_callback = collect_changes_cb;
564 rev.diffopt.format_callback_data = &s;
566 if (ps)
567 copy_pathspec(&rev.prune_data, ps);
569 if (s.mode == FROM_INDEX)
570 run_diff_index(&rev, 1);
571 else {
572 rev.diffopt.flags.ignore_dirty_submodules = 1;
573 run_diff_files(&rev, 0);
576 release_revisions(&rev);
578 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
579 if (unmerged_count)
580 *unmerged_count = s.unmerged_count;
581 if (binary_count)
582 *binary_count = s.binary_count;
584 /* While the diffs are ordered already, we ran *two* diffs... */
585 string_list_sort(&files->items);
587 return 0;
590 static void render_adddel(struct strbuf *buf,
591 struct adddel *ad, const char *no_changes)
593 if (ad->binary)
594 strbuf_addstr(buf, _("binary"));
595 else if (ad->seen)
596 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
597 (uintmax_t)ad->add, (uintmax_t)ad->del);
598 else
599 strbuf_addstr(buf, no_changes);
602 /* filters out prefixes which have special meaning to list_and_choose() */
603 static int is_valid_prefix(const char *prefix, size_t prefix_len)
605 return prefix_len && prefix &&
607 * We expect `prefix` to be NUL terminated, therefore this
608 * `strcspn()` call is okay, even if it might do much more
609 * work than strictly necessary.
611 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
612 *prefix != '-' && /* deselection */
613 !isdigit(*prefix) && /* selection */
614 (prefix_len != 1 ||
615 (*prefix != '*' && /* "all" wildcard */
616 *prefix != '?')); /* prompt help */
619 struct print_file_item_data {
620 const char *modified_fmt, *color, *reset;
621 struct strbuf buf, name, index, worktree;
622 unsigned only_names:1;
625 static void print_file_item(int i, int selected, struct string_list_item *item,
626 void *print_file_item_data)
628 struct file_item *c = item->util;
629 struct print_file_item_data *d = print_file_item_data;
630 const char *highlighted = NULL;
632 strbuf_reset(&d->index);
633 strbuf_reset(&d->worktree);
634 strbuf_reset(&d->buf);
636 /* Format the item with the prefix highlighted. */
637 if (c->prefix_length > 0 &&
638 is_valid_prefix(item->string, c->prefix_length)) {
639 strbuf_reset(&d->name);
640 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
641 (int)c->prefix_length, item->string, d->reset,
642 item->string + c->prefix_length);
643 highlighted = d->name.buf;
646 if (d->only_names) {
647 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
648 highlighted ? highlighted : item->string);
649 return;
652 render_adddel(&d->worktree, &c->worktree, _("nothing"));
653 render_adddel(&d->index, &c->index, _("unchanged"));
655 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
656 highlighted ? highlighted : item->string);
658 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
661 static int run_status(struct add_i_state *s, const struct pathspec *ps,
662 struct prefix_item_list *files,
663 struct list_and_choose_options *opts)
665 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
666 return -1;
668 list(s, &files->items, NULL, &opts->list_opts);
669 putchar('\n');
671 return 0;
674 static int run_update(struct add_i_state *s, const struct pathspec *ps,
675 struct prefix_item_list *files,
676 struct list_and_choose_options *opts)
678 int res = 0, fd;
679 size_t count, i;
680 struct lock_file index_lock;
682 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
683 return -1;
685 if (!files->items.nr) {
686 putchar('\n');
687 return 0;
690 opts->prompt = N_("Update");
691 count = list_and_choose(s, files, opts);
692 if (count <= 0) {
693 putchar('\n');
694 return 0;
697 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
698 if (fd < 0) {
699 putchar('\n');
700 return -1;
703 for (i = 0; i < files->items.nr; i++) {
704 const char *name = files->items.items[i].string;
705 struct stat st;
707 if (!files->selected[i])
708 continue;
709 if (lstat(name, &st) && is_missing_file_error(errno)) {
710 if (remove_file_from_index(s->r->index, name) < 0) {
711 res = error(_("could not stage '%s'"), name);
712 break;
714 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
715 res = error(_("could not stage '%s'"), name);
716 break;
720 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
721 res = error(_("could not write index"));
723 if (!res)
724 printf(Q_("updated %d path\n",
725 "updated %d paths\n", count), (int)count);
727 putchar('\n');
728 return res;
731 static void revert_from_diff(struct diff_queue_struct *q,
732 struct diff_options *opt, void *data UNUSED)
734 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
736 for (i = 0; i < q->nr; i++) {
737 struct diff_filespec *one = q->queue[i]->one;
738 struct cache_entry *ce;
740 if (!(one->mode && !is_null_oid(&one->oid))) {
741 remove_file_from_index(opt->repo->index, one->path);
742 printf(_("note: %s is untracked now.\n"), one->path);
743 } else {
744 ce = make_cache_entry(opt->repo->index, one->mode,
745 &one->oid, one->path, 0, 0);
746 if (!ce)
747 die(_("make_cache_entry failed for path '%s'"),
748 one->path);
749 add_index_entry(opt->repo->index, ce, add_flags);
754 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
755 struct prefix_item_list *files,
756 struct list_and_choose_options *opts)
758 int res = 0, fd;
759 size_t count, i, j;
761 struct object_id oid;
762 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
763 NULL);
764 struct lock_file index_lock;
765 const char **paths;
766 struct tree *tree;
767 struct diff_options diffopt = { NULL };
769 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
770 return -1;
772 if (!files->items.nr) {
773 putchar('\n');
774 return 0;
777 opts->prompt = N_("Revert");
778 count = list_and_choose(s, files, opts);
779 if (count <= 0)
780 goto finish_revert;
782 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
783 if (fd < 0) {
784 res = -1;
785 goto finish_revert;
788 if (is_initial)
789 oidcpy(&oid, s->r->hash_algo->empty_tree);
790 else {
791 tree = parse_tree_indirect(&oid);
792 if (!tree) {
793 res = error(_("Could not parse HEAD^{tree}"));
794 goto finish_revert;
796 oidcpy(&oid, &tree->object.oid);
799 ALLOC_ARRAY(paths, count + 1);
800 for (i = j = 0; i < files->items.nr; i++)
801 if (files->selected[i])
802 paths[j++] = files->items.items[i].string;
803 paths[j] = NULL;
805 parse_pathspec(&diffopt.pathspec, 0,
806 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
807 NULL, paths);
809 diffopt.output_format = DIFF_FORMAT_CALLBACK;
810 diffopt.format_callback = revert_from_diff;
811 diffopt.flags.override_submodule_config = 1;
812 diffopt.repo = s->r;
814 if (do_diff_cache(&oid, &diffopt)) {
815 diff_free(&diffopt);
816 res = -1;
817 } else {
818 diffcore_std(&diffopt);
819 diff_flush(&diffopt);
821 free(paths);
823 if (!res && write_locked_index(s->r->index, &index_lock,
824 COMMIT_LOCK) < 0)
825 res = -1;
826 else
827 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
828 NULL, NULL, NULL);
830 if (!res)
831 printf(Q_("reverted %d path\n",
832 "reverted %d paths\n", count), (int)count);
834 finish_revert:
835 putchar('\n');
836 return res;
839 static int get_untracked_files(struct repository *r,
840 struct prefix_item_list *files,
841 const struct pathspec *ps)
843 struct dir_struct dir = { 0 };
844 size_t i;
845 struct strbuf buf = STRBUF_INIT;
847 if (repo_read_index(r) < 0)
848 return error(_("could not read index"));
850 prefix_item_list_clear(files);
851 setup_standard_excludes(&dir);
852 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
853 fill_directory(&dir, r->index, ps);
855 for (i = 0; i < dir.nr; i++) {
856 struct dir_entry *ent = dir.entries[i];
858 if (index_name_is_other(r->index, ent->name, ent->len)) {
859 strbuf_reset(&buf);
860 strbuf_add(&buf, ent->name, ent->len);
861 add_file_item(&files->items, buf.buf);
865 strbuf_release(&buf);
866 return 0;
869 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
870 struct prefix_item_list *files,
871 struct list_and_choose_options *opts)
873 struct print_file_item_data *d = opts->list_opts.print_item_data;
874 int res = 0, fd;
875 size_t count, i;
876 struct lock_file index_lock;
878 if (get_untracked_files(s->r, files, ps) < 0)
879 return -1;
881 if (!files->items.nr) {
882 printf(_("No untracked files.\n"));
883 goto finish_add_untracked;
886 opts->prompt = N_("Add untracked");
887 d->only_names = 1;
888 count = list_and_choose(s, files, opts);
889 d->only_names = 0;
890 if (count <= 0)
891 goto finish_add_untracked;
893 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
894 if (fd < 0) {
895 res = -1;
896 goto finish_add_untracked;
899 for (i = 0; i < files->items.nr; i++) {
900 const char *name = files->items.items[i].string;
901 if (files->selected[i] &&
902 add_file_to_index(s->r->index, name, 0) < 0) {
903 res = error(_("could not stage '%s'"), name);
904 break;
908 if (!res &&
909 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
910 res = error(_("could not write index"));
912 if (!res)
913 printf(Q_("added %d path\n",
914 "added %d paths\n", count), (int)count);
916 finish_add_untracked:
917 putchar('\n');
918 return res;
921 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
922 struct prefix_item_list *files,
923 struct list_and_choose_options *opts)
925 int res = 0;
926 ssize_t count, i, j;
927 size_t unmerged_count = 0, binary_count = 0;
929 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
930 &unmerged_count, &binary_count) < 0)
931 return -1;
933 if (unmerged_count || binary_count) {
934 for (i = j = 0; i < files->items.nr; i++) {
935 struct file_item *item = files->items.items[i].util;
937 if (item->index.binary || item->worktree.binary) {
938 free(item);
939 free(files->items.items[i].string);
940 } else if (item->index.unmerged ||
941 item->worktree.unmerged) {
942 color_fprintf_ln(stderr, s->error_color,
943 _("ignoring unmerged: %s"),
944 files->items.items[i].string);
945 free(item);
946 free(files->items.items[i].string);
947 } else
948 files->items.items[j++] = files->items.items[i];
950 files->items.nr = j;
953 if (!files->items.nr) {
954 if (binary_count)
955 fprintf(stderr, _("Only binary files changed.\n"));
956 else
957 fprintf(stderr, _("No changes.\n"));
958 return 0;
961 opts->prompt = N_("Patch update");
962 count = list_and_choose(s, files, opts);
963 if (count > 0) {
964 struct strvec args = STRVEC_INIT;
965 struct pathspec ps_selected = { 0 };
967 for (i = 0; i < files->items.nr; i++)
968 if (files->selected[i])
969 strvec_push(&args,
970 files->items.items[i].string);
971 parse_pathspec(&ps_selected,
972 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
973 PATHSPEC_LITERAL_PATH, "", args.v);
974 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
975 strvec_clear(&args);
976 clear_pathspec(&ps_selected);
979 return res;
982 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
983 struct prefix_item_list *files,
984 struct list_and_choose_options *opts)
986 int res = 0;
987 ssize_t count, i;
989 struct object_id oid;
990 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
991 NULL);
992 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
993 return -1;
995 if (!files->items.nr) {
996 putchar('\n');
997 return 0;
1000 opts->prompt = N_("Review diff");
1001 opts->flags = IMMEDIATE;
1002 count = list_and_choose(s, files, opts);
1003 opts->flags = 0;
1004 if (count > 0) {
1005 struct child_process cmd = CHILD_PROCESS_INIT;
1007 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
1008 oid_to_hex(!is_initial ? &oid :
1009 s->r->hash_algo->empty_tree),
1010 "--", NULL);
1011 for (i = 0; i < files->items.nr; i++)
1012 if (files->selected[i])
1013 strvec_push(&cmd.args,
1014 files->items.items[i].string);
1015 res = run_command(&cmd);
1018 putchar('\n');
1019 return res;
1022 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1023 struct prefix_item_list *unused_files,
1024 struct list_and_choose_options *unused_opts)
1026 color_fprintf_ln(stdout, s->help_color, "status - %s",
1027 _("show paths with changes"));
1028 color_fprintf_ln(stdout, s->help_color, "update - %s",
1029 _("add working tree state to the staged set of changes"));
1030 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1031 _("revert staged set of changes back to the HEAD version"));
1032 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1033 _("pick hunks and update selectively"));
1034 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1035 _("view diff between HEAD and index"));
1036 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1037 _("add contents of untracked files to the staged set of changes"));
1039 return 0;
1042 static void choose_prompt_help(struct add_i_state *s)
1044 color_fprintf_ln(stdout, s->help_color, "%s",
1045 _("Prompt help:"));
1046 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1047 _("select a single item"));
1048 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1049 _("select a range of items"));
1050 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1051 _("select multiple ranges"));
1052 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1053 _("select item based on unique prefix"));
1054 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1055 _("unselect specified items"));
1056 color_fprintf_ln(stdout, s->help_color, "* - %s",
1057 _("choose all items"));
1058 color_fprintf_ln(stdout, s->help_color, " - %s",
1059 _("(empty) finish selecting"));
1062 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1063 struct prefix_item_list *files,
1064 struct list_and_choose_options *opts);
1066 struct command_item {
1067 size_t prefix_length;
1068 command_t command;
1071 struct print_command_item_data {
1072 const char *color, *reset;
1075 static void print_command_item(int i, int selected,
1076 struct string_list_item *item,
1077 void *print_command_item_data)
1079 struct print_command_item_data *d = print_command_item_data;
1080 struct command_item *util = item->util;
1082 if (!util->prefix_length ||
1083 !is_valid_prefix(item->string, util->prefix_length))
1084 printf(" %2d: %s", i + 1, item->string);
1085 else
1086 printf(" %2d: %s%.*s%s%s", i + 1,
1087 d->color, (int)util->prefix_length, item->string,
1088 d->reset, item->string + util->prefix_length);
1091 static void command_prompt_help(struct add_i_state *s)
1093 const char *help_color = s->help_color;
1094 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1095 color_fprintf_ln(stdout, help_color, "1 - %s",
1096 _("select a numbered item"));
1097 color_fprintf_ln(stdout, help_color, "foo - %s",
1098 _("select item based on unique prefix"));
1099 color_fprintf_ln(stdout, help_color, " - %s",
1100 _("(empty) select nothing"));
1103 int run_add_i(struct repository *r, const struct pathspec *ps)
1105 struct add_i_state s = { NULL };
1106 struct print_command_item_data data = { "[", "]" };
1107 struct list_and_choose_options main_loop_opts = {
1108 { 4, N_("*** Commands ***"), print_command_item, &data },
1109 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1111 struct {
1112 const char *string;
1113 command_t command;
1114 } command_list[] = {
1115 { "status", run_status },
1116 { "update", run_update },
1117 { "revert", run_revert },
1118 { "add untracked", run_add_untracked },
1119 { "patch", run_patch },
1120 { "diff", run_diff },
1121 { "quit", NULL },
1122 { "help", run_help },
1124 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1126 struct print_file_item_data print_file_item_data = {
1127 "%12s %12s %s", NULL, NULL,
1128 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1130 struct list_and_choose_options opts = {
1131 { 0, NULL, print_file_item, &print_file_item_data },
1132 NULL, 0, choose_prompt_help
1134 struct strbuf header = STRBUF_INIT;
1135 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1136 ssize_t i;
1137 int res = 0;
1139 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1140 struct command_item *util = xcalloc(1, sizeof(*util));
1141 util->command = command_list[i].command;
1142 string_list_append(&commands.items, command_list[i].string)
1143 ->util = util;
1146 init_add_i_state(&s, r);
1149 * When color was asked for, use the prompt color for
1150 * highlighting, otherwise use square brackets.
1152 if (s.use_color) {
1153 data.color = s.prompt_color;
1154 data.reset = s.reset_color;
1156 print_file_item_data.color = data.color;
1157 print_file_item_data.reset = data.reset;
1159 strbuf_addstr(&header, " ");
1160 strbuf_addf(&header, print_file_item_data.modified_fmt,
1161 _("staged"), _("unstaged"), _("path"));
1162 opts.list_opts.header = header.buf;
1164 discard_index(r->index);
1165 if (repo_read_index(r) < 0 ||
1166 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1167 NULL, NULL, NULL) < 0)
1168 warning(_("could not refresh index"));
1170 res = run_status(&s, ps, &files, &opts);
1172 for (;;) {
1173 struct command_item *util;
1175 i = list_and_choose(&s, &commands, &main_loop_opts);
1176 if (i < 0 || i >= commands.items.nr)
1177 util = NULL;
1178 else
1179 util = commands.items.items[i].util;
1181 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1182 printf(_("Bye.\n"));
1183 res = 0;
1184 break;
1187 if (util)
1188 res = util->command(&s, ps, &files, &opts);
1191 prefix_item_list_clear(&files);
1192 strbuf_release(&print_file_item_data.buf);
1193 strbuf_release(&print_file_item_data.name);
1194 strbuf_release(&print_file_item_data.index);
1195 strbuf_release(&print_file_item_data.worktree);
1196 strbuf_release(&header);
1197 prefix_item_list_clear(&commands);
1198 clear_add_i_state(&s);
1200 return res;