interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / add-interactive.c

1168 lines · 30600 bytes Raw Blame History
1#define DISABLE_SIGN_COMPARE_WARNINGS
2
3#include "git-compat-util.h"
4#include "add-interactive.h"
5#include "color.h"
6#include "diffcore.h"
7#include "gettext.h"
8#include "hash.h"
9#include "hex.h"
10#include "preload-index.h"
11#include "read-cache-ll.h"
12#include "repository.h"
13#include "revision.h"
14#include "refs.h"
15#include "string-list.h"
16#include "lockfile.h"
17#include "dir.h"
18#include "run-command.h"
19#include "prompt.h"
20#include "tree.h"
21
22struct add_i_state {
23 struct repository *r;
24 struct interactive_config cfg;
25};
26
27static void init_add_i_state(struct add_i_state *s, struct repository *r,
28 struct interactive_options *opts)
29{
30 s->r = r;
31 interactive_config_init(&s->cfg, r, opts);
32}
33
34static void clear_add_i_state(struct add_i_state *s)
35{
36 interactive_config_clear(&s->cfg);
37 memset(s, 0, sizeof(*s));
38 interactive_config_clear(&s->cfg);
39}
40
41/*
42 * A "prefix item list" is a list of items that are identified by a string, and
43 * a unique prefix (if any) is determined for each item.
44 *
45 * It is implemented in the form of a pair of `string_list`s, the first one
46 * duplicating the strings, with the `util` field pointing at a structure whose
47 * first field must be `size_t prefix_length`.
48 *
49 * That `prefix_length` field will be computed by `find_unique_prefixes()`; It
50 * will be set to zero if no valid, unique prefix could be found.
51 *
52 * The second `string_list` is called `sorted` and does _not_ duplicate the
53 * strings but simply reuses the first one's, with the `util` field pointing at
54 * the `string_item_list` of the first `string_list`. It will be populated and
55 * sorted by `find_unique_prefixes()`.
56 */
57struct prefix_item_list {
58 struct string_list items;
59 struct string_list sorted;
60 int *selected; /* for multi-selections */
61 size_t min_length, max_length;
62};
63#define PREFIX_ITEM_LIST_INIT { \
64 .items = STRING_LIST_INIT_DUP, \
65 .sorted = STRING_LIST_INIT_NODUP, \
66 .min_length = 1, \
67 .max_length = 4, \
68}
69
70static void prefix_item_list_clear(struct prefix_item_list *list)
71{
72 string_list_clear(&list->items, 1);
73 string_list_clear(&list->sorted, 0);
74 FREE_AND_NULL(list->selected);
75}
76
77static void extend_prefix_length(struct string_list_item *p,
78 const char *other_string, size_t max_length)
79{
80 size_t *len = p->util;
81
82 if (!*len || memcmp(p->string, other_string, *len))
83 return;
84
85 for (;;) {
86 char c = p->string[*len];
87
88 /*
89 * Is `p` a strict prefix of `other`? Or have we exhausted the
90 * maximal length of the prefix? Or is the current character a
91 * multi-byte UTF-8 one? If so, there is no valid, unique
92 * prefix.
93 */
94 if (!c || ++*len > max_length || !isascii(c)) {
95 *len = 0;
96 break;
97 }
98
99 if (c != other_string[*len - 1])
100 break;
101 }
102}
103
104static void find_unique_prefixes(struct prefix_item_list *list)
105{
106 size_t i;
107
108 if (list->sorted.nr == list->items.nr)
109 return;
110
111 string_list_clear(&list->sorted, 0);
112 /* Avoid reallocating incrementally */
113 list->sorted.items = xmalloc(st_mult(sizeof(*list->sorted.items),
114 list->items.nr));
115 list->sorted.nr = list->sorted.alloc = list->items.nr;
116
117 for (i = 0; i < list->items.nr; i++) {
118 list->sorted.items[i].string = list->items.items[i].string;
119 list->sorted.items[i].util = list->items.items + i;
120 }
121
122 string_list_sort(&list->sorted);
123
124 for (i = 0; i < list->sorted.nr; i++) {
125 struct string_list_item *sorted_item = list->sorted.items + i;
126 struct string_list_item *item = sorted_item->util;
127 size_t *len = item->util;
128
129 *len = 0;
130 while (*len < list->min_length) {
131 char c = item->string[(*len)++];
132
133 if (!c || !isascii(c)) {
134 *len = 0;
135 break;
136 }
137 }
138
139 if (i > 0)
140 extend_prefix_length(item, sorted_item[-1].string,
141 list->max_length);
142 if (i + 1 < list->sorted.nr)
143 extend_prefix_length(item, sorted_item[1].string,
144 list->max_length);
145 }
146}
147
148static ssize_t find_unique(const char *string, struct prefix_item_list *list)
149{
150 bool exact_match;
151 size_t index = string_list_find_insert_index(&list->sorted, string, &exact_match);
152 struct string_list_item *item;
153
154 if (list->items.nr != list->sorted.nr)
155 BUG("prefix_item_list in inconsistent state (%"PRIuMAX
156 " vs %"PRIuMAX")",
157 (uintmax_t)list->items.nr, (uintmax_t)list->sorted.nr);
158
159 if (exact_match)
160 item = list->sorted.items[index].util;
161 else if (index > 0 &&
162 starts_with(list->sorted.items[index - 1].string, string))
163 return -1;
164 else if (index + 1 < list->sorted.nr &&
165 starts_with(list->sorted.items[index + 1].string, string))
166 return -1;
167 else if (index < list->sorted.nr &&
168 starts_with(list->sorted.items[index].string, string))
169 item = list->sorted.items[index].util;
170 else
171 return -1;
172 return item - list->items.items;
173}
174
175struct list_options {
176 int columns;
177 const char *header;
178 void (*print_item)(int i, int selected, struct string_list_item *item,
179 void *print_item_data);
180 void *print_item_data;
181};
182
183static void list(struct add_i_state *s, struct string_list *list, int *selected,
184 struct list_options *opts)
185{
186 int i, last_lf = 0;
187
188 if (!list->nr)
189 return;
190
191 if (opts->header)
192 color_fprintf_ln(stdout, s->cfg.header_color,
193 "%s", opts->header);
194
195 for (i = 0; i < list->nr; i++) {
196 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
197 opts->print_item_data);
198
199 if ((opts->columns) && ((i + 1) % (opts->columns))) {
200 putchar('\t');
201 last_lf = 0;
202 }
203 else {
204 putchar('\n');
205 last_lf = 1;
206 }
207 }
208
209 if (!last_lf)
210 putchar('\n');
211}
212struct list_and_choose_options {
213 struct list_options list_opts;
214
215 const char *prompt;
216 enum {
217 SINGLETON = (1<<0),
218 IMMEDIATE = (1<<1),
219 } flags;
220 void (*print_help)(struct add_i_state *s);
221};
222
223#define LIST_AND_CHOOSE_ERROR (-1)
224#define LIST_AND_CHOOSE_QUIT (-2)
225
226/*
227 * Returns the selected index in singleton mode, the number of selected items
228 * otherwise.
229 *
230 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
231 * `LIST_AND_CHOOSE_QUIT` is returned.
232 */
233static ssize_t list_and_choose(struct add_i_state *s,
234 struct prefix_item_list *items,
235 struct list_and_choose_options *opts)
236{
237 int singleton = opts->flags & SINGLETON;
238 int immediate = opts->flags & IMMEDIATE;
239
240 struct strbuf input = STRBUF_INIT;
241 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
242
243 if (!singleton) {
244 free(items->selected);
245 CALLOC_ARRAY(items->selected, items->items.nr);
246 }
247
248 if (singleton && !immediate)
249 BUG("singleton requires immediate");
250
251 find_unique_prefixes(items);
252
253 for (;;) {
254 char *p;
255
256 strbuf_reset(&input);
257
258 list(s, &items->items, items->selected, &opts->list_opts);
259
260 color_fprintf(stdout, s->cfg.prompt_color, "%s", opts->prompt);
261 fputs(singleton ? "> " : ">> ", stdout);
262 fflush(stdout);
263
264 if (git_read_line_interactively(&input) == EOF) {
265 putchar('\n');
266 if (immediate)
267 res = LIST_AND_CHOOSE_QUIT;
268 break;
269 }
270
271 if (!input.len)
272 break;
273
274 if (!strcmp(input.buf, "?")) {
275 opts->print_help(s);
276 continue;
277 }
278
279 p = input.buf;
280 for (;;) {
281 size_t sep = strcspn(p, " \t\r\n,");
282 int choose = 1;
283 /* `from` is inclusive, `to` is exclusive */
284 ssize_t from = -1, to = -1;
285
286 if (!sep) {
287 if (!*p)
288 break;
289 p++;
290 continue;
291 }
292
293 /* Input that begins with '-'; de-select */
294 if (*p == '-') {
295 choose = 0;
296 p++;
297 sep--;
298 }
299
300 if (sep == 1 && *p == '*') {
301 from = 0;
302 to = items->items.nr;
303 } else if (isdigit(*p)) {
304 char *endp;
305 /*
306 * A range can be specified like 5-7 or 5-.
307 *
308 * Note: `from` is 0-based while the user input
309 * is 1-based, hence we have to decrement by
310 * one. We do not have to decrement `to` even
311 * if it is 0-based because it is an exclusive
312 * boundary.
313 */
314 from = strtoul(p, &endp, 10) - 1;
315 if (endp == p + sep)
316 to = from + 1;
317 else if (*endp == '-') {
318 if (isdigit(*(++endp)))
319 to = strtoul(endp, &endp, 10);
320 else
321 to = items->items.nr;
322 /* extra characters after the range? */
323 if (endp != p + sep)
324 from = -1;
325 }
326 }
327
328 if (p[sep])
329 p[sep++] = '\0';
330 if (from < 0) {
331 from = find_unique(p, items);
332 if (from >= 0)
333 to = from + 1;
334 }
335
336 if (from < 0 || from >= items->items.nr ||
337 (singleton && from + 1 != to)) {
338 color_fprintf_ln(stderr, s->cfg.error_color,
339 _("Huh (%s)?"), p);
340 break;
341 } else if (singleton) {
342 res = from;
343 break;
344 }
345
346 if (to > items->items.nr)
347 to = items->items.nr;
348
349 for (; from < to; from++)
350 if (items->selected[from] != choose) {
351 items->selected[from] = choose;
352 res += choose ? +1 : -1;
353 }
354
355 p += sep;
356 }
357
358 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
359 !strcmp(input.buf, "*"))
360 break;
361 }
362
363 strbuf_release(&input);
364 return res;
365}
366
367struct adddel {
368 uintmax_t add, del;
369 unsigned seen:1, unmerged:1, binary:1;
370};
371
372struct file_item {
373 size_t prefix_length;
374 struct adddel index, worktree;
375};
376
377static void add_file_item(struct string_list *files, const char *name)
378{
379 struct file_item *item = xcalloc(1, sizeof(*item));
380
381 string_list_append(files, name)->util = item;
382}
383
384struct pathname_entry {
385 struct hashmap_entry ent;
386 const char *name;
387 struct file_item *item;
388};
389
390static int pathname_entry_cmp(const void *cmp_data UNUSED,
391 const struct hashmap_entry *he1,
392 const struct hashmap_entry *he2,
393 const void *name)
394{
395 const struct pathname_entry *e1 =
396 container_of(he1, const struct pathname_entry, ent);
397 const struct pathname_entry *e2 =
398 container_of(he2, const struct pathname_entry, ent);
399
400 return strcmp(e1->name, name ? (const char *)name : e2->name);
401}
402
403struct collection_status {
404 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
405
406 const char *reference;
407
408 unsigned skip_unseen:1;
409 size_t unmerged_count, binary_count;
410 struct string_list *files;
411 struct hashmap file_map;
412};
413
414static void collect_changes_cb(struct diff_queue_struct *q,
415 struct diff_options *options,
416 void *data)
417{
418 struct collection_status *s = data;
419 struct diffstat_t stat = { 0 };
420 int i;
421
422 if (!q->nr)
423 return;
424
425 compute_diffstat(options, &stat, q);
426
427 for (i = 0; i < stat.nr; i++) {
428 const char *name = stat.files[i]->name;
429 int hash = strhash(name);
430 struct pathname_entry *entry;
431 struct file_item *file_item;
432 struct adddel *adddel, *other_adddel;
433
434 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
435 struct pathname_entry, ent);
436 if (!entry) {
437 if (s->skip_unseen)
438 continue;
439
440 add_file_item(s->files, name);
441
442 CALLOC_ARRAY(entry, 1);
443 hashmap_entry_init(&entry->ent, hash);
444 entry->name = s->files->items[s->files->nr - 1].string;
445 entry->item = s->files->items[s->files->nr - 1].util;
446 hashmap_add(&s->file_map, &entry->ent);
447 }
448
449 file_item = entry->item;
450 adddel = s->mode == FROM_INDEX ?
451 &file_item->index : &file_item->worktree;
452 other_adddel = s->mode == FROM_INDEX ?
453 &file_item->worktree : &file_item->index;
454 adddel->seen = 1;
455 adddel->add = stat.files[i]->added;
456 adddel->del = stat.files[i]->deleted;
457 if (stat.files[i]->is_binary) {
458 if (!other_adddel->binary)
459 s->binary_count++;
460 adddel->binary = 1;
461 }
462 if (stat.files[i]->is_unmerged) {
463 if (!other_adddel->unmerged)
464 s->unmerged_count++;
465 adddel->unmerged = 1;
466 }
467 }
468 free_diffstat_info(&stat);
469}
470
471enum modified_files_filter {
472 NO_FILTER = 0,
473 WORKTREE_ONLY = 1,
474 INDEX_ONLY = 2,
475};
476
477static int get_modified_files(struct repository *r,
478 enum modified_files_filter filter,
479 struct prefix_item_list *files,
480 const struct pathspec *ps,
481 size_t *unmerged_count,
482 size_t *binary_count)
483{
484 struct object_id head_oid;
485 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(r),
486 "HEAD", RESOLVE_REF_READING,
487 &head_oid, NULL);
488 struct collection_status s = { 0 };
489 int i;
490
491 discard_index(r->index);
492 if (repo_read_index_preload(r, ps, 0) < 0)
493 return error(_("could not read index"));
494
495 prefix_item_list_clear(files);
496 s.files = &files->items;
497 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
498
499 for (i = 0; i < 2; i++) {
500 struct rev_info rev;
501 struct setup_revision_opt opt = { 0 };
502
503 if (filter == INDEX_ONLY)
504 s.mode = (i == 0) ? FROM_INDEX : FROM_WORKTREE;
505 else
506 s.mode = (i == 0) ? FROM_WORKTREE : FROM_INDEX;
507 s.skip_unseen = filter && i;
508
509 opt.def = is_initial ?
510 empty_tree_oid_hex(r->hash_algo) : oid_to_hex(&head_oid);
511
512 repo_init_revisions(r, &rev, NULL);
513 setup_revisions(0, NULL, &rev, &opt);
514
515 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
516 rev.diffopt.format_callback = collect_changes_cb;
517 rev.diffopt.format_callback_data = &s;
518
519 if (ps)
520 copy_pathspec(&rev.prune_data, ps);
521
522 if (s.mode == FROM_INDEX)
523 run_diff_index(&rev, DIFF_INDEX_CACHED);
524 else {
525 rev.diffopt.flags.ignore_dirty_submodules = 1;
526 run_diff_files(&rev, 0);
527 }
528
529 release_revisions(&rev);
530 }
531 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
532 if (unmerged_count)
533 *unmerged_count = s.unmerged_count;
534 if (binary_count)
535 *binary_count = s.binary_count;
536
537 /* While the diffs are ordered already, we ran *two* diffs... */
538 string_list_sort(&files->items);
539
540 return 0;
541}
542
543static void render_adddel(struct strbuf *buf,
544 struct adddel *ad, const char *no_changes)
545{
546 if (ad->binary)
547 strbuf_addstr(buf, _("binary"));
548 else if (ad->seen)
549 strbuf_addf(buf, "+%"PRIuMAX"/-%"PRIuMAX,
550 (uintmax_t)ad->add, (uintmax_t)ad->del);
551 else
552 strbuf_addstr(buf, no_changes);
553}
554
555/* filters out prefixes which have special meaning to list_and_choose() */
556static int is_valid_prefix(const char *prefix, size_t prefix_len)
557{
558 return prefix_len && prefix &&
559 /*
560 * We expect `prefix` to be NUL terminated, therefore this
561 * `strcspn()` call is okay, even if it might do much more
562 * work than strictly necessary.
563 */
564 strcspn(prefix, " \t\r\n,") >= prefix_len && /* separators */
565 *prefix != '-' && /* deselection */
566 !isdigit(*prefix) && /* selection */
567 (prefix_len != 1 ||
568 (*prefix != '*' && /* "all" wildcard */
569 *prefix != '?')); /* prompt help */
570}
571
572struct print_file_item_data {
573 const char *modified_fmt, *color, *reset;
574 struct strbuf buf, name, index, worktree;
575 unsigned only_names:1;
576};
577
578static void print_file_item(int i, int selected, struct string_list_item *item,
579 void *print_file_item_data)
580{
581 struct file_item *c = item->util;
582 struct print_file_item_data *d = print_file_item_data;
583 const char *highlighted = NULL;
584
585 strbuf_reset(&d->index);
586 strbuf_reset(&d->worktree);
587 strbuf_reset(&d->buf);
588
589 /* Format the item with the prefix highlighted. */
590 if (c->prefix_length > 0 &&
591 is_valid_prefix(item->string, c->prefix_length)) {
592 strbuf_reset(&d->name);
593 strbuf_addf(&d->name, "%s%.*s%s%s", d->color,
594 (int)c->prefix_length, item->string, d->reset,
595 item->string + c->prefix_length);
596 highlighted = d->name.buf;
597 }
598
599 if (d->only_names) {
600 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
601 highlighted ? highlighted : item->string);
602 return;
603 }
604
605 render_adddel(&d->worktree, &c->worktree, _("nothing"));
606 render_adddel(&d->index, &c->index, _("unchanged"));
607
608 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
609 highlighted ? highlighted : item->string);
610
611 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
612}
613
614static int run_status(struct add_i_state *s, const struct pathspec *ps,
615 struct prefix_item_list *files,
616 struct list_and_choose_options *opts)
617{
618 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
619 return -1;
620
621 list(s, &files->items, NULL, &opts->list_opts);
622 putchar('\n');
623
624 return 0;
625}
626
627static int run_update(struct add_i_state *s, const struct pathspec *ps,
628 struct prefix_item_list *files,
629 struct list_and_choose_options *opts)
630{
631 int res = 0, fd;
632 size_t count, i;
633 struct lock_file index_lock;
634
635 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
636 return -1;
637
638 if (!files->items.nr) {
639 putchar('\n');
640 return 0;
641 }
642
643 opts->prompt = N_("Update");
644 count = list_and_choose(s, files, opts);
645 if (count <= 0) {
646 putchar('\n');
647 return 0;
648 }
649
650 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
651 if (fd < 0) {
652 putchar('\n');
653 return -1;
654 }
655
656 for (i = 0; i < files->items.nr; i++) {
657 const char *name = files->items.items[i].string;
658 struct stat st;
659
660 if (!files->selected[i])
661 continue;
662 if (lstat(name, &st) && is_missing_file_error(errno)) {
663 if (remove_file_from_index(s->r->index, name) < 0) {
664 res = error(_("could not stage '%s'"), name);
665 break;
666 }
667 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
668 res = error(_("could not stage '%s'"), name);
669 break;
670 }
671 }
672
673 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
674 res = error(_("could not write index"));
675
676 if (!res)
677 printf(Q_("updated %d path\n",
678 "updated %d paths\n", count), (int)count);
679
680 putchar('\n');
681 return res;
682}
683
684static void revert_from_diff(struct diff_queue_struct *q,
685 struct diff_options *opt, void *data UNUSED)
686{
687 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
688
689 for (i = 0; i < q->nr; i++) {
690 struct diff_filespec *one = q->queue[i]->one;
691 struct cache_entry *ce;
692
693 if (!(one->mode && !is_null_oid(&one->oid))) {
694 remove_file_from_index(opt->repo->index, one->path);
695 printf(_("note: %s is untracked now.\n"), one->path);
696 } else {
697 ce = make_cache_entry(opt->repo->index, one->mode,
698 &one->oid, one->path, 0, 0);
699 if (!ce)
700 die(_("make_cache_entry failed for path '%s'"),
701 one->path);
702 add_index_entry(opt->repo->index, ce, add_flags);
703 }
704 }
705}
706
707static int run_revert(struct add_i_state *s, const struct pathspec *ps,
708 struct prefix_item_list *files,
709 struct list_and_choose_options *opts)
710{
711 int res = 0, fd;
712 size_t count, i, j;
713
714 struct object_id oid;
715 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(s->r),
716 "HEAD", RESOLVE_REF_READING,
717 &oid,
718 NULL);
719 struct lock_file index_lock;
720 const char **paths;
721 struct tree *tree;
722 struct diff_options diffopt = { NULL };
723
724 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
725 return -1;
726
727 if (!files->items.nr) {
728 putchar('\n');
729 return 0;
730 }
731
732 opts->prompt = N_("Revert");
733 count = list_and_choose(s, files, opts);
734 if (count <= 0)
735 goto finish_revert;
736
737 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
738 if (fd < 0) {
739 res = -1;
740 goto finish_revert;
741 }
742
743 if (is_initial)
744 oidcpy(&oid, s->r->hash_algo->empty_tree);
745 else {
746 tree = repo_parse_tree_indirect(s->r, &oid);
747 if (!tree) {
748 res = error(_("Could not parse HEAD^{tree}"));
749 goto finish_revert;
750 }
751 oidcpy(&oid, &tree->object.oid);
752 }
753
754 ALLOC_ARRAY(paths, count + 1);
755 for (i = j = 0; i < files->items.nr; i++)
756 if (files->selected[i])
757 paths[j++] = files->items.items[i].string;
758 paths[j] = NULL;
759
760 parse_pathspec(&diffopt.pathspec, 0,
761 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
762 NULL, paths);
763
764 diffopt.output_format = DIFF_FORMAT_CALLBACK;
765 diffopt.format_callback = revert_from_diff;
766 diffopt.flags.override_submodule_config = 1;
767 diffopt.repo = s->r;
768
769 if (do_diff_cache(&oid, &diffopt)) {
770 diff_free(&diffopt);
771 res = -1;
772 } else {
773 diffcore_std(&diffopt);
774 diff_flush(&diffopt);
775 }
776 free(paths);
777
778 if (!res && write_locked_index(s->r->index, &index_lock,
779 COMMIT_LOCK) < 0)
780 res = -1;
781 else
782 res = repo_refresh_and_write_index(s->r, REFRESH_QUIET, 0, 1,
783 NULL, NULL, NULL);
784
785 if (!res)
786 printf(Q_("reverted %d path\n",
787 "reverted %d paths\n", count), (int)count);
788
789finish_revert:
790 putchar('\n');
791 return res;
792}
793
794static int get_untracked_files(struct repository *r,
795 struct prefix_item_list *files,
796 const struct pathspec *ps)
797{
798 struct dir_struct dir = { 0 };
799 size_t i;
800 struct strbuf buf = STRBUF_INIT;
801
802 if (repo_read_index(r) < 0)
803 return error(_("could not read index"));
804
805 prefix_item_list_clear(files);
806 setup_standard_excludes(&dir);
807 add_pattern_list(&dir, EXC_CMDL, "--exclude option");
808 fill_directory(&dir, r->index, ps);
809
810 for (i = 0; i < dir.nr; i++) {
811 struct dir_entry *ent = dir.entries[i];
812
813 if (index_name_is_other(r->index, ent->name, ent->len)) {
814 strbuf_reset(&buf);
815 strbuf_add(&buf, ent->name, ent->len);
816 add_file_item(&files->items, buf.buf);
817 }
818 }
819
820 strbuf_release(&buf);
821 dir_clear(&dir);
822 return 0;
823}
824
825static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
826 struct prefix_item_list *files,
827 struct list_and_choose_options *opts)
828{
829 struct print_file_item_data *d = opts->list_opts.print_item_data;
830 int res = 0, fd;
831 size_t count, i;
832 struct lock_file index_lock;
833
834 if (get_untracked_files(s->r, files, ps) < 0)
835 return -1;
836
837 if (!files->items.nr) {
838 printf(_("No untracked files.\n"));
839 goto finish_add_untracked;
840 }
841
842 opts->prompt = N_("Add untracked");
843 d->only_names = 1;
844 count = list_and_choose(s, files, opts);
845 d->only_names = 0;
846 if (count <= 0)
847 goto finish_add_untracked;
848
849 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
850 if (fd < 0) {
851 res = -1;
852 goto finish_add_untracked;
853 }
854
855 for (i = 0; i < files->items.nr; i++) {
856 const char *name = files->items.items[i].string;
857 if (files->selected[i] &&
858 add_file_to_index(s->r->index, name, 0) < 0) {
859 res = error(_("could not stage '%s'"), name);
860 break;
861 }
862 }
863
864 if (!res &&
865 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
866 res = error(_("could not write index"));
867
868 if (!res)
869 printf(Q_("added %d path\n",
870 "added %d paths\n", count), (int)count);
871
872finish_add_untracked:
873 putchar('\n');
874 return res;
875}
876
877static int run_patch(struct add_i_state *s, const struct pathspec *ps,
878 struct prefix_item_list *files,
879 struct list_and_choose_options *opts)
880{
881 int res = 0;
882 ssize_t count, i, j;
883 size_t unmerged_count = 0, binary_count = 0;
884
885 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
886 &unmerged_count, &binary_count) < 0)
887 return -1;
888
889 if (unmerged_count || binary_count) {
890 for (i = j = 0; i < files->items.nr; i++) {
891 struct file_item *item = files->items.items[i].util;
892
893 if (item->index.binary || item->worktree.binary) {
894 free(item);
895 free(files->items.items[i].string);
896 } else if (item->index.unmerged ||
897 item->worktree.unmerged) {
898 color_fprintf_ln(stderr, s->cfg.error_color,
899 _("ignoring unmerged: %s"),
900 files->items.items[i].string);
901 free(item);
902 free(files->items.items[i].string);
903 } else
904 files->items.items[j++] = files->items.items[i];
905 }
906 files->items.nr = j;
907 }
908
909 if (!files->items.nr) {
910 if (binary_count)
911 fprintf(stderr, _("Only binary files changed.\n"));
912 else
913 fprintf(stderr, _("No changes.\n"));
914 return 0;
915 }
916
917 opts->prompt = N_("Patch update");
918 count = list_and_choose(s, files, opts);
919 if (count > 0) {
920 struct interactive_options opts = {
921 .context = s->cfg.context,
922 .interhunkcontext = s->cfg.interhunkcontext,
923 .auto_advance = s->cfg.auto_advance,
924 };
925 struct strvec args = STRVEC_INIT;
926 struct pathspec ps_selected = { 0 };
927
928 for (i = 0; i < files->items.nr; i++)
929 if (files->selected[i])
930 strvec_push(&args,
931 files->items.items[i].string);
932 parse_pathspec(&ps_selected,
933 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
934 PATHSPEC_LITERAL_PATH, "", args.v);
935 res = run_add_p(s->r, ADD_P_ADD, &opts, NULL, &ps_selected, 0);
936 strvec_clear(&args);
937 clear_pathspec(&ps_selected);
938 }
939
940 return res;
941}
942
943static int run_diff(struct add_i_state *s, const struct pathspec *ps,
944 struct prefix_item_list *files,
945 struct list_and_choose_options *opts)
946{
947 int res = 0;
948 ssize_t count, i;
949
950 struct object_id oid;
951 int is_initial = !refs_resolve_ref_unsafe(get_main_ref_store(s->r),
952 "HEAD", RESOLVE_REF_READING,
953 &oid,
954 NULL);
955 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
956 return -1;
957
958 if (!files->items.nr) {
959 putchar('\n');
960 return 0;
961 }
962
963 opts->prompt = N_("Review diff");
964 opts->flags = IMMEDIATE;
965 count = list_and_choose(s, files, opts);
966 opts->flags = 0;
967 if (count > 0) {
968 struct child_process cmd = CHILD_PROCESS_INIT;
969
970 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached", NULL);
971 if (s->cfg.context != -1)
972 strvec_pushf(&cmd.args, "--unified=%i", s->cfg.context);
973 if (s->cfg.interhunkcontext != -1)
974 strvec_pushf(&cmd.args, "--inter-hunk-context=%i", s->cfg.interhunkcontext);
975 strvec_pushl(&cmd.args, oid_to_hex(!is_initial ? &oid :
976 s->r->hash_algo->empty_tree), "--", NULL);
977 for (i = 0; i < files->items.nr; i++)
978 if (files->selected[i])
979 strvec_push(&cmd.args,
980 files->items.items[i].string);
981 res = run_command(&cmd);
982 }
983
984 putchar('\n');
985 return res;
986}
987
988static int run_help(struct add_i_state *s, const struct pathspec *ps UNUSED,
989 struct prefix_item_list *files UNUSED,
990 struct list_and_choose_options *opts UNUSED)
991{
992 color_fprintf_ln(stdout, s->cfg.help_color, "status - %s",
993 _("show paths with changes"));
994 color_fprintf_ln(stdout, s->cfg.help_color, "update - %s",
995 _("add working tree state to the staged set of changes"));
996 color_fprintf_ln(stdout, s->cfg.help_color, "revert - %s",
997 _("revert staged set of changes back to the HEAD version"));
998 color_fprintf_ln(stdout, s->cfg.help_color, "patch - %s",
999 _("pick hunks and update selectively"));
1000 color_fprintf_ln(stdout, s->cfg.help_color, "diff - %s",
1001 _("view diff between HEAD and index"));
1002 color_fprintf_ln(stdout, s->cfg.help_color, "add untracked - %s",
1003 _("add contents of untracked files to the staged set of changes"));
1004
1005 return 0;
1006}
1007
1008static void choose_prompt_help(struct add_i_state *s)
1009{
1010 color_fprintf_ln(stdout, s->cfg.help_color, "%s",
1011 _("Prompt help:"));
1012 color_fprintf_ln(stdout, s->cfg.help_color, "1 - %s",
1013 _("select a single item"));
1014 color_fprintf_ln(stdout, s->cfg.help_color, "3-5 - %s",
1015 _("select a range of items"));
1016 color_fprintf_ln(stdout, s->cfg.help_color, "2-3,6-9 - %s",
1017 _("select multiple ranges"));
1018 color_fprintf_ln(stdout, s->cfg.help_color, "foo - %s",
1019 _("select item based on unique prefix"));
1020 color_fprintf_ln(stdout, s->cfg.help_color, "-... - %s",
1021 _("unselect specified items"));
1022 color_fprintf_ln(stdout, s->cfg.help_color, "* - %s",
1023 _("choose all items"));
1024 color_fprintf_ln(stdout, s->cfg.help_color, " - %s",
1025 _("(empty) finish selecting"));
1026}
1027
1028typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
1029 struct prefix_item_list *files,
1030 struct list_and_choose_options *opts);
1031
1032struct command_item {
1033 size_t prefix_length;
1034 command_t command;
1035};
1036
1037struct print_command_item_data {
1038 const char *color, *reset;
1039};
1040
1041static void print_command_item(int i, int selected UNUSED,
1042 struct string_list_item *item,
1043 void *print_command_item_data)
1044{
1045 struct print_command_item_data *d = print_command_item_data;
1046 struct command_item *util = item->util;
1047
1048 if (!util->prefix_length ||
1049 !is_valid_prefix(item->string, util->prefix_length))
1050 printf(" %2d: %s", i + 1, item->string);
1051 else
1052 printf(" %2d: %s%.*s%s%s", i + 1,
1053 d->color, (int)util->prefix_length, item->string,
1054 d->reset, item->string + util->prefix_length);
1055}
1056
1057static void command_prompt_help(struct add_i_state *s)
1058{
1059 const char *help_color = s->cfg.help_color;
1060 color_fprintf_ln(stdout, help_color, "%s", _("Prompt help:"));
1061 color_fprintf_ln(stdout, help_color, "1 - %s",
1062 _("select a numbered item"));
1063 color_fprintf_ln(stdout, help_color, "foo - %s",
1064 _("select item based on unique prefix"));
1065 color_fprintf_ln(stdout, help_color, " - %s",
1066 _("(empty) select nothing"));
1067}
1068
1069int run_add_i(struct repository *r, const struct pathspec *ps,
1070 struct interactive_options *interactive_opts)
1071{
1072 struct add_i_state s = { NULL };
1073 struct print_command_item_data data = { "[", "]" };
1074 struct list_and_choose_options main_loop_opts = {
1075 { 4, N_("*** Commands ***"), print_command_item, &data },
1076 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
1077 };
1078 struct {
1079 const char *string;
1080 command_t command;
1081 } command_list[] = {
1082 { "status", run_status },
1083 { "update", run_update },
1084 { "revert", run_revert },
1085 { "add untracked", run_add_untracked },
1086 { "patch", run_patch },
1087 { "diff", run_diff },
1088 { "quit", NULL },
1089 { "help", run_help },
1090 };
1091 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1092
1093 struct print_file_item_data print_file_item_data = {
1094 "%12s %12s %s", NULL, NULL,
1095 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
1096 };
1097 struct list_and_choose_options opts = {
1098 { 0, NULL, print_file_item, &print_file_item_data },
1099 NULL, 0, choose_prompt_help
1100 };
1101 struct strbuf header = STRBUF_INIT;
1102 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1103 ssize_t i;
1104 int res = 0;
1105
1106 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
1107 struct command_item *util = xcalloc(1, sizeof(*util));
1108 util->command = command_list[i].command;
1109 string_list_append(&commands.items, command_list[i].string)
1110 ->util = util;
1111 }
1112
1113 init_add_i_state(&s, r, interactive_opts);
1114
1115 /*
1116 * When color was asked for, use the prompt color for
1117 * highlighting, otherwise use square brackets.
1118 */
1119 if (want_color(s.cfg.use_color_interactive)) {
1120 data.color = s.cfg.prompt_color;
1121 data.reset = s.cfg.reset_color_interactive;
1122 }
1123 print_file_item_data.color = data.color;
1124 print_file_item_data.reset = data.reset;
1125
1126 strbuf_addstr(&header, " ");
1127 strbuf_addf(&header, print_file_item_data.modified_fmt,
1128 _("staged"), _("unstaged"), _("path"));
1129 opts.list_opts.header = header.buf;
1130
1131 discard_index(r->index);
1132 if (repo_read_index(r) < 0 ||
1133 repo_refresh_and_write_index(r, REFRESH_QUIET, 0, 1,
1134 NULL, NULL, NULL) < 0)
1135 warning(_("could not refresh index"));
1136
1137 res = run_status(&s, ps, &files, &opts);
1138
1139 for (;;) {
1140 struct command_item *util;
1141
1142 i = list_and_choose(&s, &commands, &main_loop_opts);
1143 if (i < 0 || i >= commands.items.nr)
1144 util = NULL;
1145 else
1146 util = commands.items.items[i].util;
1147
1148 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1149 printf(_("Bye.\n"));
1150 res = 0;
1151 break;
1152 }
1153
1154 if (util)
1155 res = util->command(&s, ps, &files, &opts);
1156 }
1157
1158 prefix_item_list_clear(&files);
1159 strbuf_release(&print_file_item_data.buf);
1160 strbuf_release(&print_file_item_data.name);
1161 strbuf_release(&print_file_item_data.index);
1162 strbuf_release(&print_file_item_data.worktree);
1163 strbuf_release(&header);
1164 prefix_item_list_clear(&commands);
1165 clear_add_i_state(&s);
1166
1167 return res;
1168}