rebase --continue: refuse to commit after failed command
[alt-git.git] / add-interactive.c
blob757a9929d41242fd878dae25d12839cd2a6cb52d
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"
16 static void init_color(struct repository *r, struct add_i_state *s,
17 const char *section_and_slot, char *dst,
18 const char *default_color)
20 char *key = xstrfmt("color.%s", section_and_slot);
21 const char *value;
23 if (!s->use_color)
24 dst[0] = '\0';
25 else if (repo_config_get_value(r, key, &value) ||
26 color_parse(value, dst))
27 strlcpy(dst, default_color, COLOR_MAXLEN);
29 free(key);
32 void init_add_i_state(struct add_i_state *s, struct repository *r)
34 const char *value;
36 s->r = r;
38 if (repo_config_get_value(r, "color.interactive", &value))
39 s->use_color = -1;
40 else
41 s->use_color =
42 git_config_colorbool("color.interactive", value);
43 s->use_color = want_color(s->use_color);
45 init_color(r, s, "interactive.header", s->header_color, GIT_COLOR_BOLD);
46 init_color(r, s, "interactive.help", s->help_color, GIT_COLOR_BOLD_RED);
47 init_color(r, s, "interactive.prompt", s->prompt_color,
48 GIT_COLOR_BOLD_BLUE);
49 init_color(r, s, "interactive.error", s->error_color,
50 GIT_COLOR_BOLD_RED);
52 init_color(r, s, "diff.frag", s->fraginfo_color,
53 diff_get_color(s->use_color, DIFF_FRAGINFO));
54 init_color(r, s, "diff.context", s->context_color, "fall back");
55 if (!strcmp(s->context_color, "fall back"))
56 init_color(r, s, "diff.plain", s->context_color,
57 diff_get_color(s->use_color, DIFF_CONTEXT));
58 init_color(r, s, "diff.old", s->file_old_color,
59 diff_get_color(s->use_color, DIFF_FILE_OLD));
60 init_color(r, s, "diff.new", s->file_new_color,
61 diff_get_color(s->use_color, DIFF_FILE_NEW));
63 strlcpy(s->reset_color,
64 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
66 FREE_AND_NULL(s->interactive_diff_filter);
67 git_config_get_string("interactive.difffilter",
68 &s->interactive_diff_filter);
70 FREE_AND_NULL(s->interactive_diff_algorithm);
71 git_config_get_string("diff.algorithm",
72 &s->interactive_diff_algorithm);
74 git_config_get_bool("interactive.singlekey", &s->use_single_key);
75 if (s->use_single_key)
76 setbuf(stdin, NULL);
79 void clear_add_i_state(struct add_i_state *s)
81 FREE_AND_NULL(s->interactive_diff_filter);
82 FREE_AND_NULL(s->interactive_diff_algorithm);
83 memset(s, 0, sizeof(*s));
84 s->use_color = -1;
88 * A "prefix item list" is a list of items that are identified by a string, and
89 * a unique prefix (if any) is determined for each item.
91 * It is implemented in the form of a pair of `string_list`s, the first one
92 * duplicating the strings, with the `util` field pointing at a structure whose
93 * first field must be `size_t prefix_length`.
95 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
96 * will be set to zero if no valid, unique prefix could be found.
98 * The second `string_list` is called `sorted` and does _not_ duplicate the
99 * strings but simply reuses the first one's, with the `util` field pointing at
100 * the `string_item_list` of the first `string_list`. It will be populated and
101 * sorted by `find_unique_prefixes()`.
103 struct prefix_item_list {
104 struct string_list items;
105 struct string_list sorted;
106 int *selected; /* for multi-selections */
107 size_t min_length, max_length;
109 #define PREFIX_ITEM_LIST_INIT { \
110 .items = STRING_LIST_INIT_DUP, \
111 .sorted = STRING_LIST_INIT_NODUP, \
112 .min_length = 1, \
113 .max_length = 4, \
116 static void prefix_item_list_clear(struct prefix_item_list *list)
118 string_list_clear(&list->items, 1);
119 string_list_clear(&list->sorted, 0);
120 FREE_AND_NULL(list->selected);
123 static void extend_prefix_length(struct string_list_item *p,
124 const char *other_string, size_t max_length)
126 size_t *len = p->util;
128 if (!*len || memcmp(p->string, other_string, *len))
129 return;
131 for (;;) {
132 char c = p->string[*len];
135 * Is `p` a strict prefix of `other`? Or have we exhausted the
136 * maximal length of the prefix? Or is the current character a
137 * multi-byte UTF-8 one? If so, there is no valid, unique
138 * prefix.
140 if (!c || ++*len > max_length || !isascii(c)) {
141 *len = 0;
142 break;
145 if (c != other_string[*len - 1])
146 break;
150 static void find_unique_prefixes(struct prefix_item_list *list)
152 size_t i;
154 if (list->sorted.nr == list->items.nr)
155 return;
157 string_list_clear(&list->sorted, 0);
158 /* Avoid reallocating incrementally */
159 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
160 list->items.nr));
161 list->sorted.nr = list->sorted.alloc = list->items.nr;
163 for (i = 0; i < list->items.nr; i++) {
164 list->sorted.items[i].string = list->items.items[i].string;
165 list->sorted.items[i].util = list->items.items + i;
168 string_list_sort(&list->sorted);
170 for (i = 0; i < list->sorted.nr; i++) {
171 struct string_list_item *sorted_item = list->sorted.items + i;
172 struct string_list_item *item = sorted_item->util;
173 size_t *len = item->util;
175 *len = 0;
176 while (*len < list->min_length) {
177 char c = item->string[(*len)++];
179 if (!c || !isascii(c)) {
180 *len = 0;
181 break;
185 if (i > 0)
186 extend_prefix_length(item, sorted_item[-1].string,
187 list->max_length);
188 if (i + 1 < list->sorted.nr)
189 extend_prefix_length(item, sorted_item[1].string,
190 list->max_length);
194 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
196 int index = string_list_find_insert_index(&list->sorted, string, 1);
197 struct string_list_item *item;
199 if (list->items.nr != list->sorted.nr)
200 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
201 " vs %"PRIuMAX")",
202 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
204 if (index < 0)
205 item = list->sorted.items[-1 - index].util;
206 else if (index > 0 &&
207 starts_with(list->sorted.items[index - 1].string, string))
208 return -1;
209 else if (index + 1 < list->sorted.nr &&
210 starts_with(list->sorted.items[index + 1].string, string))
211 return -1;
212 else if (index < list->sorted.nr &&
213 starts_with(list->sorted.items[index].string, string))
214 item = list->sorted.items[index].util;
215 else
216 return -1;
217 return item - list->items.items;
220 struct list_options {
221 int columns;
222 const char *header;
223 void (*print_item)(int i, int selected, struct string_list_item *item,
224 void *print_item_data);
225 void *print_item_data;
228 static void list(struct add_i_state *s, struct string_list *list, int *selected,
229 struct list_options *opts)
231 int i, last_lf = 0;
233 if (!list->nr)
234 return;
236 if (opts->header)
237 color_fprintf_ln(stdout, s->header_color,
238 "%s", opts->header);
240 for (i = 0; i < list->nr; i++) {
241 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
242 opts->print_item_data);
244 if ((opts->columns) && ((i + 1) % (opts->columns))) {
245 putchar('\t');
246 last_lf = 0;
248 else {
249 putchar('\n');
250 last_lf = 1;
254 if (!last_lf)
255 putchar('\n');
257 struct list_and_choose_options {
258 struct list_options list_opts;
260 const char *prompt;
261 enum {
262 SINGLETON = (1<<0),
263 IMMEDIATE = (1<<1),
264 } flags;
265 void (*print_help)(struct add_i_state *s);
268 #define LIST_AND_CHOOSE_ERROR (-1)
269 #define LIST_AND_CHOOSE_QUIT (-2)
272 * Returns the selected index in singleton mode, the number of selected items
273 * otherwise.
275 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
276 * `LIST_AND_CHOOSE_QUIT` is returned.
278 static ssize_t list_and_choose(struct add_i_state *s,
279 struct prefix_item_list *items,
280 struct list_and_choose_options *opts)
282 int singleton = opts->flags & SINGLETON;
283 int immediate = opts->flags & IMMEDIATE;
285 struct strbuf input = STRBUF_INIT;
286 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
288 if (!singleton) {
289 free(items->selected);
290 CALLOC_ARRAY(items->selected, items->items.nr);
293 if (singleton && !immediate)
294 BUG("singleton requires immediate");
296 find_unique_prefixes(items);
298 for (;;) {
299 char *p;
301 strbuf_reset(&input);
303 list(s, &items->items, items->selected, &opts->list_opts);
305 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
306 fputs(singleton ? "> " : ">> ", stdout);
307 fflush(stdout);
309 if (git_read_line_interactively(&input) == EOF) {
310 putchar('\n');
311 if (immediate)
312 res = LIST_AND_CHOOSE_QUIT;
313 break;
316 if (!input.len)
317 break;
319 if (!strcmp(input.buf, "?")) {
320 opts->print_help(s);
321 continue;
324 p = input.buf;
325 for (;;) {
326 size_t sep = strcspn(p, " \t\r\n,");
327 int choose = 1;
328 /* `from` is inclusive, `to` is exclusive */
329 ssize_t from = -1, to = -1;
331 if (!sep) {
332 if (!*p)
333 break;
334 p++;
335 continue;
338 /* Input that begins with '-'; de-select */
339 if (*p == '-') {
340 choose = 0;
341 p++;
342 sep--;
345 if (sep == 1 && *p == '*') {
346 from = 0;
347 to = items->items.nr;
348 } else if (isdigit(*p)) {
349 char *endp;
351 * A range can be specified like 5-7 or 5-.
353 * Note: `from` is 0-based while the user input
354 * is 1-based, hence we have to decrement by
355 * one. We do not have to decrement `to` even
356 * if it is 0-based because it is an exclusive
357 * boundary.
359 from = strtoul(p, &endp, 10) - 1;
360 if (endp == p + sep)
361 to = from + 1;
362 else if (*endp == '-') {
363 if (isdigit(*(++endp)))
364 to = strtoul(endp, &endp, 10);
365 else
366 to = items->items.nr;
367 /* extra characters after the range? */
368 if (endp != p + sep)
369 from = -1;
373 if (p[sep])
374 p[sep++] = '\0';
375 if (from < 0) {
376 from = find_unique(p, items);
377 if (from >= 0)
378 to = from + 1;
381 if (from < 0 || from >= items->items.nr ||
382 (singleton && from + 1 != to)) {
383 color_fprintf_ln(stderr, s->error_color,
384 _("Huh (%s)?"), p);
385 break;
386 } else if (singleton) {
387 res = from;
388 break;
391 if (to > items->items.nr)
392 to = items->items.nr;
394 for (; from < to; from++)
395 if (items->selected[from] != choose) {
396 items->selected[from] = choose;
397 res += choose ? +1 : -1;
400 p += sep;
403 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
404 !strcmp(input.buf, "*"))
405 break;
408 strbuf_release(&input);
409 return res;
412 struct adddel {
413 uintmax_t add, del;
414 unsigned seen:1, unmerged:1, binary:1;
417 struct file_item {
418 size_t prefix_length;
419 struct adddel index, worktree;
422 static void add_file_item(struct string_list *files, const char *name)
424 struct file_item *item = xcalloc(1, sizeof(*item));
426 string_list_append(files, name)->util = item;
429 struct pathname_entry {
430 struct hashmap_entry ent;
431 const char *name;
432 struct file_item *item;
435 static int pathname_entry_cmp(const void *cmp_data UNUSED,
436 const struct hashmap_entry *he1,
437 const struct hashmap_entry *he2,
438 const void *name)
440 const struct pathname_entry *e1 =
441 container_of(he1, const struct pathname_entry, ent);
442 const struct pathname_entry *e2 =
443 container_of(he2, const struct pathname_entry, ent);
445 return strcmp(e1->name, name ? (const char *)name : e2->name);
448 struct collection_status {
449 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
451 const char *reference;
453 unsigned skip_unseen:1;
454 size_t unmerged_count, binary_count;
455 struct string_list *files;
456 struct hashmap file_map;
459 static void collect_changes_cb(struct diff_queue_struct *q,
460 struct diff_options *options,
461 void *data)
463 struct collection_status *s = data;
464 struct diffstat_t stat = { 0 };
465 int i;
467 if (!q->nr)
468 return;
470 compute_diffstat(options, &stat, q);
472 for (i = 0; i < stat.nr; i++) {
473 const char *name = stat.files[i]->name;
474 int hash = strhash(name);
475 struct pathname_entry *entry;
476 struct file_item *file_item;
477 struct adddel *adddel, *other_adddel;
479 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
480 struct pathname_entry, ent);
481 if (!entry) {
482 if (s->skip_unseen)
483 continue;
485 add_file_item(s->files, name);
487 CALLOC_ARRAY(entry, 1);
488 hashmap_entry_init(&entry->ent, hash);
489 entry->name = s->files->items[s->files->nr - 1].string;
490 entry->item = s->files->items[s->files->nr - 1].util;
491 hashmap_add(&s->file_map, &entry->ent);
494 file_item = entry->item;
495 adddel = s->mode == FROM_INDEX ?
496 &file_item->index : &file_item->worktree;
497 other_adddel = s->mode == FROM_INDEX ?
498 &file_item->worktree : &file_item->index;
499 adddel->seen = 1;
500 adddel->add = stat.files[i]->added;
501 adddel->del = stat.files[i]->deleted;
502 if (stat.files[i]->is_binary) {
503 if (!other_adddel->binary)
504 s->binary_count++;
505 adddel->binary = 1;
507 if (stat.files[i]->is_unmerged) {
508 if (!other_adddel->unmerged)
509 s->unmerged_count++;
510 adddel->unmerged = 1;
513 free_diffstat_info(&stat);
516 enum modified_files_filter {
517 NO_FILTER = 0,
518 WORKTREE_ONLY = 1,
519 INDEX_ONLY = 2,
522 static int get_modified_files(struct repository *r,
523 enum modified_files_filter filter,
524 struct prefix_item_list *files,
525 const struct pathspec *ps,
526 size_t *unmerged_count,
527 size_t *binary_count)
529 struct object_id head_oid;
530 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
531 &head_oid, NULL);
532 struct collection_status s = { 0 };
533 int i;
535 discard_index(r->index);
536 if (repo_read_index_preload(r, ps, 0) < 0)
537 return error(_("could not read index"));
539 prefix_item_list_clear(files);
540 s.files = &files->items;
541 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
543 for (i = 0; i < 2; i++) {
544 struct rev_info rev;
545 struct setup_revision_opt opt = { 0 };
547 if (filter == INDEX_ONLY)
548 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
549 else
550 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
551 s.skip_unseen = filter && i;
553 opt.def = is_initial ?
554 empty_tree_oid_hex() : oid_to_hex(&head_oid);
556 repo_init_revisions(r, &rev, NULL);
557 setup_revisions(0, NULL, &rev, &opt);
559 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
560 rev.diffopt.format_callback = collect_changes_cb;
561 rev.diffopt.format_callback_data = &s;
563 if (ps)
564 copy_pathspec(&rev.prune_data, ps);
566 if (s.mode == FROM_INDEX)
567 run_diff_index(&rev, 1);
568 else {
569 rev.diffopt.flags.ignore_dirty_submodules = 1;
570 run_diff_files(&rev, 0);
573 release_revisions(&rev);
575 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
576 if (unmerged_count)
577 *unmerged_count = s.unmerged_count;
578 if (binary_count)
579 *binary_count = s.binary_count;
581 /* While the diffs are ordered already, we ran *two* diffs... */
582 string_list_sort(&files->items);
584 return 0;
587 static void render_adddel(struct strbuf *buf,
588 struct adddel *ad, const char *no_changes)
590 if (ad->binary)
591 strbuf_addstr(buf, _("binary"));
592 else if (ad->seen)
593 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
594 (uintmax_t)ad->add, (uintmax_t)ad->del);
595 else
596 strbuf_addstr(buf, no_changes);
599 /* filters out prefixes which have special meaning to list_and_choose() */
600 static int is_valid_prefix(const char *prefix, size_t prefix_len)
602 return prefix_len && prefix &&
604 * We expect `prefix` to be NUL terminated, therefore this
605 * `strcspn()` call is okay, even if it might do much more
606 * work than strictly necessary.
608 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
609 *prefix != '-' && /* deselection */
610 !isdigit(*prefix) && /* selection */
611 (prefix_len != 1 ||
612 (*prefix != '*' && /* "all" wildcard */
613 *prefix != '?')); /* prompt help */
616 struct print_file_item_data {
617 const char *modified_fmt, *color, *reset;
618 struct strbuf buf, name, index, worktree;
619 unsigned only_names:1;
622 static void print_file_item(int i, int selected, struct string_list_item *item,
623 void *print_file_item_data)
625 struct file_item *c = item->util;
626 struct print_file_item_data *d = print_file_item_data;
627 const char *highlighted = NULL;
629 strbuf_reset(&d->index);
630 strbuf_reset(&d->worktree);
631 strbuf_reset(&d->buf);
633 /* Format the item with the prefix highlighted. */
634 if (c->prefix_length > 0 &&
635 is_valid_prefix(item->string, c->prefix_length)) {
636 strbuf_reset(&d->name);
637 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
638 (int)c->prefix_length, item->string, d->reset,
639 item->string + c->prefix_length);
640 highlighted = d->name.buf;
643 if (d->only_names) {
644 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
645 highlighted ? highlighted : item->string);
646 return;
649 render_adddel(&d->worktree, &c->worktree, _("nothing"));
650 render_adddel(&d->index, &c->index, _("unchanged"));
652 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
653 highlighted ? highlighted : item->string);
655 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
658 static int run_status(struct add_i_state *s, const struct pathspec *ps,
659 struct prefix_item_list *files,
660 struct list_and_choose_options *opts)
662 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
663 return -1;
665 list(s, &files->items, NULL, &opts->list_opts);
666 putchar('\n');
668 return 0;
671 static int run_update(struct add_i_state *s, const struct pathspec *ps,
672 struct prefix_item_list *files,
673 struct list_and_choose_options *opts)
675 int res = 0, fd;
676 size_t count, i;
677 struct lock_file index_lock;
679 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
680 return -1;
682 if (!files->items.nr) {
683 putchar('\n');
684 return 0;
687 opts->prompt = N_("Update");
688 count = list_and_choose(s, files, opts);
689 if (count <= 0) {
690 putchar('\n');
691 return 0;
694 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
695 if (fd < 0) {
696 putchar('\n');
697 return -1;
700 for (i = 0; i < files->items.nr; i++) {
701 const char *name = files->items.items[i].string;
702 struct stat st;
704 if (!files->selected[i])
705 continue;
706 if (lstat(name, &st) && is_missing_file_error(errno)) {
707 if (remove_file_from_index(s->r->index, name) < 0) {
708 res = error(_("could not stage '%s'"), name);
709 break;
711 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
712 res = error(_("could not stage '%s'"), name);
713 break;
717 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
718 res = error(_("could not write index"));
720 if (!res)
721 printf(Q_("updated %d path\n",
722 "updated %d paths\n", count), (int)count);
724 putchar('\n');
725 return res;
728 static void revert_from_diff(struct diff_queue_struct *q,
729 struct diff_options *opt, void *data UNUSED)
731 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
733 for (i = 0; i < q->nr; i++) {
734 struct diff_filespec *one = q->queue[i]->one;
735 struct cache_entry *ce;
737 if (!(one->mode && !is_null_oid(&one->oid))) {
738 remove_file_from_index(opt->repo->index, one->path);
739 printf(_("note: %s is untracked now.\n"), one->path);
740 } else {
741 ce = make_cache_entry(opt->repo->index, one->mode,
742 &one->oid, one->path, 0, 0);
743 if (!ce)
744 die(_("make_cache_entry failed for path '%s'"),
745 one->path);
746 add_index_entry(opt->repo->index, ce, add_flags);
751 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
752 struct prefix_item_list *files,
753 struct list_and_choose_options *opts)
755 int res = 0, fd;
756 size_t count, i, j;
758 struct object_id oid;
759 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
760 NULL);
761 struct lock_file index_lock;
762 const char **paths;
763 struct tree *tree;
764 struct diff_options diffopt = { NULL };
766 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
767 return -1;
769 if (!files->items.nr) {
770 putchar('\n');
771 return 0;
774 opts->prompt = N_("Revert");
775 count = list_and_choose(s, files, opts);
776 if (count <= 0)
777 goto finish_revert;
779 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
780 if (fd < 0) {
781 res = -1;
782 goto finish_revert;
785 if (is_initial)
786 oidcpy(&oid, s->r->hash_algo->empty_tree);
787 else {
788 tree = parse_tree_indirect(&oid);
789 if (!tree) {
790 res = error(_("Could not parse HEAD^{tree}"));
791 goto finish_revert;
793 oidcpy(&oid, &tree->object.oid);
796 ALLOC_ARRAY(paths, count + 1);
797 for (i = j = 0; i < files->items.nr; i++)
798 if (files->selected[i])
799 paths[j++] = files->items.items[i].string;
800 paths[j] = NULL;
802 parse_pathspec(&diffopt.pathspec, 0,
803 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
804 NULL, paths);
806 diffopt.output_format = DIFF_FORMAT_CALLBACK;
807 diffopt.format_callback = revert_from_diff;
808 diffopt.flags.override_submodule_config = 1;
809 diffopt.repo = s->r;
811 if (do_diff_cache(&oid, &diffopt)) {
812 diff_free(&diffopt);
813 res = -1;
814 } else {
815 diffcore_std(&diffopt);
816 diff_flush(&diffopt);
818 free(paths);
820 if (!res && write_locked_index(s->r->index, &index_lock,
821 COMMIT_LOCK) < 0)
822 res = -1;
823 else
824 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
825 NULL, NULL, NULL);
827 if (!res)
828 printf(Q_("reverted %d path\n",
829 "reverted %d paths\n", count), (int)count);
831 finish_revert:
832 putchar('\n');
833 return res;
836 static int get_untracked_files(struct repository *r,
837 struct prefix_item_list *files,
838 const struct pathspec *ps)
840 struct dir_struct dir = { 0 };
841 size_t i;
842 struct strbuf buf = STRBUF_INIT;
844 if (repo_read_index(r) < 0)
845 return error(_("could not read index"));
847 prefix_item_list_clear(files);
848 setup_standard_excludes(&dir);
849 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
850 fill_directory(&dir, r->index, ps);
852 for (i = 0; i < dir.nr; i++) {
853 struct dir_entry *ent = dir.entries[i];
855 if (index_name_is_other(r->index, ent->name, ent->len)) {
856 strbuf_reset(&buf);
857 strbuf_add(&buf, ent->name, ent->len);
858 add_file_item(&files->items, buf.buf);
862 strbuf_release(&buf);
863 return 0;
866 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
867 struct prefix_item_list *files,
868 struct list_and_choose_options *opts)
870 struct print_file_item_data *d = opts->list_opts.print_item_data;
871 int res = 0, fd;
872 size_t count, i;
873 struct lock_file index_lock;
875 if (get_untracked_files(s->r, files, ps) < 0)
876 return -1;
878 if (!files->items.nr) {
879 printf(_("No untracked files.\n"));
880 goto finish_add_untracked;
883 opts->prompt = N_("Add untracked");
884 d->only_names = 1;
885 count = list_and_choose(s, files, opts);
886 d->only_names = 0;
887 if (count <= 0)
888 goto finish_add_untracked;
890 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
891 if (fd < 0) {
892 res = -1;
893 goto finish_add_untracked;
896 for (i = 0; i < files->items.nr; i++) {
897 const char *name = files->items.items[i].string;
898 if (files->selected[i] &&
899 add_file_to_index(s->r->index, name, 0) < 0) {
900 res = error(_("could not stage '%s'"), name);
901 break;
905 if (!res &&
906 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
907 res = error(_("could not write index"));
909 if (!res)
910 printf(Q_("added %d path\n",
911 "added %d paths\n", count), (int)count);
913 finish_add_untracked:
914 putchar('\n');
915 return res;
918 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
919 struct prefix_item_list *files,
920 struct list_and_choose_options *opts)
922 int res = 0;
923 ssize_t count, i, j;
924 size_t unmerged_count = 0, binary_count = 0;
926 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
927 &unmerged_count, &binary_count) < 0)
928 return -1;
930 if (unmerged_count || binary_count) {
931 for (i = j = 0; i < files->items.nr; i++) {
932 struct file_item *item = files->items.items[i].util;
934 if (item->index.binary || item->worktree.binary) {
935 free(item);
936 free(files->items.items[i].string);
937 } else if (item->index.unmerged ||
938 item->worktree.unmerged) {
939 color_fprintf_ln(stderr, s->error_color,
940 _("ignoring unmerged: %s"),
941 files->items.items[i].string);
942 free(item);
943 free(files->items.items[i].string);
944 } else
945 files->items.items[j++] = files->items.items[i];
947 files->items.nr = j;
950 if (!files->items.nr) {
951 if (binary_count)
952 fprintf(stderr, _("Only binary files changed.\n"));
953 else
954 fprintf(stderr, _("No changes.\n"));
955 return 0;
958 opts->prompt = N_("Patch update");
959 count = list_and_choose(s, files, opts);
960 if (count > 0) {
961 struct strvec args = STRVEC_INIT;
962 struct pathspec ps_selected = { 0 };
964 for (i = 0; i < files->items.nr; i++)
965 if (files->selected[i])
966 strvec_push(&args,
967 files->items.items[i].string);
968 parse_pathspec(&ps_selected,
969 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
970 PATHSPEC_LITERAL_PATH, "", args.v);
971 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
972 strvec_clear(&args);
973 clear_pathspec(&ps_selected);
976 return res;
979 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
980 struct prefix_item_list *files,
981 struct list_and_choose_options *opts)
983 int res = 0;
984 ssize_t count, i;
986 struct object_id oid;
987 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
988 NULL);
989 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
990 return -1;
992 if (!files->items.nr) {
993 putchar('\n');
994 return 0;
997 opts->prompt = N_("Review diff");
998 opts->flags = IMMEDIATE;
999 count = list_and_choose(s, files, opts);
1000 opts->flags = 0;
1001 if (count > 0) {
1002 struct child_process cmd = CHILD_PROCESS_INIT;
1004 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
1005 oid_to_hex(!is_initial ? &oid :
1006 s->r->hash_algo->empty_tree),
1007 "--", NULL);
1008 for (i = 0; i < files->items.nr; i++)
1009 if (files->selected[i])
1010 strvec_push(&cmd.args,
1011 files->items.items[i].string);
1012 res = run_command(&cmd);
1015 putchar('\n');
1016 return res;
1019 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1020 struct prefix_item_list *unused_files,
1021 struct list_and_choose_options *unused_opts)
1023 color_fprintf_ln(stdout, s->help_color, "status - %s",
1024 _("show paths with changes"));
1025 color_fprintf_ln(stdout, s->help_color, "update - %s",
1026 _("add working tree state to the staged set of changes"));
1027 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1028 _("revert staged set of changes back to the HEAD version"));
1029 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1030 _("pick hunks and update selectively"));
1031 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1032 _("view diff between HEAD and index"));
1033 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1034 _("add contents of untracked files to the staged set of changes"));
1036 return 0;
1039 static void choose_prompt_help(struct add_i_state *s)
1041 color_fprintf_ln(stdout, s->help_color, "%s",
1042 _("Prompt help:"));
1043 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1044 _("select a single item"));
1045 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1046 _("select a range of items"));
1047 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1048 _("select multiple ranges"));
1049 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1050 _("select item based on unique prefix"));
1051 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1052 _("unselect specified items"));
1053 color_fprintf_ln(stdout, s->help_color, "* - %s",
1054 _("choose all items"));
1055 color_fprintf_ln(stdout, s->help_color, " - %s",
1056 _("(empty) finish selecting"));
1059 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1060 struct prefix_item_list *files,
1061 struct list_and_choose_options *opts);
1063 struct command_item {
1064 size_t prefix_length;
1065 command_t command;
1068 struct print_command_item_data {
1069 const char *color, *reset;
1072 static void print_command_item(int i, int selected,
1073 struct string_list_item *item,
1074 void *print_command_item_data)
1076 struct print_command_item_data *d = print_command_item_data;
1077 struct command_item *util = item->util;
1079 if (!util->prefix_length ||
1080 !is_valid_prefix(item->string, util->prefix_length))
1081 printf(" %2d: %s", i + 1, item->string);
1082 else
1083 printf(" %2d: %s%.*s%s%s", i + 1,
1084 d->color, (int)util->prefix_length, item->string,
1085 d->reset, item->string + util->prefix_length);
1088 static void command_prompt_help(struct add_i_state *s)
1090 const char *help_color = s->help_color;
1091 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1092 color_fprintf_ln(stdout, help_color, "1 - %s",
1093 _("select a numbered item"));
1094 color_fprintf_ln(stdout, help_color, "foo - %s",
1095 _("select item based on unique prefix"));
1096 color_fprintf_ln(stdout, help_color, " - %s",
1097 _("(empty) select nothing"));
1100 int run_add_i(struct repository *r, const struct pathspec *ps)
1102 struct add_i_state s = { NULL };
1103 struct print_command_item_data data = { "[", "]" };
1104 struct list_and_choose_options main_loop_opts = {
1105 { 4, N_("*** Commands ***"), print_command_item, &data },
1106 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1108 struct {
1109 const char *string;
1110 command_t command;
1111 } command_list[] = {
1112 { "status", run_status },
1113 { "update", run_update },
1114 { "revert", run_revert },
1115 { "add untracked", run_add_untracked },
1116 { "patch", run_patch },
1117 { "diff", run_diff },
1118 { "quit", NULL },
1119 { "help", run_help },
1121 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1123 struct print_file_item_data print_file_item_data = {
1124 "%12s %12s %s", NULL, NULL,
1125 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1127 struct list_and_choose_options opts = {
1128 { 0, NULL, print_file_item, &print_file_item_data },
1129 NULL, 0, choose_prompt_help
1131 struct strbuf header = STRBUF_INIT;
1132 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1133 ssize_t i;
1134 int res = 0;
1136 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1137 struct command_item *util = xcalloc(1, sizeof(*util));
1138 util->command = command_list[i].command;
1139 string_list_append(&commands.items, command_list[i].string)
1140 ->util = util;
1143 init_add_i_state(&s, r);
1146 * When color was asked for, use the prompt color for
1147 * highlighting, otherwise use square brackets.
1149 if (s.use_color) {
1150 data.color = s.prompt_color;
1151 data.reset = s.reset_color;
1153 print_file_item_data.color = data.color;
1154 print_file_item_data.reset = data.reset;
1156 strbuf_addstr(&header, " ");
1157 strbuf_addf(&header, print_file_item_data.modified_fmt,
1158 _("staged"), _("unstaged"), _("path"));
1159 opts.list_opts.header = header.buf;
1161 discard_index(r->index);
1162 if (repo_read_index(r) < 0 ||
1163 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1164 NULL, NULL, NULL) < 0)
1165 warning(_("could not refresh index"));
1167 res = run_status(&s, ps, &files, &opts);
1169 for (;;) {
1170 struct command_item *util;
1172 i = list_and_choose(&s, &commands, &main_loop_opts);
1173 if (i < 0 || i >= commands.items.nr)
1174 util = NULL;
1175 else
1176 util = commands.items.items[i].util;
1178 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1179 printf(_("Bye.\n"));
1180 res = 0;
1181 break;
1184 if (util)
1185 res = util->command(&s, ps, &files, &opts);
1188 prefix_item_list_clear(&files);
1189 strbuf_release(&print_file_item_data.buf);
1190 strbuf_release(&print_file_item_data.name);
1191 strbuf_release(&print_file_item_data.index);
1192 strbuf_release(&print_file_item_data.worktree);
1193 strbuf_release(&header);
1194 prefix_item_list_clear(&commands);
1195 clear_add_i_state(&s);
1197 return res;