Merge branch 'jc/gpg-lazy-init'
[git/debian.git] / add-interactive.c
blobae25ec50bce77289a7486bda135de8f91f8fb6cc
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "color.h"
4 #include "config.h"
5 #include "diffcore.h"
6 #include "hex.h"
7 #include "revision.h"
8 #include "refs.h"
9 #include "string-list.h"
10 #include "lockfile.h"
11 #include "dir.h"
12 #include "run-command.h"
13 #include "prompt.h"
15 static void init_color(struct repository *r, struct add_i_state *s,
16 const char *section_and_slot, char *dst,
17 const char *default_color)
19 char *key = xstrfmt("color.%s", section_and_slot);
20 const char *value;
22 if (!s->use_color)
23 dst[0] = '\0';
24 else if (repo_config_get_value(r, key, &value) ||
25 color_parse(value, dst))
26 strlcpy(dst, default_color, COLOR_MAXLEN);
28 free(key);
31 void init_add_i_state(struct add_i_state *s, struct repository *r)
33 const char *value;
35 s->r = r;
37 if (repo_config_get_value(r, "color.interactive", &value))
38 s->use_color = -1;
39 else
40 s->use_color =
41 git_config_colorbool("color.interactive", value);
42 s->use_color = want_color(s->use_color);
44 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
45 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
46 init_color(r, s, "interactive.prompt", s->prompt_color,
47 GIT_COLOR_BOLD_BLUE);
48 init_color(r, s, "interactive.error", s->error_color,
49 GIT_COLOR_BOLD_RED);
51 init_color(r, s, "diff.frag", s->fraginfo_color,
52 diff_get_color(s->use_color, DIFF_FRAGINFO));
53 init_color(r, s, "diff.context", s->context_color, "fall back");
54 if (!strcmp(s->context_color, "fall back"))
55 init_color(r, s, "diff.plain", s->context_color,
56 diff_get_color(s->use_color, DIFF_CONTEXT));
57 init_color(r, s, "diff.old", s->file_old_color,
58 diff_get_color(s->use_color, DIFF_FILE_OLD));
59 init_color(r, s, "diff.new", s->file_new_color,
60 diff_get_color(s->use_color, DIFF_FILE_NEW));
62 strlcpy(s->reset_color,
63 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
65 FREE_AND_NULL(s->interactive_diff_filter);
66 git_config_get_string("interactive.difffilter",
67 &s->interactive_diff_filter);
69 FREE_AND_NULL(s->interactive_diff_algorithm);
70 git_config_get_string("diff.algorithm",
71 &s->interactive_diff_algorithm);
73 git_config_get_bool("interactive.singlekey", &s->use_single_key);
74 if (s->use_single_key)
75 setbuf(stdin, NULL);
78 void clear_add_i_state(struct add_i_state *s)
80 FREE_AND_NULL(s->interactive_diff_filter);
81 FREE_AND_NULL(s->interactive_diff_algorithm);
82 memset(s, 0, sizeof(*s));
83 s->use_color = -1;
87 * A "prefix item list" is a list of items that are identified by a string, and
88 * a unique prefix (if any) is determined for each item.
90 * It is implemented in the form of a pair of `string_list`s, the first one
91 * duplicating the strings, with the `util` field pointing at a structure whose
92 * first field must be `size_t prefix_length`.
94 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
95 * will be set to zero if no valid, unique prefix could be found.
97 * The second `string_list` is called `sorted` and does _not_ duplicate the
98 * strings but simply reuses the first one's, with the `util` field pointing at
99 * the `string_item_list` of the first `string_list`. It will be populated and
100 * sorted by `find_unique_prefixes()`.
102 struct prefix_item_list {
103 struct string_list items;
104 struct string_list sorted;
105 int *selected; /* for multi-selections */
106 size_t min_length, max_length;
108 #define PREFIX_ITEM_LIST_INIT { \
109 .items = STRING_LIST_INIT_DUP, \
110 .sorted = STRING_LIST_INIT_NODUP, \
111 .min_length = 1, \
112 .max_length = 4, \
115 static void prefix_item_list_clear(struct prefix_item_list *list)
117 string_list_clear(&list->items, 1);
118 string_list_clear(&list->sorted, 0);
119 FREE_AND_NULL(list->selected);
122 static void extend_prefix_length(struct string_list_item *p,
123 const char *other_string, size_t max_length)
125 size_t *len = p->util;
127 if (!*len || memcmp(p->string, other_string, *len))
128 return;
130 for (;;) {
131 char c = p->string[*len];
134 * Is `p` a strict prefix of `other`? Or have we exhausted the
135 * maximal length of the prefix? Or is the current character a
136 * multi-byte UTF-8 one? If so, there is no valid, unique
137 * prefix.
139 if (!c || ++*len > max_length || !isascii(c)) {
140 *len = 0;
141 break;
144 if (c != other_string[*len - 1])
145 break;
149 static void find_unique_prefixes(struct prefix_item_list *list)
151 size_t i;
153 if (list->sorted.nr == list->items.nr)
154 return;
156 string_list_clear(&list->sorted, 0);
157 /* Avoid reallocating incrementally */
158 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
159 list->items.nr));
160 list->sorted.nr = list->sorted.alloc = list->items.nr;
162 for (i = 0; i < list->items.nr; i++) {
163 list->sorted.items[i].string = list->items.items[i].string;
164 list->sorted.items[i].util = list->items.items + i;
167 string_list_sort(&list->sorted);
169 for (i = 0; i < list->sorted.nr; i++) {
170 struct string_list_item *sorted_item = list->sorted.items + i;
171 struct string_list_item *item = sorted_item->util;
172 size_t *len = item->util;
174 *len = 0;
175 while (*len < list->min_length) {
176 char c = item->string[(*len)++];
178 if (!c || !isascii(c)) {
179 *len = 0;
180 break;
184 if (i > 0)
185 extend_prefix_length(item, sorted_item[-1].string,
186 list->max_length);
187 if (i + 1 < list->sorted.nr)
188 extend_prefix_length(item, sorted_item[1].string,
189 list->max_length);
193 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
195 int index = string_list_find_insert_index(&list->sorted, string, 1);
196 struct string_list_item *item;
198 if (list->items.nr != list->sorted.nr)
199 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
200 " vs %"PRIuMAX")",
201 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
203 if (index < 0)
204 item = list->sorted.items[-1 - index].util;
205 else if (index > 0 &&
206 starts_with(list->sorted.items[index - 1].string, string))
207 return -1;
208 else if (index + 1 < list->sorted.nr &&
209 starts_with(list->sorted.items[index + 1].string, string))
210 return -1;
211 else if (index < list->sorted.nr &&
212 starts_with(list->sorted.items[index].string, string))
213 item = list->sorted.items[index].util;
214 else
215 return -1;
216 return item - list->items.items;
219 struct list_options {
220 int columns;
221 const char *header;
222 void (*print_item)(int i, int selected, struct string_list_item *item,
223 void *print_item_data);
224 void *print_item_data;
227 static void list(struct add_i_state *s, struct string_list *list, int *selected,
228 struct list_options *opts)
230 int i, last_lf = 0;
232 if (!list->nr)
233 return;
235 if (opts->header)
236 color_fprintf_ln(stdout, s->header_color,
237 "%s", opts->header);
239 for (i = 0; i < list->nr; i++) {
240 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
241 opts->print_item_data);
243 if ((opts->columns) && ((i + 1) % (opts->columns))) {
244 putchar('\t');
245 last_lf = 0;
247 else {
248 putchar('\n');
249 last_lf = 1;
253 if (!last_lf)
254 putchar('\n');
256 struct list_and_choose_options {
257 struct list_options list_opts;
259 const char *prompt;
260 enum {
261 SINGLETON = (1<<0),
262 IMMEDIATE = (1<<1),
263 } flags;
264 void (*print_help)(struct add_i_state *s);
267 #define LIST_AND_CHOOSE_ERROR (-1)
268 #define LIST_AND_CHOOSE_QUIT (-2)
271 * Returns the selected index in singleton mode, the number of selected items
272 * otherwise.
274 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
275 * `LIST_AND_CHOOSE_QUIT` is returned.
277 static ssize_t list_and_choose(struct add_i_state *s,
278 struct prefix_item_list *items,
279 struct list_and_choose_options *opts)
281 int singleton = opts->flags & SINGLETON;
282 int immediate = opts->flags & IMMEDIATE;
284 struct strbuf input = STRBUF_INIT;
285 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
287 if (!singleton) {
288 free(items->selected);
289 CALLOC_ARRAY(items->selected, items->items.nr);
292 if (singleton && !immediate)
293 BUG("singleton requires immediate");
295 find_unique_prefixes(items);
297 for (;;) {
298 char *p;
300 strbuf_reset(&input);
302 list(s, &items->items, items->selected, &opts->list_opts);
304 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
305 fputs(singleton ? "> " : ">> ", stdout);
306 fflush(stdout);
308 if (git_read_line_interactively(&input) == EOF) {
309 putchar('\n');
310 if (immediate)
311 res = LIST_AND_CHOOSE_QUIT;
312 break;
315 if (!input.len)
316 break;
318 if (!strcmp(input.buf, "?")) {
319 opts->print_help(s);
320 continue;
323 p = input.buf;
324 for (;;) {
325 size_t sep = strcspn(p, " \t\r\n,");
326 int choose = 1;
327 /* `from` is inclusive, `to` is exclusive */
328 ssize_t from = -1, to = -1;
330 if (!sep) {
331 if (!*p)
332 break;
333 p++;
334 continue;
337 /* Input that begins with '-'; de-select */
338 if (*p == '-') {
339 choose = 0;
340 p++;
341 sep--;
344 if (sep == 1 && *p == '*') {
345 from = 0;
346 to = items->items.nr;
347 } else if (isdigit(*p)) {
348 char *endp;
350 * A range can be specified like 5-7 or 5-.
352 * Note: `from` is 0-based while the user input
353 * is 1-based, hence we have to decrement by
354 * one. We do not have to decrement `to` even
355 * if it is 0-based because it is an exclusive
356 * boundary.
358 from = strtoul(p, &endp, 10) - 1;
359 if (endp == p + sep)
360 to = from + 1;
361 else if (*endp == '-') {
362 if (isdigit(*(++endp)))
363 to = strtoul(endp, &endp, 10);
364 else
365 to = items->items.nr;
366 /* extra characters after the range? */
367 if (endp != p + sep)
368 from = -1;
372 if (p[sep])
373 p[sep++] = '\0';
374 if (from < 0) {
375 from = find_unique(p, items);
376 if (from >= 0)
377 to = from + 1;
380 if (from < 0 || from >= items->items.nr ||
381 (singleton && from + 1 != to)) {
382 color_fprintf_ln(stderr, s->error_color,
383 _("Huh (%s)?"), p);
384 break;
385 } else if (singleton) {
386 res = from;
387 break;
390 if (to > items->items.nr)
391 to = items->items.nr;
393 for (; from < to; from++)
394 if (items->selected[from] != choose) {
395 items->selected[from] = choose;
396 res += choose ? +1 : -1;
399 p += sep;
402 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
403 !strcmp(input.buf, "*"))
404 break;
407 strbuf_release(&input);
408 return res;
411 struct adddel {
412 uintmax_t add, del;
413 unsigned seen:1, unmerged:1, binary:1;
416 struct file_item {
417 size_t prefix_length;
418 struct adddel index, worktree;
421 static void add_file_item(struct string_list *files, const char *name)
423 struct file_item *item = xcalloc(1, sizeof(*item));
425 string_list_append(files, name)->util = item;
428 struct pathname_entry {
429 struct hashmap_entry ent;
430 const char *name;
431 struct file_item *item;
434 static int pathname_entry_cmp(const void *cmp_data UNUSED,
435 const struct hashmap_entry *he1,
436 const struct hashmap_entry *he2,
437 const void *name)
439 const struct pathname_entry *e1 =
440 container_of(he1, const struct pathname_entry, ent);
441 const struct pathname_entry *e2 =
442 container_of(he2, const struct pathname_entry, ent);
444 return strcmp(e1->name, name ? (const char *)name : e2->name);
447 struct collection_status {
448 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
450 const char *reference;
452 unsigned skip_unseen:1;
453 size_t unmerged_count, binary_count;
454 struct string_list *files;
455 struct hashmap file_map;
458 static void collect_changes_cb(struct diff_queue_struct *q,
459 struct diff_options *options,
460 void *data)
462 struct collection_status *s = data;
463 struct diffstat_t stat = { 0 };
464 int i;
466 if (!q->nr)
467 return;
469 compute_diffstat(options, &stat, q);
471 for (i = 0; i < stat.nr; i++) {
472 const char *name = stat.files[i]->name;
473 int hash = strhash(name);
474 struct pathname_entry *entry;
475 struct file_item *file_item;
476 struct adddel *adddel, *other_adddel;
478 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
479 struct pathname_entry, ent);
480 if (!entry) {
481 if (s->skip_unseen)
482 continue;
484 add_file_item(s->files, name);
486 CALLOC_ARRAY(entry, 1);
487 hashmap_entry_init(&entry->ent, hash);
488 entry->name = s->files->items[s->files->nr - 1].string;
489 entry->item = s->files->items[s->files->nr - 1].util;
490 hashmap_add(&s->file_map, &entry->ent);
493 file_item = entry->item;
494 adddel = s->mode == FROM_INDEX ?
495 &file_item->index : &file_item->worktree;
496 other_adddel = s->mode == FROM_INDEX ?
497 &file_item->worktree : &file_item->index;
498 adddel->seen = 1;
499 adddel->add = stat.files[i]->added;
500 adddel->del = stat.files[i]->deleted;
501 if (stat.files[i]->is_binary) {
502 if (!other_adddel->binary)
503 s->binary_count++;
504 adddel->binary = 1;
506 if (stat.files[i]->is_unmerged) {
507 if (!other_adddel->unmerged)
508 s->unmerged_count++;
509 adddel->unmerged = 1;
512 free_diffstat_info(&stat);
515 enum modified_files_filter {
516 NO_FILTER = 0,
517 WORKTREE_ONLY = 1,
518 INDEX_ONLY = 2,
521 static int get_modified_files(struct repository *r,
522 enum modified_files_filter filter,
523 struct prefix_item_list *files,
524 const struct pathspec *ps,
525 size_t *unmerged_count,
526 size_t *binary_count)
528 struct object_id head_oid;
529 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
530 &head_oid, NULL);
531 struct collection_status s = { 0 };
532 int i;
534 discard_index(r->index);
535 if (repo_read_index_preload(r, ps, 0) < 0)
536 return error(_("could not read index"));
538 prefix_item_list_clear(files);
539 s.files = &files->items;
540 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
542 for (i = 0; i < 2; i++) {
543 struct rev_info rev;
544 struct setup_revision_opt opt = { 0 };
546 if (filter == INDEX_ONLY)
547 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
548 else
549 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
550 s.skip_unseen = filter && i;
552 opt.def = is_initial ?
553 empty_tree_oid_hex() : oid_to_hex(&head_oid);
555 init_revisions(&rev, NULL);
556 setup_revisions(0, NULL, &rev, &opt);
558 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
559 rev.diffopt.format_callback = collect_changes_cb;
560 rev.diffopt.format_callback_data = &s;
562 if (ps)
563 copy_pathspec(&rev.prune_data, ps);
565 if (s.mode == FROM_INDEX)
566 run_diff_index(&rev, 1);
567 else {
568 rev.diffopt.flags.ignore_dirty_submodules = 1;
569 run_diff_files(&rev, 0);
572 release_revisions(&rev);
574 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
575 if (unmerged_count)
576 *unmerged_count = s.unmerged_count;
577 if (binary_count)
578 *binary_count = s.binary_count;
580 /* While the diffs are ordered already, we ran *two* diffs... */
581 string_list_sort(&files->items);
583 return 0;
586 static void render_adddel(struct strbuf *buf,
587 struct adddel *ad, const char *no_changes)
589 if (ad->binary)
590 strbuf_addstr(buf, _("binary"));
591 else if (ad->seen)
592 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
593 (uintmax_t)ad->add, (uintmax_t)ad->del);
594 else
595 strbuf_addstr(buf, no_changes);
598 /* filters out prefixes which have special meaning to list_and_choose() */
599 static int is_valid_prefix(const char *prefix, size_t prefix_len)
601 return prefix_len && prefix &&
603 * We expect `prefix` to be NUL terminated, therefore this
604 * `strcspn()` call is okay, even if it might do much more
605 * work than strictly necessary.
607 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
608 *prefix != '-' && /* deselection */
609 !isdigit(*prefix) && /* selection */
610 (prefix_len != 1 ||
611 (*prefix != '*' && /* "all" wildcard */
612 *prefix != '?')); /* prompt help */
615 struct print_file_item_data {
616 const char *modified_fmt, *color, *reset;
617 struct strbuf buf, name, index, worktree;
618 unsigned only_names:1;
621 static void print_file_item(int i, int selected, struct string_list_item *item,
622 void *print_file_item_data)
624 struct file_item *c = item->util;
625 struct print_file_item_data *d = print_file_item_data;
626 const char *highlighted = NULL;
628 strbuf_reset(&d->index);
629 strbuf_reset(&d->worktree);
630 strbuf_reset(&d->buf);
632 /* Format the item with the prefix highlighted. */
633 if (c->prefix_length > 0 &&
634 is_valid_prefix(item->string, c->prefix_length)) {
635 strbuf_reset(&d->name);
636 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
637 (int)c->prefix_length, item->string, d->reset,
638 item->string + c->prefix_length);
639 highlighted = d->name.buf;
642 if (d->only_names) {
643 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
644 highlighted ? highlighted : item->string);
645 return;
648 render_adddel(&d->worktree, &c->worktree, _("nothing"));
649 render_adddel(&d->index, &c->index, _("unchanged"));
651 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
652 highlighted ? highlighted : item->string);
654 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
657 static int run_status(struct add_i_state *s, const struct pathspec *ps,
658 struct prefix_item_list *files,
659 struct list_and_choose_options *opts)
661 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
662 return -1;
664 list(s, &files->items, NULL, &opts->list_opts);
665 putchar('\n');
667 return 0;
670 static int run_update(struct add_i_state *s, const struct pathspec *ps,
671 struct prefix_item_list *files,
672 struct list_and_choose_options *opts)
674 int res = 0, fd;
675 size_t count, i;
676 struct lock_file index_lock;
678 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
679 return -1;
681 if (!files->items.nr) {
682 putchar('\n');
683 return 0;
686 opts->prompt = N_("Update");
687 count = list_and_choose(s, files, opts);
688 if (count <= 0) {
689 putchar('\n');
690 return 0;
693 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
694 if (fd < 0) {
695 putchar('\n');
696 return -1;
699 for (i = 0; i < files->items.nr; i++) {
700 const char *name = files->items.items[i].string;
701 struct stat st;
703 if (!files->selected[i])
704 continue;
705 if (lstat(name, &st) && is_missing_file_error(errno)) {
706 if (remove_file_from_index(s->r->index, name) < 0) {
707 res = error(_("could not stage '%s'"), name);
708 break;
710 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
711 res = error(_("could not stage '%s'"), name);
712 break;
716 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
717 res = error(_("could not write index"));
719 if (!res)
720 printf(Q_("updated %d path\n",
721 "updated %d paths\n", count), (int)count);
723 putchar('\n');
724 return res;
727 static void revert_from_diff(struct diff_queue_struct *q,
728 struct diff_options *opt, void *data UNUSED)
730 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
732 for (i = 0; i < q->nr; i++) {
733 struct diff_filespec *one = q->queue[i]->one;
734 struct cache_entry *ce;
736 if (!(one->mode && !is_null_oid(&one->oid))) {
737 remove_file_from_index(opt->repo->index, one->path);
738 printf(_("note: %s is untracked now.\n"), one->path);
739 } else {
740 ce = make_cache_entry(opt->repo->index, one->mode,
741 &one->oid, one->path, 0, 0);
742 if (!ce)
743 die(_("make_cache_entry failed for path '%s'"),
744 one->path);
745 add_index_entry(opt->repo->index, ce, add_flags);
750 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
751 struct prefix_item_list *files,
752 struct list_and_choose_options *opts)
754 int res = 0, fd;
755 size_t count, i, j;
757 struct object_id oid;
758 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
759 NULL);
760 struct lock_file index_lock;
761 const char **paths;
762 struct tree *tree;
763 struct diff_options diffopt = { NULL };
765 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
766 return -1;
768 if (!files->items.nr) {
769 putchar('\n');
770 return 0;
773 opts->prompt = N_("Revert");
774 count = list_and_choose(s, files, opts);
775 if (count <= 0)
776 goto finish_revert;
778 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
779 if (fd < 0) {
780 res = -1;
781 goto finish_revert;
784 if (is_initial)
785 oidcpy(&oid, s->r->hash_algo->empty_tree);
786 else {
787 tree = parse_tree_indirect(&oid);
788 if (!tree) {
789 res = error(_("Could not parse HEAD^{tree}"));
790 goto finish_revert;
792 oidcpy(&oid, &tree->object.oid);
795 ALLOC_ARRAY(paths, count + 1);
796 for (i = j = 0; i < files->items.nr; i++)
797 if (files->selected[i])
798 paths[j++] = files->items.items[i].string;
799 paths[j] = NULL;
801 parse_pathspec(&diffopt.pathspec, 0,
802 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
803 NULL, paths);
805 diffopt.output_format = DIFF_FORMAT_CALLBACK;
806 diffopt.format_callback = revert_from_diff;
807 diffopt.flags.override_submodule_config = 1;
808 diffopt.repo = s->r;
810 if (do_diff_cache(&oid, &diffopt)) {
811 diff_free(&diffopt);
812 res = -1;
813 } else {
814 diffcore_std(&diffopt);
815 diff_flush(&diffopt);
817 free(paths);
819 if (!res && write_locked_index(s->r->index, &index_lock,
820 COMMIT_LOCK) < 0)
821 res = -1;
822 else
823 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
824 NULL, NULL, NULL);
826 if (!res)
827 printf(Q_("reverted %d path\n",
828 "reverted %d paths\n", count), (int)count);
830 finish_revert:
831 putchar('\n');
832 return res;
835 static int get_untracked_files(struct repository *r,
836 struct prefix_item_list *files,
837 const struct pathspec *ps)
839 struct dir_struct dir = { 0 };
840 size_t i;
841 struct strbuf buf = STRBUF_INIT;
843 if (repo_read_index(r) < 0)
844 return error(_("could not read index"));
846 prefix_item_list_clear(files);
847 setup_standard_excludes(&dir);
848 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
849 fill_directory(&dir, r->index, ps);
851 for (i = 0; i < dir.nr; i++) {
852 struct dir_entry *ent = dir.entries[i];
854 if (index_name_is_other(r->index, ent->name, ent->len)) {
855 strbuf_reset(&buf);
856 strbuf_add(&buf, ent->name, ent->len);
857 add_file_item(&files->items, buf.buf);
861 strbuf_release(&buf);
862 return 0;
865 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
866 struct prefix_item_list *files,
867 struct list_and_choose_options *opts)
869 struct print_file_item_data *d = opts->list_opts.print_item_data;
870 int res = 0, fd;
871 size_t count, i;
872 struct lock_file index_lock;
874 if (get_untracked_files(s->r, files, ps) < 0)
875 return -1;
877 if (!files->items.nr) {
878 printf(_("No untracked files.\n"));
879 goto finish_add_untracked;
882 opts->prompt = N_("Add untracked");
883 d->only_names = 1;
884 count = list_and_choose(s, files, opts);
885 d->only_names = 0;
886 if (count <= 0)
887 goto finish_add_untracked;
889 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
890 if (fd < 0) {
891 res = -1;
892 goto finish_add_untracked;
895 for (i = 0; i < files->items.nr; i++) {
896 const char *name = files->items.items[i].string;
897 if (files->selected[i] &&
898 add_file_to_index(s->r->index, name, 0) < 0) {
899 res = error(_("could not stage '%s'"), name);
900 break;
904 if (!res &&
905 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
906 res = error(_("could not write index"));
908 if (!res)
909 printf(Q_("added %d path\n",
910 "added %d paths\n", count), (int)count);
912 finish_add_untracked:
913 putchar('\n');
914 return res;
917 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
918 struct prefix_item_list *files,
919 struct list_and_choose_options *opts)
921 int res = 0;
922 ssize_t count, i, j;
923 size_t unmerged_count = 0, binary_count = 0;
925 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
926 &unmerged_count, &binary_count) < 0)
927 return -1;
929 if (unmerged_count || binary_count) {
930 for (i = j = 0; i < files->items.nr; i++) {
931 struct file_item *item = files->items.items[i].util;
933 if (item->index.binary || item->worktree.binary) {
934 free(item);
935 free(files->items.items[i].string);
936 } else if (item->index.unmerged ||
937 item->worktree.unmerged) {
938 color_fprintf_ln(stderr, s->error_color,
939 _("ignoring unmerged: %s"),
940 files->items.items[i].string);
941 free(item);
942 free(files->items.items[i].string);
943 } else
944 files->items.items[j++] = files->items.items[i];
946 files->items.nr = j;
949 if (!files->items.nr) {
950 if (binary_count)
951 fprintf(stderr, _("Only binary files changed.\n"));
952 else
953 fprintf(stderr, _("No changes.\n"));
954 return 0;
957 opts->prompt = N_("Patch update");
958 count = list_and_choose(s, files, opts);
959 if (count > 0) {
960 struct strvec args = STRVEC_INIT;
961 struct pathspec ps_selected = { 0 };
963 for (i = 0; i < files->items.nr; i++)
964 if (files->selected[i])
965 strvec_push(&args,
966 files->items.items[i].string);
967 parse_pathspec(&ps_selected,
968 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
969 PATHSPEC_LITERAL_PATH, "", args.v);
970 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
971 strvec_clear(&args);
972 clear_pathspec(&ps_selected);
975 return res;
978 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
979 struct prefix_item_list *files,
980 struct list_and_choose_options *opts)
982 int res = 0;
983 ssize_t count, i;
985 struct object_id oid;
986 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
987 NULL);
988 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
989 return -1;
991 if (!files->items.nr) {
992 putchar('\n');
993 return 0;
996 opts->prompt = N_("Review diff");
997 opts->flags = IMMEDIATE;
998 count = list_and_choose(s, files, opts);
999 opts->flags = 0;
1000 if (count > 0) {
1001 struct child_process cmd = CHILD_PROCESS_INIT;
1003 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
1004 oid_to_hex(!is_initial ? &oid :
1005 s->r->hash_algo->empty_tree),
1006 "--", NULL);
1007 for (i = 0; i < files->items.nr; i++)
1008 if (files->selected[i])
1009 strvec_push(&cmd.args,
1010 files->items.items[i].string);
1011 res = run_command(&cmd);
1014 putchar('\n');
1015 return res;
1018 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1019 struct prefix_item_list *unused_files,
1020 struct list_and_choose_options *unused_opts)
1022 color_fprintf_ln(stdout, s->help_color, "status - %s",
1023 _("show paths with changes"));
1024 color_fprintf_ln(stdout, s->help_color, "update - %s",
1025 _("add working tree state to the staged set of changes"));
1026 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1027 _("revert staged set of changes back to the HEAD version"));
1028 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1029 _("pick hunks and update selectively"));
1030 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1031 _("view diff between HEAD and index"));
1032 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1033 _("add contents of untracked files to the staged set of changes"));
1035 return 0;
1038 static void choose_prompt_help(struct add_i_state *s)
1040 color_fprintf_ln(stdout, s->help_color, "%s",
1041 _("Prompt help:"));
1042 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1043 _("select a single item"));
1044 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1045 _("select a range of items"));
1046 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1047 _("select multiple ranges"));
1048 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1049 _("select item based on unique prefix"));
1050 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1051 _("unselect specified items"));
1052 color_fprintf_ln(stdout, s->help_color, "* - %s",
1053 _("choose all items"));
1054 color_fprintf_ln(stdout, s->help_color, " - %s",
1055 _("(empty) finish selecting"));
1058 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1059 struct prefix_item_list *files,
1060 struct list_and_choose_options *opts);
1062 struct command_item {
1063 size_t prefix_length;
1064 command_t command;
1067 struct print_command_item_data {
1068 const char *color, *reset;
1071 static void print_command_item(int i, int selected,
1072 struct string_list_item *item,
1073 void *print_command_item_data)
1075 struct print_command_item_data *d = print_command_item_data;
1076 struct command_item *util = item->util;
1078 if (!util->prefix_length ||
1079 !is_valid_prefix(item->string, util->prefix_length))
1080 printf(" %2d: %s", i + 1, item->string);
1081 else
1082 printf(" %2d: %s%.*s%s%s", i + 1,
1083 d->color, (int)util->prefix_length, item->string,
1084 d->reset, item->string + util->prefix_length);
1087 static void command_prompt_help(struct add_i_state *s)
1089 const char *help_color = s->help_color;
1090 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1091 color_fprintf_ln(stdout, help_color, "1 - %s",
1092 _("select a numbered item"));
1093 color_fprintf_ln(stdout, help_color, "foo - %s",
1094 _("select item based on unique prefix"));
1095 color_fprintf_ln(stdout, help_color, " - %s",
1096 _("(empty) select nothing"));
1099 int run_add_i(struct repository *r, const struct pathspec *ps)
1101 struct add_i_state s = { NULL };
1102 struct print_command_item_data data = { "[", "]" };
1103 struct list_and_choose_options main_loop_opts = {
1104 { 4, N_("*** Commands ***"), print_command_item, &data },
1105 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1107 struct {
1108 const char *string;
1109 command_t command;
1110 } command_list[] = {
1111 { "status", run_status },
1112 { "update", run_update },
1113 { "revert", run_revert },
1114 { "add untracked", run_add_untracked },
1115 { "patch", run_patch },
1116 { "diff", run_diff },
1117 { "quit", NULL },
1118 { "help", run_help },
1120 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1122 struct print_file_item_data print_file_item_data = {
1123 "%12s %12s %s", NULL, NULL,
1124 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1126 struct list_and_choose_options opts = {
1127 { 0, NULL, print_file_item, &print_file_item_data },
1128 NULL, 0, choose_prompt_help
1130 struct strbuf header = STRBUF_INIT;
1131 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1132 ssize_t i;
1133 int res = 0;
1135 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1136 struct command_item *util = xcalloc(1, sizeof(*util));
1137 util->command = command_list[i].command;
1138 string_list_append(&commands.items, command_list[i].string)
1139 ->util = util;
1142 init_add_i_state(&s, r);
1145 * When color was asked for, use the prompt color for
1146 * highlighting, otherwise use square brackets.
1148 if (s.use_color) {
1149 data.color = s.prompt_color;
1150 data.reset = s.reset_color;
1152 print_file_item_data.color = data.color;
1153 print_file_item_data.reset = data.reset;
1155 strbuf_addstr(&header, " ");
1156 strbuf_addf(&header, print_file_item_data.modified_fmt,
1157 _("staged"), _("unstaged"), _("path"));
1158 opts.list_opts.header = header.buf;
1160 discard_index(r->index);
1161 if (repo_read_index(r) < 0 ||
1162 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1163 NULL, NULL, NULL) < 0)
1164 warning(_("could not refresh index"));
1166 res = run_status(&s, ps, &files, &opts);
1168 for (;;) {
1169 struct command_item *util;
1171 i = list_and_choose(&s, &commands, &main_loop_opts);
1172 if (i < 0 || i >= commands.items.nr)
1173 util = NULL;
1174 else
1175 util = commands.items.items[i].util;
1177 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1178 printf(_("Bye.\n"));
1179 res = 0;
1180 break;
1183 if (util)
1184 res = util->command(&s, ps, &files, &opts);
1187 prefix_item_list_clear(&files);
1188 strbuf_release(&print_file_item_data.buf);
1189 strbuf_release(&print_file_item_data.name);
1190 strbuf_release(&print_file_item_data.index);
1191 strbuf_release(&print_file_item_data.worktree);
1192 strbuf_release(&header);
1193 prefix_item_list_clear(&commands);
1194 clear_add_i_state(&s);
1196 return res;