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