Merge branch 'jt/reset-grafts-when-resetting-shallow'
[git/debian.git] / add-interactive.c
blob72472103017920ac227641042f05383a40e5c673
1 #include "cache.h"
2 #include "add-interactive.h"
3 #include "color.h"
4 #include "config.h"
5 #include "diffcore.h"
6 #include "revision.h"
7 #include "refs.h"
8 #include "string-list.h"
9 #include "lockfile.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "prompt.h"
14 static void init_color(struct repository *r, struct add_i_state *s,
15 const char *section_and_slot, char *dst,
16 const char *default_color)
18 char *key = xstrfmt("color.%s", section_and_slot);
19 const char *value;
21 if (!s->use_color)
22 dst[0] = '\0';
23 else if (repo_config_get_value(r, key, &value) ||
24 color_parse(value, dst))
25 strlcpy(dst, default_color, COLOR_MAXLEN);
27 free(key);
30 void init_add_i_state(struct add_i_state *s, struct repository *r)
32 const char *value;
34 s->r = r;
36 if (repo_config_get_value(r, "color.interactive", &value))
37 s->use_color = -1;
38 else
39 s->use_color =
40 git_config_colorbool("color.interactive", value);
41 s->use_color = want_color(s->use_color);
43 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
44 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
45 init_color(r, s, "interactive.prompt", s->prompt_color,
46 GIT_COLOR_BOLD_BLUE);
47 init_color(r, s, "interactive.error", s->error_color,
48 GIT_COLOR_BOLD_RED);
50 init_color(r, s, "diff.frag", s->fraginfo_color,
51 diff_get_color(s->use_color, DIFF_FRAGINFO));
52 init_color(r, s, "diff.context", s->context_color, "fall back");
53 if (!strcmp(s->context_color, "fall back"))
54 init_color(r, s, "diff.plain", s->context_color,
55 diff_get_color(s->use_color, DIFF_CONTEXT));
56 init_color(r, s, "diff.old", s->file_old_color,
57 diff_get_color(s->use_color, DIFF_FILE_OLD));
58 init_color(r, s, "diff.new", s->file_new_color,
59 diff_get_color(s->use_color, DIFF_FILE_NEW));
61 strlcpy(s->reset_color,
62 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
64 FREE_AND_NULL(s->interactive_diff_filter);
65 git_config_get_string("interactive.difffilter",
66 &s->interactive_diff_filter);
68 FREE_AND_NULL(s->interactive_diff_algorithm);
69 git_config_get_string("diff.algorithm",
70 &s->interactive_diff_algorithm);
72 git_config_get_bool("interactive.singlekey", &s->use_single_key);
73 if (s->use_single_key)
74 setbuf(stdin, NULL);
77 void clear_add_i_state(struct add_i_state *s)
79 FREE_AND_NULL(s->interactive_diff_filter);
80 FREE_AND_NULL(s->interactive_diff_algorithm);
81 memset(s, 0, sizeof(*s));
82 s->use_color = -1;
86 * A "prefix item list" is a list of items that are identified by a string, and
87 * a unique prefix (if any) is determined for each item.
89 * It is implemented in the form of a pair of `string_list`s, the first one
90 * duplicating the strings, with the `util` field pointing at a structure whose
91 * first field must be `size_t prefix_length`.
93 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
94 * will be set to zero if no valid, unique prefix could be found.
96 * The second `string_list` is called `sorted` and does _not_ duplicate the
97 * strings but simply reuses the first one's, with the `util` field pointing at
98 * the `string_item_list` of the first `string_list`. It will be populated and
99 * sorted by `find_unique_prefixes()`.
101 struct prefix_item_list {
102 struct string_list items;
103 struct string_list sorted;
104 int *selected; /* for multi-selections */
105 size_t min_length, max_length;
107 #define PREFIX_ITEM_LIST_INIT { \
108 .items = STRING_LIST_INIT_DUP, \
109 .sorted = STRING_LIST_INIT_NODUP, \
110 .min_length = 1, \
111 .max_length = 4, \
114 static void prefix_item_list_clear(struct prefix_item_list *list)
116 string_list_clear(&list->items, 1);
117 string_list_clear(&list->sorted, 0);
118 FREE_AND_NULL(list->selected);
121 static void extend_prefix_length(struct string_list_item *p,
122 const char *other_string, size_t max_length)
124 size_t *len = p->util;
126 if (!*len || memcmp(p->string, other_string, *len))
127 return;
129 for (;;) {
130 char c = p->string[*len];
133 * Is `p` a strict prefix of `other`? Or have we exhausted the
134 * maximal length of the prefix? Or is the current character a
135 * multi-byte UTF-8 one? If so, there is no valid, unique
136 * prefix.
138 if (!c || ++*len > max_length || !isascii(c)) {
139 *len = 0;
140 break;
143 if (c != other_string[*len - 1])
144 break;
148 static void find_unique_prefixes(struct prefix_item_list *list)
150 size_t i;
152 if (list->sorted.nr == list->items.nr)
153 return;
155 string_list_clear(&list->sorted, 0);
156 /* Avoid reallocating incrementally */
157 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
158 list->items.nr));
159 list->sorted.nr = list->sorted.alloc = list->items.nr;
161 for (i = 0; i < list->items.nr; i++) {
162 list->sorted.items[i].string = list->items.items[i].string;
163 list->sorted.items[i].util = list->items.items + i;
166 string_list_sort(&list->sorted);
168 for (i = 0; i < list->sorted.nr; i++) {
169 struct string_list_item *sorted_item = list->sorted.items + i;
170 struct string_list_item *item = sorted_item->util;
171 size_t *len = item->util;
173 *len = 0;
174 while (*len < list->min_length) {
175 char c = item->string[(*len)++];
177 if (!c || !isascii(c)) {
178 *len = 0;
179 break;
183 if (i > 0)
184 extend_prefix_length(item, sorted_item[-1].string,
185 list->max_length);
186 if (i + 1 < list->sorted.nr)
187 extend_prefix_length(item, sorted_item[1].string,
188 list->max_length);
192 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
194 int index = string_list_find_insert_index(&list->sorted, string, 1);
195 struct string_list_item *item;
197 if (list->items.nr != list->sorted.nr)
198 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
199 " vs %"PRIuMAX")",
200 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
202 if (index < 0)
203 item = list->sorted.items[-1 - index].util;
204 else if (index > 0 &&
205 starts_with(list->sorted.items[index - 1].string, string))
206 return -1;
207 else if (index + 1 < list->sorted.nr &&
208 starts_with(list->sorted.items[index + 1].string, string))
209 return -1;
210 else if (index < list->sorted.nr &&
211 starts_with(list->sorted.items[index].string, string))
212 item = list->sorted.items[index].util;
213 else
214 return -1;
215 return item - list->items.items;
218 struct list_options {
219 int columns;
220 const char *header;
221 void (*print_item)(int i, int selected, struct string_list_item *item,
222 void *print_item_data);
223 void *print_item_data;
226 static void list(struct add_i_state *s, struct string_list *list, int *selected,
227 struct list_options *opts)
229 int i, last_lf = 0;
231 if (!list->nr)
232 return;
234 if (opts->header)
235 color_fprintf_ln(stdout, s->header_color,
236 "%s", opts->header);
238 for (i = 0; i < list->nr; i++) {
239 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
240 opts->print_item_data);
242 if ((opts->columns) && ((i + 1) % (opts->columns))) {
243 putchar('\t');
244 last_lf = 0;
246 else {
247 putchar('\n');
248 last_lf = 1;
252 if (!last_lf)
253 putchar('\n');
255 struct list_and_choose_options {
256 struct list_options list_opts;
258 const char *prompt;
259 enum {
260 SINGLETON = (1<<0),
261 IMMEDIATE = (1<<1),
262 } flags;
263 void (*print_help)(struct add_i_state *s);
266 #define LIST_AND_CHOOSE_ERROR (-1)
267 #define LIST_AND_CHOOSE_QUIT (-2)
270 * Returns the selected index in singleton mode, the number of selected items
271 * otherwise.
273 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
274 * `LIST_AND_CHOOSE_QUIT` is returned.
276 static ssize_t list_and_choose(struct add_i_state *s,
277 struct prefix_item_list *items,
278 struct list_and_choose_options *opts)
280 int singleton = opts->flags & SINGLETON;
281 int immediate = opts->flags & IMMEDIATE;
283 struct strbuf input = STRBUF_INIT;
284 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
286 if (!singleton) {
287 free(items->selected);
288 CALLOC_ARRAY(items->selected, items->items.nr);
291 if (singleton && !immediate)
292 BUG("singleton requires immediate");
294 find_unique_prefixes(items);
296 for (;;) {
297 char *p;
299 strbuf_reset(&input);
301 list(s, &items->items, items->selected, &opts->list_opts);
303 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
304 fputs(singleton ? "> " : ">> ", stdout);
305 fflush(stdout);
307 if (git_read_line_interactively(&input) == EOF) {
308 putchar('\n');
309 if (immediate)
310 res = LIST_AND_CHOOSE_QUIT;
311 break;
314 if (!input.len)
315 break;
317 if (!strcmp(input.buf, "?")) {
318 opts->print_help(s);
319 continue;
322 p = input.buf;
323 for (;;) {
324 size_t sep = strcspn(p, " \t\r\n,");
325 int choose = 1;
326 /* `from` is inclusive, `to` is exclusive */
327 ssize_t from = -1, to = -1;
329 if (!sep) {
330 if (!*p)
331 break;
332 p++;
333 continue;
336 /* Input that begins with '-'; de-select */
337 if (*p == '-') {
338 choose = 0;
339 p++;
340 sep--;
343 if (sep == 1 && *p == '*') {
344 from = 0;
345 to = items->items.nr;
346 } else if (isdigit(*p)) {
347 char *endp;
349 * A range can be specified like 5-7 or 5-.
351 * Note: `from` is 0-based while the user input
352 * is 1-based, hence we have to decrement by
353 * one. We do not have to decrement `to` even
354 * if it is 0-based because it is an exclusive
355 * boundary.
357 from = strtoul(p, &endp, 10) - 1;
358 if (endp == p + sep)
359 to = from + 1;
360 else if (*endp == '-') {
361 if (isdigit(*(++endp)))
362 to = strtoul(endp, &endp, 10);
363 else
364 to = items->items.nr;
365 /* extra characters after the range? */
366 if (endp != p + sep)
367 from = -1;
371 if (p[sep])
372 p[sep++] = '\0';
373 if (from < 0) {
374 from = find_unique(p, items);
375 if (from >= 0)
376 to = from + 1;
379 if (from < 0 || from >= items->items.nr ||
380 (singleton && from + 1 != to)) {
381 color_fprintf_ln(stderr, s->error_color,
382 _("Huh (%s)?"), p);
383 break;
384 } else if (singleton) {
385 res = from;
386 break;
389 if (to > items->items.nr)
390 to = items->items.nr;
392 for (; from < to; from++)
393 if (items->selected[from] != choose) {
394 items->selected[from] = choose;
395 res += choose ? +1 : -1;
398 p += sep;
401 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
402 !strcmp(input.buf, "*"))
403 break;
406 strbuf_release(&input);
407 return res;
410 struct adddel {
411 uintmax_t add, del;
412 unsigned seen:1, unmerged:1, binary:1;
415 struct file_item {
416 size_t prefix_length;
417 struct adddel index, worktree;
420 static void add_file_item(struct string_list *files, const char *name)
422 struct file_item *item = xcalloc(1, sizeof(*item));
424 string_list_append(files, name)->util = item;
427 struct pathname_entry {
428 struct hashmap_entry ent;
429 const char *name;
430 struct file_item *item;
433 static int pathname_entry_cmp(const void *unused_cmp_data,
434 const struct hashmap_entry *he1,
435 const struct hashmap_entry *he2,
436 const void *name)
438 const struct pathname_entry *e1 =
439 container_of(he1, const struct pathname_entry, ent);
440 const struct pathname_entry *e2 =
441 container_of(he2, const struct pathname_entry, ent);
443 return strcmp(e1->name, name ? (const char *)name : e2->name);
446 struct collection_status {
447 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
449 const char *reference;
451 unsigned skip_unseen:1;
452 size_t unmerged_count, binary_count;
453 struct string_list *files;
454 struct hashmap file_map;
457 static void collect_changes_cb(struct diff_queue_struct *q,
458 struct diff_options *options,
459 void *data)
461 struct collection_status *s = data;
462 struct diffstat_t stat = { 0 };
463 int i;
465 if (!q->nr)
466 return;
468 compute_diffstat(options, &stat, q);
470 for (i = 0; i < stat.nr; i++) {
471 const char *name = stat.files[i]->name;
472 int hash = strhash(name);
473 struct pathname_entry *entry;
474 struct file_item *file_item;
475 struct adddel *adddel, *other_adddel;
477 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
478 struct pathname_entry, ent);
479 if (!entry) {
480 if (s->skip_unseen)
481 continue;
483 add_file_item(s->files, name);
485 CALLOC_ARRAY(entry, 1);
486 hashmap_entry_init(&entry->ent, hash);
487 entry->name = s->files->items[s->files->nr - 1].string;
488 entry->item = s->files->items[s->files->nr - 1].util;
489 hashmap_add(&s->file_map, &entry->ent);
492 file_item = entry->item;
493 adddel = s->mode == FROM_INDEX ?
494 &file_item->index : &file_item->worktree;
495 other_adddel = s->mode == FROM_INDEX ?
496 &file_item->worktree : &file_item->index;
497 adddel->seen = 1;
498 adddel->add = stat.files[i]->added;
499 adddel->del = stat.files[i]->deleted;
500 if (stat.files[i]->is_binary) {
501 if (!other_adddel->binary)
502 s->binary_count++;
503 adddel->binary = 1;
505 if (stat.files[i]->is_unmerged) {
506 if (!other_adddel->unmerged)
507 s->unmerged_count++;
508 adddel->unmerged = 1;
511 free_diffstat_info(&stat);
514 enum modified_files_filter {
515 NO_FILTER = 0,
516 WORKTREE_ONLY = 1,
517 INDEX_ONLY = 2,
520 static int get_modified_files(struct repository *r,
521 enum modified_files_filter filter,
522 struct prefix_item_list *files,
523 const struct pathspec *ps,
524 size_t *unmerged_count,
525 size_t *binary_count)
527 struct object_id head_oid;
528 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
529 &head_oid, NULL);
530 struct collection_status s = { 0 };
531 int i;
533 if (discard_index(r->index) < 0 ||
534 repo_read_index_preload(r, ps, 0) < 0)
535 return error(_("could not read index"));
537 prefix_item_list_clear(files);
538 s.files = &files->items;
539 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
541 for (i = 0; i < 2; i++) {
542 struct rev_info rev;
543 struct setup_revision_opt opt = { 0 };
545 if (filter == INDEX_ONLY)
546 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
547 else
548 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
549 s.skip_unseen = filter && i;
551 opt.def = is_initial ?
552 empty_tree_oid_hex() : oid_to_hex(&head_oid);
554 init_revisions(&rev, NULL);
555 setup_revisions(0, NULL, &rev, &opt);
557 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
558 rev.diffopt.format_callback = collect_changes_cb;
559 rev.diffopt.format_callback_data = &s;
561 if (ps)
562 copy_pathspec(&rev.prune_data, ps);
564 if (s.mode == FROM_INDEX)
565 run_diff_index(&rev, 1);
566 else {
567 rev.diffopt.flags.ignore_dirty_submodules = 1;
568 run_diff_files(&rev, 0);
571 if (ps)
572 clear_pathspec(&rev.prune_data);
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 if (files->selected[i] &&
702 add_file_to_index(s->r->index, name, 0) < 0) {
703 res = error(_("could not stage '%s'"), name);
704 break;
708 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
709 res = error(_("could not write index"));
711 if (!res)
712 printf(Q_("updated %d path\n",
713 "updated %d paths\n", count), (int)count);
715 putchar('\n');
716 return res;
719 static void revert_from_diff(struct diff_queue_struct *q,
720 struct diff_options *opt, void *data)
722 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
724 for (i = 0; i < q->nr; i++) {
725 struct diff_filespec *one = q->queue[i]->one;
726 struct cache_entry *ce;
728 if (!(one->mode && !is_null_oid(&one->oid))) {
729 remove_file_from_index(opt->repo->index, one->path);
730 printf(_("note: %s is untracked now.\n"), one->path);
731 } else {
732 ce = make_cache_entry(opt->repo->index, one->mode,
733 &one->oid, one->path, 0, 0);
734 if (!ce)
735 die(_("make_cache_entry failed for path '%s'"),
736 one->path);
737 add_index_entry(opt->repo->index, ce, add_flags);
742 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
743 struct prefix_item_list *files,
744 struct list_and_choose_options *opts)
746 int res = 0, fd;
747 size_t count, i, j;
749 struct object_id oid;
750 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
751 NULL);
752 struct lock_file index_lock;
753 const char **paths;
754 struct tree *tree;
755 struct diff_options diffopt = { NULL };
757 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
758 return -1;
760 if (!files->items.nr) {
761 putchar('\n');
762 return 0;
765 opts->prompt = N_("Revert");
766 count = list_and_choose(s, files, opts);
767 if (count <= 0)
768 goto finish_revert;
770 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
771 if (fd < 0) {
772 res = -1;
773 goto finish_revert;
776 if (is_initial)
777 oidcpy(&oid, s->r->hash_algo->empty_tree);
778 else {
779 tree = parse_tree_indirect(&oid);
780 if (!tree) {
781 res = error(_("Could not parse HEAD^{tree}"));
782 goto finish_revert;
784 oidcpy(&oid, &tree->object.oid);
787 ALLOC_ARRAY(paths, count + 1);
788 for (i = j = 0; i < files->items.nr; i++)
789 if (files->selected[i])
790 paths[j++] = files->items.items[i].string;
791 paths[j] = NULL;
793 parse_pathspec(&diffopt.pathspec, 0,
794 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
795 NULL, paths);
797 diffopt.output_format = DIFF_FORMAT_CALLBACK;
798 diffopt.format_callback = revert_from_diff;
799 diffopt.flags.override_submodule_config = 1;
800 diffopt.repo = s->r;
802 if (do_diff_cache(&oid, &diffopt)) {
803 diff_free(&diffopt);
804 res = -1;
805 } else {
806 diffcore_std(&diffopt);
807 diff_flush(&diffopt);
809 free(paths);
811 if (!res && write_locked_index(s->r->index, &index_lock,
812 COMMIT_LOCK) < 0)
813 res = -1;
814 else
815 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
816 NULL, NULL, NULL);
818 if (!res)
819 printf(Q_("reverted %d path\n",
820 "reverted %d paths\n", count), (int)count);
822 finish_revert:
823 putchar('\n');
824 return res;
827 static int get_untracked_files(struct repository *r,
828 struct prefix_item_list *files,
829 const struct pathspec *ps)
831 struct dir_struct dir = { 0 };
832 size_t i;
833 struct strbuf buf = STRBUF_INIT;
835 if (repo_read_index(r) < 0)
836 return error(_("could not read index"));
838 prefix_item_list_clear(files);
839 setup_standard_excludes(&dir);
840 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
841 fill_directory(&dir, r->index, ps);
843 for (i = 0; i < dir.nr; i++) {
844 struct dir_entry *ent = dir.entries[i];
846 if (index_name_is_other(r->index, ent->name, ent->len)) {
847 strbuf_reset(&buf);
848 strbuf_add(&buf, ent->name, ent->len);
849 add_file_item(&files->items, buf.buf);
853 strbuf_release(&buf);
854 return 0;
857 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
858 struct prefix_item_list *files,
859 struct list_and_choose_options *opts)
861 struct print_file_item_data *d = opts->list_opts.print_item_data;
862 int res = 0, fd;
863 size_t count, i;
864 struct lock_file index_lock;
866 if (get_untracked_files(s->r, files, ps) < 0)
867 return -1;
869 if (!files->items.nr) {
870 printf(_("No untracked files.\n"));
871 goto finish_add_untracked;
874 opts->prompt = N_("Add untracked");
875 d->only_names = 1;
876 count = list_and_choose(s, files, opts);
877 d->only_names = 0;
878 if (count <= 0)
879 goto finish_add_untracked;
881 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
882 if (fd < 0) {
883 res = -1;
884 goto finish_add_untracked;
887 for (i = 0; i < files->items.nr; i++) {
888 const char *name = files->items.items[i].string;
889 if (files->selected[i] &&
890 add_file_to_index(s->r->index, name, 0) < 0) {
891 res = error(_("could not stage '%s'"), name);
892 break;
896 if (!res &&
897 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
898 res = error(_("could not write index"));
900 if (!res)
901 printf(Q_("added %d path\n",
902 "added %d paths\n", count), (int)count);
904 finish_add_untracked:
905 putchar('\n');
906 return res;
909 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
910 struct prefix_item_list *files,
911 struct list_and_choose_options *opts)
913 int res = 0;
914 ssize_t count, i, j;
915 size_t unmerged_count = 0, binary_count = 0;
917 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
918 &unmerged_count, &binary_count) < 0)
919 return -1;
921 if (unmerged_count || binary_count) {
922 for (i = j = 0; i < files->items.nr; i++) {
923 struct file_item *item = files->items.items[i].util;
925 if (item->index.binary || item->worktree.binary) {
926 free(item);
927 free(files->items.items[i].string);
928 } else if (item->index.unmerged ||
929 item->worktree.unmerged) {
930 color_fprintf_ln(stderr, s->error_color,
931 _("ignoring unmerged: %s"),
932 files->items.items[i].string);
933 free(item);
934 free(files->items.items[i].string);
935 } else
936 files->items.items[j++] = files->items.items[i];
938 files->items.nr = j;
941 if (!files->items.nr) {
942 if (binary_count)
943 fprintf(stderr, _("Only binary files changed.\n"));
944 else
945 fprintf(stderr, _("No changes.\n"));
946 return 0;
949 opts->prompt = N_("Patch update");
950 count = list_and_choose(s, files, opts);
951 if (count > 0) {
952 struct strvec args = STRVEC_INIT;
953 struct pathspec ps_selected = { 0 };
955 for (i = 0; i < files->items.nr; i++)
956 if (files->selected[i])
957 strvec_push(&args,
958 files->items.items[i].string);
959 parse_pathspec(&ps_selected,
960 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
961 PATHSPEC_LITERAL_PATH, "", args.v);
962 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
963 strvec_clear(&args);
964 clear_pathspec(&ps_selected);
967 return res;
970 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
971 struct prefix_item_list *files,
972 struct list_and_choose_options *opts)
974 int res = 0;
975 ssize_t count, i;
977 struct object_id oid;
978 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
979 NULL);
980 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
981 return -1;
983 if (!files->items.nr) {
984 putchar('\n');
985 return 0;
988 opts->prompt = N_("Review diff");
989 opts->flags = IMMEDIATE;
990 count = list_and_choose(s, files, opts);
991 opts->flags = 0;
992 if (count > 0) {
993 struct strvec args = STRVEC_INIT;
995 strvec_pushl(&args, "git", "diff", "-p", "--cached",
996 oid_to_hex(!is_initial ? &oid :
997 s->r->hash_algo->empty_tree),
998 "--", NULL);
999 for (i = 0; i < files->items.nr; i++)
1000 if (files->selected[i])
1001 strvec_push(&args,
1002 files->items.items[i].string);
1003 res = run_command_v_opt(args.v, 0);
1004 strvec_clear(&args);
1007 putchar('\n');
1008 return res;
1011 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1012 struct prefix_item_list *unused_files,
1013 struct list_and_choose_options *unused_opts)
1015 color_fprintf_ln(stdout, s->help_color, "status - %s",
1016 _("show paths with changes"));
1017 color_fprintf_ln(stdout, s->help_color, "update - %s",
1018 _("add working tree state to the staged set of changes"));
1019 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1020 _("revert staged set of changes back to the HEAD version"));
1021 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1022 _("pick hunks and update selectively"));
1023 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1024 _("view diff between HEAD and index"));
1025 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1026 _("add contents of untracked files to the staged set of changes"));
1028 return 0;
1031 static void choose_prompt_help(struct add_i_state *s)
1033 color_fprintf_ln(stdout, s->help_color, "%s",
1034 _("Prompt help:"));
1035 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1036 _("select a single item"));
1037 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1038 _("select a range of items"));
1039 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1040 _("select multiple ranges"));
1041 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1042 _("select item based on unique prefix"));
1043 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1044 _("unselect specified items"));
1045 color_fprintf_ln(stdout, s->help_color, "* - %s",
1046 _("choose all items"));
1047 color_fprintf_ln(stdout, s->help_color, " - %s",
1048 _("(empty) finish selecting"));
1051 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1052 struct prefix_item_list *files,
1053 struct list_and_choose_options *opts);
1055 struct command_item {
1056 size_t prefix_length;
1057 command_t command;
1060 struct print_command_item_data {
1061 const char *color, *reset;
1064 static void print_command_item(int i, int selected,
1065 struct string_list_item *item,
1066 void *print_command_item_data)
1068 struct print_command_item_data *d = print_command_item_data;
1069 struct command_item *util = item->util;
1071 if (!util->prefix_length ||
1072 !is_valid_prefix(item->string, util->prefix_length))
1073 printf(" %2d: %s", i + 1, item->string);
1074 else
1075 printf(" %2d: %s%.*s%s%s", i + 1,
1076 d->color, (int)util->prefix_length, item->string,
1077 d->reset, item->string + util->prefix_length);
1080 static void command_prompt_help(struct add_i_state *s)
1082 const char *help_color = s->help_color;
1083 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1084 color_fprintf_ln(stdout, help_color, "1 - %s",
1085 _("select a numbered item"));
1086 color_fprintf_ln(stdout, help_color, "foo - %s",
1087 _("select item based on unique prefix"));
1088 color_fprintf_ln(stdout, help_color, " - %s",
1089 _("(empty) select nothing"));
1092 int run_add_i(struct repository *r, const struct pathspec *ps)
1094 struct add_i_state s = { NULL };
1095 struct print_command_item_data data = { "[", "]" };
1096 struct list_and_choose_options main_loop_opts = {
1097 { 4, N_("*** Commands ***"), print_command_item, &data },
1098 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1100 struct {
1101 const char *string;
1102 command_t command;
1103 } command_list[] = {
1104 { "status", run_status },
1105 { "update", run_update },
1106 { "revert", run_revert },
1107 { "add untracked", run_add_untracked },
1108 { "patch", run_patch },
1109 { "diff", run_diff },
1110 { "quit", NULL },
1111 { "help", run_help },
1113 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1115 struct print_file_item_data print_file_item_data = {
1116 "%12s %12s %s", NULL, NULL,
1117 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1119 struct list_and_choose_options opts = {
1120 { 0, NULL, print_file_item, &print_file_item_data },
1121 NULL, 0, choose_prompt_help
1123 struct strbuf header = STRBUF_INIT;
1124 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1125 ssize_t i;
1126 int res = 0;
1128 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1129 struct command_item *util = xcalloc(1, sizeof(*util));
1130 util->command = command_list[i].command;
1131 string_list_append(&commands.items, command_list[i].string)
1132 ->util = util;
1135 init_add_i_state(&s, r);
1138 * When color was asked for, use the prompt color for
1139 * highlighting, otherwise use square brackets.
1141 if (s.use_color) {
1142 data.color = s.prompt_color;
1143 data.reset = s.reset_color;
1145 print_file_item_data.color = data.color;
1146 print_file_item_data.reset = data.reset;
1148 strbuf_addstr(&header, " ");
1149 strbuf_addf(&header, print_file_item_data.modified_fmt,
1150 _("staged"), _("unstaged"), _("path"));
1151 opts.list_opts.header = header.buf;
1153 if (discard_index(r->index) < 0 ||
1154 repo_read_index(r) < 0 ||
1155 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1156 NULL, NULL, NULL) < 0)
1157 warning(_("could not refresh index"));
1159 res = run_status(&s, ps, &files, &opts);
1161 for (;;) {
1162 struct command_item *util;
1164 i = list_and_choose(&s, &commands, &main_loop_opts);
1165 if (i < 0 || i >= commands.items.nr)
1166 util = NULL;
1167 else
1168 util = commands.items.items[i].util;
1170 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1171 printf(_("Bye.\n"));
1172 res = 0;
1173 break;
1176 if (util)
1177 res = util->command(&s, ps, &files, &opts);
1180 prefix_item_list_clear(&files);
1181 strbuf_release(&print_file_item_data.buf);
1182 strbuf_release(&print_file_item_data.name);
1183 strbuf_release(&print_file_item_data.index);
1184 strbuf_release(&print_file_item_data.worktree);
1185 strbuf_release(&header);
1186 prefix_item_list_clear(&commands);
1187 clear_add_i_state(&s);
1189 return res;