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