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