]> git.ipfire.org Git - thirdparty/git.git/blob - add-interactive.c
treewide: be explicit about dependence on strbuf.h
[thirdparty/git.git] / add-interactive.c
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"
15
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)
19 {
20 char *key = xstrfmt("color.%s", section_and_slot);
21 const char *value;
22
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);
28
29 free(key);
30 }
31
32 void init_add_i_state(struct add_i_state *s, struct repository *r)
33 {
34 const char *value;
35
36 s->r = r;
37
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);
44
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);
51
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));
62
63 strlcpy(s->reset_color,
64 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
65
66 FREE_AND_NULL(s->interactive_diff_filter);
67 git_config_get_string("interactive.difffilter",
68 &s->interactive_diff_filter);
69
70 FREE_AND_NULL(s->interactive_diff_algorithm);
71 git_config_get_string("diff.algorithm",
72 &s->interactive_diff_algorithm);
73
74 git_config_get_bool("interactive.singlekey", &s->use_single_key);
75 if (s->use_single_key)
76 setbuf(stdin, NULL);
77 }
78
79 void clear_add_i_state(struct add_i_state *s)
80 {
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;
85 }
86
87 /*
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.
90 *
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`.
94 *
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.
97 *
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()`.
102 */
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;
108 };
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, \
114 }
115
116 static void prefix_item_list_clear(struct prefix_item_list *list)
117 {
118 string_list_clear(&list->items, 1);
119 string_list_clear(&list->sorted, 0);
120 FREE_AND_NULL(list->selected);
121 }
122
123 static void extend_prefix_length(struct string_list_item *p,
124 const char *other_string, size_t max_length)
125 {
126 size_t *len = p->util;
127
128 if (!*len || memcmp(p->string, other_string, *len))
129 return;
130
131 for (;;) {
132 char c = p->string[*len];
133
134 /*
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.
139 */
140 if (!c || ++*len > max_length || !isascii(c)) {
141 *len = 0;
142 break;
143 }
144
145 if (c != other_string[*len - 1])
146 break;
147 }
148 }
149
150 static void find_unique_prefixes(struct prefix_item_list *list)
151 {
152 size_t i;
153
154 if (list->sorted.nr == list->items.nr)
155 return;
156
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;
162
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;
166 }
167
168 string_list_sort(&list->sorted);
169
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;
174
175 *len = 0;
176 while (*len < list->min_length) {
177 char c = item->string[(*len)++];
178
179 if (!c || !isascii(c)) {
180 *len = 0;
181 break;
182 }
183 }
184
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);
191 }
192 }
193
194 static ssize_t find_unique(const char *string, struct prefix_item_list *list)
195 {
196 int index = string_list_find_insert_index(&list->sorted, string, 1);
197 struct string_list_item *item;
198
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);
203
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;
218 }
219
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;
226 };
227
228 static void list(struct add_i_state *s, struct string_list *list, int *selected,
229 struct list_options *opts)
230 {
231 int i, last_lf = 0;
232
233 if (!list->nr)
234 return;
235
236 if (opts->header)
237 color_fprintf_ln(stdout, s->header_color,
238 "%s", opts->header);
239
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);
243
244 if ((opts->columns) && ((i + 1) % (opts->columns))) {
245 putchar('\t');
246 last_lf = 0;
247 }
248 else {
249 putchar('\n');
250 last_lf = 1;
251 }
252 }
253
254 if (!last_lf)
255 putchar('\n');
256 }
257 struct list_and_choose_options {
258 struct list_options list_opts;
259
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);
266 };
267
268 #define LIST_AND_CHOOSE_ERROR (-1)
269 #define LIST_AND_CHOOSE_QUIT (-2)
270
271 /*
272 * Returns the selected index in singleton mode, the number of selected items
273 * otherwise.
274 *
275 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
276 * `LIST_AND_CHOOSE_QUIT` is returned.
277 */
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)
281 {
282 int singleton = opts->flags & SINGLETON;
283 int immediate = opts->flags & IMMEDIATE;
284
285 struct strbuf input = STRBUF_INIT;
286 ssize_t res = singleton ? LIST_AND_CHOOSE_ERROR : 0;
287
288 if (!singleton) {
289 free(items->selected);
290 CALLOC_ARRAY(items->selected, items->items.nr);
291 }
292
293 if (singleton && !immediate)
294 BUG("singleton requires immediate");
295
296 find_unique_prefixes(items);
297
298 for (;;) {
299 char *p;
300
301 strbuf_reset(&input);
302
303 list(s, &items->items, items->selected, &opts->list_opts);
304
305 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
306 fputs(singleton ? "> " : ">> ", stdout);
307 fflush(stdout);
308
309 if (git_read_line_interactively(&input) == EOF) {
310 putchar('\n');
311 if (immediate)
312 res = LIST_AND_CHOOSE_QUIT;
313 break;
314 }
315
316 if (!input.len)
317 break;
318
319 if (!strcmp(input.buf, "?")) {
320 opts->print_help(s);
321 continue;
322 }
323
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;
330
331 if (!sep) {
332 if (!*p)
333 break;
334 p++;
335 continue;
336 }
337
338 /* Input that begins with '-'; de-select */
339 if (*p == '-') {
340 choose = 0;
341 p++;
342 sep--;
343 }
344
345 if (sep == 1 && *p == '*') {
346 from = 0;
347 to = items->items.nr;
348 } else if (isdigit(*p)) {
349 char *endp;
350 /*
351 * A range can be specified like 5-7 or 5-.
352 *
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.
358 */
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;
370 }
371 }
372
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;
379 }
380
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;
389 }
390
391 if (to > items->items.nr)
392 to = items->items.nr;
393
394 for (; from < to; from++)
395 if (items->selected[from] != choose) {
396 items->selected[from] = choose;
397 res += choose ? +1 : -1;
398 }
399
400 p += sep;
401 }
402
403 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
404 !strcmp(input.buf, "*"))
405 break;
406 }
407
408 strbuf_release(&input);
409 return res;
410 }
411
412 struct adddel {
413 uintmax_t add, del;
414 unsigned seen:1, unmerged:1, binary:1;
415 };
416
417 struct file_item {
418 size_t prefix_length;
419 struct adddel index, worktree;
420 };
421
422 static void add_file_item(struct string_list *files, const char *name)
423 {
424 struct file_item *item = xcalloc(1, sizeof(*item));
425
426 string_list_append(files, name)->util = item;
427 }
428
429 struct pathname_entry {
430 struct hashmap_entry ent;
431 const char *name;
432 struct file_item *item;
433 };
434
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)
439 {
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);
444
445 return strcmp(e1->name, name ? (const char *)name : e2->name);
446 }
447
448 struct collection_status {
449 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
450
451 const char *reference;
452
453 unsigned skip_unseen:1;
454 size_t unmerged_count, binary_count;
455 struct string_list *files;
456 struct hashmap file_map;
457 };
458
459 static void collect_changes_cb(struct diff_queue_struct *q,
460 struct diff_options *options,
461 void *data)
462 {
463 struct collection_status *s = data;
464 struct diffstat_t stat = { 0 };
465 int i;
466
467 if (!q->nr)
468 return;
469
470 compute_diffstat(options, &stat, q);
471
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;
478
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;
484
485 add_file_item(s->files, name);
486
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);
492 }
493
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;
506 }
507 if (stat.files[i]->is_unmerged) {
508 if (!other_adddel->unmerged)
509 s->unmerged_count++;
510 adddel->unmerged = 1;
511 }
512 }
513 free_diffstat_info(&stat);
514 }
515
516 enum modified_files_filter {
517 NO_FILTER = 0,
518 WORKTREE_ONLY = 1,
519 INDEX_ONLY = 2,
520 };
521
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)
528 {
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;
534
535 discard_index(r->index);
536 if (repo_read_index_preload(r, ps, 0) < 0)
537 return error(_("could not read index"));
538
539 prefix_item_list_clear(files);
540 s.files = &files->items;
541 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
542
543 for (i = 0; i < 2; i++) {
544 struct rev_info rev;
545 struct setup_revision_opt opt = { 0 };
546
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;
552
553 opt.def = is_initial ?
554 empty_tree_oid_hex() : oid_to_hex(&head_oid);
555
556 repo_init_revisions(r, &rev, NULL);
557 setup_revisions(0, NULL, &rev, &opt);
558
559 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
560 rev.diffopt.format_callback = collect_changes_cb;
561 rev.diffopt.format_callback_data = &s;
562
563 if (ps)
564 copy_pathspec(&rev.prune_data, ps);
565
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);
571 }
572
573 release_revisions(&rev);
574 }
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;
580
581 /* While the diffs are ordered already, we ran *two* diffs... */
582 string_list_sort(&files->items);
583
584 return 0;
585 }
586
587 static void render_adddel(struct strbuf *buf,
588 struct adddel *ad, const char *no_changes)
589 {
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);
597 }
598
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)
601 {
602 return prefix_len && prefix &&
603 /*
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.
607 */
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 */
614 }
615
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;
620 };
621
622 static void print_file_item(int i, int selected, struct string_list_item *item,
623 void *print_file_item_data)
624 {
625 struct file_item *c = item->util;
626 struct print_file_item_data *d = print_file_item_data;
627 const char *highlighted = NULL;
628
629 strbuf_reset(&d->index);
630 strbuf_reset(&d->worktree);
631 strbuf_reset(&d->buf);
632
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;
641 }
642
643 if (d->only_names) {
644 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
645 highlighted ? highlighted : item->string);
646 return;
647 }
648
649 render_adddel(&d->worktree, &c->worktree, _("nothing"));
650 render_adddel(&d->index, &c->index, _("unchanged"));
651
652 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
653 highlighted ? highlighted : item->string);
654
655 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
656 }
657
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)
661 {
662 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
663 return -1;
664
665 list(s, &files->items, NULL, &opts->list_opts);
666 putchar('\n');
667
668 return 0;
669 }
670
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)
674 {
675 int res = 0, fd;
676 size_t count, i;
677 struct lock_file index_lock;
678
679 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
680 return -1;
681
682 if (!files->items.nr) {
683 putchar('\n');
684 return 0;
685 }
686
687 opts->prompt = N_("Update");
688 count = list_and_choose(s, files, opts);
689 if (count <= 0) {
690 putchar('\n');
691 return 0;
692 }
693
694 fd = repo_hold_locked_index(s->r, &index_lock, LOCK_REPORT_ON_ERROR);
695 if (fd < 0) {
696 putchar('\n');
697 return -1;
698 }
699
700 for (i = 0; i < files->items.nr; i++) {
701 const char *name = files->items.items[i].string;
702 struct stat st;
703
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;
710 }
711 } else if (add_file_to_index(s->r->index, name, 0) < 0) {
712 res = error(_("could not stage '%s'"), name);
713 break;
714 }
715 }
716
717 if (!res && write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
718 res = error(_("could not write index"));
719
720 if (!res)
721 printf(Q_("updated %d path\n",
722 "updated %d paths\n", count), (int)count);
723
724 putchar('\n');
725 return res;
726 }
727
728 static void revert_from_diff(struct diff_queue_struct *q,
729 struct diff_options *opt, void *data UNUSED)
730 {
731 int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
732
733 for (i = 0; i < q->nr; i++) {
734 struct diff_filespec *one = q->queue[i]->one;
735 struct cache_entry *ce;
736
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);
747 }
748 }
749 }
750
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)
754 {
755 int res = 0, fd;
756 size_t count, i, j;
757
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 };
765
766 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
767 return -1;
768
769 if (!files->items.nr) {
770 putchar('\n');
771 return 0;
772 }
773
774 opts->prompt = N_("Revert");
775 count = list_and_choose(s, files, opts);
776 if (count <= 0)
777 goto finish_revert;
778
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;
783 }
784
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;
792 }
793 oidcpy(&oid, &tree->object.oid);
794 }
795
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;
801
802 parse_pathspec(&diffopt.pathspec, 0,
803 PATHSPEC_PREFER_FULL | PATHSPEC_LITERAL_PATH,
804 NULL, paths);
805
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;
810
811 if (do_diff_cache(&oid, &diffopt)) {
812 diff_free(&diffopt);
813 res = -1;
814 } else {
815 diffcore_std(&diffopt);
816 diff_flush(&diffopt);
817 }
818 free(paths);
819
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);
826
827 if (!res)
828 printf(Q_("reverted %d path\n",
829 "reverted %d paths\n", count), (int)count);
830
831 finish_revert:
832 putchar('\n');
833 return res;
834 }
835
836 static int get_untracked_files(struct repository *r,
837 struct prefix_item_list *files,
838 const struct pathspec *ps)
839 {
840 struct dir_struct dir = { 0 };
841 size_t i;
842 struct strbuf buf = STRBUF_INIT;
843
844 if (repo_read_index(r) < 0)
845 return error(_("could not read index"));
846
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);
851
852 for (i = 0; i < dir.nr; i++) {
853 struct dir_entry *ent = dir.entries[i];
854
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);
859 }
860 }
861
862 strbuf_release(&buf);
863 return 0;
864 }
865
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)
869 {
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;
874
875 if (get_untracked_files(s->r, files, ps) < 0)
876 return -1;
877
878 if (!files->items.nr) {
879 printf(_("No untracked files.\n"));
880 goto finish_add_untracked;
881 }
882
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;
889
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;
894 }
895
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;
902 }
903 }
904
905 if (!res &&
906 write_locked_index(s->r->index, &index_lock, COMMIT_LOCK) < 0)
907 res = error(_("could not write index"));
908
909 if (!res)
910 printf(Q_("added %d path\n",
911 "added %d paths\n", count), (int)count);
912
913 finish_add_untracked:
914 putchar('\n');
915 return res;
916 }
917
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)
921 {
922 int res = 0;
923 ssize_t count, i, j;
924 size_t unmerged_count = 0, binary_count = 0;
925
926 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps,
927 &unmerged_count, &binary_count) < 0)
928 return -1;
929
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;
933
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];
946 }
947 files->items.nr = j;
948 }
949
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;
956 }
957
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 };
963
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);
974 }
975
976 return res;
977 }
978
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)
982 {
983 int res = 0;
984 ssize_t count, i;
985
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;
991
992 if (!files->items.nr) {
993 putchar('\n');
994 return 0;
995 }
996
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;
1003
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);
1013 }
1014
1015 putchar('\n');
1016 return res;
1017 }
1018
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)
1022 {
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"));
1035
1036 return 0;
1037 }
1038
1039 static void choose_prompt_help(struct add_i_state *s)
1040 {
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"));
1057 }
1058
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);
1062
1063 struct command_item {
1064 size_t prefix_length;
1065 command_t command;
1066 };
1067
1068 struct print_command_item_data {
1069 const char *color, *reset;
1070 };
1071
1072 static void print_command_item(int i, int selected,
1073 struct string_list_item *item,
1074 void *print_command_item_data)
1075 {
1076 struct print_command_item_data *d = print_command_item_data;
1077 struct command_item *util = item->util;
1078
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);
1086 }
1087
1088 static void command_prompt_help(struct add_i_state *s)
1089 {
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"));
1098 }
1099
1100 int run_add_i(struct repository *r, const struct pathspec *ps)
1101 {
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
1107 };
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 },
1120 };
1121 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
1122
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
1126 };
1127 struct list_and_choose_options opts = {
1128 { 0, NULL, print_file_item, &print_file_item_data },
1129 NULL, 0, choose_prompt_help
1130 };
1131 struct strbuf header = STRBUF_INIT;
1132 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
1133 ssize_t i;
1134 int res = 0;
1135
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;
1141 }
1142
1143 init_add_i_state(&s, r);
1144
1145 /*
1146 * When color was asked for, use the prompt color for
1147 * highlighting, otherwise use square brackets.
1148 */
1149 if (s.use_color) {
1150 data.color = s.prompt_color;
1151 data.reset = s.reset_color;
1152 }
1153 print_file_item_data.color = data.color;
1154 print_file_item_data.reset = data.reset;
1155
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;
1160
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"));
1166
1167 res = run_status(&s, ps, &files, &opts);
1168
1169 for (;;) {
1170 struct command_item *util;
1171
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;
1177
1178 if (i == LIST_AND_CHOOSE_QUIT || (util && !util->command)) {
1179 printf(_("Bye.\n"));
1180 res = 0;
1181 break;
1182 }
1183
1184 if (util)
1185 res = util->command(&s, ps, &files, &opts);
1186 }
1187
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);
1196
1197 return res;
1198 }