blame: remove unnecessary use of get_commit_info()
[git/debian.git] / add-interactive.c
blob9b8cdb4a31a6ab69e7bb4e698782b11764c094c7
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);
75 void clear_add_i_state(struct add_i_state *s)
77 FREE_AND_NULL(s->interactive_diff_filter);
78 FREE_AND_NULL(s->interactive_diff_algorithm);
79 memset(s, 0, sizeof(*s));
80 s->use_color = -1;
84 * A "prefix item list" is a list of items that are identified by a string, and
85 * a unique prefix (if any) is determined for each item.
87 * It is implemented in the form of a pair of `string_list`s, the first one
88 * duplicating the strings, with the `util` field pointing at a structure whose
89 * first field must be `size_t prefix_length`.
91 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
92 * will be set to zero if no valid, unique prefix could be found.
94 * The second `string_list` is called `sorted` and does _not_ duplicate the
95 * strings but simply reuses the first one's, with the `util` field pointing at
96 * the `string_item_list` of the first `string_list`. It will be populated and
97 * sorted by `find_unique_prefixes()`.
99 struct prefix_item_list {
100 struct string_list items;
101 struct string_list sorted;
102 int *selected; /* for multi-selections */
103 size_t min_length, max_length;
105 #define PREFIX_ITEM_LIST_INIT \
106 { STRING_LIST_INIT_DUP, STRING_LIST_INIT_NODUP, NULL, 1, 4 }
108 static void prefix_item_list_clear(struct prefix_item_list *list)
110 string_list_clear(&list->items, 1);
111 string_list_clear(&list->sorted, 0);
112 FREE_AND_NULL(list->selected);
115 static void extend_prefix_length(struct string_list_item *p,
116 const char *other_string, size_t max_length)
118 size_t *len = p->util;
120 if (!*len || memcmp(p->string, other_string, *len))
121 return;
123 for (;;) {
124 char c = p->string[*len];
127 * Is `p` a strict prefix of `other`? Or have we exhausted the
128 * maximal length of the prefix? Or is the current character a
129 * multi-byte UTF-8 one? If so, there is no valid, unique
130 * prefix.
132 if (!c || ++*len > max_length || !isascii(c)) {
133 *len = 0;
134 break;
137 if (c != other_string[*len - 1])
138 break;
142 static void find_unique_prefixes(struct prefix_item_list *list)
144 size_t i;
146 if (list->sorted.nr == list->items.nr)
147 return;
149 string_list_clear(&list->sorted, 0);
150 /* Avoid reallocating incrementally */
151 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
152 list->items.nr));
153 list->sorted.nr = list->sorted.alloc = list->items.nr;
155 for (i = 0; i < list->items.nr; i++) {
156 list->sorted.items[i].string = list->items.items[i].string;
157 list->sorted.items[i].util = list->items.items + i;
160 string_list_sort(&list->sorted);
162 for (i = 0; i < list->sorted.nr; i++) {
163 struct string_list_item *sorted_item = list->sorted.items + i;
164 struct string_list_item *item = sorted_item->util;
165 size_t *len = item->util;
167 *len = 0;
168 while (*len < list->min_length) {
169 char c = item->string[(*len)++];
171 if (!c || !isascii(c)) {
172 *len = 0;
173 break;
177 if (i > 0)
178 extend_prefix_length(item, sorted_item[-1].string,
179 list->max_length);
180 if (i + 1 < list->sorted.nr)
181 extend_prefix_length(item, sorted_item[1].string,
182 list->max_length);
186 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
188 int index = string_list_find_insert_index(&list->sorted, string, 1);
189 struct string_list_item *item;
191 if (list->items.nr != list->sorted.nr)
192 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
193 " vs %"PRIuMAX")",
194 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
196 if (index < 0)
197 item = list->sorted.items[-1 - index].util;
198 else if (index > 0 &&
199 starts_with(list->sorted.items[index - 1].string, string))
200 return -1;
201 else if (index + 1 < list->sorted.nr &&
202 starts_with(list->sorted.items[index + 1].string, string))
203 return -1;
204 else if (index < list->sorted.nr &&
205 starts_with(list->sorted.items[index].string, string))
206 item = list->sorted.items[index].util;
207 else
208 return -1;
209 return item - list->items.items;
212 struct list_options {
213 int columns;
214 const char *header;
215 void (*print_item)(int i, int selected, struct string_list_item *item,
216 void *print_item_data);
217 void *print_item_data;
220 static void list(struct add_i_state *s, struct string_list *list, int *selected,
221 struct list_options *opts)
223 int i, last_lf = 0;
225 if (!list->nr)
226 return;
228 if (opts->header)
229 color_fprintf_ln(stdout, s->header_color,
230 "%s", opts->header);
232 for (i = 0; i < list->nr; i++) {
233 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
234 opts->print_item_data);
236 if ((opts->columns) && ((i + 1) % (opts->columns))) {
237 putchar('\t');
238 last_lf = 0;
240 else {
241 putchar('\n');
242 last_lf = 1;
246 if (!last_lf)
247 putchar('\n');
249 struct list_and_choose_options {
250 struct list_options list_opts;
252 const char *prompt;
253 enum {
254 SINGLETON = (1<<0),
255 IMMEDIATE = (1<<1),
256 } flags;
257 void (*print_help)(struct add_i_state *s);
260 #define LIST_AND_CHOOSE_ERROR (-1)
261 #define LIST_AND_CHOOSE_QUIT (-2)
264 * Returns the selected index in singleton mode, the number of selected items
265 * otherwise.
267 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
268 * `LIST_AND_CHOOSE_QUIT` is returned.
270 static ssize_t list_and_choose(struct add_i_state *s,
271 struct prefix_item_list *items,
272 struct list_and_choose_options *opts)
274 int singleton = opts->flags & SINGLETON;
275 int immediate = opts->flags & IMMEDIATE;
277 struct strbuf input = STRBUF_INIT;
278 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
280 if (!singleton) {
281 free(items->selected);
282 CALLOC_ARRAY(items->selected, items->items.nr);
285 if (singleton && !immediate)
286 BUG("singleton requires immediate");
288 find_unique_prefixes(items);
290 for (;;) {
291 char *p;
293 strbuf_reset(&input);
295 list(s, &items->items, items->selected, &opts->list_opts);
297 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
298 fputs(singleton ? "> " : ">> ", stdout);
299 fflush(stdout);
301 if (git_read_line_interactively(&input) == EOF) {
302 putchar('\n');
303 if (immediate)
304 res = LIST_AND_CHOOSE_QUIT;
305 break;
308 if (!input.len)
309 break;
311 if (!strcmp(input.buf, "?")) {
312 opts->print_help(s);
313 continue;
316 p = input.buf;
317 for (;;) {
318 size_t sep = strcspn(p, " \t\r\n,");
319 int choose = 1;
320 /* `from` is inclusive, `to` is exclusive */
321 ssize_t from = -1, to = -1;
323 if (!sep) {
324 if (!*p)
325 break;
326 p++;
327 continue;
330 /* Input that begins with '-'; de-select */
331 if (*p == '-') {
332 choose = 0;
333 p++;
334 sep--;
337 if (sep == 1 && *p == '*') {
338 from = 0;
339 to = items->items.nr;
340 } else if (isdigit(*p)) {
341 char *endp;
343 * A range can be specified like 5-7 or 5-.
345 * Note: `from` is 0-based while the user input
346 * is 1-based, hence we have to decrement by
347 * one. We do not have to decrement `to` even
348 * if it is 0-based because it is an exclusive
349 * boundary.
351 from = strtoul(p, &endp, 10) - 1;
352 if (endp == p + sep)
353 to = from + 1;
354 else if (*endp == '-') {
355 if (isdigit(*(++endp)))
356 to = strtoul(endp, &endp, 10);
357 else
358 to = items->items.nr;
359 /* extra characters after the range? */
360 if (endp != p + sep)
361 from = -1;
365 if (p[sep])
366 p[sep++] = '\0';
367 if (from < 0) {
368 from = find_unique(p, items);
369 if (from >= 0)
370 to = from + 1;
373 if (from < 0 || from >= items->items.nr ||
374 (singleton && from + 1 != to)) {
375 color_fprintf_ln(stderr, s->error_color,
376 _("Huh (%s)?"), p);
377 break;
378 } else if (singleton) {
379 res = from;
380 break;
383 if (to > items->items.nr)
384 to = items->items.nr;
386 for (; from < to; from++)
387 if (items->selected[from] != choose) {
388 items->selected[from] = choose;
389 res += choose ? +1 : -1;
392 p += sep;
395 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
396 !strcmp(input.buf, "*"))
397 break;
400 strbuf_release(&input);
401 return res;
404 struct adddel {
405 uintmax_t add, del;
406 unsigned seen:1, unmerged:1, binary:1;
409 struct file_item {
410 size_t prefix_length;
411 struct adddel index, worktree;
414 static void add_file_item(struct string_list *files, const char *name)
416 struct file_item *item = xcalloc(sizeof(*item), 1);
418 string_list_append(files, name)->util = item;
421 struct pathname_entry {
422 struct hashmap_entry ent;
423 const char *name;
424 struct file_item *item;
427 static int pathname_entry_cmp(const void *unused_cmp_data,
428 const struct hashmap_entry *he1,
429 const struct hashmap_entry *he2,
430 const void *name)
432 const struct pathname_entry *e1 =
433 container_of(he1, const struct pathname_entry, ent);
434 const struct pathname_entry *e2 =
435 container_of(he2, const struct pathname_entry, ent);
437 return strcmp(e1->name, name ? (const char *)name : e2->name);
440 struct collection_status {
441 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
443 const char *reference;
445 unsigned skip_unseen:1;
446 size_t unmerged_count, binary_count;
447 struct string_list *files;
448 struct hashmap file_map;
451 static void collect_changes_cb(struct diff_queue_struct *q,
452 struct diff_options *options,
453 void *data)
455 struct collection_status *s = data;
456 struct diffstat_t stat = { 0 };
457 int i;
459 if (!q->nr)
460 return;
462 compute_diffstat(options, &stat, q);
464 for (i = 0; i < stat.nr; i++) {
465 const char *name = stat.files[i]->name;
466 int hash = strhash(name);
467 struct pathname_entry *entry;
468 struct file_item *file_item;
469 struct adddel *adddel, *other_adddel;
471 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
472 struct pathname_entry, ent);
473 if (!entry) {
474 if (s->skip_unseen)
475 continue;
477 add_file_item(s->files, name);
479 entry = xcalloc(sizeof(*entry), 1);
480 hashmap_entry_init(&entry->ent, hash);
481 entry->name = s->files->items[s->files->nr - 1].string;
482 entry->item = s->files->items[s->files->nr - 1].util;
483 hashmap_add(&s->file_map, &entry->ent);
486 file_item = entry->item;
487 adddel = s->mode == FROM_INDEX ?
488 &file_item->index : &file_item->worktree;
489 other_adddel = s->mode == FROM_INDEX ?
490 &file_item->worktree : &file_item->index;
491 adddel->seen = 1;
492 adddel->add = stat.files[i]->added;
493 adddel->del = stat.files[i]->deleted;
494 if (stat.files[i]->is_binary) {
495 if (!other_adddel->binary)
496 s->binary_count++;
497 adddel->binary = 1;
499 if (stat.files[i]->is_unmerged) {
500 if (!other_adddel->unmerged)
501 s->unmerged_count++;
502 adddel->unmerged = 1;
505 free_diffstat_info(&stat);
508 enum modified_files_filter {
509 NO_FILTER = 0,
510 WORKTREE_ONLY = 1,
511 INDEX_ONLY = 2,
514 static int get_modified_files(struct repository *r,
515 enum modified_files_filter filter,
516 struct prefix_item_list *files,
517 const struct pathspec *ps,
518 size_t *unmerged_count,
519 size_t *binary_count)
521 struct object_id head_oid;
522 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
523 &head_oid, NULL);
524 struct collection_status s = { 0 };
525 int i;
527 if (discard_index(r->index) < 0 ||
528 repo_read_index_preload(r, ps, 0) < 0)
529 return error(_("could not read index"));
531 prefix_item_list_clear(files);
532 s.files = &files->items;
533 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
535 for (i = 0; i < 2; i++) {
536 struct rev_info rev;
537 struct setup_revision_opt opt = { 0 };
539 if (filter == INDEX_ONLY)
540 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
541 else
542 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
543 s.skip_unseen = filter && i;
545 opt.def = is_initial ?
546 empty_tree_oid_hex() : oid_to_hex(&head_oid);
548 init_revisions(&rev, NULL);
549 setup_revisions(0, NULL, &rev, &opt);
551 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
552 rev.diffopt.format_callback = collect_changes_cb;
553 rev.diffopt.format_callback_data = &s;
555 if (ps)
556 copy_pathspec(&rev.prune_data, ps);
558 if (s.mode == FROM_INDEX)
559 run_diff_index(&rev, 1);
560 else {
561 rev.diffopt.flags.ignore_dirty_submodules = 1;
562 run_diff_files(&rev, 0);
565 if (ps)
566 clear_pathspec(&rev.prune_data);
568 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
569 if (unmerged_count)
570 *unmerged_count = s.unmerged_count;
571 if (binary_count)
572 *binary_count = s.binary_count;
574 /* While the diffs are ordered already, we ran *two* diffs... */
575 string_list_sort(&files->items);
577 return 0;
580 static void render_adddel(struct strbuf *buf,
581 struct adddel *ad, const char *no_changes)
583 if (ad->binary)
584 strbuf_addstr(buf, _("binary"));
585 else if (ad->seen)
586 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
587 (uintmax_t)ad->add, (uintmax_t)ad->del);
588 else
589 strbuf_addstr(buf, no_changes);
592 /* filters out prefixes which have special meaning to list_and_choose() */
593 static int is_valid_prefix(const char *prefix, size_t prefix_len)
595 return prefix_len && prefix &&
597 * We expect `prefix` to be NUL terminated, therefore this
598 * `strcspn()` call is okay, even if it might do much more
599 * work than strictly necessary.
601 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
602 *prefix != '-' && /* deselection */
603 !isdigit(*prefix) && /* selection */
604 (prefix_len != 1 ||
605 (*prefix != '*' && /* "all" wildcard */
606 *prefix != '?')); /* prompt help */
609 struct print_file_item_data {
610 const char *modified_fmt, *color, *reset;
611 struct strbuf buf, name, index, worktree;
612 unsigned only_names:1;
615 static void print_file_item(int i, int selected, struct string_list_item *item,
616 void *print_file_item_data)
618 struct file_item *c = item->util;
619 struct print_file_item_data *d = print_file_item_data;
620 const char *highlighted = NULL;
622 strbuf_reset(&d->index);
623 strbuf_reset(&d->worktree);
624 strbuf_reset(&d->buf);
626 /* Format the item with the prefix highlighted. */
627 if (c->prefix_length > 0 &&
628 is_valid_prefix(item->string, c->prefix_length)) {
629 strbuf_reset(&d->name);
630 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
631 (int)c->prefix_length, item->string, d->reset,
632 item->string + c->prefix_length);
633 highlighted = d->name.buf;
636 if (d->only_names) {
637 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
638 highlighted ? highlighted : item->string);
639 return;
642 render_adddel(&d->worktree, &c->worktree, _("nothing"));
643 render_adddel(&d->index, &c->index, _("unchanged"));
645 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
646 highlighted ? highlighted : item->string);
648 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
651 static int run_status(struct add_i_state *s, const struct pathspec *ps,
652 struct prefix_item_list *files,
653 struct list_and_choose_options *opts)
655 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
656 return -1;
658 list(s, &files->items, NULL, &opts->list_opts);
659 putchar('\n');
661 return 0;
664 static int run_update(struct add_i_state *s, const struct pathspec *ps,
665 struct prefix_item_list *files,
666 struct list_and_choose_options *opts)
668 int res = 0, fd;
669 size_t count, i;
670 struct lock_file index_lock;
672 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
673 return -1;
675 if (!files->items.nr) {
676 putchar('\n');
677 return 0;
680 opts->prompt = N_("Update");
681 count = list_and_choose(s, files, opts);
682 if (count <= 0) {
683 putchar('\n');
684 return 0;
687 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
688 if (fd < 0) {
689 putchar('\n');
690 return -1;
693 for (i = 0; i < files->items.nr; i++) {
694 const char *name = files->items.items[i].string;
695 if (files->selected[i] &&
696 add_file_to_index(s->r->index, name, 0) < 0) {
697 res = error(_("could not stage '%s'"), name);
698 break;
702 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
703 res = error(_("could not write index"));
705 if (!res)
706 printf(Q_("updated %d path\n",
707 "updated %d paths\n", count), (int)count);
709 putchar('\n');
710 return res;
713 static void revert_from_diff(struct diff_queue_struct *q,
714 struct diff_options *opt, void *data)
716 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
718 for (i = 0; i < q->nr; i++) {
719 struct diff_filespec *one = q->queue[i]->one;
720 struct cache_entry *ce;
722 if (!(one->mode && !is_null_oid(&one->oid))) {
723 remove_file_from_index(opt->repo->index, one->path);
724 printf(_("note: %s is untracked now.\n"), one->path);
725 } else {
726 ce = make_cache_entry(opt->repo->index, one->mode,
727 &one->oid, one->path, 0, 0);
728 if (!ce)
729 die(_("make_cache_entry failed for path '%s'"),
730 one->path);
731 add_index_entry(opt->repo->index, ce, add_flags);
736 static int run_revert(struct add_i_state *s, const struct pathspec *ps,
737 struct prefix_item_list *files,
738 struct list_and_choose_options *opts)
740 int res = 0, fd;
741 size_t count, i, j;
743 struct object_id oid;
744 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
745 NULL);
746 struct lock_file index_lock;
747 const char **paths;
748 struct tree *tree;
749 struct diff_options diffopt = { NULL };
751 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
752 return -1;
754 if (!files->items.nr) {
755 putchar('\n');
756 return 0;
759 opts->prompt = N_("Revert");
760 count = list_and_choose(s, files, opts);
761 if (count <= 0)
762 goto finish_revert;
764 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
765 if (fd < 0) {
766 res = -1;
767 goto finish_revert;
770 if (is_initial)
771 oidcpy(&oid, s->r->hash_algo->empty_tree);
772 else {
773 tree = parse_tree_indirect(&oid);
774 if (!tree) {
775 res = error(_("Could not parse HEAD^{tree}"));
776 goto finish_revert;
778 oidcpy(&oid, &tree->object.oid);
781 ALLOC_ARRAY(paths, count + 1);
782 for (i = j = 0; i < files->items.nr; i++)
783 if (files->selected[i])
784 paths[j++] = files->items.items[i].string;
785 paths[j] = NULL;
787 parse_pathspec(&diffopt.pathspec, 0,
788 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
789 NULL, paths);
791 diffopt.output_format = DIFF_FORMAT_CALLBACK;
792 diffopt.format_callback = revert_from_diff;
793 diffopt.flags.override_submodule_config = 1;
794 diffopt.repo = s->r;
796 if (do_diff_cache(&oid, &diffopt))
797 res = -1;
798 else {
799 diffcore_std(&diffopt);
800 diff_flush(&diffopt);
802 free(paths);
803 clear_pathspec(&diffopt.pathspec);
805 if (!res && write_locked_index(s->r->index, &index_lock,
806 COMMIT_LOCK) < 0)
807 res = -1;
808 else
809 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
810 NULL, NULL, NULL);
812 if (!res)
813 printf(Q_("reverted %d path\n",
814 "reverted %d paths\n", count), (int)count);
816 finish_revert:
817 putchar('\n');
818 return res;
821 static int get_untracked_files(struct repository *r,
822 struct prefix_item_list *files,
823 const struct pathspec *ps)
825 struct dir_struct dir = { 0 };
826 size_t i;
827 struct strbuf buf = STRBUF_INIT;
829 if (repo_read_index(r) < 0)
830 return error(_("could not read index"));
832 prefix_item_list_clear(files);
833 setup_standard_excludes(&dir);
834 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
835 fill_directory(&dir, r->index, ps);
837 for (i = 0; i < dir.nr; i++) {
838 struct dir_entry *ent = dir.entries[i];
840 if (index_name_is_other(r->index, ent->name, ent->len)) {
841 strbuf_reset(&buf);
842 strbuf_add(&buf, ent->name, ent->len);
843 add_file_item(&files->items, buf.buf);
847 strbuf_release(&buf);
848 return 0;
851 static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
852 struct prefix_item_list *files,
853 struct list_and_choose_options *opts)
855 struct print_file_item_data *d = opts->list_opts.print_item_data;
856 int res = 0, fd;
857 size_t count, i;
858 struct lock_file index_lock;
860 if (get_untracked_files(s->r, files, ps) < 0)
861 return -1;
863 if (!files->items.nr) {
864 printf(_("No untracked files.\n"));
865 goto finish_add_untracked;
868 opts->prompt = N_("Add untracked");
869 d->only_names = 1;
870 count = list_and_choose(s, files, opts);
871 d->only_names = 0;
872 if (count <= 0)
873 goto finish_add_untracked;
875 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
876 if (fd < 0) {
877 res = -1;
878 goto finish_add_untracked;
881 for (i = 0; i < files->items.nr; i++) {
882 const char *name = files->items.items[i].string;
883 if (files->selected[i] &&
884 add_file_to_index(s->r->index, name, 0) < 0) {
885 res = error(_("could not stage '%s'"), name);
886 break;
890 if (!res &&
891 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
892 res = error(_("could not write index"));
894 if (!res)
895 printf(Q_("added %d path\n",
896 "added %d paths\n", count), (int)count);
898 finish_add_untracked:
899 putchar('\n');
900 return res;
903 static int run_patch(struct add_i_state *s, const struct pathspec *ps,
904 struct prefix_item_list *files,
905 struct list_and_choose_options *opts)
907 int res = 0;
908 ssize_t count, i, j;
909 size_t unmerged_count = 0, binary_count = 0;
911 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
912 &unmerged_count, &binary_count) < 0)
913 return -1;
915 if (unmerged_count || binary_count) {
916 for (i = j = 0; i < files->items.nr; i++) {
917 struct file_item *item = files->items.items[i].util;
919 if (item->index.binary || item->worktree.binary) {
920 free(item);
921 free(files->items.items[i].string);
922 } else if (item->index.unmerged ||
923 item->worktree.unmerged) {
924 color_fprintf_ln(stderr, s->error_color,
925 _("ignoring unmerged: %s"),
926 files->items.items[i].string);
927 free(item);
928 free(files->items.items[i].string);
929 } else
930 files->items.items[j++] = files->items.items[i];
932 files->items.nr = j;
935 if (!files->items.nr) {
936 if (binary_count)
937 fprintf(stderr, _("Only binary files changed.\n"));
938 else
939 fprintf(stderr, _("No changes.\n"));
940 return 0;
943 opts->prompt = N_("Patch update");
944 count = list_and_choose(s, files, opts);
945 if (count > 0) {
946 struct strvec args = STRVEC_INIT;
947 struct pathspec ps_selected = { 0 };
949 for (i = 0; i < files->items.nr; i++)
950 if (files->selected[i])
951 strvec_push(&args,
952 files->items.items[i].string);
953 parse_pathspec(&ps_selected,
954 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
955 PATHSPEC_LITERAL_PATH, "", args.v);
956 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
957 strvec_clear(&args);
958 clear_pathspec(&ps_selected);
961 return res;
964 static int run_diff(struct add_i_state *s, const struct pathspec *ps,
965 struct prefix_item_list *files,
966 struct list_and_choose_options *opts)
968 int res = 0;
969 ssize_t count, i;
971 struct object_id oid;
972 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
973 NULL);
974 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
975 return -1;
977 if (!files->items.nr) {
978 putchar('\n');
979 return 0;
982 opts->prompt = N_("Review diff");
983 opts->flags = IMMEDIATE;
984 count = list_and_choose(s, files, opts);
985 opts->flags = 0;
986 if (count > 0) {
987 struct strvec args = STRVEC_INIT;
989 strvec_pushl(&args, "git", "diff", "-p", "--cached",
990 oid_to_hex(!is_initial ? &oid :
991 s->r->hash_algo->empty_tree),
992 "--", NULL);
993 for (i = 0; i < files->items.nr; i++)
994 if (files->selected[i])
995 strvec_push(&args,
996 files->items.items[i].string);
997 res = run_command_v_opt(args.v, 0);
998 strvec_clear(&args);
1001 putchar('\n');
1002 return res;
1005 static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
1006 struct prefix_item_list *unused_files,
1007 struct list_and_choose_options *unused_opts)
1009 color_fprintf_ln(stdout, s->help_color, "status - %s",
1010 _("show paths with changes"));
1011 color_fprintf_ln(stdout, s->help_color, "update - %s",
1012 _("add working tree state to the staged set of changes"));
1013 color_fprintf_ln(stdout, s->help_color, "revert - %s",
1014 _("revert staged set of changes back to the HEAD version"));
1015 color_fprintf_ln(stdout, s->help_color, "patch - %s",
1016 _("pick hunks and update selectively"));
1017 color_fprintf_ln(stdout, s->help_color, "diff - %s",
1018 _("view diff between HEAD and index"));
1019 color_fprintf_ln(stdout, s->help_color, "add untracked - %s",
1020 _("add contents of untracked files to the staged set of changes"));
1022 return 0;
1025 static void choose_prompt_help(struct add_i_state *s)
1027 color_fprintf_ln(stdout, s->help_color, "%s",
1028 _("Prompt help:"));
1029 color_fprintf_ln(stdout, s->help_color, "1 - %s",
1030 _("select a single item"));
1031 color_fprintf_ln(stdout, s->help_color, "3-5 - %s",
1032 _("select a range of items"));
1033 color_fprintf_ln(stdout, s->help_color, "2-3,6-9 - %s",
1034 _("select multiple ranges"));
1035 color_fprintf_ln(stdout, s->help_color, "foo - %s",
1036 _("select item based on unique prefix"));
1037 color_fprintf_ln(stdout, s->help_color, "-... - %s",
1038 _("unselect specified items"));
1039 color_fprintf_ln(stdout, s->help_color, "* - %s",
1040 _("choose all items"));
1041 color_fprintf_ln(stdout, s->help_color, " - %s",
1042 _("(empty) finish selecting"));
1045 typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1046 struct prefix_item_list *files,
1047 struct list_and_choose_options *opts);
1049 struct command_item {
1050 size_t prefix_length;
1051 command_t command;
1054 struct print_command_item_data {
1055 const char *color, *reset;
1058 static void print_command_item(int i, int selected,
1059 struct string_list_item *item,
1060 void *print_command_item_data)
1062 struct print_command_item_data *d = print_command_item_data;
1063 struct command_item *util = item->util;
1065 if (!util->prefix_length ||
1066 !is_valid_prefix(item->string, util->prefix_length))
1067 printf(" %2d: %s", i + 1, item->string);
1068 else
1069 printf(" %2d: %s%.*s%s%s", i + 1,
1070 d->color, (int)util->prefix_length, item->string,
1071 d->reset, item->string + util->prefix_length);
1074 static void command_prompt_help(struct add_i_state *s)
1076 const char *help_color = s->help_color;
1077 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1078 color_fprintf_ln(stdout, help_color, "1 - %s",
1079 _("select a numbered item"));
1080 color_fprintf_ln(stdout, help_color, "foo - %s",
1081 _("select item based on unique prefix"));
1082 color_fprintf_ln(stdout, help_color, " - %s",
1083 _("(empty) select nothing"));
1086 int run_add_i(struct repository *r, const struct pathspec *ps)
1088 struct add_i_state s = { NULL };
1089 struct print_command_item_data data = { "[", "]" };
1090 struct list_and_choose_options main_loop_opts = {
1091 { 4, N_("*** Commands ***"), print_command_item, &data },
1092 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1094 struct {
1095 const char *string;
1096 command_t command;
1097 } command_list[] = {
1098 { "status", run_status },
1099 { "update", run_update },
1100 { "revert", run_revert },
1101 { "add untracked", run_add_untracked },
1102 { "patch", run_patch },
1103 { "diff", run_diff },
1104 { "quit", NULL },
1105 { "help", run_help },
1107 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1109 struct print_file_item_data print_file_item_data = {
1110 "%12s %12s %s", NULL, NULL,
1111 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1113 struct list_and_choose_options opts = {
1114 { 0, NULL, print_file_item, &print_file_item_data },
1115 NULL, 0, choose_prompt_help
1117 struct strbuf header = STRBUF_INIT;
1118 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1119 ssize_t i;
1120 int res = 0;
1122 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1123 struct command_item *util = xcalloc(sizeof(*util), 1);
1124 util->command = command_list[i].command;
1125 string_list_append(&commands.items, command_list[i].string)
1126 ->util = util;
1129 init_add_i_state(&s, r);
1132 * When color was asked for, use the prompt color for
1133 * highlighting, otherwise use square brackets.
1135 if (s.use_color) {
1136 data.color = s.prompt_color;
1137 data.reset = s.reset_color;
1139 print_file_item_data.color = data.color;
1140 print_file_item_data.reset = data.reset;
1142 strbuf_addstr(&header, " ");
1143 strbuf_addf(&header, print_file_item_data.modified_fmt,
1144 _("staged"), _("unstaged"), _("path"));
1145 opts.list_opts.header = header.buf;
1147 if (discard_index(r->index) < 0 ||
1148 repo_read_index(r) < 0 ||
1149 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1150 NULL, NULL, NULL) < 0)
1151 warning(_("could not refresh index"));
1153 res = run_status(&s, ps, &files, &opts);
1155 for (;;) {
1156 struct command_item *util;
1158 i = list_and_choose(&s, &commands, &main_loop_opts);
1159 if (i < 0 || i >= commands.items.nr)
1160 util = NULL;
1161 else
1162 util = commands.items.items[i].util;
1164 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1165 printf(_("Bye.\n"));
1166 res = 0;
1167 break;
1170 if (util)
1171 res = util->command(&s, ps, &files, &opts);
1174 prefix_item_list_clear(&files);
1175 strbuf_release(&print_file_item_data.buf);
1176 strbuf_release(&print_file_item_data.name);
1177 strbuf_release(&print_file_item_data.index);
1178 strbuf_release(&print_file_item_data.worktree);
1179 strbuf_release(&header);
1180 prefix_item_list_clear(&commands);
1181 clear_add_i_state(&s);
1183 return res;