]> git.ipfire.org Git - thirdparty/git.git/blame - add-interactive.c
fsmonitor: reduce includes of 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"
5e82b9e4
DF
8#include "revision.h"
9#include "refs.h"
10#include "string-list.h"
a8c45be9 11#include "lockfile.h"
ab1e1ccc 12#include "dir.h"
8746e072 13#include "run-command.h"
08d383f2 14#include "prompt.h"
5e82b9e4 15
1daaebca 16static void init_color(struct repository *r, struct add_i_state *s,
25d9e5cc 17 const char *section_and_slot, char *dst,
1daaebca
18 const char *default_color)
19{
25d9e5cc 20 char *key = xstrfmt("color.%s", section_and_slot);
1daaebca
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
25ea47af 32void init_add_i_state(struct add_i_state *s, struct repository *r)
5e82b9e4 33{
1daaebca
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
25d9e5cc
JS
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,
25ea47af 53 diff_get_color(s->use_color, DIFF_FRAGINFO));
890b68b2
JS
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));
25d9e5cc 58 init_color(r, s, "diff.old", s->file_old_color,
bcdd297b 59 diff_get_color(s->use_color, DIFF_FILE_OLD));
25d9e5cc 60 init_color(r, s, "diff.new", s->file_new_color,
bcdd297b 61 diff_get_color(s->use_color, DIFF_FILE_NEW));
180f48df 62
c62cd172
JS
63 strlcpy(s->reset_color,
64 s->use_color ? GIT_COLOR_RESET : "", COLOR_MAXLEN);
65
180f48df
JS
66 FREE_AND_NULL(s->interactive_diff_filter);
67 git_config_get_string("interactive.difffilter",
68 &s->interactive_diff_filter);
08b1ea4c
JS
69
70 FREE_AND_NULL(s->interactive_diff_algorithm);
71 git_config_get_string("diff.algorithm",
72 &s->interactive_diff_algorithm);
04f816b1
JS
73
74 git_config_get_bool("interactive.singlekey", &s->use_single_key);
ac618c41
PW
75 if (s->use_single_key)
76 setbuf(stdin, NULL);
180f48df
JS
77}
78
79void clear_add_i_state(struct add_i_state *s)
80{
81 FREE_AND_NULL(s->interactive_diff_filter);
08b1ea4c 82 FREE_AND_NULL(s->interactive_diff_algorithm);
180f48df
JS
83 memset(s, 0, sizeof(*s));
84 s->use_color = -1;
5e82b9e4
DF
85}
86
76b74323
JS
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 */
103struct prefix_item_list {
104 struct string_list items;
105 struct string_list sorted;
f37c2264 106 int *selected; /* for multi-selections */
76b74323
JS
107 size_t min_length, max_length;
108};
f69a6e4f
ÆAB
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}
76b74323
JS
115
116static 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);
f37c2264 120 FREE_AND_NULL(list->selected);
76b74323
JS
121}
122
123static 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
150static 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
194static 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;
d34e4502
JS
212 else if (index < list->sorted.nr &&
213 starts_with(list->sorted.items[index].string, string))
76b74323
JS
214 item = list->sorted.items[index].util;
215 else
216 return -1;
217 return item - list->items.items;
218}
219
5e82b9e4 220struct list_options {
6348bfba 221 int columns;
5e82b9e4 222 const char *header;
f37c2264
JS
223 void (*print_item)(int i, int selected, struct string_list_item *item,
224 void *print_item_data);
5e82b9e4
DF
225 void *print_item_data;
226};
227
f37c2264 228static void list(struct add_i_state *s, struct string_list *list, int *selected,
1daaebca 229 struct list_options *opts)
5e82b9e4 230{
6348bfba 231 int i, last_lf = 0;
5e82b9e4
DF
232
233 if (!list->nr)
234 return;
235
236 if (opts->header)
1daaebca
237 color_fprintf_ln(stdout, s->header_color,
238 "%s", opts->header);
5e82b9e4
DF
239
240 for (i = 0; i < list->nr; i++) {
f37c2264
JS
241 opts->print_item(i, selected ? selected[i] : 0, list->items + i,
242 opts->print_item_data);
6348bfba
JS
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)
5e82b9e4 255 putchar('\n');
6348bfba
JS
256}
257struct list_and_choose_options {
258 struct list_options list_opts;
259
260 const char *prompt;
f37c2264
JS
261 enum {
262 SINGLETON = (1<<0),
263 IMMEDIATE = (1<<1),
264 } flags;
68db1cbf 265 void (*print_help)(struct add_i_state *s);
6348bfba
JS
266};
267
268#define LIST_AND_CHOOSE_ERROR (-1)
269#define LIST_AND_CHOOSE_QUIT (-2)
270
271/*
f37c2264
JS
272 * Returns the selected index in singleton mode, the number of selected items
273 * otherwise.
6348bfba
JS
274 *
275 * If an error occurred, returns `LIST_AND_CHOOSE_ERROR`. Upon EOF,
276 * `LIST_AND_CHOOSE_QUIT` is returned.
277 */
76b74323
JS
278static ssize_t list_and_choose(struct add_i_state *s,
279 struct prefix_item_list *items,
6348bfba
JS
280 struct list_and_choose_options *opts)
281{
f37c2264
JS
282 int singleton = opts->flags & SINGLETON;
283 int immediate = opts->flags & IMMEDIATE;
284
6348bfba 285 struct strbuf input = STRBUF_INIT;
f37c2264
JS
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");
6348bfba 295
76b74323
JS
296 find_unique_prefixes(items);
297
6348bfba
JS
298 for (;;) {
299 char *p;
300
301 strbuf_reset(&input);
302
f37c2264 303 list(s, &items->items, items->selected, &opts->list_opts);
6348bfba 304
3d965c76 305 color_fprintf(stdout, s->prompt_color, "%s", opts->prompt);
f37c2264 306 fputs(singleton ? "> " : ">> ", stdout);
6348bfba
JS
307 fflush(stdout);
308
08d383f2 309 if (git_read_line_interactively(&input) == EOF) {
6348bfba 310 putchar('\n');
f37c2264
JS
311 if (immediate)
312 res = LIST_AND_CHOOSE_QUIT;
6348bfba
JS
313 break;
314 }
6348bfba
JS
315
316 if (!input.len)
317 break;
318
68db1cbf
JS
319 if (!strcmp(input.buf, "?")) {
320 opts->print_help(s);
321 continue;
322 }
323
6348bfba
JS
324 p = input.buf;
325 for (;;) {
326 size_t sep = strcspn(p, " \t\r\n,");
f37c2264
JS
327 int choose = 1;
328 /* `from` is inclusive, `to` is exclusive */
329 ssize_t from = -1, to = -1;
6348bfba
JS
330
331 if (!sep) {
332 if (!*p)
333 break;
334 p++;
335 continue;
336 }
337
f37c2264
JS
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)) {
6348bfba 349 char *endp;
f37c2264
JS
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 == '-') {
849e43cc
JS
363 if (isdigit(*(++endp)))
364 to = strtoul(endp, &endp, 10);
365 else
366 to = items->items.nr;
f37c2264
JS
367 /* extra characters after the range? */
368 if (endp != p + sep)
369 from = -1;
370 }
6348bfba
JS
371 }
372
373 if (p[sep])
374 p[sep++] = '\0';
f37c2264
JS
375 if (from < 0) {
376 from = find_unique(p, items);
377 if (from >= 0)
378 to = from + 1;
379 }
76b74323 380
f37c2264
JS
381 if (from < 0 || from >= items->items.nr ||
382 (singleton && from + 1 != to)) {
cb581b16 383 color_fprintf_ln(stderr, s->error_color,
3d965c76 384 _("Huh (%s)?"), p);
f37c2264
JS
385 break;
386 } else if (singleton) {
387 res = from;
6348bfba
JS
388 break;
389 }
390
f37c2264
JS
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
6348bfba
JS
400 p += sep;
401 }
402
f37c2264
JS
403 if ((immediate && res != LIST_AND_CHOOSE_ERROR) ||
404 !strcmp(input.buf, "*"))
6348bfba 405 break;
5e82b9e4 406 }
6348bfba
JS
407
408 strbuf_release(&input);
409 return res;
5e82b9e4
DF
410}
411
412struct adddel {
413 uintmax_t add, del;
8746e072 414 unsigned seen:1, unmerged:1, binary:1;
5e82b9e4
DF
415};
416
417struct file_item {
a8c45be9 418 size_t prefix_length;
5e82b9e4
DF
419 struct adddel index, worktree;
420};
421
422static void add_file_item(struct string_list *files, const char *name)
423{
241b5d3e 424 struct file_item *item = xcalloc(1, sizeof(*item));
5e82b9e4
DF
425
426 string_list_append(files, name)->util = item;
427}
428
429struct pathname_entry {
430 struct hashmap_entry ent;
431 const char *name;
432 struct file_item *item;
433};
434
5cf88fd8 435static int pathname_entry_cmp(const void *cmp_data UNUSED,
5e82b9e4
DF
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
448struct collection_status {
c08171d1 449 enum { FROM_WORKTREE = 0, FROM_INDEX = 1 } mode;
5e82b9e4
DF
450
451 const char *reference;
452
c08171d1 453 unsigned skip_unseen:1;
8746e072 454 size_t unmerged_count, binary_count;
5e82b9e4
DF
455 struct string_list *files;
456 struct hashmap file_map;
457};
458
459static 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;
8746e072 477 struct adddel *adddel, *other_adddel;
5e82b9e4
DF
478
479 entry = hashmap_get_entry_from_hash(&s->file_map, hash, name,
480 struct pathname_entry, ent);
481 if (!entry) {
c08171d1
JS
482 if (s->skip_unseen)
483 continue;
484
5e82b9e4
DF
485 add_file_item(s->files, name);
486
ca56dadb 487 CALLOC_ARRAY(entry, 1);
5e82b9e4
DF
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;
c08171d1 495 adddel = s->mode == FROM_INDEX ?
5e82b9e4 496 &file_item->index : &file_item->worktree;
8746e072
JS
497 other_adddel = s->mode == FROM_INDEX ?
498 &file_item->worktree : &file_item->index;
5e82b9e4
DF
499 adddel->seen = 1;
500 adddel->add = stat.files[i]->added;
501 adddel->del = stat.files[i]->deleted;
8746e072
JS
502 if (stat.files[i]->is_binary) {
503 if (!other_adddel->binary)
504 s->binary_count++;
5e82b9e4 505 adddel->binary = 1;
8746e072
JS
506 }
507 if (stat.files[i]->is_unmerged) {
508 if (!other_adddel->unmerged)
509 s->unmerged_count++;
510 adddel->unmerged = 1;
511 }
5e82b9e4
DF
512 }
513 free_diffstat_info(&stat);
514}
515
c08171d1
JS
516enum modified_files_filter {
517 NO_FILTER = 0,
518 WORKTREE_ONLY = 1,
519 INDEX_ONLY = 2,
520};
521
522static int get_modified_files(struct repository *r,
523 enum modified_files_filter filter,
a8c45be9 524 struct prefix_item_list *files,
8746e072
JS
525 const struct pathspec *ps,
526 size_t *unmerged_count,
527 size_t *binary_count)
5e82b9e4
DF
528{
529 struct object_id head_oid;
530 int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
531 &head_oid, NULL);
c08171d1
JS
532 struct collection_status s = { 0 };
533 int i;
5e82b9e4 534
9c5f3ee3
ÆAB
535 discard_index(r->index);
536 if (repo_read_index_preload(r, ps, 0) < 0)
5e82b9e4
DF
537 return error(_("could not read index"));
538
a8c45be9
JS
539 prefix_item_list_clear(files);
540 s.files = &files->items;
5e82b9e4
DF
541 hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
542
c08171d1 543 for (i = 0; i < 2; i++) {
5e82b9e4
DF
544 struct rev_info rev;
545 struct setup_revision_opt opt = { 0 };
546
c08171d1
JS
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
5e82b9e4
DF
553 opt.def = is_initial ?
554 empty_tree_oid_hex() : oid_to_hex(&head_oid);
555
4a93b899 556 repo_init_revisions(r, &rev, NULL);
5e82b9e4
DF
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
c08171d1 566 if (s.mode == FROM_INDEX)
5e82b9e4
DF
567 run_diff_index(&rev, 1);
568 else {
569 rev.diffopt.flags.ignore_dirty_submodules = 1;
570 run_diff_files(&rev, 0);
571 }
0c3944a6 572
2108fe4a 573 release_revisions(&rev);
5e82b9e4 574 }
6da1a258 575 hashmap_clear_and_free(&s.file_map, struct pathname_entry, ent);
8746e072
JS
576 if (unmerged_count)
577 *unmerged_count = s.unmerged_count;
578 if (binary_count)
579 *binary_count = s.binary_count;
5e82b9e4
DF
580
581 /* While the diffs are ordered already, we ran *two* diffs... */
a8c45be9 582 string_list_sort(&files->items);
5e82b9e4
DF
583
584 return 0;
585}
586
587static 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
76b74323
JS
599/* filters out prefixes which have special meaning to list_and_choose() */
600static 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
5e82b9e4 616struct print_file_item_data {
a8c45be9
JS
617 const char *modified_fmt, *color, *reset;
618 struct strbuf buf, name, index, worktree;
ab1e1ccc 619 unsigned only_names:1;
5e82b9e4
DF
620};
621
f37c2264 622static void print_file_item(int i, int selected, struct string_list_item *item,
5e82b9e4
DF
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;
a8c45be9 627 const char *highlighted = NULL;
5e82b9e4
DF
628
629 strbuf_reset(&d->index);
630 strbuf_reset(&d->worktree);
631 strbuf_reset(&d->buf);
632
a8c45be9
JS
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
ab1e1ccc
JS
643 if (d->only_names) {
644 printf("%c%2d: %s", selected ? '*' : ' ', i + 1,
645 highlighted ? highlighted : item->string);
646 return;
647 }
648
5e82b9e4
DF
649 render_adddel(&d->worktree, &c->worktree, _("nothing"));
650 render_adddel(&d->index, &c->index, _("unchanged"));
a8c45be9
JS
651
652 strbuf_addf(&d->buf, d->modified_fmt, d->index.buf, d->worktree.buf,
653 highlighted ? highlighted : item->string);
5e82b9e4 654
f37c2264 655 printf("%c%2d: %s", selected ? '*' : ' ', i + 1, d->buf.buf);
5e82b9e4
DF
656}
657
658static int run_status(struct add_i_state *s, const struct pathspec *ps,
a8c45be9
JS
659 struct prefix_item_list *files,
660 struct list_and_choose_options *opts)
5e82b9e4 661{
8746e072 662 if (get_modified_files(s->r, NO_FILTER, files, ps, NULL, NULL) < 0)
5e82b9e4
DF
663 return -1;
664
a8c45be9 665 list(s, &files->items, NULL, &opts->list_opts);
5e82b9e4
DF
666 putchar('\n');
667
668 return 0;
669}
f83dff60 670
a8c45be9
JS
671static 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
8746e072 679 if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
a8c45be9
JS
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;
4788e8b2
JS
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) {
a8c45be9
JS
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
c54ef5e4 728static void revert_from_diff(struct diff_queue_struct *q,
61bdc7c5 729 struct diff_options *opt, void *data UNUSED)
c54ef5e4
JS
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
751static 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
8746e072 766 if (get_modified_files(s->r, INDEX_ONLY, files, ps, NULL, NULL) < 0)
c54ef5e4
JS
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
244c2724
ÆAB
811 if (do_diff_cache(&oid, &diffopt)) {
812 diff_free(&diffopt);
c54ef5e4 813 res = -1;
244c2724 814 } else {
c54ef5e4
JS
815 diffcore_std(&diffopt);
816 diff_flush(&diffopt);
817 }
818 free(paths);
c54ef5e4
JS
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
831finish_revert:
832 putchar('\n');
833 return res;
834}
835
ab1e1ccc
JS
836static 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
866static 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
913finish_add_untracked:
914 putchar('\n');
915 return res;
916}
917
8746e072
JS
918static 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);
d660a30c 960 if (count > 0) {
ef8d7ac4 961 struct strvec args = STRVEC_INIT;
1942ee44 962 struct pathspec ps_selected = { 0 };
8746e072 963
8746e072
JS
964 for (i = 0; i < files->items.nr; i++)
965 if (files->selected[i])
ef8d7ac4 966 strvec_push(&args,
f6d8942b 967 files->items.items[i].string);
1942ee44
JS
968 parse_pathspec(&ps_selected,
969 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
d70a9eb6 970 PATHSPEC_LITERAL_PATH, "", args.v);
d2a233cb 971 res = run_add_p(s->r, ADD_P_ADD, NULL, &ps_selected);
ef8d7ac4 972 strvec_clear(&args);
1942ee44 973 clear_pathspec(&ps_selected);
8746e072
JS
974 }
975
976 return res;
977}
978
d7633578
JS
979static 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;
d660a30c 1001 if (count > 0) {
0e906739 1002 struct child_process cmd = CHILD_PROCESS_INIT;
d7633578 1003
0e906739 1004 strvec_pushl(&cmd.args, "git", "diff", "-p", "--cached",
f6d8942b
JK
1005 oid_to_hex(!is_initial ? &oid :
1006 s->r->hash_algo->empty_tree),
1007 "--", NULL);
d7633578
JS
1008 for (i = 0; i < files->items.nr; i++)
1009 if (files->selected[i])
0e906739 1010 strvec_push(&cmd.args,
f6d8942b 1011 files->items.items[i].string);
0e906739 1012 res = run_command(&cmd);
d7633578
JS
1013 }
1014
1015 putchar('\n');
1016 return res;
1017}
1018
8c159044 1019static int run_help(struct add_i_state *s, const struct pathspec *unused_ps,
a8c45be9
JS
1020 struct prefix_item_list *unused_files,
1021 struct list_and_choose_options *unused_opts)
8c159044
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
a8c45be9
JS
1039static 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
6348bfba 1059typedef int (*command_t)(struct add_i_state *s, const struct pathspec *ps,
a8c45be9
JS
1060 struct prefix_item_list *files,
1061 struct list_and_choose_options *opts);
6348bfba 1062
76b74323
JS
1063struct command_item {
1064 size_t prefix_length;
1065 command_t command;
1066};
1067
3d965c76
1068struct print_command_item_data {
1069 const char *color, *reset;
1070};
1071
f37c2264
JS
1072static void print_command_item(int i, int selected,
1073 struct string_list_item *item,
6348bfba
JS
1074 void *print_command_item_data)
1075{
3d965c76 1076 struct print_command_item_data *d = print_command_item_data;
76b74323
JS
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
3d965c76
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);
6348bfba
JS
1086}
1087
68db1cbf
JS
1088static 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
f83dff60
JS
1100int run_add_i(struct repository *r, const struct pathspec *ps)
1101{
5e82b9e4 1102 struct add_i_state s = { NULL };
3d965c76 1103 struct print_command_item_data data = { "[", "]" };
6348bfba 1104 struct list_and_choose_options main_loop_opts = {
3d965c76 1105 { 4, N_("*** Commands ***"), print_command_item, &data },
f37c2264 1106 N_("What now"), SINGLETON | IMMEDIATE, command_prompt_help
6348bfba
JS
1107 };
1108 struct {
1109 const char *string;
1110 command_t command;
1111 } command_list[] = {
1112 { "status", run_status },
a8c45be9 1113 { "update", run_update },
c54ef5e4 1114 { "revert", run_revert },
ab1e1ccc 1115 { "add untracked", run_add_untracked },
8746e072 1116 { "patch", run_patch },
d7633578 1117 { "diff", run_diff },
2e697ced 1118 { "quit", NULL },
8c159044 1119 { "help", run_help },
6348bfba 1120 };
76b74323 1121 struct prefix_item_list commands = PREFIX_ITEM_LIST_INIT;
6348bfba 1122
5e82b9e4 1123 struct print_file_item_data print_file_item_data = {
a8c45be9
JS
1124 "%12s %12s %s", NULL, NULL,
1125 STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
5e82b9e4 1126 };
a8c45be9
JS
1127 struct list_and_choose_options opts = {
1128 { 0, NULL, print_file_item, &print_file_item_data },
1129 NULL, 0, choose_prompt_help
5e82b9e4
DF
1130 };
1131 struct strbuf header = STRBUF_INIT;
a8c45be9 1132 struct prefix_item_list files = PREFIX_ITEM_LIST_INIT;
6348bfba 1133 ssize_t i;
5e82b9e4
DF
1134 int res = 0;
1135
76b74323 1136 for (i = 0; i < ARRAY_SIZE(command_list); i++) {
241b5d3e 1137 struct command_item *util = xcalloc(1, sizeof(*util));
76b74323
JS
1138 util->command = command_list[i].command;
1139 string_list_append(&commands.items, command_list[i].string)
1140 ->util = util;
1141 }
6348bfba 1142
5e82b9e4 1143 init_add_i_state(&s, r);
6348bfba 1144
3d965c76
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 }
a8c45be9
JS
1153 print_file_item_data.color = data.color;
1154 print_file_item_data.reset = data.reset;
3d965c76 1155
afae3cb6 1156 strbuf_addstr(&header, " ");
5e82b9e4
DF
1157 strbuf_addf(&header, print_file_item_data.modified_fmt,
1158 _("staged"), _("unstaged"), _("path"));
a8c45be9 1159 opts.list_opts.header = header.buf;
5e82b9e4 1160
9c5f3ee3
ÆAB
1161 discard_index(r->index);
1162 if (repo_read_index(r) < 0 ||
5e82b9e4
DF
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
6348bfba 1169 for (;;) {
2e697ced
JS
1170 struct command_item *util;
1171
6348bfba 1172 i = list_and_choose(&s, &commands, &main_loop_opts);
2e697ced
JS
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)) {
6348bfba
JS
1179 printf(_("Bye.\n"));
1180 res = 0;
1181 break;
1182 }
2e697ced
JS
1183
1184 if (util)
76b74323 1185 res = util->command(&s, ps, &files, &opts);
6348bfba
JS
1186 }
1187
a8c45be9 1188 prefix_item_list_clear(&files);
5e82b9e4 1189 strbuf_release(&print_file_item_data.buf);
a8c45be9 1190 strbuf_release(&print_file_item_data.name);
5e82b9e4
DF
1191 strbuf_release(&print_file_item_data.index);
1192 strbuf_release(&print_file_item_data.worktree);
1193 strbuf_release(&header);
76b74323 1194 prefix_item_list_clear(&commands);
180f48df 1195 clear_add_i_state(&s);
5e82b9e4
DF
1196
1197 return res;
f83dff60 1198}