describe: fix --no-exact-match
[git.git] / add-interactive.c
blobde877ca0525482c9a5a2a6ad9d86e02e5fc79e53
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 "revision.h"
9 #include "refs.h"
10 #include "string-list.h"
11 #include "lockfile.h"
12 #include "dir.h"
13 #include "run-command.h"
14 #include "prompt.h"
15 #include "tree.h"
17 static void init_color(struct repository *r, struct add_i_state *s,
18 const char *section_and_slot, char *dst,
19 const char *default_color)
21 char *key = xstrfmt("color.%s", section_and_slot);
22 const char *value;
24 if (!s->use_color)
25 dst[0] = '\0';
26 else if (repo_config_get_value(r, key, &value) ||
27 color_parse(value, dst))
28 strlcpy(dst, default_color, COLOR_MAXLEN);
30 free(key);
33 void init_add_i_state(struct add_i_state *s, struct repository *r)
35 const char *value;
37 s->r = r;
39 if (repo_config_get_value(r, "color.interactive", &value))
40 s->use_color = -1;
41 else
42 s->use_color =
43 git_config_colorbool("color.interactive", value);
44 s->use_color = want_color(s->use_color);
46 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
47 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
48 init_color(r, s, "interactive.prompt", s->prompt_color,
49 GIT_COLOR_BOLD_BLUE);
50 init_color(r, s, "interactive.error", s->error_color,
51 GIT_COLOR_BOLD_RED);
53 init_color(r, s, "diff.frag", s->fraginfo_color,
54 diff_get_color(s->use_color, DIFF_FRAGINFO));
55 init_color(r, s, "diff.context", s->context_color, "fall back");
56 if (!strcmp(s->context_color, "fall back"))
57 init_color(r, s, "diff.plain", s->context_color,
58 diff_get_color(s->use_color, DIFF_CONTEXT));
59 init_color(r, s, "diff.old", s->file_old_color,
60 diff_get_color(s->use_color, DIFF_FILE_OLD));
61 init_color(r, s, "diff.new", s->file_new_color,
62 diff_get_color(s->use_color, DIFF_FILE_NEW));
64 strlcpy(s->reset_color,
65 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
67 FREE_AND_NULL(s->interactive_diff_filter);
68 git_config_get_string("interactive.difffilter",
69 &s->interactive_diff_filter);
71 FREE_AND_NULL(s->interactive_diff_algorithm);
72 git_config_get_string("diff.algorithm",
73 &s->interactive_diff_algorithm);
75 git_config_get_bool("interactive.singlekey", &s->use_single_key);
76 if (s->use_single_key)
77 setbuf(stdin, NULL);
80 void clear_add_i_state(struct add_i_state *s)
82 FREE_AND_NULL(s->interactive_diff_filter);
83 FREE_AND_NULL(s->interactive_diff_algorithm);
84 memset(s, 0, sizeof(*s));
85 s->use_color = -1;
89 * A "prefix item list" is a list of items that are identified by a string, and
90 * a unique prefix (if any) is determined for each item.
92 * It is implemented in the form of a pair of `string_list`s, the first one
93 * duplicating the strings, with the `util` field pointing at a structure whose
94 * first field must be `size_t prefix_length`.
96 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
97 * will be set to zero if no valid, unique prefix could be found.
99 * The second `string_list` is called `sorted` and does _not_ duplicate the
100 * strings but simply reuses the first one's, with the `util` field pointing at
101 * the `string_item_list` of the first `string_list`. It will be populated and
102 * sorted by `find_unique_prefixes()`.
104 struct prefix_item_list {
105 struct string_list items;
106 struct string_list sorted;
107 int *selected; /* for multi-selections */
108 size_t min_length, max_length;
110 #define PREFIX_ITEM_LIST_INIT { \
111 .items = STRING_LIST_INIT_DUP, \
112 .sorted = STRING_LIST_INIT_NODUP, \
113 .min_length = 1, \
114 .max_length = 4, \
117 static void prefix_item_list_clear(struct prefix_item_list *list)
119 string_list_clear(&list->items, 1);
120 string_list_clear(&list->sorted, 0);
121 FREE_AND_NULL(list->selected);
124 static void extend_prefix_length(struct string_list_item *p,
125 const char *other_string, size_t max_length)
127 size_t *len = p->util;
129 if (!*len || memcmp(p->string, other_string, *len))
130 return;
132 for (;;) {
133 char c = p->string[*len];
136 * Is `p` a strict prefix of `other`? Or have we exhausted the
137 * maximal length of the prefix? Or is the current character a
138 * multi-byte UTF-8 one? If so, there is no valid, unique
139 * prefix.
141 if (!c || ++*len > max_length || !isascii(c)) {
142 *len = 0;
143 break;
146 if (c != other_string[*len - 1])
147 break;
151 static void find_unique_prefixes(struct prefix_item_list *list)
153 size_t i;
155 if (list->sorted.nr == list->items.nr)
156 return;
158 string_list_clear(&list->sorted, 0);
159 /* Avoid reallocating incrementally */
160 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
161 list->items.nr));
162 list->sorted.nr = list->sorted.alloc = list->items.nr;
164 for (i = 0; i < list->items.nr; i++) {
165 list->sorted.items[i].string = list->items.items[i].string;
166 list->sorted.items[i].util = list->items.items + i;
169 string_list_sort(&list->sorted);
171 for (i = 0; i < list->sorted.nr; i++) {
172 struct string_list_item *sorted_item = list->sorted.items + i;
173 struct string_list_item *item = sorted_item->util;
174 size_t *len = item->util;
176 *len = 0;
177 while (*len < list->min_length) {
178 char c = item->string[(*len)++];
180 if (!c || !isascii(c)) {
181 *len = 0;
182 break;
186 if (i > 0)
187 extend_prefix_length(item, sorted_item[-1].string,
188 list->max_length);
189 if (i + 1 < list->sorted.nr)
190 extend_prefix_length(item, sorted_item[1].string,
191 list->max_length);
195 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
197 int index = string_list_find_insert_index(&list->sorted, string, 1);
198 struct string_list_item *item;
200 if (list->items.nr != list->sorted.nr)
201 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
202 " vs %"PRIuMAX")",
203 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
205 if (index < 0)
206 item = list->sorted.items[-1 - index].util;
207 else if (index > 0 &&
208 starts_with(list->sorted.items[index - 1].string, string))
209 return -1;
210 else if (index + 1 < list->sorted.nr &&
211 starts_with(list->sorted.items[index + 1].string, string))
212 return -1;
213 else if (index < list->sorted.nr &&
214 starts_with(list->sorted.items[index].string, string))
215 item = list->sorted.items[index].util;
216 else
217 return -1;
218 return item - list->items.items;
221 struct list_options {
222 int columns;
223 const char *header;
224 void (*print_item)(int i, int selected, struct string_list_item *item,
225 void *print_item_data);
226 void *print_item_data;
229 static void list(struct add_i_state *s, struct string_list *list, int *selected,
230 struct list_options *opts)
232 int i, last_lf = 0;
234 if (!list->nr)
235 return;
237 if (opts->header)
238 color_fprintf_ln(stdout, s->header_color,
239 "%s", opts->header);
241 for (i = 0; i < list->nr; i++) {
242 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
243 opts->print_item_data);
245 if ((opts->columns) && ((i + 1) % (opts->columns))) {
246 putchar('\t');
247 last_lf = 0;
249 else {
250 putchar('\n');
251 last_lf = 1;
255 if (!last_lf)
256 putchar('\n');
258 struct list_and_choose_options {
259 struct list_options list_opts;
261 const char *prompt;
262 enum {
263 SINGLETON = (1<<0),
264 IMMEDIATE = (1<<1),
265 } flags;
266 void (*print_help)(struct add_i_state *s);
269 #define LIST_AND_CHOOSE_ERROR (-1)
270 #define LIST_AND_CHOOSE_QUIT (-2)
273 * Returns the selected index in singleton mode, the number of selected items
274 * otherwise.
276 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
277 * `LIST_AND_CHOOSE_QUIT` is returned.
279 static ssize_t list_and_choose(struct add_i_state *s,
280 struct prefix_item_list *items,
281 struct list_and_choose_options *opts)
283 int singleton = opts->flags & SINGLETON;
284 int immediate = opts->flags & IMMEDIATE;
286 struct strbuf input = STRBUF_INIT;
287 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
289 if (!singleton) {
290 free(items->selected);
291 CALLOC_ARRAY(items->selected, items->items.nr);
294 if (singleton && !immediate)
295 BUG("singleton requires immediate");
297 find_unique_prefixes(items);
299 for (;;) {
300 char *p;
302 strbuf_reset(&input);
304 list(s, &items->items, items->selected, &opts->list_opts);
306 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
307 fputs(singleton ? "> " : ">> ", stdout);
308 fflush(stdout);
310 if (git_read_line_interactively(&input) == EOF) {
311 putchar('\n');
312 if (immediate)
313 res = LIST_AND_CHOOSE_QUIT;
314 break;
317 if (!input.len)
318 break;
320 if (!strcmp(input.buf, "?")) {
321 opts->print_help(s);
322 continue;
325 p = input.buf;
326 for (;;) {
327 size_t sep = strcspn(p, " \t\r\n,");
328 int choose = 1;
329 /* `from` is inclusive, `to` is exclusive */
330 ssize_t from = -1, to = -1;
332 if (!sep) {
333 if (!*p)
334 break;
335 p++;
336 continue;
339 /* Input that begins with '-'; de-select */
340 if (*p == '-') {
341 choose = 0;
342 p++;
343 sep--;
346 if (sep == 1 && *p == '*') {
347 from = 0;
348 to = items->items.nr;
349 } else if (isdigit(*p)) {
350 char *endp;
352 * A range can be specified like 5-7 or 5-.
354 * Note: `from` is 0-based while the user input
355 * is 1-based, hence we have to decrement by
356 * one. We do not have to decrement `to` even
357 * if it is 0-based because it is an exclusive
358 * boundary.
360 from = strtoul(p, &endp, 10) - 1;
361 if (endp == p + sep)
362 to = from + 1;
363 else if (*endp == '-') {
364 if (isdigit(*(++endp)))
365 to = strtoul(endp, &endp, 10);
366 else
367 to = items->items.nr;
368 /* extra characters after the range? */
369 if (endp != p + sep)
370 from = -1;
374 if (p[sep])
375 p[sep++] = '\0';
376 if (from < 0) {
377 from = find_unique(p, items);
378 if (from >= 0)
379 to = from + 1;
382 if (from < 0 || from >= items->items.nr ||
383 (singleton && from + 1 != to)) {
384 color_fprintf_ln(stderr, s->error_color,
385 _("Huh (%s)?"), p);
386 break;
387 } else if (singleton) {
388 res = from;
389 break;
392 if (to > items->items.nr)
393 to = items->items.nr;
395 for (; from < to; from++)
396 if (items->selected[from] != choose) {
397 items->selected[from] = choose;
398 res += choose ? +1 : -1;
401 p += sep;
404 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
405 !strcmp(input.buf, "*"))
406 break;
409 strbuf_release(&input);
410 return res;
413 struct adddel {
414 uintmax_t add, del;
415 unsigned seen:1, unmerged:1, binary:1;
418 struct file_item {
419 size_t prefix_length;
420 struct adddel index, worktree;
423 static void add_file_item(struct string_list *files, const char *name)
425 struct file_item *item = xcalloc(1, sizeof(*item));
427 string_list_append(files, name)->util = item;
430 struct pathname_entry {
431 struct hashmap_entry ent;
432 const char *name;
433 struct file_item *item;
436 static int pathname_entry_cmp(const void *cmp_data UNUSED,
437 const struct hashmap_entry *he1,
438 const struct hashmap_entry *he2,
439 const void *name)
441 const struct pathname_entry *e1 =
442 container_of(he1, const struct pathname_entry, ent);
443 const struct pathname_entry *e2 =
444 container_of(he2, const struct pathname_entry, ent);
446 return strcmp(e1->name, name ? (const char *)name : e2->name);
449 struct collection_status {
450 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
452 const char *reference;
454 unsigned skip_unseen:1;
455 size_t unmerged_count, binary_count;
456 struct string_list *files;
457 struct hashmap file_map;
460 static void collect_changes_cb(struct diff_queue_struct *q,
461 struct diff_options *options,
462 void *data)
464 struct collection_status *s = data;
465 struct diffstat_t stat = { 0 };
466 int i;
468 if (!q->nr)
469 return;
471 compute_diffstat(options, &stat, q);
473 for (i = 0; i < stat.nr; i++) {
474 const char *name = stat.files[i]->name;
475 int hash = strhash(name);
476 struct pathname_entry *entry;
477 struct file_item *file_item;
478 struct adddel *adddel, *other_adddel;
480 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
481 struct pathname_entry, ent);
482 if (!entry) {
483 if (s->skip_unseen)
484 continue;
486 add_file_item(s->files, name);
488 CALLOC_ARRAY(entry, 1);
489 hashmap_entry_init(&entry->ent, hash);
490 entry->name = s->files->items[s->files->nr - 1].string;
491 entry->item = s->files->items[s->files->nr - 1].util;
492 hashmap_add(&s->file_map, &entry->ent);
495 file_item = entry->item;
496 adddel = s->mode == FROM_INDEX ?
497 &file_item->index : &file_item->worktree;
498 other_adddel = s->mode == FROM_INDEX ?
499 &file_item->worktree : &file_item->index;
500 adddel->seen = 1;
501 adddel->add = stat.files[i]->added;
502 adddel->del = stat.files[i]->deleted;
503 if (stat.files[i]->is_binary) {
504 if (!other_adddel->binary)
505 s->binary_count++;
506 adddel->binary = 1;
508 if (stat.files[i]->is_unmerged) {
509 if (!other_adddel->unmerged)
510 s->unmerged_count++;
511 adddel->unmerged = 1;
514 free_diffstat_info(&stat);
517 enum modified_files_filter {
518 NO_FILTER = 0,
519 WORKTREE_ONLY = 1,
520 INDEX_ONLY = 2,
523 static int get_modified_files(struct repository *r,
524 enum modified_files_filter filter,
525 struct prefix_item_list *files,
526 const struct pathspec *ps,
527 size_t *unmerged_count,
528 size_t *binary_count)
530 struct object_id head_oid;
531 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
532 &head_oid, NULL);
533 struct collection_status s = { 0 };
534 int i;
536 discard_index(r->index);
537 if (repo_read_index_preload(r, ps, 0) < 0)
538 return error(_("could not read index"));
540 prefix_item_list_clear(files);
541 s.files = &files->items;
542 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
544 for (i = 0; i < 2; i++) {
545 struct rev_info rev;
546 struct setup_revision_opt opt = { 0 };
548 if (filter == INDEX_ONLY)
549 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
550 else
551 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
552 s.skip_unseen = filter && i;
554 opt.def = is_initial ?
555 empty_tree_oid_hex() : oid_to_hex(&head_oid);
557 repo_init_revisions(r, &rev, NULL);
558 setup_revisions(0, NULL, &rev, &opt);
560 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
561 rev.diffopt.format_callback = collect_changes_cb;
562 rev.diffopt.format_callback_data = &s;
564 if (ps)
565 copy_pathspec(&rev.prune_data, ps);
567 if (s.mode == FROM_INDEX)
568 run_diff_index(&rev, 1);
569 else {
570 rev.diffopt.flags.ignore_dirty_submodules = 1;
571 run_diff_files(&rev, 0);
574 release_revisions(&rev);
576 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
577 if (unmerged_count)
578 *unmerged_count = s.unmerged_count;
579 if (binary_count)
580 *binary_count = s.binary_count;
582 /* While the diffs are ordered already, we ran *two* diffs... */
583 string_list_sort(&files->items);
585 return 0;
588 static void render_adddel(struct strbuf *buf,
589 struct adddel *ad, const char *no_changes)
591 if (ad->binary)
592 strbuf_addstr(buf, _("binary"));
593 else if (ad->seen)
594 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
595 (uintmax_t)ad->add, (uintmax_t)ad->del);
596 else
597 strbuf_addstr(buf, no_changes);
600 /* filters out prefixes which have special meaning to list_and_choose() */
601 static int is_valid_prefix(const char *prefix, size_t prefix_len)
603 return prefix_len && prefix &&
605 * We expect `prefix` to be NUL terminated, therefore this
606 * `strcspn()` call is okay, even if it might do much more
607 * work than strictly necessary.
609 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
610 *prefix != '-' && /* deselection */
611 !isdigit(*prefix) && /* selection */
612 (prefix_len != 1 ||
613 (*prefix != '*' && /* "all" wildcard */
614 *prefix != '?')); /* prompt help */
617 struct print_file_item_data {
618 const char *modified_fmt, *color, *reset;
619 struct strbuf buf, name, index, worktree;
620 unsigned only_names:1;
623 static void print_file_item(int i, int selected, struct string_list_item *item,
624 void *print_file_item_data)
626 struct file_item *c = item->util;
627 struct print_file_item_data *d = print_file_item_data;
628 const char *highlighted = NULL;
630 strbuf_reset(&d->index);
631 strbuf_reset(&d->worktree);
632 strbuf_reset(&d->buf);
634 /* Format the item with the prefix highlighted. */
635 if (c->prefix_length > 0 &&
636 is_valid_prefix(item->string, c->prefix_length)) {
637 strbuf_reset(&d->name);
638 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
639 (int)c->prefix_length, item->string, d->reset,
640 item->string + c->prefix_length);
641 highlighted = d->name.buf;
644 if (d->only_names) {
645 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
646 highlighted ? highlighted : item->string);
647 return;
650 render_adddel(&d->worktree, &c->worktree, _("nothing"));
651 render_adddel(&d->index, &c->index, _("unchanged"));
653 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
654 highlighted ? highlighted : item->string);
656 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
659 static int run_status(struct add_i_state *s, const struct pathspec *ps,
660 struct prefix_item_list *files,
661 struct list_and_choose_options *opts)
663 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
664 return -1;
666 list(s, &files->items, NULL, &opts->list_opts);
667 putchar('\n');
669 return 0;
672 static int run_update(struct add_i_state *s, const struct pathspec *ps,
673 struct prefix_item_list *files,
674 struct list_and_choose_options *opts)
676 int res = 0, fd;
677 size_t count, i;
678 struct lock_file index_lock;
680 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
681 return -1;
683 if (!files->items.nr) {
684 putchar('\n');
685 return 0;
688 opts->prompt = N_("Update");
689 count = list_and_choose(s, files, opts);
690 if (count <= 0) {
691 putchar('\n');
692 return 0;
695 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
696 if (fd < 0) {
697 putchar('\n');
698 return -1;
701 for (i = 0; i < files->items.nr; i++) {
702 const char *name = files->items.items[i].string;
703 struct stat st;
705 if (!files->selected[i])
706 continue;
707 if (lstat(name, &st) && is_missing_file_error(errno)) {
708 if (remove_file_from_index(s->r->index, name) < 0) {
709 res = error(_("could not stage '%s'"), name);
710 break;
712 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
713 res = error(_("could not stage '%s'"), name);
714 break;
718 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
719 res = error(_("could not write index"));
721 if (!res)
722 printf(Q_("updated %d path\n",
723 "updated %d paths\n", count), (int)count);
725 putchar('\n');
726 return res;
729 static void revert_from_diff(struct diff_queue_struct *q,
730 struct diff_options *opt, void *data UNUSED)
732 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
734 for (i = 0; i < q->nr; i++) {
735 struct diff_filespec *one = q->queue[i]->one;
736 struct cache_entry *ce;
738 if (!(one->mode && !is_null_oid(&one->oid))) {
739 remove_file_from_index(opt->repo->index, one->path);
740 printf(_("note: %s is untracked now.\n"), one->path);
741 } else {
742 ce = make_cache_entry(opt->repo->index, one->mode,
743 &one->oid, one->path, 0, 0);
744 if (!ce)
745 die(_("make_cache_entry failed for path '%s'"),
746 one->path);
747 add_index_entry(opt->repo->index, ce, add_flags);
752 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
753 struct prefix_item_list *files,
754 struct list_and_choose_options *opts)
756 int res = 0, fd;
757 size_t count, i, j;
759 struct object_id oid;
760 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
761 NULL);
762 struct lock_file index_lock;
763 const char **paths;
764 struct tree *tree;
765 struct diff_options diffopt = { NULL };
767 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
768 return -1;
770 if (!files->items.nr) {
771 putchar('\n');
772 return 0;
775 opts->prompt = N_("Revert");
776 count = list_and_choose(s, files, opts);
777 if (count <= 0)
778 goto finish_revert;
780 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
781 if (fd < 0) {
782 res = -1;
783 goto finish_revert;
786 if (is_initial)
787 oidcpy(&oid, s->r->hash_algo->empty_tree);
788 else {
789 tree = parse_tree_indirect(&oid);
790 if (!tree) {
791 res = error(_("Could not parse HEAD^{tree}"));
792 goto finish_revert;
794 oidcpy(&oid, &tree->object.oid);
797 ALLOC_ARRAY(paths, count + 1);
798 for (i = j = 0; i < files->items.nr; i++)
799 if (files->selected[i])
800 paths[j++] = files->items.items[i].string;
801 paths[j] = NULL;
803 parse_pathspec(&diffopt.pathspec, 0,
804 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
805 NULL, paths);
807 diffopt.output_format = DIFF_FORMAT_CALLBACK;
808 diffopt.format_callback = revert_from_diff;
809 diffopt.flags.override_submodule_config = 1;
810 diffopt.repo = s->r;
812 if (do_diff_cache(&oid, &diffopt)) {
813 diff_free(&diffopt);
814 res = -1;
815 } else {
816 diffcore_std(&diffopt);
817 diff_flush(&diffopt);
819 free(paths);
821 if (!res && write_locked_index(s->r->index, &index_lock,
822 COMMIT_LOCK) < 0)
823 res = -1;
824 else
825 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
826 NULL, NULL, NULL);
828 if (!res)
829 printf(Q_("reverted %d path\n",
830 "reverted %d paths\n", count), (int)count);
832 finish_revert:
833 putchar('\n');
834 return res;
837 static int get_untracked_files(struct repository *r,
838 struct prefix_item_list *files,
839 const struct pathspec *ps)
841 struct dir_struct dir = { 0 };
842 size_t i;
843 struct strbuf buf = STRBUF_INIT;
845 if (repo_read_index(r) < 0)
846 return error(_("could not read index"));
848 prefix_item_list_clear(files);
849 setup_standard_excludes(&dir);
850 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
851 fill_directory(&dir, r->index, ps);
853 for (i = 0; i < dir.nr; i++) {
854 struct dir_entry *ent = dir.entries[i];
856 if (index_name_is_other(r->index, ent->name, ent->len)) {
857 strbuf_reset(&buf);
858 strbuf_add(&buf, ent->name, ent->len);
859 add_file_item(&files->items, buf.buf);
863 strbuf_release(&buf);
864 return 0;
867 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
868 struct prefix_item_list *files,
869 struct list_and_choose_options *opts)
871 struct print_file_item_data *d = opts->list_opts.print_item_data;
872 int res = 0, fd;
873 size_t count, i;
874 struct lock_file index_lock;
876 if (get_untracked_files(s->r, files, ps) < 0)
877 return -1;
879 if (!files->items.nr) {
880 printf(_("No untracked files.\n"));
881 goto finish_add_untracked;
884 opts->prompt = N_("Add untracked");
885 d->only_names = 1;
886 count = list_and_choose(s, files, opts);
887 d->only_names = 0;
888 if (count <= 0)
889 goto finish_add_untracked;
891 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
892 if (fd < 0) {
893 res = -1;
894 goto finish_add_untracked;
897 for (i = 0; i < files->items.nr; i++) {
898 const char *name = files->items.items[i].string;
899 if (files->selected[i] &&
900 add_file_to_index(s->r->index, name, 0) < 0) {
901 res = error(_("could not stage '%s'"), name);
902 break;
906 if (!res &&
907 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
908 res = error(_("could not write index"));
910 if (!res)
911 printf(Q_("added %d path\n",
912 "added %d paths\n", count), (int)count);
914 finish_add_untracked:
915 putchar('\n');
916 return res;
919 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
920 struct prefix_item_list *files,
921 struct list_and_choose_options *opts)
923 int res = 0;
924 ssize_t count, i, j;
925 size_t unmerged_count = 0, binary_count = 0;
927 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
928 &unmerged_count, &binary_count) < 0)
929 return -1;
931 if (unmerged_count || binary_count) {
932 for (i = j = 0; i < files->items.nr; i++) {
933 struct file_item *item = files->items.items[i].util;
935 if (item->index.binary || item->worktree.binary) {
936 free(item);
937 free(files->items.items[i].string);
938 } else if (item->index.unmerged ||
939 item->worktree.unmerged) {
940 color_fprintf_ln(stderr, s->error_color,
941 _("ignoring unmerged: %s"),
942 files->items.items[i].string);
943 free(item);
944 free(files->items.items[i].string);
945 } else
946 files->items.items[j++] = files->items.items[i];
948 files->items.nr = j;
951 if (!files->items.nr) {
952 if (binary_count)
953 fprintf(stderr, _("Only binary files changed.\n"));
954 else
955 fprintf(stderr, _("No changes.\n"));
956 return 0;
959 opts->prompt = N_("Patch update");
960 count = list_and_choose(s, files, opts);
961 if (count > 0) {
962 struct strvec args = STRVEC_INIT;
963 struct pathspec ps_selected = { 0 };
965 for (i = 0; i < files->items.nr; i++)
966 if (files->selected[i])
967 strvec_push(&args,
968 files->items.items[i].string);
969 parse_pathspec(&ps_selected,
970 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
971 PATHSPEC_LITERAL_PATH, "", args.v);
972 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
973 strvec_clear(&args);
974 clear_pathspec(&ps_selected);
977 return res;
980 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
981 struct prefix_item_list *files,
982 struct list_and_choose_options *opts)
984 int res = 0;
985 ssize_t count, i;
987 struct object_id oid;
988 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
989 NULL);
990 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
991 return -1;
993 if (!files->items.nr) {
994 putchar('\n');
995 return 0;
998 opts->prompt = N_("Review diff");
999 opts->flags = IMMEDIATE;
1000 count = list_and_choose(s, files, opts);
1001 opts->flags = 0;
1002 if (count > 0) {
1003 struct child_process cmd = CHILD_PROCESS_INIT;
1005 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
1006 oid_to_hex(!is_initial ? &oid :
1007 s->r->hash_algo->empty_tree),
1008 "--", NULL);
1009 for (i = 0; i < files->items.nr; i++)
1010 if (files->selected[i])
1011 strvec_push(&cmd.args,
1012 files->items.items[i].string);
1013 res = run_command(&cmd);
1016 putchar('\n');
1017 return res;
1020 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1021 struct prefix_item_list *unused_files,
1022 struct list_and_choose_options *unused_opts)
1024 color_fprintf_ln(stdout, s->help_color, "status - %s",
1025 _("show paths with changes"));
1026 color_fprintf_ln(stdout, s->help_color, "update - %s",
1027 _("add working tree state to the staged set of changes"));
1028 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1029 _("revert staged set of changes back to the HEAD version"));
1030 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1031 _("pick hunks and update selectively"));
1032 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1033 _("view diff between HEAD and index"));
1034 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1035 _("add contents of untracked files to the staged set of changes"));
1037 return 0;
1040 static void choose_prompt_help(struct add_i_state *s)
1042 color_fprintf_ln(stdout, s->help_color, "%s",
1043 _("Prompt help:"));
1044 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1045 _("select a single item"));
1046 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1047 _("select a range of items"));
1048 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1049 _("select multiple ranges"));
1050 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1051 _("select item based on unique prefix"));
1052 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1053 _("unselect specified items"));
1054 color_fprintf_ln(stdout, s->help_color, "* - %s",
1055 _("choose all items"));
1056 color_fprintf_ln(stdout, s->help_color, " - %s",
1057 _("(empty) finish selecting"));
1060 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1061 struct prefix_item_list *files,
1062 struct list_and_choose_options *opts);
1064 struct command_item {
1065 size_t prefix_length;
1066 command_t command;
1069 struct print_command_item_data {
1070 const char *color, *reset;
1073 static void print_command_item(int i, int selected,
1074 struct string_list_item *item,
1075 void *print_command_item_data)
1077 struct print_command_item_data *d = print_command_item_data;
1078 struct command_item *util = item->util;
1080 if (!util->prefix_length ||
1081 !is_valid_prefix(item->string, util->prefix_length))
1082 printf(" %2d: %s", i + 1, item->string);
1083 else
1084 printf(" %2d: %s%.*s%s%s", i + 1,
1085 d->color, (int)util->prefix_length, item->string,
1086 d->reset, item->string + util->prefix_length);
1089 static void command_prompt_help(struct add_i_state *s)
1091 const char *help_color = s->help_color;
1092 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1093 color_fprintf_ln(stdout, help_color, "1 - %s",
1094 _("select a numbered item"));
1095 color_fprintf_ln(stdout, help_color, "foo - %s",
1096 _("select item based on unique prefix"));
1097 color_fprintf_ln(stdout, help_color, " - %s",
1098 _("(empty) select nothing"));
1101 int run_add_i(struct repository *r, const struct pathspec *ps)
1103 struct add_i_state s = { NULL };
1104 struct print_command_item_data data = { "[", "]" };
1105 struct list_and_choose_options main_loop_opts = {
1106 { 4, N_("*** Commands ***"), print_command_item, &data },
1107 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1109 struct {
1110 const char *string;
1111 command_t command;
1112 } command_list[] = {
1113 { "status", run_status },
1114 { "update", run_update },
1115 { "revert", run_revert },
1116 { "add untracked", run_add_untracked },
1117 { "patch", run_patch },
1118 { "diff", run_diff },
1119 { "quit", NULL },
1120 { "help", run_help },
1122 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1124 struct print_file_item_data print_file_item_data = {
1125 "%12s %12s %s", NULL, NULL,
1126 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1128 struct list_and_choose_options opts = {
1129 { 0, NULL, print_file_item, &print_file_item_data },
1130 NULL, 0, choose_prompt_help
1132 struct strbuf header = STRBUF_INIT;
1133 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1134 ssize_t i;
1135 int res = 0;
1137 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1138 struct command_item *util = xcalloc(1, sizeof(*util));
1139 util->command = command_list[i].command;
1140 string_list_append(&commands.items, command_list[i].string)
1141 ->util = util;
1144 init_add_i_state(&s, r);
1147 * When color was asked for, use the prompt color for
1148 * highlighting, otherwise use square brackets.
1150 if (s.use_color) {
1151 data.color = s.prompt_color;
1152 data.reset = s.reset_color;
1154 print_file_item_data.color = data.color;
1155 print_file_item_data.reset = data.reset;
1157 strbuf_addstr(&header, " ");
1158 strbuf_addf(&header, print_file_item_data.modified_fmt,
1159 _("staged"), _("unstaged"), _("path"));
1160 opts.list_opts.header = header.buf;
1162 discard_index(r->index);
1163 if (repo_read_index(r) < 0 ||
1164 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1165 NULL, NULL, NULL) < 0)
1166 warning(_("could not refresh index"));
1168 res = run_status(&s, ps, &files, &opts);
1170 for (;;) {
1171 struct command_item *util;
1173 i = list_and_choose(&s, &commands, &main_loop_opts);
1174 if (i < 0 || i >= commands.items.nr)
1175 util = NULL;
1176 else
1177 util = commands.items.items[i].util;
1179 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1180 printf(_("Bye.\n"));
1181 res = 0;
1182 break;
1185 if (util)
1186 res = util->command(&s, ps, &files, &opts);
1189 prefix_item_list_clear(&files);
1190 strbuf_release(&print_file_item_data.buf);
1191 strbuf_release(&print_file_item_data.name);
1192 strbuf_release(&print_file_item_data.index);
1193 strbuf_release(&print_file_item_data.worktree);
1194 strbuf_release(&header);
1195 prefix_item_list_clear(&commands);
1196 clear_add_i_state(&s);
1198 return res;