git
/
merge-recursive.c
4079 строк · 121.7 Кб
1/*
2* Recursive Merge algorithm stolen from git-merge-recursive.py by
3* Fredrik Kuivinen.
4* The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
5*/
6
7#define USE_THE_REPOSITORY_VARIABLE8
9#include "git-compat-util.h"10#include "merge-recursive.h"11
12#include "alloc.h"13#include "cache-tree.h"14#include "commit.h"15#include "commit-reach.h"16#include "config.h"17#include "diff.h"18#include "diffcore.h"19#include "dir.h"20#include "environment.h"21#include "gettext.h"22#include "hex.h"23#include "merge-ll.h"24#include "lockfile.h"25#include "match-trees.h"26#include "name-hash.h"27#include "object-file.h"28#include "object-name.h"29#include "object-store-ll.h"30#include "path.h"31#include "repository.h"32#include "revision.h"33#include "sparse-index.h"34#include "string-list.h"35#include "symlinks.h"36#include "tag.h"37#include "tree-walk.h"38#include "unpack-trees.h"39#include "xdiff-interface.h"40
41struct merge_options_internal {42int call_depth;43int needed_rename_limit;44struct hashmap current_file_dir_set;45struct string_list df_conflict_file_set;46struct unpack_trees_options unpack_opts;47struct index_state orig_index;48};49
50struct path_hashmap_entry {51struct hashmap_entry e;52char path[FLEX_ARRAY];53};54
55static int path_hashmap_cmp(const void *cmp_data UNUSED,56const struct hashmap_entry *eptr,57const struct hashmap_entry *entry_or_key,58const void *keydata)59{
60const struct path_hashmap_entry *a, *b;61const char *key = keydata;62
63a = container_of(eptr, const struct path_hashmap_entry, e);64b = container_of(entry_or_key, const struct path_hashmap_entry, e);65
66return fspathcmp(a->path, key ? key : b->path);67}
68
69/*
70* For dir_rename_entry, directory names are stored as a full path from the
71* toplevel of the repository and do not include a trailing '/'. Also:
72*
73* dir: original name of directory being renamed
74* non_unique_new_dir: if true, could not determine new_dir
75* new_dir: final name of directory being renamed
76* possible_new_dirs: temporary used to help determine new_dir; see comments
77* in get_directory_renames() for details
78*/
79struct dir_rename_entry {80struct hashmap_entry ent;81char *dir;82unsigned non_unique_new_dir:1;83struct strbuf new_dir;84struct string_list possible_new_dirs;85};86
87static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap,88char *dir)89{
90struct dir_rename_entry key;91
92if (!dir)93return NULL;94hashmap_entry_init(&key.ent, strhash(dir));95key.dir = dir;96return hashmap_get_entry(hashmap, &key, ent, NULL);97}
98
99static int dir_rename_cmp(const void *cmp_data UNUSED,100const struct hashmap_entry *eptr,101const struct hashmap_entry *entry_or_key,102const void *keydata UNUSED)103{
104const struct dir_rename_entry *e1, *e2;105
106e1 = container_of(eptr, const struct dir_rename_entry, ent);107e2 = container_of(entry_or_key, const struct dir_rename_entry, ent);108
109return strcmp(e1->dir, e2->dir);110}
111
112static void dir_rename_init(struct hashmap *map)113{
114hashmap_init(map, dir_rename_cmp, NULL, 0);115}
116
117static void dir_rename_entry_init(struct dir_rename_entry *entry,118char *directory)119{
120hashmap_entry_init(&entry->ent, strhash(directory));121entry->dir = directory;122entry->non_unique_new_dir = 0;123strbuf_init(&entry->new_dir, 0);124string_list_init_nodup(&entry->possible_new_dirs);125}
126
127struct collision_entry {128struct hashmap_entry ent;129char *target_file;130struct string_list source_files;131unsigned reported_already:1;132};133
134static struct collision_entry *collision_find_entry(struct hashmap *hashmap,135char *target_file)136{
137struct collision_entry key;138
139hashmap_entry_init(&key.ent, strhash(target_file));140key.target_file = target_file;141return hashmap_get_entry(hashmap, &key, ent, NULL);142}
143
144static int collision_cmp(const void *cmp_data UNUSED,145const struct hashmap_entry *eptr,146const struct hashmap_entry *entry_or_key,147const void *keydata UNUSED)148{
149const struct collision_entry *e1, *e2;150
151e1 = container_of(eptr, const struct collision_entry, ent);152e2 = container_of(entry_or_key, const struct collision_entry, ent);153
154return strcmp(e1->target_file, e2->target_file);155}
156
157static void collision_init(struct hashmap *map)158{
159hashmap_init(map, collision_cmp, NULL, 0);160}
161
162static void flush_output(struct merge_options *opt)163{
164if (opt->buffer_output < 2 && opt->obuf.len) {165fputs(opt->obuf.buf, stdout);166strbuf_reset(&opt->obuf);167}168}
169
170__attribute__((format (printf, 2, 3)))171static int err(struct merge_options *opt, const char *err, ...)172{
173va_list params;174
175if (opt->buffer_output < 2)176flush_output(opt);177else {178strbuf_complete(&opt->obuf, '\n');179strbuf_addstr(&opt->obuf, "error: ");180}181va_start(params, err);182strbuf_vaddf(&opt->obuf, err, params);183va_end(params);184if (opt->buffer_output > 1)185strbuf_addch(&opt->obuf, '\n');186else {187error("%s", opt->obuf.buf);188strbuf_reset(&opt->obuf);189}190
191return -1;192}
193
194static struct tree *shift_tree_object(struct repository *repo,195struct tree *one, struct tree *two,196const char *subtree_shift)197{
198struct object_id shifted;199
200if (!*subtree_shift) {201shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);202} else {203shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,204subtree_shift);205}206if (oideq(&two->object.oid, &shifted))207return two;208return lookup_tree(repo, &shifted);209}
210
211static inline void set_commit_tree(struct commit *c, struct tree *t)212{
213c->maybe_tree = t;214}
215
216static struct commit *make_virtual_commit(struct repository *repo,217struct tree *tree,218const char *comment)219{
220struct commit *commit = alloc_commit_node(repo);221
222set_merge_remote_desc(commit, comment, (struct object *)commit);223set_commit_tree(commit, tree);224commit->object.parsed = 1;225return commit;226}
227
228enum rename_type {229RENAME_NORMAL = 0,230RENAME_VIA_DIR,231RENAME_ADD,232RENAME_DELETE,233RENAME_ONE_FILE_TO_ONE,234RENAME_ONE_FILE_TO_TWO,235RENAME_TWO_FILES_TO_ONE
236};237
238/*
239* Since we want to write the index eventually, we cannot reuse the index
240* for these (temporary) data.
241*/
242struct stage_data {243struct diff_filespec stages[4]; /* mostly for oid & mode; maybe path */244struct rename_conflict_info *rename_conflict_info;245unsigned processed:1,246rename_conflict_info_owned:1;247};248
249struct rename {250unsigned processed:1;251struct diff_filepair *pair;252const char *branch; /* branch that the rename occurred on */253/*254* If directory rename detection affected this rename, what was its
255* original type ('A' or 'R') and it's original destination before
256* the directory rename (otherwise, '\0' and NULL for these two vars).
257*/
258char dir_rename_original_type;259char *dir_rename_original_dest;260/*261* Purpose of src_entry and dst_entry:
262*
263* If 'before' is renamed to 'after' then src_entry will contain
264* the versions of 'before' from the merge_base, HEAD, and MERGE in
265* stages 1, 2, and 3; dst_entry will contain the respective
266* versions of 'after' in corresponding locations. Thus, we have a
267* total of six modes and oids, though some will be null. (Stage 0
268* is ignored; we're interested in handling conflicts.)
269*
270* Since we don't turn on break-rewrites by default, neither
271* src_entry nor dst_entry can have all three of their stages have
272* non-null oids, meaning at most four of the six will be non-null.
273* Also, since this is a rename, both src_entry and dst_entry will
274* have at least one non-null oid, meaning at least two will be
275* non-null. Of the six oids, a typical rename will have three be
276* non-null. Only two implies a rename/delete, and four implies a
277* rename/add.
278*/
279struct stage_data *src_entry;280struct stage_data *dst_entry;281};282
283struct rename_conflict_info {284enum rename_type rename_type;285struct rename *ren1;286struct rename *ren2;287};288
289static inline void setup_rename_conflict_info(enum rename_type rename_type,290struct merge_options *opt,291struct rename *ren1,292struct rename *ren2)293{
294struct rename_conflict_info *ci;295
296/*297* When we have two renames involved, it's easiest to get the
298* correct things into stage 2 and 3, and to make sure that the
299* content merge puts HEAD before the other branch if we just
300* ensure that branch1 == opt->branch1. So, simply flip arguments
301* around if we don't have that.
302*/
303if (ren2 && ren1->branch != opt->branch1) {304setup_rename_conflict_info(rename_type, opt, ren2, ren1);305return;306}307
308CALLOC_ARRAY(ci, 1);309ci->rename_type = rename_type;310ci->ren1 = ren1;311ci->ren2 = ren2;312
313ci->ren1->dst_entry->processed = 0;314ci->ren1->dst_entry->rename_conflict_info = ci;315ci->ren1->dst_entry->rename_conflict_info_owned = 1;316if (ren2) {317ci->ren2->dst_entry->rename_conflict_info = ci;318}319}
320
321static int show(struct merge_options *opt, int v)322{
323return (!opt->priv->call_depth && opt->verbosity >= v) ||324opt->verbosity >= 5;325}
326
327__attribute__((format (printf, 3, 4)))328static void output(struct merge_options *opt, int v, const char *fmt, ...)329{
330va_list ap;331
332if (!show(opt, v))333return;334
335strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);336
337va_start(ap, fmt);338strbuf_vaddf(&opt->obuf, fmt, ap);339va_end(ap);340
341strbuf_addch(&opt->obuf, '\n');342if (!opt->buffer_output)343flush_output(opt);344}
345
346static void repo_output_commit_title(struct merge_options *opt,347struct repository *repo,348struct commit *commit)349{
350struct merge_remote_desc *desc;351
352strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);353desc = merge_remote_util(commit);354if (desc)355strbuf_addf(&opt->obuf, "virtual %s\n", desc->name);356else {357strbuf_repo_add_unique_abbrev(&opt->obuf, repo,358&commit->object.oid,359DEFAULT_ABBREV);360strbuf_addch(&opt->obuf, ' ');361if (repo_parse_commit(repo, commit) != 0)362strbuf_addstr(&opt->obuf, _("(bad commit)\n"));363else {364const char *title;365const char *msg = repo_get_commit_buffer(repo, commit, NULL);366int len = find_commit_subject(msg, &title);367if (len)368strbuf_addf(&opt->obuf, "%.*s\n", len, title);369repo_unuse_commit_buffer(repo, commit, msg);370}371}372flush_output(opt);373}
374
375static void output_commit_title(struct merge_options *opt, struct commit *commit)376{
377repo_output_commit_title(opt, the_repository, commit);378}
379
380static int add_cacheinfo(struct merge_options *opt,381const struct diff_filespec *blob,382const char *path, int stage, int refresh, int options)383{
384struct index_state *istate = opt->repo->index;385struct cache_entry *ce;386int ret;387
388ce = make_cache_entry(istate, blob->mode, &blob->oid, path, stage, 0);389if (!ce)390return err(opt, _("add_cacheinfo failed for path '%s'; merge aborting."), path);391
392ret = add_index_entry(istate, ce, options);393if (refresh) {394struct cache_entry *nce;395
396nce = refresh_cache_entry(istate, ce,397CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);398if (!nce)399return err(opt, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);400if (nce != ce)401ret = add_index_entry(istate, nce, options);402}403return ret;404}
405
406static inline int merge_detect_rename(struct merge_options *opt)407{
408return (opt->detect_renames >= 0) ? opt->detect_renames : 1;409}
410
411static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)412{
413if (parse_tree(tree) < 0)414exit(128);415init_tree_desc(desc, &tree->object.oid, tree->buffer, tree->size);416}
417
418static int unpack_trees_start(struct merge_options *opt,419struct tree *common,420struct tree *head,421struct tree *merge)422{
423int rc;424struct tree_desc t[3];425struct index_state tmp_index = INDEX_STATE_INIT(opt->repo);426
427memset(&opt->priv->unpack_opts, 0, sizeof(opt->priv->unpack_opts));428if (opt->priv->call_depth)429opt->priv->unpack_opts.index_only = 1;430else {431opt->priv->unpack_opts.update = 1;432/* FIXME: should only do this if !overwrite_ignore */433opt->priv->unpack_opts.preserve_ignored = 0;434}435opt->priv->unpack_opts.merge = 1;436opt->priv->unpack_opts.head_idx = 2;437opt->priv->unpack_opts.fn = threeway_merge;438opt->priv->unpack_opts.src_index = opt->repo->index;439opt->priv->unpack_opts.dst_index = &tmp_index;440opt->priv->unpack_opts.aggressive = !merge_detect_rename(opt);441setup_unpack_trees_porcelain(&opt->priv->unpack_opts, "merge");442
443init_tree_desc_from_tree(t+0, common);444init_tree_desc_from_tree(t+1, head);445init_tree_desc_from_tree(t+2, merge);446
447rc = unpack_trees(3, t, &opt->priv->unpack_opts);448cache_tree_free(&opt->repo->index->cache_tree);449
450/*451* Update opt->repo->index to match the new results, AFTER saving a
452* copy in opt->priv->orig_index. Update src_index to point to the
453* saved copy. (verify_uptodate() checks src_index, and the original
454* index is the one that had the necessary modification timestamps.)
455*/
456opt->priv->orig_index = *opt->repo->index;457*opt->repo->index = tmp_index;458opt->priv->unpack_opts.src_index = &opt->priv->orig_index;459
460return rc;461}
462
463static void unpack_trees_finish(struct merge_options *opt)464{
465discard_index(&opt->priv->orig_index);466clear_unpack_trees_porcelain(&opt->priv->unpack_opts);467}
468
469static int save_files_dirs(const struct object_id *oid UNUSED,470struct strbuf *base, const char *path,471unsigned int mode, void *context)472{
473struct path_hashmap_entry *entry;474int baselen = base->len;475struct merge_options *opt = context;476
477strbuf_addstr(base, path);478
479FLEX_ALLOC_MEM(entry, path, base->buf, base->len);480hashmap_entry_init(&entry->e, fspathhash(entry->path));481hashmap_add(&opt->priv->current_file_dir_set, &entry->e);482
483strbuf_setlen(base, baselen);484return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);485}
486
487static void get_files_dirs(struct merge_options *opt, struct tree *tree)488{
489struct pathspec match_all;490memset(&match_all, 0, sizeof(match_all));491read_tree(opt->repo, tree,492&match_all, save_files_dirs, opt);493}
494
495static int get_tree_entry_if_blob(struct repository *r,496const struct object_id *tree,497const char *path,498struct diff_filespec *dfs)499{
500int ret;501
502ret = get_tree_entry(r, tree, path, &dfs->oid, &dfs->mode);503if (S_ISDIR(dfs->mode)) {504oidcpy(&dfs->oid, null_oid());505dfs->mode = 0;506}507return ret;508}
509
510/*
511* Returns an index_entry instance which doesn't have to correspond to
512* a real cache entry in Git's index.
513*/
514static struct stage_data *insert_stage_data(struct repository *r,515const char *path,516struct tree *o, struct tree *a, struct tree *b,517struct string_list *entries)518{
519struct string_list_item *item;520struct stage_data *e = xcalloc(1, sizeof(struct stage_data));521get_tree_entry_if_blob(r, &o->object.oid, path, &e->stages[1]);522get_tree_entry_if_blob(r, &a->object.oid, path, &e->stages[2]);523get_tree_entry_if_blob(r, &b->object.oid, path, &e->stages[3]);524item = string_list_insert(entries, path);525item->util = e;526return e;527}
528
529/*
530* Create a dictionary mapping file names to stage_data objects. The
531* dictionary contains one entry for every path with a non-zero stage entry.
532*/
533static struct string_list *get_unmerged(struct index_state *istate)534{
535struct string_list *unmerged = xmalloc(sizeof(struct string_list));536int i;537
538string_list_init_dup(unmerged);539
540/* TODO: audit for interaction with sparse-index. */541ensure_full_index(istate);542for (i = 0; i < istate->cache_nr; i++) {543struct string_list_item *item;544struct stage_data *e;545const struct cache_entry *ce = istate->cache[i];546if (!ce_stage(ce))547continue;548
549item = string_list_lookup(unmerged, ce->name);550if (!item) {551item = string_list_insert(unmerged, ce->name);552item->util = xcalloc(1, sizeof(struct stage_data));553}554e = item->util;555e->stages[ce_stage(ce)].mode = ce->ce_mode;556oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);557}558
559return unmerged;560}
561
562static int string_list_df_name_compare(const char *one, const char *two)563{
564int onelen = strlen(one);565int twolen = strlen(two);566/*567* Here we only care that entries for D/F conflicts are
568* adjacent, in particular with the file of the D/F conflict
569* appearing before files below the corresponding directory.
570* The order of the rest of the list is irrelevant for us.
571*
572* To achieve this, we sort with df_name_compare and provide
573* the mode S_IFDIR so that D/F conflicts will sort correctly.
574* We use the mode S_IFDIR for everything else for simplicity,
575* since in other cases any changes in their order due to
576* sorting cause no problems for us.
577*/
578int cmp = df_name_compare(one, onelen, S_IFDIR,579two, twolen, S_IFDIR);580/*581* Now that 'foo' and 'foo/bar' compare equal, we have to make sure
582* that 'foo' comes before 'foo/bar'.
583*/
584if (cmp)585return cmp;586return onelen - twolen;587}
588
589static void record_df_conflict_files(struct merge_options *opt,590struct string_list *entries)591{
592/* If there is a D/F conflict and the file for such a conflict593* currently exists in the working tree, we want to allow it to be
594* removed to make room for the corresponding directory if needed.
595* The files underneath the directories of such D/F conflicts will
596* be processed before the corresponding file involved in the D/F
597* conflict. If the D/F directory ends up being removed by the
598* merge, then we won't have to touch the D/F file. If the D/F
599* directory needs to be written to the working copy, then the D/F
600* file will simply be removed (in make_room_for_path()) to make
601* room for the necessary paths. Note that if both the directory
602* and the file need to be present, then the D/F file will be
603* reinstated with a new unique name at the time it is processed.
604*/
605struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;606const char *last_file = NULL;607int last_len = 0;608int i;609
610/*611* If we're merging merge-bases, we don't want to bother with
612* any working directory changes.
613*/
614if (opt->priv->call_depth)615return;616
617/* Ensure D/F conflicts are adjacent in the entries list. */618for (i = 0; i < entries->nr; i++) {619struct string_list_item *next = &entries->items[i];620string_list_append(&df_sorted_entries, next->string)->util =621next->util;622}623df_sorted_entries.cmp = string_list_df_name_compare;624string_list_sort(&df_sorted_entries);625
626string_list_clear(&opt->priv->df_conflict_file_set, 1);627for (i = 0; i < df_sorted_entries.nr; i++) {628const char *path = df_sorted_entries.items[i].string;629int len = strlen(path);630struct stage_data *e = df_sorted_entries.items[i].util;631
632/*633* Check if last_file & path correspond to a D/F conflict;
634* i.e. whether path is last_file+'/'+<something>.
635* If so, record that it's okay to remove last_file to make
636* room for path and friends if needed.
637*/
638if (last_file &&639len > last_len &&640memcmp(path, last_file, last_len) == 0 &&641path[last_len] == '/') {642string_list_insert(&opt->priv->df_conflict_file_set, last_file);643}644
645/*646* Determine whether path could exist as a file in the
647* working directory as a possible D/F conflict. This
648* will only occur when it exists in stage 2 as a
649* file.
650*/
651if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {652last_file = path;653last_len = len;654} else {655last_file = NULL;656}657}658string_list_clear(&df_sorted_entries, 0);659}
660
661static int update_stages(struct merge_options *opt, const char *path,662const struct diff_filespec *o,663const struct diff_filespec *a,664const struct diff_filespec *b)665{
666
667/*668* NOTE: It is usually a bad idea to call update_stages on a path
669* before calling update_file on that same path, since it can
670* sometimes lead to spurious "refusing to lose untracked file..."
671* messages from update_file (via make_room_for path via
672* would_lose_untracked). Instead, reverse the order of the calls
673* (executing update_file first and then update_stages).
674*/
675int clear = 1;676int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;677if (clear)678if (remove_file_from_index(opt->repo->index, path))679return -1;680if (o)681if (add_cacheinfo(opt, o, path, 1, 0, options))682return -1;683if (a)684if (add_cacheinfo(opt, a, path, 2, 0, options))685return -1;686if (b)687if (add_cacheinfo(opt, b, path, 3, 0, options))688return -1;689return 0;690}
691
692static void update_entry(struct stage_data *entry,693struct diff_filespec *o,694struct diff_filespec *a,695struct diff_filespec *b)696{
697entry->processed = 0;698entry->stages[1].mode = o->mode;699entry->stages[2].mode = a->mode;700entry->stages[3].mode = b->mode;701oidcpy(&entry->stages[1].oid, &o->oid);702oidcpy(&entry->stages[2].oid, &a->oid);703oidcpy(&entry->stages[3].oid, &b->oid);704}
705
706static int remove_file(struct merge_options *opt, int clean,707const char *path, int no_wd)708{
709int update_cache = opt->priv->call_depth || clean;710int update_working_directory = !opt->priv->call_depth && !no_wd;711
712if (update_cache) {713if (remove_file_from_index(opt->repo->index, path))714return -1;715}716if (update_working_directory) {717if (ignore_case) {718struct cache_entry *ce;719ce = index_file_exists(opt->repo->index, path, strlen(path),720ignore_case);721if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))722return 0;723}724if (remove_path(path))725return -1;726}727return 0;728}
729
730/* add a string to a strbuf, but converting "/" to "_" */
731static void add_flattened_path(struct strbuf *out, const char *s)732{
733size_t i = out->len;734strbuf_addstr(out, s);735for (; i < out->len; i++)736if (out->buf[i] == '/')737out->buf[i] = '_';738}
739
740static char *unique_path(struct merge_options *opt,741const char *path,742const char *branch)743{
744struct path_hashmap_entry *entry;745struct strbuf newpath = STRBUF_INIT;746int suffix = 0;747size_t base_len;748
749strbuf_addf(&newpath, "%s~", path);750add_flattened_path(&newpath, branch);751
752base_len = newpath.len;753while (hashmap_get_from_hash(&opt->priv->current_file_dir_set,754fspathhash(newpath.buf), newpath.buf) ||755(!opt->priv->call_depth && file_exists(newpath.buf))) {756strbuf_setlen(&newpath, base_len);757strbuf_addf(&newpath, "_%d", suffix++);758}759
760FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);761hashmap_entry_init(&entry->e, fspathhash(entry->path));762hashmap_add(&opt->priv->current_file_dir_set, &entry->e);763return strbuf_detach(&newpath, NULL);764}
765
766/**
767* Check whether a directory in the index is in the way of an incoming
768* file. Return 1 if so. If check_working_copy is non-zero, also
769* check the working directory. If empty_ok is non-zero, also return
770* 0 in the case where the working-tree dir exists but is empty.
771*/
772static int dir_in_way(struct index_state *istate, const char *path,773int check_working_copy, int empty_ok)774{
775int pos;776struct strbuf dirpath = STRBUF_INIT;777struct stat st;778
779strbuf_addstr(&dirpath, path);780strbuf_addch(&dirpath, '/');781
782pos = index_name_pos(istate, dirpath.buf, dirpath.len);783
784if (pos < 0)785pos = -1 - pos;786if (pos < istate->cache_nr &&787!strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) {788strbuf_release(&dirpath);789return 1;790}791
792strbuf_release(&dirpath);793return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&794!(empty_ok && is_empty_dir(path)) &&795!has_symlink_leading_path(path, strlen(path));796}
797
798/*
799* Returns whether path was tracked in the index before the merge started,
800* and its oid and mode match the specified values
801*/
802static int was_tracked_and_matches(struct merge_options *opt, const char *path,803const struct diff_filespec *blob)804{
805int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));806struct cache_entry *ce;807
808if (0 > pos)809/* we were not tracking this path before the merge */810return 0;811
812/* See if the file we were tracking before matches */813ce = opt->priv->orig_index.cache[pos];814return (oideq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode);815}
816
817/*
818* Returns whether path was tracked in the index before the merge started
819*/
820static int was_tracked(struct merge_options *opt, const char *path)821{
822int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));823
824if (0 <= pos)825/* we were tracking this path before the merge */826return 1;827
828return 0;829}
830
831static int would_lose_untracked(struct merge_options *opt, const char *path)832{
833struct index_state *istate = opt->repo->index;834
835/*836* This may look like it can be simplified to:
837* return !was_tracked(opt, path) && file_exists(path)
838* but it can't. This function needs to know whether path was in
839* the working tree due to EITHER having been tracked in the index
840* before the merge OR having been put into the working copy and
841* index by unpack_trees(). Due to that either-or requirement, we
842* check the current index instead of the original one.
843*
844* Note that we do not need to worry about merge-recursive itself
845* updating the index after unpack_trees() and before calling this
846* function, because we strictly require all code paths in
847* merge-recursive to update the working tree first and the index
848* second. Doing otherwise would break
849* update_file()/would_lose_untracked(); see every comment in this
850* file which mentions "update_stages".
851*/
852int pos = index_name_pos(istate, path, strlen(path));853
854if (pos < 0)855pos = -1 - pos;856while (pos < istate->cache_nr &&857!strcmp(path, istate->cache[pos]->name)) {858/*859* If stage #0, it is definitely tracked.
860* If it has stage #2 then it was tracked
861* before this merge started. All other
862* cases the path was not tracked.
863*/
864switch (ce_stage(istate->cache[pos])) {865case 0:866case 2:867return 0;868}869pos++;870}871return file_exists(path);872}
873
874static int was_dirty(struct merge_options *opt, const char *path)875{
876struct cache_entry *ce;877int dirty = 1;878
879if (opt->priv->call_depth || !was_tracked(opt, path))880return !dirty;881
882ce = index_file_exists(opt->priv->unpack_opts.src_index,883path, strlen(path), ignore_case);884dirty = verify_uptodate(ce, &opt->priv->unpack_opts) != 0;885return dirty;886}
887
888static int make_room_for_path(struct merge_options *opt, const char *path)889{
890int status, i;891const char *msg = _("failed to create path '%s'%s");892
893/* Unlink any D/F conflict files that are in the way */894for (i = 0; i < opt->priv->df_conflict_file_set.nr; i++) {895const char *df_path = opt->priv->df_conflict_file_set.items[i].string;896size_t pathlen = strlen(path);897size_t df_pathlen = strlen(df_path);898if (df_pathlen < pathlen &&899path[df_pathlen] == '/' &&900strncmp(path, df_path, df_pathlen) == 0) {901output(opt, 3,902_("Removing %s to make room for subdirectory\n"),903df_path);904unlink(df_path);905unsorted_string_list_delete_item(&opt->priv->df_conflict_file_set,906i, 0);907break;908}909}910
911/* Make sure leading directories are created */912status = safe_create_leading_directories_const(path);913if (status) {914if (status == SCLD_EXISTS)915/* something else exists */916return err(opt, msg, path, _(": perhaps a D/F conflict?"));917return err(opt, msg, path, "");918}919
920/*921* Do not unlink a file in the work tree if we are not
922* tracking it.
923*/
924if (would_lose_untracked(opt, path))925return err(opt, _("refusing to lose untracked file at '%s'"),926path);927
928/* Successful unlink is good.. */929if (!unlink(path))930return 0;931/* .. and so is no existing file */932if (errno == ENOENT)933return 0;934/* .. but not some other error (who really cares what?) */935return err(opt, msg, path, _(": perhaps a D/F conflict?"));936}
937
938static int update_file_flags(struct merge_options *opt,939const struct diff_filespec *contents,940const char *path,941int update_cache,942int update_wd)943{
944int ret = 0;945
946if (opt->priv->call_depth)947update_wd = 0;948
949if (update_wd) {950enum object_type type;951void *buf;952unsigned long size;953
954if (S_ISGITLINK(contents->mode)) {955/*956* We may later decide to recursively descend into
957* the submodule directory and update its index
958* and/or work tree, but we do not do that now.
959*/
960update_wd = 0;961goto update_index;962}963
964buf = repo_read_object_file(the_repository, &contents->oid,965&type, &size);966if (!buf) {967ret = err(opt, _("cannot read object %s '%s'"),968oid_to_hex(&contents->oid), path);969goto free_buf;970}971if (type != OBJ_BLOB) {972ret = err(opt, _("blob expected for %s '%s'"),973oid_to_hex(&contents->oid), path);974goto free_buf;975}976if (S_ISREG(contents->mode)) {977struct strbuf strbuf = STRBUF_INIT;978if (convert_to_working_tree(opt->repo->index,979path, buf, size, &strbuf, NULL)) {980free(buf);981size = strbuf.len;982buf = strbuf_detach(&strbuf, NULL);983}984}985
986if (make_room_for_path(opt, path) < 0) {987update_wd = 0;988goto free_buf;989}990if (S_ISREG(contents->mode) ||991(!has_symlinks && S_ISLNK(contents->mode))) {992int fd;993int mode = (contents->mode & 0100 ? 0777 : 0666);994
995fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);996if (fd < 0) {997ret = err(opt, _("failed to open '%s': %s"),998path, strerror(errno));999goto free_buf;1000}1001write_in_full(fd, buf, size);1002close(fd);1003} else if (S_ISLNK(contents->mode)) {1004char *lnk = xmemdupz(buf, size);1005safe_create_leading_directories_const(path);1006unlink(path);1007if (symlink(lnk, path))1008ret = err(opt, _("failed to symlink '%s': %s"),1009path, strerror(errno));1010free(lnk);1011} else1012ret = err(opt,1013_("do not know what to do with %06o %s '%s'"),1014contents->mode, oid_to_hex(&contents->oid), path);1015free_buf:1016free(buf);1017}1018update_index:1019if (!ret && update_cache) {1020int refresh = (!opt->priv->call_depth &&1021contents->mode != S_IFGITLINK);1022if (add_cacheinfo(opt, contents, path, 0, refresh,1023ADD_CACHE_OK_TO_ADD))1024return -1;1025}1026return ret;1027}
1028
1029static int update_file(struct merge_options *opt,1030int clean,1031const struct diff_filespec *contents,1032const char *path)1033{
1034return update_file_flags(opt, contents, path,1035opt->priv->call_depth || clean, !opt->priv->call_depth);1036}
1037
1038/* Low level file merging, update and removal */
1039
1040struct merge_file_info {1041struct diff_filespec blob; /* mostly use oid & mode; sometimes path */1042unsigned clean:1,1043merge:1;1044};1045
1046static int merge_3way(struct merge_options *opt,1047mmbuffer_t *result_buf,1048const struct diff_filespec *o,1049const struct diff_filespec *a,1050const struct diff_filespec *b,1051const char *branch1,1052const char *branch2,1053const int extra_marker_size)1054{
1055mmfile_t orig, src1, src2;1056struct ll_merge_options ll_opts = LL_MERGE_OPTIONS_INIT;1057char *base, *name1, *name2;1058enum ll_merge_result merge_status;1059
1060ll_opts.renormalize = opt->renormalize;1061ll_opts.extra_marker_size = extra_marker_size;1062ll_opts.xdl_opts = opt->xdl_opts;1063ll_opts.conflict_style = opt->conflict_style;1064
1065if (opt->priv->call_depth) {1066ll_opts.virtual_ancestor = 1;1067ll_opts.variant = 0;1068} else {1069switch (opt->recursive_variant) {1070case MERGE_VARIANT_OURS:1071ll_opts.variant = XDL_MERGE_FAVOR_OURS;1072break;1073case MERGE_VARIANT_THEIRS:1074ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;1075break;1076default:1077ll_opts.variant = 0;1078break;1079}1080}1081
1082assert(a->path && b->path && o->path && opt->ancestor);1083if (strcmp(a->path, b->path) || strcmp(a->path, o->path) != 0) {1084base = mkpathdup("%s:%s", opt->ancestor, o->path);1085name1 = mkpathdup("%s:%s", branch1, a->path);1086name2 = mkpathdup("%s:%s", branch2, b->path);1087} else {1088base = mkpathdup("%s", opt->ancestor);1089name1 = mkpathdup("%s", branch1);1090name2 = mkpathdup("%s", branch2);1091}1092
1093read_mmblob(&orig, &o->oid);1094read_mmblob(&src1, &a->oid);1095read_mmblob(&src2, &b->oid);1096
1097/*1098* FIXME: Using a->path for normalization rules in ll_merge could be
1099* wrong if we renamed from a->path to b->path. We should use the
1100* target path for where the file will be written.
1101*/
1102merge_status = ll_merge(result_buf, a->path, &orig, base,1103&src1, name1, &src2, name2,1104opt->repo->index, &ll_opts);1105if (merge_status == LL_MERGE_BINARY_CONFLICT)1106warning("Cannot merge binary files: %s (%s vs. %s)",1107a->path, name1, name2);1108
1109free(base);1110free(name1);1111free(name2);1112free(orig.ptr);1113free(src1.ptr);1114free(src2.ptr);1115return merge_status;1116}
1117
1118static int find_first_merges(struct repository *repo,1119struct object_array *result, const char *path,1120struct commit *a, struct commit *b)1121{
1122int i, j;1123struct object_array merges = OBJECT_ARRAY_INIT;1124struct commit *commit;1125int contains_another;1126
1127char merged_revision[GIT_MAX_HEXSZ + 2];1128const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",1129"--all", merged_revision, NULL };1130struct rev_info revs;1131struct setup_revision_opt rev_opts;1132
1133memset(result, 0, sizeof(struct object_array));1134memset(&rev_opts, 0, sizeof(rev_opts));1135
1136/* get all revisions that merge commit a */1137xsnprintf(merged_revision, sizeof(merged_revision), "^%s",1138oid_to_hex(&a->object.oid));1139repo_init_revisions(repo, &revs, NULL);1140/* FIXME: can't handle linked worktrees in submodules yet */1141revs.single_worktree = path != NULL;1142setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);1143
1144/* save all revisions from the above list that contain b */1145if (prepare_revision_walk(&revs))1146die("revision walk setup failed");1147while ((commit = get_revision(&revs)) != NULL) {1148struct object *o = &(commit->object);1149int ret = repo_in_merge_bases(repo, b, commit);1150if (ret < 0) {1151object_array_clear(&merges);1152release_revisions(&revs);1153return ret;1154}1155if (ret)1156add_object_array(o, NULL, &merges);1157}1158reset_revision_walk();1159
1160/* Now we've got all merges that contain a and b. Prune all1161* merges that contain another found merge and save them in
1162* result.
1163*/
1164for (i = 0; i < merges.nr; i++) {1165struct commit *m1 = (struct commit *) merges.objects[i].item;1166
1167contains_another = 0;1168for (j = 0; j < merges.nr; j++) {1169struct commit *m2 = (struct commit *) merges.objects[j].item;1170if (i != j) {1171int ret = repo_in_merge_bases(repo, m2, m1);1172if (ret < 0) {1173object_array_clear(&merges);1174release_revisions(&revs);1175return ret;1176}1177if (ret > 0) {1178contains_another = 1;1179break;1180}1181}1182}1183
1184if (!contains_another)1185add_object_array(merges.objects[i].item, NULL, result);1186}1187
1188object_array_clear(&merges);1189release_revisions(&revs);1190return result->nr;1191}
1192
1193static void print_commit(struct repository *repo, struct commit *commit)1194{
1195struct strbuf sb = STRBUF_INIT;1196struct pretty_print_context ctx = {0};1197ctx.date_mode.type = DATE_NORMAL;1198/* FIXME: Merge this with output_commit_title() */1199assert(!merge_remote_util(commit));1200repo_format_commit_message(repo, commit, " %h: %m %s", &sb, &ctx);1201fprintf(stderr, "%s\n", sb.buf);1202strbuf_release(&sb);1203}
1204
1205static int is_valid(const struct diff_filespec *dfs)1206{
1207return dfs->mode != 0 && !is_null_oid(&dfs->oid);1208}
1209
1210static int merge_submodule(struct merge_options *opt,1211struct object_id *result, const char *path,1212const struct object_id *base, const struct object_id *a,1213const struct object_id *b)1214{
1215struct repository subrepo;1216int ret = 0, ret2;1217struct commit *commit_base, *commit_a, *commit_b;1218int parent_count;1219struct object_array merges;1220
1221int i;1222int search = !opt->priv->call_depth;1223
1224/* store a in result in case we fail */1225/* FIXME: This is the WRONG resolution for the recursive case when1226* we need to be careful to avoid accidentally matching either side.
1227* Should probably use o instead there, much like we do for merging
1228* binaries.
1229*/
1230oidcpy(result, a);1231
1232/* we can not handle deletion conflicts */1233if (is_null_oid(base))1234return 0;1235if (is_null_oid(a))1236return 0;1237if (is_null_oid(b))1238return 0;1239
1240if (repo_submodule_init(&subrepo, opt->repo, path, null_oid())) {1241output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);1242return 0;1243}1244
1245if (!(commit_base = lookup_commit_reference(&subrepo, base)) ||1246!(commit_a = lookup_commit_reference(&subrepo, a)) ||1247!(commit_b = lookup_commit_reference(&subrepo, b))) {1248output(opt, 1, _("Failed to merge submodule %s (commits not present)"), path);1249goto cleanup;1250}1251
1252/* check whether both changes are forward */1253ret2 = repo_in_merge_bases(&subrepo, commit_base, commit_a);1254if (ret2 < 0) {1255output(opt, 1, _("Failed to merge submodule %s (repository corrupt)"), path);1256ret = -1;1257goto cleanup;1258}1259if (ret2 > 0)1260ret2 = repo_in_merge_bases(&subrepo, commit_base, commit_b);1261if (ret2 < 0) {1262output(opt, 1, _("Failed to merge submodule %s (repository corrupt)"), path);1263ret = -1;1264goto cleanup;1265}1266if (!ret2) {1267output(opt, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);1268goto cleanup;1269}1270
1271/* Case #1: a is contained in b or vice versa */1272ret2 = repo_in_merge_bases(&subrepo, commit_a, commit_b);1273if (ret2 < 0) {1274output(opt, 1, _("Failed to merge submodule %s (repository corrupt)"), path);1275ret = -1;1276goto cleanup;1277}1278if (ret2) {1279oidcpy(result, b);1280if (show(opt, 3)) {1281output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);1282repo_output_commit_title(opt, &subrepo, commit_b);1283} else if (show(opt, 2))1284output(opt, 2, _("Fast-forwarding submodule %s"), path);1285else1286; /* no output */1287
1288ret = 1;1289goto cleanup;1290}1291ret2 = repo_in_merge_bases(&subrepo, commit_b, commit_a);1292if (ret2 < 0) {1293output(opt, 1, _("Failed to merge submodule %s (repository corrupt)"), path);1294ret = -1;1295goto cleanup;1296}1297if (ret2) {1298oidcpy(result, a);1299if (show(opt, 3)) {1300output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);1301repo_output_commit_title(opt, &subrepo, commit_a);1302} else if (show(opt, 2))1303output(opt, 2, _("Fast-forwarding submodule %s"), path);1304else1305; /* no output */1306
1307ret = 1;1308goto cleanup;1309}1310
1311/*1312* Case #2: There are one or more merges that contain a and b in
1313* the submodule. If there is only one, then present it as a
1314* suggestion to the user, but leave it marked unmerged so the
1315* user needs to confirm the resolution.
1316*/
1317
1318/* Skip the search if makes no sense to the calling context. */1319if (!search)1320goto cleanup;1321
1322/* find commit which merges them */1323parent_count = find_first_merges(&subrepo, &merges, path,1324commit_a, commit_b);1325switch (parent_count) {1326case -1:1327output(opt, 1,_("Failed to merge submodule %s (repository corrupt)"), path);1328ret = -1;1329break;1330case 0:1331output(opt, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);1332break;1333
1334case 1:1335output(opt, 1, _("Failed to merge submodule %s (not fast-forward)"), path);1336output(opt, 2, _("Found a possible merge resolution for the submodule:\n"));1337print_commit(&subrepo, (struct commit *) merges.objects[0].item);1338output(opt, 2, _(1339"If this is correct simply add it to the index "1340"for example\n"1341"by using:\n\n"1342" git update-index --cacheinfo 160000 %s \"%s\"\n\n"1343"which will accept this suggestion.\n"),1344oid_to_hex(&merges.objects[0].item->oid), path);1345break;1346
1347default:1348output(opt, 1, _("Failed to merge submodule %s (multiple merges found)"), path);1349for (i = 0; i < merges.nr; i++)1350print_commit(&subrepo, (struct commit *) merges.objects[i].item);1351}1352
1353object_array_clear(&merges);1354cleanup:1355repo_clear(&subrepo);1356return ret;1357}
1358
1359static int merge_mode_and_contents(struct merge_options *opt,1360const struct diff_filespec *o,1361const struct diff_filespec *a,1362const struct diff_filespec *b,1363const char *filename,1364const char *branch1,1365const char *branch2,1366const int extra_marker_size,1367struct merge_file_info *result)1368{
1369if (opt->branch1 != branch1) {1370/*1371* It's weird getting a reverse merge with HEAD on the bottom
1372* side of the conflict markers and the other branch on the
1373* top. Fix that.
1374*/
1375return merge_mode_and_contents(opt, o, b, a,1376filename,1377branch2, branch1,1378extra_marker_size, result);1379}1380
1381result->merge = 0;1382result->clean = 1;1383
1384if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1385result->clean = 0;1386/*1387* FIXME: This is a bad resolution for recursive case; for
1388* the recursive case we want something that is unlikely to
1389* accidentally match either side. Also, while it makes
1390* sense to prefer regular files over symlinks, it doesn't
1391* make sense to prefer regular files over submodules.
1392*/
1393if (S_ISREG(a->mode)) {1394result->blob.mode = a->mode;1395oidcpy(&result->blob.oid, &a->oid);1396} else {1397result->blob.mode = b->mode;1398oidcpy(&result->blob.oid, &b->oid);1399}1400} else {1401if (!oideq(&a->oid, &o->oid) && !oideq(&b->oid, &o->oid))1402result->merge = 1;1403
1404/*1405* Merge modes
1406*/
1407if (a->mode == b->mode || a->mode == o->mode)1408result->blob.mode = b->mode;1409else {1410result->blob.mode = a->mode;1411if (b->mode != o->mode) {1412result->clean = 0;1413result->merge = 1;1414}1415}1416
1417if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))1418oidcpy(&result->blob.oid, &b->oid);1419else if (oideq(&b->oid, &o->oid))1420oidcpy(&result->blob.oid, &a->oid);1421else if (S_ISREG(a->mode)) {1422mmbuffer_t result_buf;1423int ret = 0, merge_status;1424
1425merge_status = merge_3way(opt, &result_buf, o, a, b,1426branch1, branch2,1427extra_marker_size);1428
1429if ((merge_status < 0) || !result_buf.ptr)1430ret = err(opt, _("failed to execute internal merge"));1431
1432if (!ret &&1433write_object_file(result_buf.ptr, result_buf.size,1434OBJ_BLOB, &result->blob.oid))1435ret = err(opt, _("unable to add %s to database"),1436a->path);1437
1438free(result_buf.ptr);1439if (ret)1440return ret;1441/* FIXME: bug, what if modes didn't match? */1442result->clean = (merge_status == 0);1443} else if (S_ISGITLINK(a->mode)) {1444int clean = merge_submodule(opt, &result->blob.oid,1445o->path,1446&o->oid,1447&a->oid,1448&b->oid);1449if (clean < 0)1450return -1;1451result->clean = clean;1452} else if (S_ISLNK(a->mode)) {1453switch (opt->recursive_variant) {1454case MERGE_VARIANT_NORMAL:1455oidcpy(&result->blob.oid, &a->oid);1456if (!oideq(&a->oid, &b->oid))1457result->clean = 0;1458break;1459case MERGE_VARIANT_OURS:1460oidcpy(&result->blob.oid, &a->oid);1461break;1462case MERGE_VARIANT_THEIRS:1463oidcpy(&result->blob.oid, &b->oid);1464break;1465}1466} else1467BUG("unsupported object type in the tree");1468}1469
1470if (result->merge)1471output(opt, 2, _("Auto-merging %s"), filename);1472
1473return 0;1474}
1475
1476static int handle_rename_via_dir(struct merge_options *opt,1477struct rename_conflict_info *ci)1478{
1479/*1480* Handle file adds that need to be renamed due to directory rename
1481* detection. This differs from handle_rename_normal, because
1482* there is no content merge to do; just move the file into the
1483* desired final location.
1484*/
1485const struct rename *ren = ci->ren1;1486const struct diff_filespec *dest = ren->pair->two;1487char *file_path = dest->path;1488int mark_conflicted = (opt->detect_directory_renames ==1489MERGE_DIRECTORY_RENAMES_CONFLICT);1490assert(ren->dir_rename_original_dest);1491
1492if (!opt->priv->call_depth && would_lose_untracked(opt, dest->path)) {1493mark_conflicted = 1;1494file_path = unique_path(opt, dest->path, ren->branch);1495output(opt, 1, _("Error: Refusing to lose untracked file at %s; "1496"writing to %s instead."),1497dest->path, file_path);1498}1499
1500if (mark_conflicted) {1501/*1502* Write the file in worktree at file_path. In the index,
1503* only record the file at dest->path in the appropriate
1504* higher stage.
1505*/
1506if (update_file(opt, 0, dest, file_path))1507return -1;1508if (file_path != dest->path)1509free(file_path);1510if (update_stages(opt, dest->path, NULL,1511ren->branch == opt->branch1 ? dest : NULL,1512ren->branch == opt->branch1 ? NULL : dest))1513return -1;1514return 0; /* not clean, but conflicted */1515} else {1516/* Update dest->path both in index and in worktree */1517if (update_file(opt, 1, dest, dest->path))1518return -1;1519return 1; /* clean */1520}1521}
1522
1523static int handle_change_delete(struct merge_options *opt,1524const char *path, const char *old_path,1525const struct diff_filespec *o,1526const struct diff_filespec *changed,1527const char *change_branch,1528const char *delete_branch,1529const char *change, const char *change_past)1530{
1531char *alt_path = NULL;1532const char *update_path = path;1533int ret = 0;1534
1535if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0) ||1536(!opt->priv->call_depth && would_lose_untracked(opt, path))) {1537update_path = alt_path = unique_path(opt, path, change_branch);1538}1539
1540if (opt->priv->call_depth) {1541/*1542* We cannot arbitrarily accept either a_sha or b_sha as
1543* correct; since there is no true "middle point" between
1544* them, simply reuse the base version for virtual merge base.
1545*/
1546ret = remove_file_from_index(opt->repo->index, path);1547if (!ret)1548ret = update_file(opt, 0, o, update_path);1549} else {1550/*1551* Despite the four nearly duplicate messages and argument
1552* lists below and the ugliness of the nested if-statements,
1553* having complete messages makes the job easier for
1554* translators.
1555*
1556* The slight variance among the cases is due to the fact
1557* that:
1558* 1) directory/file conflicts (in effect if
1559* !alt_path) could cause us to need to write the
1560* file to a different path.
1561* 2) renames (in effect if !old_path) could mean that
1562* there are two names for the path that the user
1563* may know the file by.
1564*/
1565if (!alt_path) {1566if (!old_path) {1567output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "1568"and %s in %s. Version %s of %s left in tree."),1569change, path, delete_branch, change_past,1570change_branch, change_branch, path);1571} else {1572output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "1573"and %s to %s in %s. Version %s of %s left in tree."),1574change, old_path, delete_branch, change_past, path,1575change_branch, change_branch, path);1576}1577} else {1578if (!old_path) {1579output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "1580"and %s in %s. Version %s of %s left in tree at %s."),1581change, path, delete_branch, change_past,1582change_branch, change_branch, path, alt_path);1583} else {1584output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "1585"and %s to %s in %s. Version %s of %s left in tree at %s."),1586change, old_path, delete_branch, change_past, path,1587change_branch, change_branch, path, alt_path);1588}1589}1590/*1591* No need to call update_file() on path when change_branch ==
1592* opt->branch1 && !alt_path, since that would needlessly touch
1593* path. We could call update_file_flags() with update_cache=0
1594* and update_wd=0, but that's a no-op.
1595*/
1596if (change_branch != opt->branch1 || alt_path)1597ret = update_file(opt, 0, changed, update_path);1598}1599free(alt_path);1600
1601return ret;1602}
1603
1604static int handle_rename_delete(struct merge_options *opt,1605struct rename_conflict_info *ci)1606{
1607const struct rename *ren = ci->ren1;1608const struct diff_filespec *orig = ren->pair->one;1609const struct diff_filespec *dest = ren->pair->two;1610const char *rename_branch = ren->branch;1611const char *delete_branch = (opt->branch1 == ren->branch ?1612opt->branch2 : opt->branch1);1613
1614if (handle_change_delete(opt,1615opt->priv->call_depth ? orig->path : dest->path,1616opt->priv->call_depth ? NULL : orig->path,1617orig, dest,1618rename_branch, delete_branch,1619_("rename"), _("renamed")))1620return -1;1621
1622if (opt->priv->call_depth)1623return remove_file_from_index(opt->repo->index, dest->path);1624else1625return update_stages(opt, dest->path, NULL,1626rename_branch == opt->branch1 ? dest : NULL,1627rename_branch == opt->branch1 ? NULL : dest);1628}
1629
1630static int handle_file_collision(struct merge_options *opt,1631const char *collide_path,1632const char *prev_path1,1633const char *prev_path2,1634const char *branch1, const char *branch2,1635struct diff_filespec *a,1636struct diff_filespec *b)1637{
1638struct merge_file_info mfi;1639struct diff_filespec null;1640char *alt_path = NULL;1641const char *update_path = collide_path;1642
1643/*1644* It's easiest to get the correct things into stage 2 and 3, and
1645* to make sure that the content merge puts HEAD before the other
1646* branch if we just ensure that branch1 == opt->branch1. So, simply
1647* flip arguments around if we don't have that.
1648*/
1649if (branch1 != opt->branch1) {1650return handle_file_collision(opt, collide_path,1651prev_path2, prev_path1,1652branch2, branch1,1653b, a);1654}1655
1656/* Remove rename sources if rename/add or rename/rename(2to1) */1657if (prev_path1)1658remove_file(opt, 1, prev_path1,1659opt->priv->call_depth || would_lose_untracked(opt, prev_path1));1660if (prev_path2)1661remove_file(opt, 1, prev_path2,1662opt->priv->call_depth || would_lose_untracked(opt, prev_path2));1663
1664/*1665* Remove the collision path, if it wouldn't cause dirty contents
1666* or an untracked file to get lost. We'll either overwrite with
1667* merged contents, or just write out to differently named files.
1668*/
1669if (was_dirty(opt, collide_path)) {1670output(opt, 1, _("Refusing to lose dirty file at %s"),1671collide_path);1672update_path = alt_path = unique_path(opt, collide_path, "merged");1673} else if (would_lose_untracked(opt, collide_path)) {1674/*1675* Only way we get here is if both renames were from
1676* a directory rename AND user had an untracked file
1677* at the location where both files end up after the
1678* two directory renames. See testcase 10d of t6043.
1679*/
1680output(opt, 1, _("Refusing to lose untracked file at "1681"%s, even though it's in the way."),1682collide_path);1683update_path = alt_path = unique_path(opt, collide_path, "merged");1684} else {1685/*1686* FIXME: It's possible that the two files are identical
1687* and that the current working copy happens to match, in
1688* which case we are unnecessarily touching the working
1689* tree file. It's not a likely enough scenario that I
1690* want to code up the checks for it and a better fix is
1691* available if we restructure how unpack_trees() and
1692* merge-recursive interoperate anyway, so punting for
1693* now...
1694*/
1695remove_file(opt, 0, collide_path, 0);1696}1697
1698/* Store things in diff_filespecs for functions that need it */1699null.path = (char *)collide_path;1700oidcpy(&null.oid, null_oid());1701null.mode = 0;1702
1703if (merge_mode_and_contents(opt, &null, a, b, collide_path,1704branch1, branch2, opt->priv->call_depth * 2, &mfi))1705return -1;1706mfi.clean &= !alt_path;1707if (update_file(opt, mfi.clean, &mfi.blob, update_path))1708return -1;1709if (!mfi.clean && !opt->priv->call_depth &&1710update_stages(opt, collide_path, NULL, a, b))1711return -1;1712free(alt_path);1713/*1714* FIXME: If both a & b both started with conflicts (only possible
1715* if they came from a rename/rename(2to1)), but had IDENTICAL
1716* contents including those conflicts, then in the next line we claim
1717* it was clean. If someone cares about this case, we should have the
1718* caller notify us if we started with conflicts.
1719*/
1720return mfi.clean;1721}
1722
1723static int handle_rename_add(struct merge_options *opt,1724struct rename_conflict_info *ci)1725{
1726/* a was renamed to c, and a separate c was added. */1727struct diff_filespec *a = ci->ren1->pair->one;1728struct diff_filespec *c = ci->ren1->pair->two;1729char *path = c->path;1730char *prev_path_desc;1731struct merge_file_info mfi;1732
1733const char *rename_branch = ci->ren1->branch;1734const char *add_branch = (opt->branch1 == rename_branch ?1735opt->branch2 : opt->branch1);1736int other_stage = (ci->ren1->branch == opt->branch1 ? 3 : 2);1737
1738output(opt, 1, _("CONFLICT (rename/add): "1739"Rename %s->%s in %s. Added %s in %s"),1740a->path, c->path, rename_branch,1741c->path, add_branch);1742
1743prev_path_desc = xstrfmt("version of %s from %s", path, a->path);1744ci->ren1->src_entry->stages[other_stage].path = a->path;1745if (merge_mode_and_contents(opt, a, c,1746&ci->ren1->src_entry->stages[other_stage],1747prev_path_desc,1748opt->branch1, opt->branch2,17491 + opt->priv->call_depth * 2, &mfi))1750return -1;1751free(prev_path_desc);1752
1753ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;1754return handle_file_collision(opt,1755c->path, a->path, NULL,1756rename_branch, add_branch,1757&mfi.blob,1758&ci->ren1->dst_entry->stages[other_stage]);1759}
1760
1761static char *find_path_for_conflict(struct merge_options *opt,1762const char *path,1763const char *branch1,1764const char *branch2)1765{
1766char *new_path = NULL;1767if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0)) {1768new_path = unique_path(opt, path, branch1);1769output(opt, 1, _("%s is a directory in %s adding "1770"as %s instead"),1771path, branch2, new_path);1772} else if (would_lose_untracked(opt, path)) {1773new_path = unique_path(opt, path, branch1);1774output(opt, 1, _("Refusing to lose untracked file"1775" at %s; adding as %s instead"),1776path, new_path);1777}1778
1779return new_path;1780}
1781
1782/*
1783* Toggle the stage number between "ours" and "theirs" (2 and 3).
1784*/
1785static inline int flip_stage(int stage)1786{
1787return (2 + 3) - stage;1788}
1789
1790static int handle_rename_rename_1to2(struct merge_options *opt,1791struct rename_conflict_info *ci)1792{
1793/* One file was renamed in both branches, but to different names. */1794struct merge_file_info mfi;1795struct diff_filespec *add;1796struct diff_filespec *o = ci->ren1->pair->one;1797struct diff_filespec *a = ci->ren1->pair->two;1798struct diff_filespec *b = ci->ren2->pair->two;1799char *path_desc;1800
1801output(opt, 1, _("CONFLICT (rename/rename): "1802"Rename \"%s\"->\"%s\" in branch \"%s\" "1803"rename \"%s\"->\"%s\" in \"%s\"%s"),1804o->path, a->path, ci->ren1->branch,1805o->path, b->path, ci->ren2->branch,1806opt->priv->call_depth ? _(" (left unresolved)") : "");1807
1808path_desc = xstrfmt("%s and %s, both renamed from %s",1809a->path, b->path, o->path);1810if (merge_mode_and_contents(opt, o, a, b, path_desc,1811ci->ren1->branch, ci->ren2->branch,1812opt->priv->call_depth * 2, &mfi))1813return -1;1814free(path_desc);1815
1816if (opt->priv->call_depth)1817remove_file_from_index(opt->repo->index, o->path);1818
1819/*1820* For each destination path, we need to see if there is a
1821* rename/add collision. If not, we can write the file out
1822* to the specified location.
1823*/
1824add = &ci->ren1->dst_entry->stages[flip_stage(2)];1825if (is_valid(add)) {1826add->path = mfi.blob.path = a->path;1827if (handle_file_collision(opt, a->path,1828NULL, NULL,1829ci->ren1->branch,1830ci->ren2->branch,1831&mfi.blob, add) < 0)1832return -1;1833} else {1834char *new_path = find_path_for_conflict(opt, a->path,1835ci->ren1->branch,1836ci->ren2->branch);1837if (update_file(opt, 0, &mfi.blob,1838new_path ? new_path : a->path))1839return -1;1840free(new_path);1841if (!opt->priv->call_depth &&1842update_stages(opt, a->path, NULL, a, NULL))1843return -1;1844}1845
1846if (!mfi.clean && mfi.blob.mode == a->mode &&1847oideq(&mfi.blob.oid, &a->oid)) {1848/*1849* Getting here means we were attempting to merge a binary
1850* blob. Since we can't merge binaries, the merge algorithm
1851* just takes one side. But we don't want to copy the
1852* contents of one side to both paths; we'd rather use the
1853* original content at the given path for each path.
1854*/
1855oidcpy(&mfi.blob.oid, &b->oid);1856mfi.blob.mode = b->mode;1857}1858add = &ci->ren2->dst_entry->stages[flip_stage(3)];1859if (is_valid(add)) {1860add->path = mfi.blob.path = b->path;1861if (handle_file_collision(opt, b->path,1862NULL, NULL,1863ci->ren1->branch,1864ci->ren2->branch,1865add, &mfi.blob) < 0)1866return -1;1867} else {1868char *new_path = find_path_for_conflict(opt, b->path,1869ci->ren2->branch,1870ci->ren1->branch);1871if (update_file(opt, 0, &mfi.blob,1872new_path ? new_path : b->path))1873return -1;1874free(new_path);1875if (!opt->priv->call_depth &&1876update_stages(opt, b->path, NULL, NULL, b))1877return -1;1878}1879
1880return 0;1881}
1882
1883static int handle_rename_rename_2to1(struct merge_options *opt,1884struct rename_conflict_info *ci)1885{
1886/* Two files, a & b, were renamed to the same thing, c. */1887struct diff_filespec *a = ci->ren1->pair->one;1888struct diff_filespec *b = ci->ren2->pair->one;1889struct diff_filespec *c1 = ci->ren1->pair->two;1890struct diff_filespec *c2 = ci->ren2->pair->two;1891char *path = c1->path; /* == c2->path */1892char *path_side_1_desc;1893char *path_side_2_desc;1894struct merge_file_info mfi_c1;1895struct merge_file_info mfi_c2;1896int ostage1, ostage2;1897
1898output(opt, 1, _("CONFLICT (rename/rename): "1899"Rename %s->%s in %s. "1900"Rename %s->%s in %s"),1901a->path, c1->path, ci->ren1->branch,1902b->path, c2->path, ci->ren2->branch);1903
1904path_side_1_desc = xstrfmt("version of %s from %s", path, a->path);1905path_side_2_desc = xstrfmt("version of %s from %s", path, b->path);1906ostage1 = ci->ren1->branch == opt->branch1 ? 3 : 2;1907ostage2 = flip_stage(ostage1);1908ci->ren1->src_entry->stages[ostage1].path = a->path;1909ci->ren2->src_entry->stages[ostage2].path = b->path;1910if (merge_mode_and_contents(opt, a, c1,1911&ci->ren1->src_entry->stages[ostage1],1912path_side_1_desc,1913opt->branch1, opt->branch2,19141 + opt->priv->call_depth * 2, &mfi_c1) ||1915merge_mode_and_contents(opt, b,1916&ci->ren2->src_entry->stages[ostage2],1917c2, path_side_2_desc,1918opt->branch1, opt->branch2,19191 + opt->priv->call_depth * 2, &mfi_c2))1920return -1;1921free(path_side_1_desc);1922free(path_side_2_desc);1923mfi_c1.blob.path = path;1924mfi_c2.blob.path = path;1925
1926return handle_file_collision(opt, path, a->path, b->path,1927ci->ren1->branch, ci->ren2->branch,1928&mfi_c1.blob, &mfi_c2.blob);1929}
1930
1931/*
1932* Get the diff_filepairs changed between o_tree and tree.
1933*/
1934static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,1935struct tree *o_tree,1936struct tree *tree)1937{
1938struct diff_queue_struct *ret;1939struct diff_options opts;1940
1941repo_diff_setup(opt->repo, &opts);1942opts.flags.recursive = 1;1943opts.flags.rename_empty = 0;1944opts.detect_rename = merge_detect_rename(opt);1945/*1946* We do not have logic to handle the detection of copies. In
1947* fact, it may not even make sense to add such logic: would we
1948* really want a change to a base file to be propagated through
1949* multiple other files by a merge?
1950*/
1951if (opts.detect_rename > DIFF_DETECT_RENAME)1952opts.detect_rename = DIFF_DETECT_RENAME;1953opts.rename_limit = (opt->rename_limit >= 0) ? opt->rename_limit : 7000;1954opts.rename_score = opt->rename_score;1955opts.show_rename_progress = opt->show_rename_progress;1956opts.output_format = DIFF_FORMAT_NO_OUTPUT;1957diff_setup_done(&opts);1958diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);1959diffcore_std(&opts);1960if (opts.needed_rename_limit > opt->priv->needed_rename_limit)1961opt->priv->needed_rename_limit = opts.needed_rename_limit;1962
1963ret = xmalloc(sizeof(*ret));1964*ret = diff_queued_diff;1965
1966opts.output_format = DIFF_FORMAT_NO_OUTPUT;1967diff_queued_diff.nr = 0;1968diff_queued_diff.queue = NULL;1969diff_flush(&opts);1970return ret;1971}
1972
1973static int tree_has_path(struct repository *r, struct tree *tree,1974const char *path)1975{
1976struct object_id hashy;1977unsigned short mode_o;1978
1979return !get_tree_entry(r,1980&tree->object.oid, path,1981&hashy, &mode_o);1982}
1983
1984/*
1985* Return a new string that replaces the beginning portion (which matches
1986* entry->dir), with entry->new_dir. In perl-speak:
1987* new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
1988* NOTE:
1989* Caller must ensure that old_path starts with entry->dir + '/'.
1990*/
1991static char *apply_dir_rename(struct dir_rename_entry *entry,1992const char *old_path)1993{
1994struct strbuf new_path = STRBUF_INIT;1995int oldlen, newlen;1996
1997if (entry->non_unique_new_dir)1998return NULL;1999
2000oldlen = strlen(entry->dir);2001if (entry->new_dir.len == 0)2002/*2003* If someone renamed/merged a subdirectory into the root
2004* directory (e.g. 'some/subdir' -> ''), then we want to
2005* avoid returning
2006* '' + '/filename'
2007* as the rename; we need to make old_path + oldlen advance
2008* past the '/' character.
2009*/
2010oldlen++;2011newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;2012strbuf_grow(&new_path, newlen);2013strbuf_addbuf(&new_path, &entry->new_dir);2014strbuf_addstr(&new_path, &old_path[oldlen]);2015
2016return strbuf_detach(&new_path, NULL);2017}
2018
2019static void get_renamed_dir_portion(const char *old_path, const char *new_path,2020char **old_dir, char **new_dir)2021{
2022char *end_of_old, *end_of_new;2023
2024/* Default return values: NULL, meaning no rename */2025*old_dir = NULL;2026*new_dir = NULL;2027
2028/*2029* For
2030* "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
2031* the "e/foo.c" part is the same, we just want to know that
2032* "a/b/c/d" was renamed to "a/b/some/thing/else"
2033* so, for this example, this function returns "a/b/c/d" in
2034* *old_dir and "a/b/some/thing/else" in *new_dir.
2035*/
2036
2037/*2038* If the basename of the file changed, we don't care. We want
2039* to know which portion of the directory, if any, changed.
2040*/
2041end_of_old = strrchr(old_path, '/');2042end_of_new = strrchr(new_path, '/');2043
2044/*2045* If end_of_old is NULL, old_path wasn't in a directory, so there
2046* could not be a directory rename (our rule elsewhere that a
2047* directory which still exists is not considered to have been
2048* renamed means the root directory can never be renamed -- because
2049* the root directory always exists).
2050*/
2051if (!end_of_old)2052return; /* Note: *old_dir and *new_dir are still NULL */2053
2054/*2055* If new_path contains no directory (end_of_new is NULL), then we
2056* have a rename of old_path's directory to the root directory.
2057*/
2058if (!end_of_new) {2059*old_dir = xstrndup(old_path, end_of_old - old_path);2060*new_dir = xstrdup("");2061return;2062}2063
2064/* Find the first non-matching character traversing backwards */2065while (*--end_of_new == *--end_of_old &&2066end_of_old != old_path &&2067end_of_new != new_path)2068; /* Do nothing; all in the while loop */2069
2070/*2071* If both got back to the beginning of their strings, then the
2072* directory didn't change at all, only the basename did.
2073*/
2074if (end_of_old == old_path && end_of_new == new_path &&2075*end_of_old == *end_of_new)2076return; /* Note: *old_dir and *new_dir are still NULL */2077
2078/*2079* If end_of_new got back to the beginning of its string, and
2080* end_of_old got back to the beginning of some subdirectory, then
2081* we have a rename/merge of a subdirectory into the root, which
2082* needs slightly special handling.
2083*
2084* Note: There is no need to consider the opposite case, with a
2085* rename/merge of the root directory into some subdirectory
2086* because as noted above the root directory always exists so it
2087* cannot be considered to be renamed.
2088*/
2089if (end_of_new == new_path &&2090end_of_old != old_path && end_of_old[-1] == '/') {2091*old_dir = xstrndup(old_path, --end_of_old - old_path);2092*new_dir = xstrdup("");2093return;2094}2095
2096/*2097* We've found the first non-matching character in the directory
2098* paths. That means the current characters we were looking at
2099* were part of the first non-matching subdir name going back from
2100* the end of the strings. Get the whole name by advancing both
2101* end_of_old and end_of_new to the NEXT '/' character. That will
2102* represent the entire directory rename.
2103*
2104* The reason for the increment is cases like
2105* a/b/star/foo/whatever.c -> a/b/tar/foo/random.c
2106* After dropping the basename and going back to the first
2107* non-matching character, we're now comparing:
2108* a/b/s and a/b/
2109* and we want to be comparing:
2110* a/b/star/ and a/b/tar/
2111* but without the pre-increment, the one on the right would stay
2112* a/b/.
2113*/
2114end_of_old = strchr(++end_of_old, '/');2115end_of_new = strchr(++end_of_new, '/');2116
2117/* Copy the old and new directories into *old_dir and *new_dir. */2118*old_dir = xstrndup(old_path, end_of_old - old_path);2119*new_dir = xstrndup(new_path, end_of_new - new_path);2120}
2121
2122static void remove_hashmap_entries(struct hashmap *dir_renames,2123struct string_list *items_to_remove)2124{
2125int i;2126struct dir_rename_entry *entry;2127
2128for (i = 0; i < items_to_remove->nr; i++) {2129entry = items_to_remove->items[i].util;2130hashmap_remove(dir_renames, &entry->ent, NULL);2131}2132string_list_clear(items_to_remove, 0);2133}
2134
2135/*
2136* See if there is a directory rename for path, and if there are any file
2137* level conflicts for the renamed location. If there is a rename and
2138* there are no conflicts, return the new name. Otherwise, return NULL.
2139*/
2140static char *handle_path_level_conflicts(struct merge_options *opt,2141const char *path,2142struct dir_rename_entry *entry,2143struct hashmap *collisions,2144struct tree *tree)2145{
2146char *new_path = NULL;2147struct collision_entry *collision_ent;2148int clean = 1;2149struct strbuf collision_paths = STRBUF_INIT;2150
2151/*2152* entry has the mapping of old directory name to new directory name
2153* that we want to apply to path.
2154*/
2155new_path = apply_dir_rename(entry, path);2156
2157if (!new_path) {2158/* This should only happen when entry->non_unique_new_dir set */2159if (!entry->non_unique_new_dir)2160BUG("entry->non_unique_new_dir not set and !new_path");2161output(opt, 1, _("CONFLICT (directory rename split): "2162"Unclear where to place %s because directory "2163"%s was renamed to multiple other directories, "2164"with no destination getting a majority of the "2165"files."),2166path, entry->dir);2167clean = 0;2168return NULL;2169}2170
2171/*2172* The caller needs to have ensured that it has pre-populated
2173* collisions with all paths that map to new_path. Do a quick check
2174* to ensure that's the case.
2175*/
2176collision_ent = collision_find_entry(collisions, new_path);2177if (!collision_ent)2178BUG("collision_ent is NULL");2179
2180/*2181* Check for one-sided add/add/.../add conflicts, i.e.
2182* where implicit renames from the other side doing
2183* directory rename(s) can affect this side of history
2184* to put multiple paths into the same location. Warn
2185* and bail on directory renames for such paths.
2186*/
2187if (collision_ent->reported_already) {2188clean = 0;2189} else if (tree_has_path(opt->repo, tree, new_path)) {2190collision_ent->reported_already = 1;2191strbuf_add_separated_string_list(&collision_paths, ", ",2192&collision_ent->source_files);2193output(opt, 1, _("CONFLICT (implicit dir rename): Existing "2194"file/dir at %s in the way of implicit "2195"directory rename(s) putting the following "2196"path(s) there: %s."),2197new_path, collision_paths.buf);2198clean = 0;2199} else if (collision_ent->source_files.nr > 1) {2200collision_ent->reported_already = 1;2201strbuf_add_separated_string_list(&collision_paths, ", ",2202&collision_ent->source_files);2203output(opt, 1, _("CONFLICT (implicit dir rename): Cannot map "2204"more than one path to %s; implicit directory "2205"renames tried to put these paths there: %s"),2206new_path, collision_paths.buf);2207clean = 0;2208}2209
2210/* Free memory we no longer need */2211strbuf_release(&collision_paths);2212if (!clean && new_path) {2213free(new_path);2214return NULL;2215}2216
2217return new_path;2218}
2219
2220/*
2221* There are a couple things we want to do at the directory level:
2222* 1. Check for both sides renaming to the same thing, in order to avoid
2223* implicit renaming of files that should be left in place. (See
2224* testcase 6b in t6043 for details.)
2225* 2. Prune directory renames if there are still files left in the
2226* original directory. These represent a partial directory rename,
2227* i.e. a rename where only some of the files within the directory
2228* were renamed elsewhere. (Technically, this could be done earlier
2229* in get_directory_renames(), except that would prevent us from
2230* doing the previous check and thus failing testcase 6b.)
2231* 3. Check for rename/rename(1to2) conflicts (at the directory level).
2232* In the future, we could potentially record this info as well and
2233* omit reporting rename/rename(1to2) conflicts for each path within
2234* the affected directories, thus cleaning up the merge output.
2235* NOTE: We do NOT check for rename/rename(2to1) conflicts at the
2236* directory level, because merging directories is fine. If it
2237* causes conflicts for files within those merged directories, then
2238* that should be detected at the individual path level.
2239*/
2240static void handle_directory_level_conflicts(struct merge_options *opt,2241struct hashmap *dir_re_head,2242struct tree *head,2243struct hashmap *dir_re_merge,2244struct tree *merge)2245{
2246struct hashmap_iter iter;2247struct dir_rename_entry *head_ent;2248struct dir_rename_entry *merge_ent;2249
2250struct string_list remove_from_head = STRING_LIST_INIT_NODUP;2251struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;2252
2253hashmap_for_each_entry(dir_re_head, &iter, head_ent,2254ent /* member name */) {2255merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);2256if (merge_ent &&2257!head_ent->non_unique_new_dir &&2258!merge_ent->non_unique_new_dir &&2259!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {2260/* 1. Renamed identically; remove it from both sides */2261string_list_append(&remove_from_head,2262head_ent->dir)->util = head_ent;2263strbuf_release(&head_ent->new_dir);2264string_list_append(&remove_from_merge,2265merge_ent->dir)->util = merge_ent;2266strbuf_release(&merge_ent->new_dir);2267} else if (tree_has_path(opt->repo, head, head_ent->dir)) {2268/* 2. This wasn't a directory rename after all */2269string_list_append(&remove_from_head,2270head_ent->dir)->util = head_ent;2271strbuf_release(&head_ent->new_dir);2272}2273}2274
2275remove_hashmap_entries(dir_re_head, &remove_from_head);2276remove_hashmap_entries(dir_re_merge, &remove_from_merge);2277
2278hashmap_for_each_entry(dir_re_merge, &iter, merge_ent,2279ent /* member name */) {2280head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);2281if (tree_has_path(opt->repo, merge, merge_ent->dir)) {2282/* 2. This wasn't a directory rename after all */2283string_list_append(&remove_from_merge,2284merge_ent->dir)->util = merge_ent;2285} else if (head_ent &&2286!head_ent->non_unique_new_dir &&2287!merge_ent->non_unique_new_dir) {2288/* 3. rename/rename(1to2) */2289/*2290* We can assume it's not rename/rename(1to1) because
2291* that was case (1), already checked above. So we
2292* know that head_ent->new_dir and merge_ent->new_dir
2293* are different strings.
2294*/
2295output(opt, 1, _("CONFLICT (rename/rename): "2296"Rename directory %s->%s in %s. "2297"Rename directory %s->%s in %s"),2298head_ent->dir, head_ent->new_dir.buf, opt->branch1,2299head_ent->dir, merge_ent->new_dir.buf, opt->branch2);2300string_list_append(&remove_from_head,2301head_ent->dir)->util = head_ent;2302strbuf_release(&head_ent->new_dir);2303string_list_append(&remove_from_merge,2304merge_ent->dir)->util = merge_ent;2305strbuf_release(&merge_ent->new_dir);2306}2307}2308
2309remove_hashmap_entries(dir_re_head, &remove_from_head);2310remove_hashmap_entries(dir_re_merge, &remove_from_merge);2311}
2312
2313static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)2314{
2315struct hashmap *dir_renames;2316struct hashmap_iter iter;2317struct dir_rename_entry *entry;2318int i;2319
2320/*2321* Typically, we think of a directory rename as all files from a
2322* certain directory being moved to a target directory. However,
2323* what if someone first moved two files from the original
2324* directory in one commit, and then renamed the directory
2325* somewhere else in a later commit? At merge time, we just know
2326* that files from the original directory went to two different
2327* places, and that the bulk of them ended up in the same place.
2328* We want each directory rename to represent where the bulk of the
2329* files from that directory end up; this function exists to find
2330* where the bulk of the files went.
2331*
2332* The first loop below simply iterates through the list of file
2333* renames, finding out how often each directory rename pair
2334* possibility occurs.
2335*/
2336dir_renames = xmalloc(sizeof(*dir_renames));2337dir_rename_init(dir_renames);2338for (i = 0; i < pairs->nr; ++i) {2339struct string_list_item *item;2340int *count;2341struct diff_filepair *pair = pairs->queue[i];2342char *old_dir, *new_dir;2343
2344/* File not part of directory rename if it wasn't renamed */2345if (pair->status != 'R')2346continue;2347
2348get_renamed_dir_portion(pair->one->path, pair->two->path,2349&old_dir, &new_dir);2350if (!old_dir)2351/* Directory didn't change at all; ignore this one. */2352continue;2353
2354entry = dir_rename_find_entry(dir_renames, old_dir);2355if (!entry) {2356entry = xmalloc(sizeof(*entry));2357dir_rename_entry_init(entry, old_dir);2358hashmap_put(dir_renames, &entry->ent);2359} else {2360free(old_dir);2361}2362item = string_list_lookup(&entry->possible_new_dirs, new_dir);2363if (!item) {2364item = string_list_insert(&entry->possible_new_dirs,2365new_dir);2366item->util = xcalloc(1, sizeof(int));2367} else {2368free(new_dir);2369}2370count = item->util;2371*count += 1;2372}2373
2374/*2375* For each directory with files moved out of it, we find out which
2376* target directory received the most files so we can declare it to
2377* be the "winning" target location for the directory rename. This
2378* winner gets recorded in new_dir. If there is no winner
2379* (multiple target directories received the same number of files),
2380* we set non_unique_new_dir. Once we've determined the winner (or
2381* that there is no winner), we no longer need possible_new_dirs.
2382*/
2383hashmap_for_each_entry(dir_renames, &iter, entry,2384ent /* member name */) {2385int max = 0;2386int bad_max = 0;2387char *best = NULL;2388
2389for (i = 0; i < entry->possible_new_dirs.nr; i++) {2390int *count = entry->possible_new_dirs.items[i].util;2391
2392if (*count == max)2393bad_max = max;2394else if (*count > max) {2395max = *count;2396best = entry->possible_new_dirs.items[i].string;2397}2398}2399if (bad_max == max)2400entry->non_unique_new_dir = 1;2401else {2402assert(entry->new_dir.len == 0);2403strbuf_addstr(&entry->new_dir, best);2404}2405/*2406* The relevant directory sub-portion of the original full
2407* filepaths were xstrndup'ed before inserting into
2408* possible_new_dirs, and instead of manually iterating the
2409* list and free'ing each, just lie and tell
2410* possible_new_dirs that it did the strdup'ing so that it
2411* will free them for us.
2412*/
2413entry->possible_new_dirs.strdup_strings = 1;2414string_list_clear(&entry->possible_new_dirs, 1);2415}2416
2417return dir_renames;2418}
2419
2420static struct dir_rename_entry *check_dir_renamed(const char *path,2421struct hashmap *dir_renames)2422{
2423char *temp = xstrdup(path);2424char *end;2425struct dir_rename_entry *entry = NULL;2426
2427while ((end = strrchr(temp, '/'))) {2428*end = '\0';2429entry = dir_rename_find_entry(dir_renames, temp);2430if (entry)2431break;2432}2433free(temp);2434return entry;2435}
2436
2437static void compute_collisions(struct hashmap *collisions,2438struct hashmap *dir_renames,2439struct diff_queue_struct *pairs)2440{
2441int i;2442
2443/*2444* Multiple files can be mapped to the same path due to directory
2445* renames done by the other side of history. Since that other
2446* side of history could have merged multiple directories into one,
2447* if our side of history added the same file basename to each of
2448* those directories, then all N of them would get implicitly
2449* renamed by the directory rename detection into the same path,
2450* and we'd get an add/add/.../add conflict, and all those adds
2451* from *this* side of history. This is not representable in the
2452* index, and users aren't going to easily be able to make sense of
2453* it. So we need to provide a good warning about what's
2454* happening, and fall back to no-directory-rename detection
2455* behavior for those paths.
2456*
2457* See testcases 9e and all of section 5 from t6043 for examples.
2458*/
2459collision_init(collisions);2460
2461for (i = 0; i < pairs->nr; ++i) {2462struct dir_rename_entry *dir_rename_ent;2463struct collision_entry *collision_ent;2464char *new_path;2465struct diff_filepair *pair = pairs->queue[i];2466
2467if (pair->status != 'A' && pair->status != 'R')2468continue;2469dir_rename_ent = check_dir_renamed(pair->two->path,2470dir_renames);2471if (!dir_rename_ent)2472continue;2473
2474new_path = apply_dir_rename(dir_rename_ent, pair->two->path);2475if (!new_path)2476/*2477* dir_rename_ent->non_unique_new_path is true, which
2478* means there is no directory rename for us to use,
2479* which means it won't cause us any additional
2480* collisions.
2481*/
2482continue;2483collision_ent = collision_find_entry(collisions, new_path);2484if (!collision_ent) {2485CALLOC_ARRAY(collision_ent, 1);2486hashmap_entry_init(&collision_ent->ent,2487strhash(new_path));2488hashmap_put(collisions, &collision_ent->ent);2489collision_ent->target_file = new_path;2490} else {2491free(new_path);2492}2493string_list_insert(&collision_ent->source_files,2494pair->two->path);2495}2496}
2497
2498static char *check_for_directory_rename(struct merge_options *opt,2499const char *path,2500struct tree *tree,2501struct hashmap *dir_renames,2502struct hashmap *dir_rename_exclusions,2503struct hashmap *collisions,2504int *clean_merge)2505{
2506char *new_path = NULL;2507struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);2508struct dir_rename_entry *oentry = NULL;2509
2510if (!entry)2511return new_path;2512
2513/*2514* This next part is a little weird. We do not want to do an
2515* implicit rename into a directory we renamed on our side, because
2516* that will result in a spurious rename/rename(1to2) conflict. An
2517* example:
2518* Base commit: dumbdir/afile, otherdir/bfile
2519* Side 1: smrtdir/afile, otherdir/bfile
2520* Side 2: dumbdir/afile, dumbdir/bfile
2521* Here, while working on Side 1, we could notice that otherdir was
2522* renamed/merged to dumbdir, and change the diff_filepair for
2523* otherdir/bfile into a rename into dumbdir/bfile. However, Side
2524* 2 will notice the rename from dumbdir to smrtdir, and do the
2525* transitive rename to move it from dumbdir/bfile to
2526* smrtdir/bfile. That gives us bfile in dumbdir vs being in
2527* smrtdir, a rename/rename(1to2) conflict. We really just want
2528* the file to end up in smrtdir. And the way to achieve that is
2529* to not let Side1 do the rename to dumbdir, since we know that is
2530* the source of one of our directory renames.
2531*
2532* That's why oentry and dir_rename_exclusions is here.
2533*
2534* As it turns out, this also prevents N-way transient rename
2535* confusion; See testcases 9c and 9d of t6043.
2536*/
2537oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);2538if (oentry) {2539output(opt, 1, _("WARNING: Avoiding applying %s -> %s rename "2540"to %s, because %s itself was renamed."),2541entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);2542} else {2543new_path = handle_path_level_conflicts(opt, path, entry,2544collisions, tree);2545*clean_merge &= (new_path != NULL);2546}2547
2548return new_path;2549}
2550
2551static void apply_directory_rename_modifications(struct merge_options *opt,2552struct diff_filepair *pair,2553char *new_path,2554struct rename *re,2555struct tree *tree,2556struct tree *o_tree,2557struct tree *a_tree,2558struct tree *b_tree,2559struct string_list *entries)2560{
2561struct string_list_item *item;2562int stage = (tree == a_tree ? 2 : 3);2563int update_wd;2564
2565/*2566* In all cases where we can do directory rename detection,
2567* unpack_trees() will have read pair->two->path into the
2568* index and the working copy. We need to remove it so that
2569* we can instead place it at new_path. It is guaranteed to
2570* not be untracked (unpack_trees() would have errored out
2571* saying the file would have been overwritten), but it might
2572* be dirty, though.
2573*/
2574update_wd = !was_dirty(opt, pair->two->path);2575if (!update_wd)2576output(opt, 1, _("Refusing to lose dirty file at %s"),2577pair->two->path);2578remove_file(opt, 1, pair->two->path, !update_wd);2579
2580/* Find or create a new re->dst_entry */2581item = string_list_lookup(entries, new_path);2582if (item) {2583/*2584* Since we're renaming on this side of history, and it's
2585* due to a directory rename on the other side of history
2586* (which we only allow when the directory in question no
2587* longer exists on the other side of history), the
2588* original entry for re->dst_entry is no longer
2589* necessary...
2590*/
2591re->dst_entry->processed = 1;2592
2593/*2594* ...because we'll be using this new one.
2595*/
2596re->dst_entry = item->util;2597} else {2598/*2599* re->dst_entry is for the before-dir-rename path, and we
2600* need it to hold information for the after-dir-rename
2601* path. Before creating a new entry, we need to mark the
2602* old one as unnecessary (...unless it is shared by
2603* src_entry, i.e. this didn't use to be a rename, in which
2604* case we can just allow the normal processing to happen
2605* for it).
2606*/
2607if (pair->status == 'R')2608re->dst_entry->processed = 1;2609
2610re->dst_entry = insert_stage_data(opt->repo, new_path,2611o_tree, a_tree, b_tree,2612entries);2613item = string_list_insert(entries, new_path);2614item->util = re->dst_entry;2615}2616
2617/*2618* Update the stage_data with the information about the path we are
2619* moving into place. That slot will be empty and available for us
2620* to write to because of the collision checks in
2621* handle_path_level_conflicts(). In other words,
2622* re->dst_entry->stages[stage].oid will be the null_oid, so it's
2623* open for us to write to.
2624*
2625* It may be tempting to actually update the index at this point as
2626* well, using update_stages_for_stage_data(), but as per the big
2627* "NOTE" in update_stages(), doing so will modify the current
2628* in-memory index which will break calls to would_lose_untracked()
2629* that we need to make. Instead, we need to just make sure that
2630* the various handle_rename_*() functions update the index
2631* explicitly rather than relying on unpack_trees() to have done it.
2632*/
2633get_tree_entry(opt->repo,2634&tree->object.oid,2635pair->two->path,2636&re->dst_entry->stages[stage].oid,2637&re->dst_entry->stages[stage].mode);2638
2639/*2640* Record the original change status (or 'type' of change). If it
2641* was originally an add ('A'), this lets us differentiate later
2642* between a RENAME_DELETE conflict and RENAME_VIA_DIR (they
2643* otherwise look the same). If it was originally a rename ('R'),
2644* this lets us remember and report accurately about the transitive
2645* renaming that occurred via the directory rename detection. Also,
2646* record the original destination name.
2647*/
2648re->dir_rename_original_type = pair->status;2649re->dir_rename_original_dest = pair->two->path;2650
2651/*2652* We don't actually look at pair->status again, but it seems
2653* pedagogically correct to adjust it.
2654*/
2655pair->status = 'R';2656
2657/*2658* Finally, record the new location.
2659*/
2660pair->two->path = new_path;2661}
2662
2663/*
2664* Get information of all renames which occurred in 'pairs', making use of
2665* any implicit directory renames inferred from the other side of history.
2666* We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
2667* to be able to associate the correct cache entries with the rename
2668* information; tree is always equal to either a_tree or b_tree.
2669*/
2670static struct string_list *get_renames(struct merge_options *opt,2671const char *branch,2672struct diff_queue_struct *pairs,2673struct hashmap *dir_renames,2674struct hashmap *dir_rename_exclusions,2675struct tree *tree,2676struct tree *o_tree,2677struct tree *a_tree,2678struct tree *b_tree,2679struct string_list *entries,2680int *clean_merge)2681{
2682int i;2683struct hashmap collisions;2684struct hashmap_iter iter;2685struct collision_entry *e;2686struct string_list *renames;2687
2688compute_collisions(&collisions, dir_renames, pairs);2689CALLOC_ARRAY(renames, 1);2690
2691for (i = 0; i < pairs->nr; ++i) {2692struct string_list_item *item;2693struct rename *re;2694struct diff_filepair *pair = pairs->queue[i];2695char *new_path; /* non-NULL only with directory renames */2696
2697if (pair->status != 'A' && pair->status != 'R') {2698diff_free_filepair(pair);2699continue;2700}2701new_path = check_for_directory_rename(opt, pair->two->path, tree,2702dir_renames,2703dir_rename_exclusions,2704&collisions,2705clean_merge);2706if (pair->status != 'R' && !new_path) {2707diff_free_filepair(pair);2708continue;2709}2710
2711re = xmalloc(sizeof(*re));2712re->processed = 0;2713re->pair = pair;2714re->branch = branch;2715re->dir_rename_original_type = '\0';2716re->dir_rename_original_dest = NULL;2717item = string_list_lookup(entries, re->pair->one->path);2718if (!item)2719re->src_entry = insert_stage_data(opt->repo,2720re->pair->one->path,2721o_tree, a_tree, b_tree, entries);2722else2723re->src_entry = item->util;2724
2725item = string_list_lookup(entries, re->pair->two->path);2726if (!item)2727re->dst_entry = insert_stage_data(opt->repo,2728re->pair->two->path,2729o_tree, a_tree, b_tree, entries);2730else2731re->dst_entry = item->util;2732item = string_list_insert(renames, pair->one->path);2733item->util = re;2734if (new_path)2735apply_directory_rename_modifications(opt, pair, new_path,2736re, tree, o_tree,2737a_tree, b_tree,2738entries);2739}2740
2741hashmap_for_each_entry(&collisions, &iter, e,2742ent /* member name */) {2743free(e->target_file);2744string_list_clear(&e->source_files, 0);2745}2746hashmap_clear_and_free(&collisions, struct collision_entry, ent);2747return renames;2748}
2749
2750static int process_renames(struct merge_options *opt,2751struct string_list *a_renames,2752struct string_list *b_renames)2753{
2754int clean_merge = 1, i, j;2755struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2756struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2757const struct rename *sre;2758
2759/*2760* FIXME: As string-list.h notes, it's O(n^2) to build a sorted
2761* string_list one-by-one, but O(n log n) to build it unsorted and
2762* then sort it. Note that as we build the list, we do not need to
2763* check if the existing destination path is already in the list,
2764* because the structure of diffcore_rename guarantees we won't
2765* have duplicates.
2766*/
2767for (i = 0; i < a_renames->nr; i++) {2768sre = a_renames->items[i].util;2769string_list_insert(&a_by_dst, sre->pair->two->path)->util2770= (void *)sre;2771}2772for (i = 0; i < b_renames->nr; i++) {2773sre = b_renames->items[i].util;2774string_list_insert(&b_by_dst, sre->pair->two->path)->util2775= (void *)sre;2776}2777
2778for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {2779struct string_list *renames1, *renames2Dst;2780struct rename *ren1 = NULL, *ren2 = NULL;2781const char *ren1_src, *ren1_dst;2782struct string_list_item *lookup;2783
2784if (i >= a_renames->nr) {2785ren2 = b_renames->items[j++].util;2786} else if (j >= b_renames->nr) {2787ren1 = a_renames->items[i++].util;2788} else {2789int compare = strcmp(a_renames->items[i].string,2790b_renames->items[j].string);2791if (compare <= 0)2792ren1 = a_renames->items[i++].util;2793if (compare >= 0)2794ren2 = b_renames->items[j++].util;2795}2796
2797/* TODO: refactor, so that 1/2 are not needed */2798if (ren1) {2799renames1 = a_renames;2800renames2Dst = &b_by_dst;2801} else {2802renames1 = b_renames;2803renames2Dst = &a_by_dst;2804SWAP(ren2, ren1);2805}2806
2807if (ren1->processed)2808continue;2809ren1->processed = 1;2810ren1->dst_entry->processed = 1;2811/* BUG: We should only mark src_entry as processed if we2812* are not dealing with a rename + add-source case.
2813*/
2814ren1->src_entry->processed = 1;2815
2816ren1_src = ren1->pair->one->path;2817ren1_dst = ren1->pair->two->path;2818
2819if (ren2) {2820/* One file renamed on both sides */2821const char *ren2_src = ren2->pair->one->path;2822const char *ren2_dst = ren2->pair->two->path;2823enum rename_type rename_type;2824if (strcmp(ren1_src, ren2_src) != 0)2825BUG("ren1_src != ren2_src");2826ren2->dst_entry->processed = 1;2827ren2->processed = 1;2828if (strcmp(ren1_dst, ren2_dst) != 0) {2829rename_type = RENAME_ONE_FILE_TO_TWO;2830clean_merge = 0;2831} else {2832rename_type = RENAME_ONE_FILE_TO_ONE;2833/* BUG: We should only remove ren1_src in2834* the base stage (think of rename +
2835* add-source cases).
2836*/
2837remove_file(opt, 1, ren1_src, 1);2838update_entry(ren1->dst_entry,2839ren1->pair->one,2840ren1->pair->two,2841ren2->pair->two);2842}2843setup_rename_conflict_info(rename_type, opt, ren1, ren2);2844} else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {2845/* Two different files renamed to the same thing */2846char *ren2_dst;2847ren2 = lookup->util;2848ren2_dst = ren2->pair->two->path;2849if (strcmp(ren1_dst, ren2_dst) != 0)2850BUG("ren1_dst != ren2_dst");2851
2852clean_merge = 0;2853ren2->processed = 1;2854/*2855* BUG: We should only mark src_entry as processed
2856* if we are not dealing with a rename + add-source
2857* case.
2858*/
2859ren2->src_entry->processed = 1;2860
2861setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2862opt, ren1, ren2);2863} else {2864/* Renamed in 1, maybe changed in 2 */2865/* we only use sha1 and mode of these */2866struct diff_filespec src_other, dst_other;2867int try_merge;2868
2869/*2870* unpack_trees loads entries from common-commit
2871* into stage 1, from head-commit into stage 2, and
2872* from merge-commit into stage 3. We keep track
2873* of which side corresponds to the rename.
2874*/
2875int renamed_stage = a_renames == renames1 ? 2 : 3;2876int other_stage = a_renames == renames1 ? 3 : 2;2877
2878/*2879* Directory renames have a funny corner case...
2880*/
2881int renamed_to_self = !strcmp(ren1_src, ren1_dst);2882
2883/* BUG: We should only remove ren1_src in the base2884* stage and in other_stage (think of rename +
2885* add-source case).
2886*/
2887if (!renamed_to_self)2888remove_file(opt, 1, ren1_src,2889renamed_stage == 2 ||2890!was_tracked(opt, ren1_src));2891
2892oidcpy(&src_other.oid,2893&ren1->src_entry->stages[other_stage].oid);2894src_other.mode = ren1->src_entry->stages[other_stage].mode;2895oidcpy(&dst_other.oid,2896&ren1->dst_entry->stages[other_stage].oid);2897dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2898try_merge = 0;2899
2900if (oideq(&src_other.oid, null_oid()) &&2901ren1->dir_rename_original_type == 'A') {2902setup_rename_conflict_info(RENAME_VIA_DIR,2903opt, ren1, NULL);2904} else if (renamed_to_self) {2905setup_rename_conflict_info(RENAME_NORMAL,2906opt, ren1, NULL);2907} else if (oideq(&src_other.oid, null_oid())) {2908setup_rename_conflict_info(RENAME_DELETE,2909opt, ren1, NULL);2910} else if ((dst_other.mode == ren1->pair->two->mode) &&2911oideq(&dst_other.oid, &ren1->pair->two->oid)) {2912/*2913* Added file on the other side identical to
2914* the file being renamed: clean merge.
2915* Also, there is no need to overwrite the
2916* file already in the working copy, so call
2917* update_file_flags() instead of
2918* update_file().
2919*/
2920if (update_file_flags(opt,2921ren1->pair->two,2922ren1_dst,29231, /* update_cache */29240 /* update_wd */))2925clean_merge = -1;2926} else if (!oideq(&dst_other.oid, null_oid())) {2927/*2928* Probably not a clean merge, but it's
2929* premature to set clean_merge to 0 here,
2930* because if the rename merges cleanly and
2931* the merge exactly matches the newly added
2932* file, then the merge will be clean.
2933*/
2934setup_rename_conflict_info(RENAME_ADD,2935opt, ren1, NULL);2936} else2937try_merge = 1;2938
2939if (clean_merge < 0)2940goto cleanup_and_return;2941if (try_merge) {2942struct diff_filespec *o, *a, *b;2943src_other.path = (char *)ren1_src;2944
2945o = ren1->pair->one;2946if (a_renames == renames1) {2947a = ren1->pair->two;2948b = &src_other;2949} else {2950b = ren1->pair->two;2951a = &src_other;2952}2953update_entry(ren1->dst_entry, o, a, b);2954setup_rename_conflict_info(RENAME_NORMAL,2955opt, ren1, NULL);2956}2957}2958}2959cleanup_and_return:2960string_list_clear(&a_by_dst, 0);2961string_list_clear(&b_by_dst, 0);2962
2963return clean_merge;2964}
2965
2966struct rename_info {2967struct string_list *head_renames;2968struct string_list *merge_renames;2969};2970
2971static void initial_cleanup_rename(struct diff_queue_struct *pairs,2972struct hashmap *dir_renames)2973{
2974struct hashmap_iter iter;2975struct dir_rename_entry *e;2976
2977hashmap_for_each_entry(dir_renames, &iter, e,2978ent /* member name */) {2979free(e->dir);2980strbuf_release(&e->new_dir);2981/* possible_new_dirs already cleared in get_directory_renames */2982}2983hashmap_clear_and_free(dir_renames, struct dir_rename_entry, ent);2984free(dir_renames);2985
2986free(pairs->queue);2987free(pairs);2988}
2989
2990static int detect_and_process_renames(struct merge_options *opt,2991struct tree *common,2992struct tree *head,2993struct tree *merge,2994struct string_list *entries,2995struct rename_info *ri)2996{
2997struct diff_queue_struct *head_pairs, *merge_pairs;2998struct hashmap *dir_re_head, *dir_re_merge;2999int clean = 1;3000
3001ri->head_renames = NULL;3002ri->merge_renames = NULL;3003
3004if (!merge_detect_rename(opt))3005return 1;3006
3007head_pairs = get_diffpairs(opt, common, head);3008merge_pairs = get_diffpairs(opt, common, merge);3009
3010if ((opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) ||3011(opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&3012!opt->priv->call_depth)) {3013dir_re_head = get_directory_renames(head_pairs);3014dir_re_merge = get_directory_renames(merge_pairs);3015
3016handle_directory_level_conflicts(opt,3017dir_re_head, head,3018dir_re_merge, merge);3019} else {3020dir_re_head = xmalloc(sizeof(*dir_re_head));3021dir_re_merge = xmalloc(sizeof(*dir_re_merge));3022dir_rename_init(dir_re_head);3023dir_rename_init(dir_re_merge);3024}3025
3026ri->head_renames = get_renames(opt, opt->branch1, head_pairs,3027dir_re_merge, dir_re_head, head,3028common, head, merge, entries,3029&clean);3030if (clean < 0)3031goto cleanup;3032ri->merge_renames = get_renames(opt, opt->branch2, merge_pairs,3033dir_re_head, dir_re_merge, merge,3034common, head, merge, entries,3035&clean);3036if (clean < 0)3037goto cleanup;3038clean &= process_renames(opt, ri->head_renames, ri->merge_renames);3039
3040cleanup:3041/*3042* Some cleanup is deferred until cleanup_renames() because the
3043* data structures are still needed and referenced in
3044* process_entry(). But there are a few things we can free now.
3045*/
3046initial_cleanup_rename(head_pairs, dir_re_head);3047initial_cleanup_rename(merge_pairs, dir_re_merge);3048
3049return clean;3050}
3051
3052static void final_cleanup_rename(struct string_list *rename)3053{
3054const struct rename *re;3055int i;3056
3057if (!rename)3058return;3059
3060for (i = 0; i < rename->nr; i++) {3061re = rename->items[i].util;3062diff_free_filepair(re->pair);3063if (re->src_entry->rename_conflict_info_owned)3064FREE_AND_NULL(re->src_entry->rename_conflict_info);3065if (re->dst_entry->rename_conflict_info_owned)3066FREE_AND_NULL(re->dst_entry->rename_conflict_info);3067}3068string_list_clear(rename, 1);3069free(rename);3070}
3071
3072static void final_cleanup_renames(struct rename_info *re_info)3073{
3074final_cleanup_rename(re_info->head_renames);3075final_cleanup_rename(re_info->merge_renames);3076}
3077
3078static int read_oid_strbuf(struct merge_options *opt,3079const struct object_id *oid,3080struct strbuf *dst)3081{
3082void *buf;3083enum object_type type;3084unsigned long size;3085buf = repo_read_object_file(the_repository, oid, &type, &size);3086if (!buf)3087return err(opt, _("cannot read object %s"), oid_to_hex(oid));3088if (type != OBJ_BLOB) {3089free(buf);3090return err(opt, _("object %s is not a blob"), oid_to_hex(oid));3091}3092strbuf_attach(dst, buf, size, size + 1);3093return 0;3094}
3095
3096static int blob_unchanged(struct merge_options *opt,3097const struct diff_filespec *o,3098const struct diff_filespec *a,3099int renormalize, const char *path)3100{
3101struct strbuf obuf = STRBUF_INIT;3102struct strbuf abuf = STRBUF_INIT;3103int ret = 0; /* assume changed for safety */3104struct index_state *idx = opt->repo->index;3105
3106if (a->mode != o->mode)3107return 0;3108if (oideq(&o->oid, &a->oid))3109return 1;3110if (!renormalize)3111return 0;3112
3113if (read_oid_strbuf(opt, &o->oid, &obuf) ||3114read_oid_strbuf(opt, &a->oid, &abuf))3115goto error_return;3116/*3117* Note: binary | is used so that both renormalizations are
3118* performed. Comparison can be skipped if both files are
3119* unchanged since their sha1s have already been compared.
3120*/
3121if (renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |3122renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))3123ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));3124
3125error_return:3126strbuf_release(&obuf);3127strbuf_release(&abuf);3128return ret;3129}
3130
3131static int handle_modify_delete(struct merge_options *opt,3132const char *path,3133const struct diff_filespec *o,3134const struct diff_filespec *a,3135const struct diff_filespec *b)3136{
3137const char *modify_branch, *delete_branch;3138const struct diff_filespec *changed;3139
3140if (is_valid(a)) {3141modify_branch = opt->branch1;3142delete_branch = opt->branch2;3143changed = a;3144} else {3145modify_branch = opt->branch2;3146delete_branch = opt->branch1;3147changed = b;3148}3149
3150return handle_change_delete(opt,3151path, NULL,3152o, changed,3153modify_branch, delete_branch,3154_("modify"), _("modified"));3155}
3156
3157static int handle_content_merge(struct merge_file_info *mfi,3158struct merge_options *opt,3159const char *path,3160int is_dirty,3161const struct diff_filespec *o,3162const struct diff_filespec *a,3163const struct diff_filespec *b,3164struct rename_conflict_info *ci)3165{
3166const char *reason = _("content");3167unsigned df_conflict_remains = 0;3168
3169if (!is_valid(o))3170reason = _("add/add");3171
3172assert(o->path && a->path && b->path);3173if (ci && dir_in_way(opt->repo->index, path, !opt->priv->call_depth,3174S_ISGITLINK(ci->ren1->pair->two->mode)))3175df_conflict_remains = 1;3176
3177if (merge_mode_and_contents(opt, o, a, b, path,3178opt->branch1, opt->branch2,3179opt->priv->call_depth * 2, mfi))3180return -1;3181
3182/*3183* We can skip updating the working tree file iff:
3184* a) The merge is clean
3185* b) The merge matches what was in HEAD (content, mode, pathname)
3186* c) The target path is usable (i.e. not involved in D/F conflict)
3187*/
3188if (mfi->clean && was_tracked_and_matches(opt, path, &mfi->blob) &&3189!df_conflict_remains) {3190int pos;3191struct cache_entry *ce;3192
3193output(opt, 3, _("Skipped %s (merged same as existing)"), path);3194if (add_cacheinfo(opt, &mfi->blob, path,31950, (!opt->priv->call_depth && !is_dirty), 0))3196return -1;3197/*3198* However, add_cacheinfo() will delete the old cache entry
3199* and add a new one. We need to copy over any skip_worktree
3200* flag to avoid making the file appear as if it were
3201* deleted by the user.
3202*/
3203pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));3204ce = opt->priv->orig_index.cache[pos];3205if (ce_skip_worktree(ce)) {3206pos = index_name_pos(opt->repo->index, path, strlen(path));3207ce = opt->repo->index->cache[pos];3208ce->ce_flags |= CE_SKIP_WORKTREE;3209}3210return mfi->clean;3211}3212
3213if (!mfi->clean) {3214if (S_ISGITLINK(mfi->blob.mode))3215reason = _("submodule");3216output(opt, 1, _("CONFLICT (%s): Merge conflict in %s"),3217reason, path);3218if (ci && !df_conflict_remains)3219if (update_stages(opt, path, o, a, b))3220return -1;3221}3222
3223if (df_conflict_remains || is_dirty) {3224char *new_path;3225if (opt->priv->call_depth) {3226remove_file_from_index(opt->repo->index, path);3227} else {3228if (!mfi->clean) {3229if (update_stages(opt, path, o, a, b))3230return -1;3231} else {3232int file_from_stage2 = was_tracked(opt, path);3233
3234if (update_stages(opt, path, NULL,3235file_from_stage2 ? &mfi->blob : NULL,3236file_from_stage2 ? NULL : &mfi->blob))3237return -1;3238}3239
3240}3241new_path = unique_path(opt, path, ci->ren1->branch);3242if (is_dirty) {3243output(opt, 1, _("Refusing to lose dirty file at %s"),3244path);3245}3246output(opt, 1, _("Adding as %s instead"), new_path);3247if (update_file(opt, 0, &mfi->blob, new_path)) {3248free(new_path);3249return -1;3250}3251free(new_path);3252mfi->clean = 0;3253} else if (update_file(opt, mfi->clean, &mfi->blob, path))3254return -1;3255return !is_dirty && mfi->clean;3256}
3257
3258static int handle_rename_normal(struct merge_options *opt,3259const char *path,3260const struct diff_filespec *o,3261const struct diff_filespec *a,3262const struct diff_filespec *b,3263struct rename_conflict_info *ci)3264{
3265struct rename *ren = ci->ren1;3266struct merge_file_info mfi;3267int clean;3268
3269/* Merge the content and write it out */3270clean = handle_content_merge(&mfi, opt, path, was_dirty(opt, path),3271o, a, b, ci);3272
3273if (clean &&3274opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&3275ren->dir_rename_original_dest) {3276if (update_stages(opt, path,3277&mfi.blob, &mfi.blob, &mfi.blob))3278return -1;3279clean = 0; /* not clean, but conflicted */3280}3281return clean;3282}
3283
3284static void dir_rename_warning(const char *msg,3285int is_add,3286int clean,3287struct merge_options *opt,3288struct rename *ren)3289{
3290const char *other_branch;3291other_branch = (ren->branch == opt->branch1 ?3292opt->branch2 : opt->branch1);3293if (is_add) {3294output(opt, clean ? 2 : 1, msg,3295ren->pair->one->path, ren->branch,3296other_branch, ren->pair->two->path);3297return;3298}3299output(opt, clean ? 2 : 1, msg,3300ren->pair->one->path, ren->dir_rename_original_dest, ren->branch,3301other_branch, ren->pair->two->path);3302}
3303static int warn_about_dir_renamed_entries(struct merge_options *opt,3304struct rename *ren)3305{
3306const char *msg;3307int clean = 1, is_add;3308
3309if (!ren)3310return clean;3311
3312/* Return early if ren was not affected/created by a directory rename */3313if (!ren->dir_rename_original_dest)3314return clean;3315
3316/* Sanity checks */3317assert(opt->detect_directory_renames > MERGE_DIRECTORY_RENAMES_NONE);3318assert(ren->dir_rename_original_type == 'A' ||3319ren->dir_rename_original_type == 'R');3320
3321/* Check whether to treat directory renames as a conflict */3322clean = (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE);3323
3324is_add = (ren->dir_rename_original_type == 'A');3325if (ren->dir_rename_original_type == 'A' && clean) {3326msg = _("Path updated: %s added in %s inside a "3327"directory that was renamed in %s; moving it to %s.");3328} else if (ren->dir_rename_original_type == 'A' && !clean) {3329msg = _("CONFLICT (file location): %s added in %s "3330"inside a directory that was renamed in %s, "3331"suggesting it should perhaps be moved to %s.");3332} else if (ren->dir_rename_original_type == 'R' && clean) {3333msg = _("Path updated: %s renamed to %s in %s, inside a "3334"directory that was renamed in %s; moving it to %s.");3335} else if (ren->dir_rename_original_type == 'R' && !clean) {3336msg = _("CONFLICT (file location): %s renamed to %s in %s, "3337"inside a directory that was renamed in %s, "3338"suggesting it should perhaps be moved to %s.");3339} else {3340BUG("Impossible dir_rename_original_type/clean combination");3341}3342dir_rename_warning(msg, is_add, clean, opt, ren);3343
3344return clean;3345}
3346
3347/* Per entry merge function */
3348static int process_entry(struct merge_options *opt,3349const char *path, struct stage_data *entry)3350{
3351int clean_merge = 1;3352int normalize = opt->renormalize;3353
3354struct diff_filespec *o = &entry->stages[1];3355struct diff_filespec *a = &entry->stages[2];3356struct diff_filespec *b = &entry->stages[3];3357int o_valid = is_valid(o);3358int a_valid = is_valid(a);3359int b_valid = is_valid(b);3360o->path = a->path = b->path = (char*)path;3361
3362entry->processed = 1;3363if (entry->rename_conflict_info) {3364struct rename_conflict_info *ci = entry->rename_conflict_info;3365struct diff_filespec *temp;3366int path_clean;3367
3368path_clean = warn_about_dir_renamed_entries(opt, ci->ren1);3369path_clean &= warn_about_dir_renamed_entries(opt, ci->ren2);3370
3371/*3372* For cases with a single rename, {o,a,b}->path have all been
3373* set to the rename target path; we need to set two of these
3374* back to the rename source.
3375* For rename/rename conflicts, we'll manually fix paths below.
3376*/
3377temp = (opt->branch1 == ci->ren1->branch) ? b : a;3378o->path = temp->path = ci->ren1->pair->one->path;3379if (ci->ren2) {3380assert(opt->branch1 == ci->ren1->branch);3381}3382
3383switch (ci->rename_type) {3384case RENAME_NORMAL:3385case RENAME_ONE_FILE_TO_ONE:3386clean_merge = handle_rename_normal(opt, path, o, a, b,3387ci);3388break;3389case RENAME_VIA_DIR:3390clean_merge = handle_rename_via_dir(opt, ci);3391break;3392case RENAME_ADD:3393/*3394* Probably unclean merge, but if the renamed file
3395* merges cleanly and the result can then be
3396* two-way merged cleanly with the added file, I
3397* guess it's a clean merge?
3398*/
3399clean_merge = handle_rename_add(opt, ci);3400break;3401case RENAME_DELETE:3402clean_merge = 0;3403if (handle_rename_delete(opt, ci))3404clean_merge = -1;3405break;3406case RENAME_ONE_FILE_TO_TWO:3407/*3408* Manually fix up paths; note:
3409* ren[12]->pair->one->path are equal.
3410*/
3411o->path = ci->ren1->pair->one->path;3412a->path = ci->ren1->pair->two->path;3413b->path = ci->ren2->pair->two->path;3414
3415clean_merge = 0;3416if (handle_rename_rename_1to2(opt, ci))3417clean_merge = -1;3418break;3419case RENAME_TWO_FILES_TO_ONE:3420/*3421* Manually fix up paths; note,
3422* ren[12]->pair->two->path are actually equal.
3423*/
3424o->path = NULL;3425a->path = ci->ren1->pair->two->path;3426b->path = ci->ren2->pair->two->path;3427
3428/*3429* Probably unclean merge, but if the two renamed
3430* files merge cleanly and the two resulting files
3431* can then be two-way merged cleanly, I guess it's
3432* a clean merge?
3433*/
3434clean_merge = handle_rename_rename_2to1(opt, ci);3435break;3436default:3437entry->processed = 0;3438break;3439}3440if (path_clean < clean_merge)3441clean_merge = path_clean;3442} else if (o_valid && (!a_valid || !b_valid)) {3443/* Case A: Deleted in one */3444if ((!a_valid && !b_valid) ||3445(!b_valid && blob_unchanged(opt, o, a, normalize, path)) ||3446(!a_valid && blob_unchanged(opt, o, b, normalize, path))) {3447/* Deleted in both or deleted in one and3448* unchanged in the other */
3449if (a_valid)3450output(opt, 2, _("Removing %s"), path);3451/* do not touch working file if it did not exist */3452remove_file(opt, 1, path, !a_valid);3453} else {3454/* Modify/delete; deleted side may have put a directory in the way */3455clean_merge = 0;3456if (handle_modify_delete(opt, path, o, a, b))3457clean_merge = -1;3458}3459} else if ((!o_valid && a_valid && !b_valid) ||3460(!o_valid && !a_valid && b_valid)) {3461/* Case B: Added in one. */3462/* [nothing|directory] -> ([nothing|directory], file) */3463
3464const char *add_branch;3465const char *other_branch;3466const char *conf;3467const struct diff_filespec *contents;3468
3469if (a_valid) {3470add_branch = opt->branch1;3471other_branch = opt->branch2;3472contents = a;3473conf = _("file/directory");3474} else {3475add_branch = opt->branch2;3476other_branch = opt->branch1;3477contents = b;3478conf = _("directory/file");3479}3480if (dir_in_way(opt->repo->index, path,3481!opt->priv->call_depth && !S_ISGITLINK(a->mode),34820)) {3483char *new_path = unique_path(opt, path, add_branch);3484clean_merge = 0;3485output(opt, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "3486"Adding %s as %s"),3487conf, path, other_branch, path, new_path);3488if (update_file(opt, 0, contents, new_path))3489clean_merge = -1;3490else if (opt->priv->call_depth)3491remove_file_from_index(opt->repo->index, path);3492free(new_path);3493} else {3494output(opt, 2, _("Adding %s"), path);3495/* do not overwrite file if already present */3496if (update_file_flags(opt, contents, path, 1, !a_valid))3497clean_merge = -1;3498}3499} else if (a_valid && b_valid) {3500if (!o_valid) {3501/* Case C: Added in both (check for same permissions) */3502output(opt, 1,3503_("CONFLICT (add/add): Merge conflict in %s"),3504path);3505clean_merge = handle_file_collision(opt,3506path, NULL, NULL,3507opt->branch1,3508opt->branch2,3509a, b);3510} else {3511/* case D: Modified in both, but differently. */3512struct merge_file_info mfi;3513int is_dirty = 0; /* unpack_trees would have bailed if dirty */3514clean_merge = handle_content_merge(&mfi, opt, path,3515is_dirty,3516o, a, b, NULL);3517}3518} else if (!o_valid && !a_valid && !b_valid) {3519/*3520* this entry was deleted altogether. a_mode == 0 means
3521* we had that path and want to actively remove it.
3522*/
3523remove_file(opt, 1, path, !a->mode);3524} else3525BUG("fatal merge failure, shouldn't happen.");3526
3527return clean_merge;3528}
3529
3530static int merge_trees_internal(struct merge_options *opt,3531struct tree *head,3532struct tree *merge,3533struct tree *merge_base,3534struct tree **result)3535{
3536struct index_state *istate = opt->repo->index;3537int code, clean;3538
3539if (opt->subtree_shift) {3540merge = shift_tree_object(opt->repo, head, merge,3541opt->subtree_shift);3542merge_base = shift_tree_object(opt->repo, head, merge_base,3543opt->subtree_shift);3544}3545
3546if (oideq(&merge_base->object.oid, &merge->object.oid)) {3547output(opt, 0, _("Already up to date."));3548*result = head;3549return 1;3550}3551
3552code = unpack_trees_start(opt, merge_base, head, merge);3553
3554if (code != 0) {3555if (show(opt, 4) || opt->priv->call_depth)3556err(opt, _("merging of trees %s and %s failed"),3557oid_to_hex(&head->object.oid),3558oid_to_hex(&merge->object.oid));3559unpack_trees_finish(opt);3560return -1;3561}3562
3563if (unmerged_index(istate)) {3564struct string_list *entries;3565struct rename_info re_info;3566int i;3567/*3568* Only need the hashmap while processing entries, so
3569* initialize it here and free it when we are done running
3570* through the entries. Keeping it in the merge_options as
3571* opposed to decaring a local hashmap is for convenience
3572* so that we don't have to pass it to around.
3573*/
3574hashmap_init(&opt->priv->current_file_dir_set, path_hashmap_cmp,3575NULL, 512);3576get_files_dirs(opt, head);3577get_files_dirs(opt, merge);3578
3579entries = get_unmerged(opt->repo->index);3580clean = detect_and_process_renames(opt, merge_base, head, merge,3581entries, &re_info);3582record_df_conflict_files(opt, entries);3583if (clean < 0)3584goto cleanup;3585for (i = entries->nr-1; 0 <= i; i--) {3586const char *path = entries->items[i].string;3587struct stage_data *e = entries->items[i].util;3588if (!e->processed) {3589int ret = process_entry(opt, path, e);3590if (!ret)3591clean = 0;3592else if (ret < 0) {3593clean = ret;3594goto cleanup;3595}3596}3597}3598for (i = 0; i < entries->nr; i++) {3599struct stage_data *e = entries->items[i].util;3600if (!e->processed)3601BUG("unprocessed path??? %s",3602entries->items[i].string);3603}3604
3605cleanup:3606final_cleanup_renames(&re_info);3607
3608string_list_clear(entries, 1);3609free(entries);3610
3611hashmap_clear_and_free(&opt->priv->current_file_dir_set,3612struct path_hashmap_entry, e);3613
3614if (clean < 0) {3615unpack_trees_finish(opt);3616return clean;3617}3618}3619else3620clean = 1;3621
3622unpack_trees_finish(opt);3623
3624if (opt->priv->call_depth &&3625!(*result = write_in_core_index_as_tree(opt->repo)))3626return -1;3627
3628return clean;3629}
3630
3631/*
3632* Merge the commits h1 and h2, returning a flag (int) indicating the
3633* cleanness of the merge. Also, if opt->priv->call_depth, create a
3634* virtual commit and write its location to *result.
3635*/
3636static int merge_recursive_internal(struct merge_options *opt,3637struct commit *h1,3638struct commit *h2,3639const struct commit_list *_merge_bases,3640struct commit **result)3641{
3642struct commit_list *merge_bases = copy_commit_list(_merge_bases);3643struct commit_list *iter;3644struct commit *merged_merge_bases;3645struct tree *result_tree;3646const char *ancestor_name;3647struct strbuf merge_base_abbrev = STRBUF_INIT;3648int ret;3649
3650if (show(opt, 4)) {3651output(opt, 4, _("Merging:"));3652output_commit_title(opt, h1);3653output_commit_title(opt, h2);3654}3655
3656if (!merge_bases) {3657if (repo_get_merge_bases(the_repository, h1, h2,3658&merge_bases) < 0) {3659ret = -1;3660goto out;3661}3662merge_bases = reverse_commit_list(merge_bases);3663}3664
3665if (show(opt, 5)) {3666unsigned cnt = commit_list_count(merge_bases);3667
3668output(opt, 5, Q_("found %u common ancestor:",3669"found %u common ancestors:", cnt), cnt);3670for (iter = merge_bases; iter; iter = iter->next)3671output_commit_title(opt, iter->item);3672}3673
3674merged_merge_bases = pop_commit(&merge_bases);3675if (!merged_merge_bases) {3676/* if there is no common ancestor, use an empty tree */3677struct tree *tree;3678
3679tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);3680merged_merge_bases = make_virtual_commit(opt->repo, tree,3681"ancestor");3682ancestor_name = "empty tree";3683} else if (opt->ancestor && !opt->priv->call_depth) {3684ancestor_name = opt->ancestor;3685} else if (merge_bases) {3686ancestor_name = "merged common ancestors";3687} else {3688strbuf_add_unique_abbrev(&merge_base_abbrev,3689&merged_merge_bases->object.oid,3690DEFAULT_ABBREV);3691ancestor_name = merge_base_abbrev.buf;3692}3693
3694for (iter = merge_bases; iter; iter = iter->next) {3695const char *saved_b1, *saved_b2;3696opt->priv->call_depth++;3697/*3698* When the merge fails, the result contains files
3699* with conflict markers. The cleanness flag is
3700* ignored (unless indicating an error), it was never
3701* actually used, as result of merge_trees has always
3702* overwritten it: the committed "conflicts" were
3703* already resolved.
3704*/
3705discard_index(opt->repo->index);3706saved_b1 = opt->branch1;3707saved_b2 = opt->branch2;3708opt->branch1 = "Temporary merge branch 1";3709opt->branch2 = "Temporary merge branch 2";3710if (merge_recursive_internal(opt, merged_merge_bases, iter->item,3711NULL, &merged_merge_bases) < 0) {3712ret = -1;3713goto out;3714}3715opt->branch1 = saved_b1;3716opt->branch2 = saved_b2;3717opt->priv->call_depth--;3718
3719if (!merged_merge_bases) {3720ret = err(opt, _("merge returned no commit"));3721goto out;3722}3723}3724
3725/*3726* FIXME: Since merge_recursive_internal() is only ever called by
3727* places that ensure the index is loaded first
3728* (e.g. builtin/merge.c, rebase/sequencer, etc.), in the common
3729* case where the merge base was unique that means when we get here
3730* we immediately discard the index and re-read it, which is a
3731* complete waste of time. We should only be discarding and
3732* re-reading if we were forced to recurse.
3733*/
3734discard_index(opt->repo->index);3735if (!opt->priv->call_depth)3736repo_read_index(opt->repo);3737
3738opt->ancestor = ancestor_name;3739ret = merge_trees_internal(opt,3740repo_get_commit_tree(opt->repo, h1),3741repo_get_commit_tree(opt->repo, h2),3742repo_get_commit_tree(opt->repo,3743merged_merge_bases),3744&result_tree);3745opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */3746if (ret < 0) {3747flush_output(opt);3748goto out;3749}3750
3751if (opt->priv->call_depth) {3752*result = make_virtual_commit(opt->repo, result_tree,3753"merged tree");3754commit_list_insert(h1, &(*result)->parents);3755commit_list_insert(h2, &(*result)->parents->next);3756}3757
3758out:3759strbuf_release(&merge_base_abbrev);3760free_commit_list(merge_bases);3761return ret;3762}
3763
3764static int merge_start(struct merge_options *opt, struct tree *head)3765{
3766struct strbuf sb = STRBUF_INIT;3767
3768/* Sanity checks on opt */3769assert(opt->repo);3770
3771assert(opt->branch1 && opt->branch2);3772
3773assert(opt->detect_renames >= -1 &&3774opt->detect_renames <= DIFF_DETECT_COPY);3775assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&3776opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);3777assert(opt->rename_limit >= -1);3778assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);3779assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);3780
3781assert(opt->xdl_opts >= 0);3782assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&3783opt->recursive_variant <= MERGE_VARIANT_THEIRS);3784
3785assert(opt->verbosity >= 0 && opt->verbosity <= 5);3786assert(opt->buffer_output <= 2);3787assert(opt->obuf.len == 0);3788
3789assert(opt->priv == NULL);3790
3791/* Not supported; option specific to merge-ort */3792assert(!opt->record_conflict_msgs_as_headers);3793assert(!opt->msg_header_prefix);3794
3795/* Sanity check on repo state; index must match head */3796if (repo_index_has_changes(opt->repo, head, &sb)) {3797err(opt, _("Your local changes to the following files would be overwritten by merge:\n %s"),3798sb.buf);3799strbuf_release(&sb);3800return -1;3801}3802
3803CALLOC_ARRAY(opt->priv, 1);3804string_list_init_dup(&opt->priv->df_conflict_file_set);3805return 0;3806}
3807
3808static void merge_finalize(struct merge_options *opt)3809{
3810flush_output(opt);3811if (!opt->priv->call_depth && opt->buffer_output < 2)3812strbuf_release(&opt->obuf);3813if (show(opt, 2))3814diff_warn_rename_limit("merge.renamelimit",3815opt->priv->needed_rename_limit, 0);3816hashmap_clear_and_free(&opt->priv->current_file_dir_set,3817struct path_hashmap_entry, e);3818string_list_clear(&opt->priv->df_conflict_file_set, 0);3819FREE_AND_NULL(opt->priv);3820}
3821
3822int merge_trees(struct merge_options *opt,3823struct tree *head,3824struct tree *merge,3825struct tree *merge_base)3826{
3827int clean;3828struct tree *ignored;3829
3830assert(opt->ancestor != NULL);3831
3832if (merge_start(opt, head))3833return -1;3834clean = merge_trees_internal(opt, head, merge, merge_base, &ignored);3835merge_finalize(opt);3836
3837return clean;3838}
3839
3840int merge_recursive(struct merge_options *opt,3841struct commit *h1,3842struct commit *h2,3843const struct commit_list *merge_bases,3844struct commit **result)3845{
3846int clean;3847
3848assert(opt->ancestor == NULL ||3849!strcmp(opt->ancestor, "constructed merge base"));3850
3851prepare_repo_settings(opt->repo);3852opt->repo->settings.command_requires_full_index = 1;3853
3854if (merge_start(opt, repo_get_commit_tree(opt->repo, h1)))3855return -1;3856clean = merge_recursive_internal(opt, h1, h2, merge_bases, result);3857merge_finalize(opt);3858
3859return clean;3860}
3861
3862static struct commit *get_ref(struct repository *repo,3863const struct object_id *oid,3864const char *name)3865{
3866struct object *object;3867
3868object = deref_tag(repo, parse_object(repo, oid),3869name, strlen(name));3870if (!object)3871return NULL;3872if (object->type == OBJ_TREE)3873return make_virtual_commit(repo, (struct tree*)object, name);3874if (object->type != OBJ_COMMIT)3875return NULL;3876if (repo_parse_commit(repo, (struct commit *)object))3877return NULL;3878return (struct commit *)object;3879}
3880
3881int merge_recursive_generic(struct merge_options *opt,3882const struct object_id *head,3883const struct object_id *merge,3884int num_merge_bases,3885const struct object_id *merge_bases,3886struct commit **result)3887{
3888int clean;3889struct lock_file lock = LOCK_INIT;3890struct commit *head_commit = get_ref(opt->repo, head, opt->branch1);3891struct commit *next_commit = get_ref(opt->repo, merge, opt->branch2);3892struct commit_list *ca = NULL;3893
3894if (merge_bases) {3895int i;3896for (i = 0; i < num_merge_bases; ++i) {3897struct commit *base;3898if (!(base = get_ref(opt->repo, &merge_bases[i],3899oid_to_hex(&merge_bases[i]))))3900return err(opt, _("Could not parse object '%s'"),3901oid_to_hex(&merge_bases[i]));3902commit_list_insert(base, &ca);3903}3904if (num_merge_bases == 1)3905opt->ancestor = "constructed merge base";3906}3907
3908repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);3909clean = merge_recursive(opt, head_commit, next_commit, ca,3910result);3911free_commit_list(ca);3912if (clean < 0) {3913rollback_lock_file(&lock);3914return clean;3915}3916
3917if (write_locked_index(opt->repo->index, &lock,3918COMMIT_LOCK | SKIP_IF_UNCHANGED))3919return err(opt, _("Unable to write index."));3920
3921return clean ? 0 : 1;3922}
3923
3924static void merge_recursive_config(struct merge_options *opt, int ui)3925{
3926char *value = NULL;3927int renormalize = 0;3928git_config_get_int("merge.verbosity", &opt->verbosity);3929git_config_get_int("diff.renamelimit", &opt->rename_limit);3930git_config_get_int("merge.renamelimit", &opt->rename_limit);3931git_config_get_bool("merge.renormalize", &renormalize);3932opt->renormalize = renormalize;3933if (!git_config_get_string("diff.renames", &value)) {3934opt->detect_renames = git_config_rename("diff.renames", value);3935free(value);3936}3937if (!git_config_get_string("merge.renames", &value)) {3938opt->detect_renames = git_config_rename("merge.renames", value);3939free(value);3940}3941if (!git_config_get_string("merge.directoryrenames", &value)) {3942int boolval = git_parse_maybe_bool(value);3943if (0 <= boolval) {3944opt->detect_directory_renames = boolval ?3945MERGE_DIRECTORY_RENAMES_TRUE :3946MERGE_DIRECTORY_RENAMES_NONE;3947} else if (!strcasecmp(value, "conflict")) {3948opt->detect_directory_renames =3949MERGE_DIRECTORY_RENAMES_CONFLICT;3950} /* avoid erroring on values from future versions of git */3951free(value);3952}3953if (ui) {3954if (!git_config_get_string("diff.algorithm", &value)) {3955long diff_algorithm = parse_algorithm_value(value);3956if (diff_algorithm < 0)3957die(_("unknown value for config '%s': %s"), "diff.algorithm", value);3958opt->xdl_opts = (opt->xdl_opts & ~XDF_DIFF_ALGORITHM_MASK) | diff_algorithm;3959free(value);3960}3961}3962git_config(git_xmerge_config, NULL);3963}
3964
3965static void init_merge_options(struct merge_options *opt,3966struct repository *repo, int ui)3967{
3968const char *merge_verbosity;3969memset(opt, 0, sizeof(struct merge_options));3970
3971opt->repo = repo;3972
3973opt->detect_renames = -1;3974opt->detect_directory_renames = MERGE_DIRECTORY_RENAMES_CONFLICT;3975opt->rename_limit = -1;3976
3977opt->verbosity = 2;3978opt->buffer_output = 1;3979strbuf_init(&opt->obuf, 0);3980
3981opt->renormalize = 0;3982
3983opt->conflict_style = -1;3984
3985merge_recursive_config(opt, ui);3986merge_verbosity = getenv("GIT_MERGE_VERBOSITY");3987if (merge_verbosity)3988opt->verbosity = strtol(merge_verbosity, NULL, 10);3989if (opt->verbosity >= 5)3990opt->buffer_output = 0;3991}
3992
3993void init_ui_merge_options(struct merge_options *opt,3994struct repository *repo)3995{
3996init_merge_options(opt, repo, 1);3997}
3998
3999void init_basic_merge_options(struct merge_options *opt,4000struct repository *repo)4001{
4002init_merge_options(opt, repo, 0);4003}
4004
4005/*
4006* For now, members of merge_options do not need deep copying, but
4007* it may change in the future, in which case we would need to update
4008* this, and also make a matching change to clear_merge_options() to
4009* release the resources held by a copied instance.
4010*/
4011void copy_merge_options(struct merge_options *dst, struct merge_options *src)4012{
4013*dst = *src;4014}
4015
4016void clear_merge_options(struct merge_options *opt UNUSED)4017{
4018; /* no-op as our copy is shallow right now */4019}
4020
4021int parse_merge_opt(struct merge_options *opt, const char *s)4022{
4023const char *arg;4024
4025if (!s || !*s)4026return -1;4027if (!strcmp(s, "ours"))4028opt->recursive_variant = MERGE_VARIANT_OURS;4029else if (!strcmp(s, "theirs"))4030opt->recursive_variant = MERGE_VARIANT_THEIRS;4031else if (!strcmp(s, "subtree"))4032opt->subtree_shift = "";4033else if (skip_prefix(s, "subtree=", &arg))4034opt->subtree_shift = arg;4035else if (!strcmp(s, "patience"))4036opt->xdl_opts = DIFF_WITH_ALG(opt, PATIENCE_DIFF);4037else if (!strcmp(s, "histogram"))4038opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);4039else if (skip_prefix(s, "diff-algorithm=", &arg)) {4040long value = parse_algorithm_value(arg);4041if (value < 0)4042return -1;4043/* clear out previous settings */4044DIFF_XDL_CLR(opt, NEED_MINIMAL);4045opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;4046opt->xdl_opts |= value;4047}4048else if (!strcmp(s, "ignore-space-change"))4049DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);4050else if (!strcmp(s, "ignore-all-space"))4051DIFF_XDL_SET(opt, IGNORE_WHITESPACE);4052else if (!strcmp(s, "ignore-space-at-eol"))4053DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);4054else if (!strcmp(s, "ignore-cr-at-eol"))4055DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);4056else if (!strcmp(s, "renormalize"))4057opt->renormalize = 1;4058else if (!strcmp(s, "no-renormalize"))4059opt->renormalize = 0;4060else if (!strcmp(s, "no-renames"))4061opt->detect_renames = 0;4062else if (!strcmp(s, "find-renames")) {4063opt->detect_renames = 1;4064opt->rename_score = 0;4065}4066else if (skip_prefix(s, "find-renames=", &arg) ||4067skip_prefix(s, "rename-threshold=", &arg)) {4068if ((opt->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)4069return -1;4070opt->detect_renames = 1;4071}4072/*4073* Please update $__git_merge_strategy_options in
4074* git-completion.bash when you add new options
4075*/
4076else4077return -1;4078return 0;4079}
4080