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#include"cache.h" 7#include"config.h" 8#include"advice.h" 9#include"lockfile.h" 10#include"cache-tree.h" 11#include"object-store.h" 12#include"repository.h" 13#include"commit.h" 14#include"blob.h" 15#include"builtin.h" 16#include"tree-walk.h" 17#include"diff.h" 18#include"diffcore.h" 19#include"tag.h" 20#include"alloc.h" 21#include"unpack-trees.h" 22#include"string-list.h" 23#include"xdiff-interface.h" 24#include"ll-merge.h" 25#include"attr.h" 26#include"merge-recursive.h" 27#include"dir.h" 28#include"submodule.h" 29#include"revision.h" 30#include"commit-reach.h" 31 32struct path_hashmap_entry { 33struct hashmap_entry e; 34char path[FLEX_ARRAY]; 35}; 36 37static intpath_hashmap_cmp(const void*cmp_data, 38const void*entry, 39const void*entry_or_key, 40const void*keydata) 41{ 42const struct path_hashmap_entry *a = entry; 43const struct path_hashmap_entry *b = entry_or_key; 44const char*key = keydata; 45 46if(ignore_case) 47returnstrcasecmp(a->path, key ? key : b->path); 48else 49returnstrcmp(a->path, key ? key : b->path); 50} 51 52static unsigned intpath_hash(const char*path) 53{ 54return ignore_case ?strihash(path) :strhash(path); 55} 56 57static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap, 58char*dir) 59{ 60struct dir_rename_entry key; 61 62if(dir == NULL) 63return NULL; 64hashmap_entry_init(&key,strhash(dir)); 65 key.dir = dir; 66returnhashmap_get(hashmap, &key, NULL); 67} 68 69static intdir_rename_cmp(const void*unused_cmp_data, 70const void*entry, 71const void*entry_or_key, 72const void*unused_keydata) 73{ 74const struct dir_rename_entry *e1 = entry; 75const struct dir_rename_entry *e2 = entry_or_key; 76 77returnstrcmp(e1->dir, e2->dir); 78} 79 80static voiddir_rename_init(struct hashmap *map) 81{ 82hashmap_init(map, dir_rename_cmp, NULL,0); 83} 84 85static voiddir_rename_entry_init(struct dir_rename_entry *entry, 86char*directory) 87{ 88hashmap_entry_init(entry,strhash(directory)); 89 entry->dir = directory; 90 entry->non_unique_new_dir =0; 91strbuf_init(&entry->new_dir,0); 92string_list_init(&entry->possible_new_dirs,0); 93} 94 95static struct collision_entry *collision_find_entry(struct hashmap *hashmap, 96char*target_file) 97{ 98struct collision_entry key; 99 100hashmap_entry_init(&key,strhash(target_file)); 101 key.target_file = target_file; 102returnhashmap_get(hashmap, &key, NULL); 103} 104 105static intcollision_cmp(void*unused_cmp_data, 106const struct collision_entry *e1, 107const struct collision_entry *e2, 108const void*unused_keydata) 109{ 110returnstrcmp(e1->target_file, e2->target_file); 111} 112 113static voidcollision_init(struct hashmap *map) 114{ 115hashmap_init(map, (hashmap_cmp_fn) collision_cmp, NULL,0); 116} 117 118static voidflush_output(struct merge_options *opt) 119{ 120if(opt->buffer_output <2&& opt->obuf.len) { 121fputs(opt->obuf.buf, stdout); 122strbuf_reset(&opt->obuf); 123} 124} 125 126static interr(struct merge_options *opt,const char*err, ...) 127{ 128va_list params; 129 130if(opt->buffer_output <2) 131flush_output(opt); 132else{ 133strbuf_complete(&opt->obuf,'\n'); 134strbuf_addstr(&opt->obuf,"error: "); 135} 136va_start(params, err); 137strbuf_vaddf(&opt->obuf, err, params); 138va_end(params); 139if(opt->buffer_output >1) 140strbuf_addch(&opt->obuf,'\n'); 141else{ 142error("%s", opt->obuf.buf); 143strbuf_reset(&opt->obuf); 144} 145 146return-1; 147} 148 149static struct tree *shift_tree_object(struct repository *repo, 150struct tree *one,struct tree *two, 151const char*subtree_shift) 152{ 153struct object_id shifted; 154 155if(!*subtree_shift) { 156shift_tree(&one->object.oid, &two->object.oid, &shifted,0); 157}else{ 158shift_tree_by(&one->object.oid, &two->object.oid, &shifted, 159 subtree_shift); 160} 161if(oideq(&two->object.oid, &shifted)) 162return two; 163returnlookup_tree(repo, &shifted); 164} 165 166static struct commit *make_virtual_commit(struct repository *repo, 167struct tree *tree, 168const char*comment) 169{ 170struct commit *commit =alloc_commit_node(repo); 171 172set_merge_remote_desc(commit, comment, (struct object *)commit); 173 commit->maybe_tree = tree; 174 commit->object.parsed =1; 175return commit; 176} 177 178/* 179 * Since we use get_tree_entry(), which does not put the read object into 180 * the object pool, we cannot rely on a == b. 181 */ 182static intoid_eq(const struct object_id *a,const struct object_id *b) 183{ 184if(!a && !b) 185return2; 186return a && b &&oideq(a, b); 187} 188 189enum rename_type { 190 RENAME_NORMAL =0, 191 RENAME_VIA_DIR, 192 RENAME_ADD, 193 RENAME_DELETE, 194 RENAME_ONE_FILE_TO_ONE, 195 RENAME_ONE_FILE_TO_TWO, 196 RENAME_TWO_FILES_TO_ONE 197}; 198 199/* 200 * Since we want to write the index eventually, we cannot reuse the index 201 * for these (temporary) data. 202 */ 203struct stage_data { 204struct diff_filespec stages[4];/* mostly for oid & mode; maybe path */ 205struct rename_conflict_info *rename_conflict_info; 206unsigned processed:1; 207}; 208 209struct rename { 210struct diff_filepair *pair; 211const char*branch;/* branch that the rename occurred on */ 212/* 213 * Purpose of src_entry and dst_entry: 214 * 215 * If 'before' is renamed to 'after' then src_entry will contain 216 * the versions of 'before' from the merge_base, HEAD, and MERGE in 217 * stages 1, 2, and 3; dst_entry will contain the respective 218 * versions of 'after' in corresponding locations. Thus, we have a 219 * total of six modes and oids, though some will be null. (Stage 0 220 * is ignored; we're interested in handling conflicts.) 221 * 222 * Since we don't turn on break-rewrites by default, neither 223 * src_entry nor dst_entry can have all three of their stages have 224 * non-null oids, meaning at most four of the six will be non-null. 225 * Also, since this is a rename, both src_entry and dst_entry will 226 * have at least one non-null oid, meaning at least two will be 227 * non-null. Of the six oids, a typical rename will have three be 228 * non-null. Only two implies a rename/delete, and four implies a 229 * rename/add. 230 */ 231struct stage_data *src_entry; 232struct stage_data *dst_entry; 233unsigned add_turned_into_rename:1; 234unsigned processed:1; 235}; 236 237struct rename_conflict_info { 238enum rename_type rename_type; 239struct rename *ren1; 240struct rename *ren2; 241}; 242 243staticinlinevoidsetup_rename_conflict_info(enum rename_type rename_type, 244struct merge_options *opt, 245struct rename *ren1, 246struct rename *ren2) 247{ 248struct rename_conflict_info *ci; 249 250/* 251 * When we have two renames involved, it's easiest to get the 252 * correct things into stage 2 and 3, and to make sure that the 253 * content merge puts HEAD before the other branch if we just 254 * ensure that branch1 == opt->branch1. So, simply flip arguments 255 * around if we don't have that. 256 */ 257if(ren2 && ren1->branch != opt->branch1) { 258setup_rename_conflict_info(rename_type, opt, ren2, ren1); 259return; 260} 261 262 ci =xcalloc(1,sizeof(struct rename_conflict_info)); 263 ci->rename_type = rename_type; 264 ci->ren1 = ren1; 265 ci->ren2 = ren2; 266 267 ci->ren1->dst_entry->processed =0; 268 ci->ren1->dst_entry->rename_conflict_info = ci; 269if(ren2) { 270 ci->ren2->dst_entry->rename_conflict_info = ci; 271} 272} 273 274static intshow(struct merge_options *opt,int v) 275{ 276return(!opt->call_depth && opt->verbosity >= v) || opt->verbosity >=5; 277} 278 279__attribute__((format(printf,3,4))) 280static voidoutput(struct merge_options *opt,int v,const char*fmt, ...) 281{ 282va_list ap; 283 284if(!show(opt, v)) 285return; 286 287strbuf_addchars(&opt->obuf,' ', opt->call_depth *2); 288 289va_start(ap, fmt); 290strbuf_vaddf(&opt->obuf, fmt, ap); 291va_end(ap); 292 293strbuf_addch(&opt->obuf,'\n'); 294if(!opt->buffer_output) 295flush_output(opt); 296} 297 298static voidoutput_commit_title(struct merge_options *opt,struct commit *commit) 299{ 300struct merge_remote_desc *desc; 301 302strbuf_addchars(&opt->obuf,' ', opt->call_depth *2); 303 desc =merge_remote_util(commit); 304if(desc) 305strbuf_addf(&opt->obuf,"virtual%s\n", desc->name); 306else{ 307strbuf_add_unique_abbrev(&opt->obuf, &commit->object.oid, 308 DEFAULT_ABBREV); 309strbuf_addch(&opt->obuf,' '); 310if(parse_commit(commit) !=0) 311strbuf_addstr(&opt->obuf,_("(bad commit)\n")); 312else{ 313const char*title; 314const char*msg =get_commit_buffer(commit, NULL); 315int len =find_commit_subject(msg, &title); 316if(len) 317strbuf_addf(&opt->obuf,"%.*s\n", len, title); 318unuse_commit_buffer(commit, msg); 319} 320} 321flush_output(opt); 322} 323 324static intadd_cacheinfo(struct merge_options *opt, 325const struct diff_filespec *blob, 326const char*path,int stage,int refresh,int options) 327{ 328struct index_state *istate = opt->repo->index; 329struct cache_entry *ce; 330int ret; 331 332 ce =make_cache_entry(istate, blob->mode, &blob->oid, path, stage,0); 333if(!ce) 334returnerr(opt,_("add_cacheinfo failed for path '%s'; merge aborting."), path); 335 336 ret =add_index_entry(istate, ce, options); 337if(refresh) { 338struct cache_entry *nce; 339 340 nce =refresh_cache_entry(istate, ce, 341 CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING); 342if(!nce) 343returnerr(opt,_("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path); 344if(nce != ce) 345 ret =add_index_entry(istate, nce, options); 346} 347return ret; 348} 349 350static voidinit_tree_desc_from_tree(struct tree_desc *desc,struct tree *tree) 351{ 352parse_tree(tree); 353init_tree_desc(desc, tree->buffer, tree->size); 354} 355 356static intunpack_trees_start(struct merge_options *opt, 357struct tree *common, 358struct tree *head, 359struct tree *merge) 360{ 361int rc; 362struct tree_desc t[3]; 363struct index_state tmp_index = { NULL }; 364 365memset(&opt->unpack_opts,0,sizeof(opt->unpack_opts)); 366if(opt->call_depth) 367 opt->unpack_opts.index_only =1; 368else 369 opt->unpack_opts.update =1; 370 opt->unpack_opts.merge =1; 371 opt->unpack_opts.head_idx =2; 372 opt->unpack_opts.fn = threeway_merge; 373 opt->unpack_opts.src_index = opt->repo->index; 374 opt->unpack_opts.dst_index = &tmp_index; 375 opt->unpack_opts.aggressive = !merge_detect_rename(opt); 376setup_unpack_trees_porcelain(&opt->unpack_opts,"merge"); 377 378init_tree_desc_from_tree(t+0, common); 379init_tree_desc_from_tree(t+1, head); 380init_tree_desc_from_tree(t+2, merge); 381 382 rc =unpack_trees(3, t, &opt->unpack_opts); 383cache_tree_free(&opt->repo->index->cache_tree); 384 385/* 386 * Update opt->repo->index to match the new results, AFTER saving a copy 387 * in opt->orig_index. Update src_index to point to the saved copy. 388 * (verify_uptodate() checks src_index, and the original index is 389 * the one that had the necessary modification timestamps.) 390 */ 391 opt->orig_index = *opt->repo->index; 392*opt->repo->index = tmp_index; 393 opt->unpack_opts.src_index = &opt->orig_index; 394 395return rc; 396} 397 398static voidunpack_trees_finish(struct merge_options *opt) 399{ 400discard_index(&opt->orig_index); 401clear_unpack_trees_porcelain(&opt->unpack_opts); 402} 403 404struct tree *write_tree_from_memory(struct merge_options *opt) 405{ 406struct tree *result = NULL; 407struct index_state *istate = opt->repo->index; 408 409if(unmerged_index(istate)) { 410int i; 411fprintf(stderr,"BUG: There are unmerged index entries:\n"); 412for(i =0; i < istate->cache_nr; i++) { 413const struct cache_entry *ce = istate->cache[i]; 414if(ce_stage(ce)) 415fprintf(stderr,"BUG:%d%.*s\n",ce_stage(ce), 416(int)ce_namelen(ce), ce->name); 417} 418BUG("unmerged index entries in merge-recursive.c"); 419} 420 421if(!istate->cache_tree) 422 istate->cache_tree =cache_tree(); 423 424if(!cache_tree_fully_valid(istate->cache_tree) && 425cache_tree_update(istate,0) <0) { 426err(opt,_("error building trees")); 427return NULL; 428} 429 430 result =lookup_tree(opt->repo, &istate->cache_tree->oid); 431 432return result; 433} 434 435static intsave_files_dirs(const struct object_id *oid, 436struct strbuf *base,const char*path, 437unsigned int mode,int stage,void*context) 438{ 439struct path_hashmap_entry *entry; 440int baselen = base->len; 441struct merge_options *opt = context; 442 443strbuf_addstr(base, path); 444 445FLEX_ALLOC_MEM(entry, path, base->buf, base->len); 446hashmap_entry_init(entry,path_hash(entry->path)); 447hashmap_add(&opt->current_file_dir_set, entry); 448 449strbuf_setlen(base, baselen); 450return(S_ISDIR(mode) ? READ_TREE_RECURSIVE :0); 451} 452 453static voidget_files_dirs(struct merge_options *opt,struct tree *tree) 454{ 455struct pathspec match_all; 456memset(&match_all,0,sizeof(match_all)); 457read_tree_recursive(the_repository, tree,"",0,0, 458&match_all, save_files_dirs, opt); 459} 460 461static intget_tree_entry_if_blob(const struct object_id *tree, 462const char*path, 463struct diff_filespec *dfs) 464{ 465int ret; 466 467 ret =get_tree_entry(tree, path, &dfs->oid, &dfs->mode); 468if(S_ISDIR(dfs->mode)) { 469oidcpy(&dfs->oid, &null_oid); 470 dfs->mode =0; 471} 472return ret; 473} 474 475/* 476 * Returns an index_entry instance which doesn't have to correspond to 477 * a real cache entry in Git's index. 478 */ 479static struct stage_data *insert_stage_data(const char*path, 480struct tree *o,struct tree *a,struct tree *b, 481struct string_list *entries) 482{ 483struct string_list_item *item; 484struct stage_data *e =xcalloc(1,sizeof(struct stage_data)); 485get_tree_entry_if_blob(&o->object.oid, path, &e->stages[1]); 486get_tree_entry_if_blob(&a->object.oid, path, &e->stages[2]); 487get_tree_entry_if_blob(&b->object.oid, path, &e->stages[3]); 488 item =string_list_insert(entries, path); 489 item->util = e; 490return e; 491} 492 493/* 494 * Create a dictionary mapping file names to stage_data objects. The 495 * dictionary contains one entry for every path with a non-zero stage entry. 496 */ 497static struct string_list *get_unmerged(struct index_state *istate) 498{ 499struct string_list *unmerged =xcalloc(1,sizeof(struct string_list)); 500int i; 501 502 unmerged->strdup_strings =1; 503 504for(i =0; i < istate->cache_nr; i++) { 505struct string_list_item *item; 506struct stage_data *e; 507const struct cache_entry *ce = istate->cache[i]; 508if(!ce_stage(ce)) 509continue; 510 511 item =string_list_lookup(unmerged, ce->name); 512if(!item) { 513 item =string_list_insert(unmerged, ce->name); 514 item->util =xcalloc(1,sizeof(struct stage_data)); 515} 516 e = item->util; 517 e->stages[ce_stage(ce)].mode = ce->ce_mode; 518oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid); 519} 520 521return unmerged; 522} 523 524static intstring_list_df_name_compare(const char*one,const char*two) 525{ 526int onelen =strlen(one); 527int twolen =strlen(two); 528/* 529 * Here we only care that entries for D/F conflicts are 530 * adjacent, in particular with the file of the D/F conflict 531 * appearing before files below the corresponding directory. 532 * The order of the rest of the list is irrelevant for us. 533 * 534 * To achieve this, we sort with df_name_compare and provide 535 * the mode S_IFDIR so that D/F conflicts will sort correctly. 536 * We use the mode S_IFDIR for everything else for simplicity, 537 * since in other cases any changes in their order due to 538 * sorting cause no problems for us. 539 */ 540int cmp =df_name_compare(one, onelen, S_IFDIR, 541 two, twolen, S_IFDIR); 542/* 543 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure 544 * that 'foo' comes before 'foo/bar'. 545 */ 546if(cmp) 547return cmp; 548return onelen - twolen; 549} 550 551static voidrecord_df_conflict_files(struct merge_options *opt, 552struct string_list *entries) 553{ 554/* If there is a D/F conflict and the file for such a conflict 555 * currently exists in the working tree, we want to allow it to be 556 * removed to make room for the corresponding directory if needed. 557 * The files underneath the directories of such D/F conflicts will 558 * be processed before the corresponding file involved in the D/F 559 * conflict. If the D/F directory ends up being removed by the 560 * merge, then we won't have to touch the D/F file. If the D/F 561 * directory needs to be written to the working copy, then the D/F 562 * file will simply be removed (in make_room_for_path()) to make 563 * room for the necessary paths. Note that if both the directory 564 * and the file need to be present, then the D/F file will be 565 * reinstated with a new unique name at the time it is processed. 566 */ 567struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP; 568const char*last_file = NULL; 569int last_len =0; 570int i; 571 572/* 573 * If we're merging merge-bases, we don't want to bother with 574 * any working directory changes. 575 */ 576if(opt->call_depth) 577return; 578 579/* Ensure D/F conflicts are adjacent in the entries list. */ 580for(i =0; i < entries->nr; i++) { 581struct string_list_item *next = &entries->items[i]; 582string_list_append(&df_sorted_entries, next->string)->util = 583 next->util; 584} 585 df_sorted_entries.cmp = string_list_df_name_compare; 586string_list_sort(&df_sorted_entries); 587 588string_list_clear(&opt->df_conflict_file_set,1); 589for(i =0; i < df_sorted_entries.nr; i++) { 590const char*path = df_sorted_entries.items[i].string; 591int len =strlen(path); 592struct stage_data *e = df_sorted_entries.items[i].util; 593 594/* 595 * Check if last_file & path correspond to a D/F conflict; 596 * i.e. whether path is last_file+'/'+<something>. 597 * If so, record that it's okay to remove last_file to make 598 * room for path and friends if needed. 599 */ 600if(last_file && 601 len > last_len && 602memcmp(path, last_file, last_len) ==0&& 603 path[last_len] =='/') { 604string_list_insert(&opt->df_conflict_file_set, last_file); 605} 606 607/* 608 * Determine whether path could exist as a file in the 609 * working directory as a possible D/F conflict. This 610 * will only occur when it exists in stage 2 as a 611 * file. 612 */ 613if(S_ISREG(e->stages[2].mode) ||S_ISLNK(e->stages[2].mode)) { 614 last_file = path; 615 last_len = len; 616}else{ 617 last_file = NULL; 618} 619} 620string_list_clear(&df_sorted_entries,0); 621} 622 623static intupdate_stages(struct merge_options *opt,const char*path, 624const struct diff_filespec *o, 625const struct diff_filespec *a, 626const struct diff_filespec *b) 627{ 628 629/* 630 * NOTE: It is usually a bad idea to call update_stages on a path 631 * before calling update_file on that same path, since it can 632 * sometimes lead to spurious "refusing to lose untracked file..." 633 * messages from update_file (via make_room_for path via 634 * would_lose_untracked). Instead, reverse the order of the calls 635 * (executing update_file first and then update_stages). 636 */ 637int clear =1; 638int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK; 639if(clear) 640if(remove_file_from_index(opt->repo->index, path)) 641return-1; 642if(o) 643if(add_cacheinfo(opt, o, path,1,0, options)) 644return-1; 645if(a) 646if(add_cacheinfo(opt, a, path,2,0, options)) 647return-1; 648if(b) 649if(add_cacheinfo(opt, b, path,3,0, options)) 650return-1; 651return0; 652} 653 654static voidupdate_entry(struct stage_data *entry, 655struct diff_filespec *o, 656struct diff_filespec *a, 657struct diff_filespec *b) 658{ 659 entry->processed =0; 660 entry->stages[1].mode = o->mode; 661 entry->stages[2].mode = a->mode; 662 entry->stages[3].mode = b->mode; 663oidcpy(&entry->stages[1].oid, &o->oid); 664oidcpy(&entry->stages[2].oid, &a->oid); 665oidcpy(&entry->stages[3].oid, &b->oid); 666} 667 668static intremove_file(struct merge_options *opt,int clean, 669const char*path,int no_wd) 670{ 671int update_cache = opt->call_depth || clean; 672int update_working_directory = !opt->call_depth && !no_wd; 673 674if(update_cache) { 675if(remove_file_from_index(opt->repo->index, path)) 676return-1; 677} 678if(update_working_directory) { 679if(ignore_case) { 680struct cache_entry *ce; 681 ce =index_file_exists(opt->repo->index, path,strlen(path), 682 ignore_case); 683if(ce &&ce_stage(ce) ==0&&strcmp(path, ce->name)) 684return0; 685} 686if(remove_path(path)) 687return-1; 688} 689return0; 690} 691 692/* add a string to a strbuf, but converting "/" to "_" */ 693static voidadd_flattened_path(struct strbuf *out,const char*s) 694{ 695size_t i = out->len; 696strbuf_addstr(out, s); 697for(; i < out->len; i++) 698if(out->buf[i] =='/') 699 out->buf[i] ='_'; 700} 701 702static char*unique_path(struct merge_options *opt,const char*path,const char*branch) 703{ 704struct path_hashmap_entry *entry; 705struct strbuf newpath = STRBUF_INIT; 706int suffix =0; 707size_t base_len; 708 709strbuf_addf(&newpath,"%s~", path); 710add_flattened_path(&newpath, branch); 711 712 base_len = newpath.len; 713while(hashmap_get_from_hash(&opt->current_file_dir_set, 714path_hash(newpath.buf), newpath.buf) || 715(!opt->call_depth &&file_exists(newpath.buf))) { 716strbuf_setlen(&newpath, base_len); 717strbuf_addf(&newpath,"_%d", suffix++); 718} 719 720FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len); 721hashmap_entry_init(entry,path_hash(entry->path)); 722hashmap_add(&opt->current_file_dir_set, entry); 723returnstrbuf_detach(&newpath, NULL); 724} 725 726/** 727 * Check whether a directory in the index is in the way of an incoming 728 * file. Return 1 if so. If check_working_copy is non-zero, also 729 * check the working directory. If empty_ok is non-zero, also return 730 * 0 in the case where the working-tree dir exists but is empty. 731 */ 732static intdir_in_way(struct index_state *istate,const char*path, 733int check_working_copy,int empty_ok) 734{ 735int pos; 736struct strbuf dirpath = STRBUF_INIT; 737struct stat st; 738 739strbuf_addstr(&dirpath, path); 740strbuf_addch(&dirpath,'/'); 741 742 pos =index_name_pos(istate, dirpath.buf, dirpath.len); 743 744if(pos <0) 745 pos = -1- pos; 746if(pos < istate->cache_nr && 747!strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) { 748strbuf_release(&dirpath); 749return1; 750} 751 752strbuf_release(&dirpath); 753return check_working_copy && !lstat(path, &st) &&S_ISDIR(st.st_mode) && 754!(empty_ok &&is_empty_dir(path)); 755} 756 757/* 758 * Returns whether path was tracked in the index before the merge started, 759 * and its oid and mode match the specified values 760 */ 761static intwas_tracked_and_matches(struct merge_options *opt,const char*path, 762const struct diff_filespec *blob) 763{ 764int pos =index_name_pos(&opt->orig_index, path,strlen(path)); 765struct cache_entry *ce; 766 767if(0> pos) 768/* we were not tracking this path before the merge */ 769return0; 770 771/* See if the file we were tracking before matches */ 772 ce = opt->orig_index.cache[pos]; 773return(oid_eq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode); 774} 775 776/* 777 * Returns whether path was tracked in the index before the merge started 778 */ 779static intwas_tracked(struct merge_options *opt,const char*path) 780{ 781int pos =index_name_pos(&opt->orig_index, path,strlen(path)); 782 783if(0<= pos) 784/* we were tracking this path before the merge */ 785return1; 786 787return0; 788} 789 790static intwould_lose_untracked(struct merge_options *opt,const char*path) 791{ 792struct index_state *istate = opt->repo->index; 793 794/* 795 * This may look like it can be simplified to: 796 * return !was_tracked(opt, path) && file_exists(path) 797 * but it can't. This function needs to know whether path was in 798 * the working tree due to EITHER having been tracked in the index 799 * before the merge OR having been put into the working copy and 800 * index by unpack_trees(). Due to that either-or requirement, we 801 * check the current index instead of the original one. 802 * 803 * Note that we do not need to worry about merge-recursive itself 804 * updating the index after unpack_trees() and before calling this 805 * function, because we strictly require all code paths in 806 * merge-recursive to update the working tree first and the index 807 * second. Doing otherwise would break 808 * update_file()/would_lose_untracked(); see every comment in this 809 * file which mentions "update_stages". 810 */ 811int pos =index_name_pos(istate, path,strlen(path)); 812 813if(pos <0) 814 pos = -1- pos; 815while(pos < istate->cache_nr && 816!strcmp(path, istate->cache[pos]->name)) { 817/* 818 * If stage #0, it is definitely tracked. 819 * If it has stage #2 then it was tracked 820 * before this merge started. All other 821 * cases the path was not tracked. 822 */ 823switch(ce_stage(istate->cache[pos])) { 824case0: 825case2: 826return0; 827} 828 pos++; 829} 830returnfile_exists(path); 831} 832 833static intwas_dirty(struct merge_options *opt,const char*path) 834{ 835struct cache_entry *ce; 836int dirty =1; 837 838if(opt->call_depth || !was_tracked(opt, path)) 839return!dirty; 840 841 ce =index_file_exists(opt->unpack_opts.src_index, 842 path,strlen(path), ignore_case); 843 dirty =verify_uptodate(ce, &opt->unpack_opts) !=0; 844return dirty; 845} 846 847static intmake_room_for_path(struct merge_options *opt,const char*path) 848{ 849int status, i; 850const char*msg =_("failed to create path '%s'%s"); 851 852/* Unlink any D/F conflict files that are in the way */ 853for(i =0; i < opt->df_conflict_file_set.nr; i++) { 854const char*df_path = opt->df_conflict_file_set.items[i].string; 855size_t pathlen =strlen(path); 856size_t df_pathlen =strlen(df_path); 857if(df_pathlen < pathlen && 858 path[df_pathlen] =='/'&& 859strncmp(path, df_path, df_pathlen) ==0) { 860output(opt,3, 861_("Removing%sto make room for subdirectory\n"), 862 df_path); 863unlink(df_path); 864unsorted_string_list_delete_item(&opt->df_conflict_file_set, 865 i,0); 866break; 867} 868} 869 870/* Make sure leading directories are created */ 871 status =safe_create_leading_directories_const(path); 872if(status) { 873if(status == SCLD_EXISTS) 874/* something else exists */ 875returnerr(opt, msg, path,_(": perhaps a D/F conflict?")); 876returnerr(opt, msg, path,""); 877} 878 879/* 880 * Do not unlink a file in the work tree if we are not 881 * tracking it. 882 */ 883if(would_lose_untracked(opt, path)) 884returnerr(opt,_("refusing to lose untracked file at '%s'"), 885 path); 886 887/* Successful unlink is good.. */ 888if(!unlink(path)) 889return0; 890/* .. and so is no existing file */ 891if(errno == ENOENT) 892return0; 893/* .. but not some other error (who really cares what?) */ 894returnerr(opt, msg, path,_(": perhaps a D/F conflict?")); 895} 896 897static intupdate_file_flags(struct merge_options *opt, 898const struct diff_filespec *contents, 899const char*path, 900int update_cache, 901int update_wd) 902{ 903int ret =0; 904 905if(opt->call_depth) 906 update_wd =0; 907 908if(update_wd) { 909enum object_type type; 910void*buf; 911unsigned long size; 912 913if(S_ISGITLINK(contents->mode)) { 914/* 915 * We may later decide to recursively descend into 916 * the submodule directory and update its index 917 * and/or work tree, but we do not do that now. 918 */ 919 update_wd =0; 920goto update_index; 921} 922 923 buf =read_object_file(&contents->oid, &type, &size); 924if(!buf) 925returnerr(opt,_("cannot read object%s'%s'"), 926oid_to_hex(&contents->oid), path); 927if(type != OBJ_BLOB) { 928 ret =err(opt,_("blob expected for%s'%s'"), 929oid_to_hex(&contents->oid), path); 930goto free_buf; 931} 932if(S_ISREG(contents->mode)) { 933struct strbuf strbuf = STRBUF_INIT; 934if(convert_to_working_tree(opt->repo->index, path, buf, size, &strbuf)) { 935free(buf); 936 size = strbuf.len; 937 buf =strbuf_detach(&strbuf, NULL); 938} 939} 940 941if(make_room_for_path(opt, path) <0) { 942 update_wd =0; 943goto free_buf; 944} 945if(S_ISREG(contents->mode) || 946(!has_symlinks &&S_ISLNK(contents->mode))) { 947int fd; 948int mode = (contents->mode &0100?0777:0666); 949 950 fd =open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); 951if(fd <0) { 952 ret =err(opt,_("failed to open '%s':%s"), 953 path,strerror(errno)); 954goto free_buf; 955} 956write_in_full(fd, buf, size); 957close(fd); 958}else if(S_ISLNK(contents->mode)) { 959char*lnk =xmemdupz(buf, size); 960safe_create_leading_directories_const(path); 961unlink(path); 962if(symlink(lnk, path)) 963 ret =err(opt,_("failed to symlink '%s':%s"), 964 path,strerror(errno)); 965free(lnk); 966}else 967 ret =err(opt, 968_("do not know what to do with%06o%s'%s'"), 969 contents->mode,oid_to_hex(&contents->oid), path); 970 free_buf: 971free(buf); 972} 973update_index: 974if(!ret && update_cache) 975if(add_cacheinfo(opt, contents, path,0, update_wd, 976 ADD_CACHE_OK_TO_ADD)) 977return-1; 978return ret; 979} 980 981static intupdate_file(struct merge_options *opt, 982int clean, 983const struct diff_filespec *contents, 984const char*path) 985{ 986returnupdate_file_flags(opt, contents, path, 987 opt->call_depth || clean, !opt->call_depth); 988} 989 990/* Low level file merging, update and removal */ 991 992struct merge_file_info { 993struct diff_filespec blob;/* mostly use oid & mode; sometimes path */ 994unsigned clean:1, 995 merge:1; 996}; 997 998static intmerge_3way(struct merge_options *opt, 999 mmbuffer_t *result_buf,1000const struct diff_filespec *o,1001const struct diff_filespec *a,1002const struct diff_filespec *b,1003const char*branch1,1004const char*branch2,1005const int extra_marker_size)1006{1007 mmfile_t orig, src1, src2;1008struct ll_merge_options ll_opts = {0};1009char*base_name, *name1, *name2;1010int merge_status;10111012 ll_opts.renormalize = opt->renormalize;1013 ll_opts.extra_marker_size = extra_marker_size;1014 ll_opts.xdl_opts = opt->xdl_opts;10151016if(opt->call_depth) {1017 ll_opts.virtual_ancestor =1;1018 ll_opts.variant =0;1019}else{1020switch(opt->recursive_variant) {1021case MERGE_RECURSIVE_OURS:1022 ll_opts.variant = XDL_MERGE_FAVOR_OURS;1023break;1024case MERGE_RECURSIVE_THEIRS:1025 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;1026break;1027default:1028 ll_opts.variant =0;1029break;1030}1031}10321033assert(a->path && b->path);1034if(strcmp(a->path, b->path) ||1035(opt->ancestor != NULL &&strcmp(a->path, o->path) !=0)) {1036 base_name = opt->ancestor == NULL ? NULL :1037mkpathdup("%s:%s", opt->ancestor, o->path);1038 name1 =mkpathdup("%s:%s", branch1, a->path);1039 name2 =mkpathdup("%s:%s", branch2, b->path);1040}else{1041 base_name = opt->ancestor == NULL ? NULL :1042mkpathdup("%s", opt->ancestor);1043 name1 =mkpathdup("%s", branch1);1044 name2 =mkpathdup("%s", branch2);1045}10461047read_mmblob(&orig, &o->oid);1048read_mmblob(&src1, &a->oid);1049read_mmblob(&src2, &b->oid);10501051 merge_status =ll_merge(result_buf, a->path, &orig, base_name,1052&src1, name1, &src2, name2,1053 opt->repo->index, &ll_opts);10541055free(base_name);1056free(name1);1057free(name2);1058free(orig.ptr);1059free(src1.ptr);1060free(src2.ptr);1061return merge_status;1062}10631064static intfind_first_merges(struct repository *repo,1065struct object_array *result,const char*path,1066struct commit *a,struct commit *b)1067{1068int i, j;1069struct object_array merges = OBJECT_ARRAY_INIT;1070struct commit *commit;1071int contains_another;10721073char merged_revision[42];1074const char*rev_args[] = {"rev-list","--merges","--ancestry-path",1075"--all", merged_revision, NULL };1076struct rev_info revs;1077struct setup_revision_opt rev_opts;10781079memset(result,0,sizeof(struct object_array));1080memset(&rev_opts,0,sizeof(rev_opts));10811082/* get all revisions that merge commit a */1083xsnprintf(merged_revision,sizeof(merged_revision),"^%s",1084oid_to_hex(&a->object.oid));1085repo_init_revisions(repo, &revs, NULL);1086 rev_opts.submodule = path;1087/* FIXME: can't handle linked worktrees in submodules yet */1088 revs.single_worktree = path != NULL;1089setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);10901091/* save all revisions from the above list that contain b */1092if(prepare_revision_walk(&revs))1093die("revision walk setup failed");1094while((commit =get_revision(&revs)) != NULL) {1095struct object *o = &(commit->object);1096if(in_merge_bases(b, commit))1097add_object_array(o, NULL, &merges);1098}1099reset_revision_walk();11001101/* Now we've got all merges that contain a and b. Prune all1102 * merges that contain another found merge and save them in1103 * result.1104 */1105for(i =0; i < merges.nr; i++) {1106struct commit *m1 = (struct commit *) merges.objects[i].item;11071108 contains_another =0;1109for(j =0; j < merges.nr; j++) {1110struct commit *m2 = (struct commit *) merges.objects[j].item;1111if(i != j &&in_merge_bases(m2, m1)) {1112 contains_another =1;1113break;1114}1115}11161117if(!contains_another)1118add_object_array(merges.objects[i].item, NULL, result);1119}11201121object_array_clear(&merges);1122return result->nr;1123}11241125static voidprint_commit(struct commit *commit)1126{1127struct strbuf sb = STRBUF_INIT;1128struct pretty_print_context ctx = {0};1129 ctx.date_mode.type = DATE_NORMAL;1130format_commit_message(commit,"%h:%m %s", &sb, &ctx);1131fprintf(stderr,"%s\n", sb.buf);1132strbuf_release(&sb);1133}11341135static intis_valid(const struct diff_filespec *dfs)1136{1137return dfs->mode !=0&& !is_null_oid(&dfs->oid);1138}11391140static intmerge_submodule(struct merge_options *opt,1141struct object_id *result,const char*path,1142const struct object_id *base,const struct object_id *a,1143const struct object_id *b)1144{1145struct commit *commit_base, *commit_a, *commit_b;1146int parent_count;1147struct object_array merges;11481149int i;1150int search = !opt->call_depth;11511152/* store a in result in case we fail */1153oidcpy(result, a);11541155/* we can not handle deletion conflicts */1156if(is_null_oid(base))1157return0;1158if(is_null_oid(a))1159return0;1160if(is_null_oid(b))1161return0;11621163if(add_submodule_odb(path)) {1164output(opt,1,_("Failed to merge submodule%s(not checked out)"), path);1165return0;1166}11671168if(!(commit_base =lookup_commit_reference(opt->repo, base)) ||1169!(commit_a =lookup_commit_reference(opt->repo, a)) ||1170!(commit_b =lookup_commit_reference(opt->repo, b))) {1171output(opt,1,_("Failed to merge submodule%s(commits not present)"), path);1172return0;1173}11741175/* check whether both changes are forward */1176if(!in_merge_bases(commit_base, commit_a) ||1177!in_merge_bases(commit_base, commit_b)) {1178output(opt,1,_("Failed to merge submodule%s(commits don't follow merge-base)"), path);1179return0;1180}11811182/* Case #1: a is contained in b or vice versa */1183if(in_merge_bases(commit_a, commit_b)) {1184oidcpy(result, b);1185if(show(opt,3)) {1186output(opt,3,_("Fast-forwarding submodule%sto the following commit:"), path);1187output_commit_title(opt, commit_b);1188}else if(show(opt,2))1189output(opt,2,_("Fast-forwarding submodule%s"), path);1190else1191;/* no output */11921193return1;1194}1195if(in_merge_bases(commit_b, commit_a)) {1196oidcpy(result, a);1197if(show(opt,3)) {1198output(opt,3,_("Fast-forwarding submodule%sto the following commit:"), path);1199output_commit_title(opt, commit_a);1200}else if(show(opt,2))1201output(opt,2,_("Fast-forwarding submodule%s"), path);1202else1203;/* no output */12041205return1;1206}12071208/*1209 * Case #2: There are one or more merges that contain a and b in1210 * the submodule. If there is only one, then present it as a1211 * suggestion to the user, but leave it marked unmerged so the1212 * user needs to confirm the resolution.1213 */12141215/* Skip the search if makes no sense to the calling context. */1216if(!search)1217return0;12181219/* find commit which merges them */1220 parent_count =find_first_merges(opt->repo, &merges, path,1221 commit_a, commit_b);1222switch(parent_count) {1223case0:1224output(opt,1,_("Failed to merge submodule%s(merge following commits not found)"), path);1225break;12261227case1:1228output(opt,1,_("Failed to merge submodule%s(not fast-forward)"), path);1229output(opt,2,_("Found a possible merge resolution for the submodule:\n"));1230print_commit((struct commit *) merges.objects[0].item);1231output(opt,2,_(1232"If this is correct simply add it to the index "1233"for example\n"1234"by using:\n\n"1235" git update-index --cacheinfo 160000%s\"%s\"\n\n"1236"which will accept this suggestion.\n"),1237oid_to_hex(&merges.objects[0].item->oid), path);1238break;12391240default:1241output(opt,1,_("Failed to merge submodule%s(multiple merges found)"), path);1242for(i =0; i < merges.nr; i++)1243print_commit((struct commit *) merges.objects[i].item);1244}12451246object_array_clear(&merges);1247return0;1248}12491250static intmerge_mode_and_contents(struct merge_options *opt,1251const struct diff_filespec *o,1252const struct diff_filespec *a,1253const struct diff_filespec *b,1254const char*filename,1255const char*branch1,1256const char*branch2,1257const int extra_marker_size,1258struct merge_file_info *result)1259{1260if(opt->branch1 != branch1) {1261/*1262 * It's weird getting a reverse merge with HEAD on the bottom1263 * side of the conflict markers and the other branch on the1264 * top. Fix that.1265 */1266returnmerge_mode_and_contents(opt, o, b, a,1267 filename,1268 branch2, branch1,1269 extra_marker_size, result);1270}12711272 result->merge =0;1273 result->clean =1;12741275if((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1276 result->clean =0;1277if(S_ISREG(a->mode)) {1278 result->blob.mode = a->mode;1279oidcpy(&result->blob.oid, &a->oid);1280}else{1281 result->blob.mode = b->mode;1282oidcpy(&result->blob.oid, &b->oid);1283}1284}else{1285if(!oid_eq(&a->oid, &o->oid) && !oid_eq(&b->oid, &o->oid))1286 result->merge =1;12871288/*1289 * Merge modes1290 */1291if(a->mode == b->mode || a->mode == o->mode)1292 result->blob.mode = b->mode;1293else{1294 result->blob.mode = a->mode;1295if(b->mode != o->mode) {1296 result->clean =0;1297 result->merge =1;1298}1299}13001301if(oid_eq(&a->oid, &b->oid) ||oid_eq(&a->oid, &o->oid))1302oidcpy(&result->blob.oid, &b->oid);1303else if(oid_eq(&b->oid, &o->oid))1304oidcpy(&result->blob.oid, &a->oid);1305else if(S_ISREG(a->mode)) {1306 mmbuffer_t result_buf;1307int ret =0, merge_status;13081309 merge_status =merge_3way(opt, &result_buf, o, a, b,1310 branch1, branch2,1311 extra_marker_size);13121313if((merge_status <0) || !result_buf.ptr)1314 ret =err(opt,_("Failed to execute internal merge"));13151316if(!ret &&1317write_object_file(result_buf.ptr, result_buf.size,1318 blob_type, &result->blob.oid))1319 ret =err(opt,_("Unable to add%sto database"),1320 a->path);13211322free(result_buf.ptr);1323if(ret)1324return ret;1325 result->clean = (merge_status ==0);1326}else if(S_ISGITLINK(a->mode)) {1327 result->clean =merge_submodule(opt, &result->blob.oid,1328 o->path,1329&o->oid,1330&a->oid,1331&b->oid);1332}else if(S_ISLNK(a->mode)) {1333switch(opt->recursive_variant) {1334case MERGE_RECURSIVE_NORMAL:1335oidcpy(&result->blob.oid, &a->oid);1336if(!oid_eq(&a->oid, &b->oid))1337 result->clean =0;1338break;1339case MERGE_RECURSIVE_OURS:1340oidcpy(&result->blob.oid, &a->oid);1341break;1342case MERGE_RECURSIVE_THEIRS:1343oidcpy(&result->blob.oid, &b->oid);1344break;1345}1346}else1347BUG("unsupported object type in the tree");1348}13491350if(result->merge)1351output(opt,2,_("Auto-merging%s"), filename);13521353return0;1354}13551356static inthandle_rename_via_dir(struct merge_options *opt,1357struct rename_conflict_info *ci)1358{1359/*1360 * Handle file adds that need to be renamed due to directory rename1361 * detection. This differs from handle_rename_normal, because1362 * there is no content merge to do; just move the file into the1363 * desired final location.1364 */1365const struct rename *ren = ci->ren1;1366const struct diff_filespec *dest = ren->pair->two;13671368if(!opt->call_depth &&would_lose_untracked(opt, dest->path)) {1369char*alt_path =unique_path(opt, dest->path, ren->branch);13701371output(opt,1,_("Error: Refusing to lose untracked file at%s; "1372"writing to%sinstead."),1373 dest->path, alt_path);1374/*1375 * Write the file in worktree at alt_path, but not in the1376 * index. Instead, write to dest->path for the index but1377 * only at the higher appropriate stage.1378 */1379if(update_file(opt,0, dest, alt_path))1380return-1;1381free(alt_path);1382returnupdate_stages(opt, dest->path, NULL,1383 ren->branch == opt->branch1 ? dest : NULL,1384 ren->branch == opt->branch1 ? NULL : dest);1385}13861387/* Update dest->path both in index and in worktree */1388if(update_file(opt,1, dest, dest->path))1389return-1;1390return0;1391}13921393static inthandle_change_delete(struct merge_options *opt,1394const char*path,const char*old_path,1395const struct diff_filespec *o,1396const struct diff_filespec *changed,1397const char*change_branch,1398const char*delete_branch,1399const char*change,const char*change_past)1400{1401char*alt_path = NULL;1402const char*update_path = path;1403int ret =0;14041405if(dir_in_way(opt->repo->index, path, !opt->call_depth,0) ||1406(!opt->call_depth &&would_lose_untracked(opt, path))) {1407 update_path = alt_path =unique_path(opt, path, change_branch);1408}14091410if(opt->call_depth) {1411/*1412 * We cannot arbitrarily accept either a_sha or b_sha as1413 * correct; since there is no true "middle point" between1414 * them, simply reuse the base version for virtual merge base.1415 */1416 ret =remove_file_from_index(opt->repo->index, path);1417if(!ret)1418 ret =update_file(opt,0, o, update_path);1419}else{1420/*1421 * Despite the four nearly duplicate messages and argument1422 * lists below and the ugliness of the nested if-statements,1423 * having complete messages makes the job easier for1424 * translators.1425 *1426 * The slight variance among the cases is due to the fact1427 * that:1428 * 1) directory/file conflicts (in effect if1429 * !alt_path) could cause us to need to write the1430 * file to a different path.1431 * 2) renames (in effect if !old_path) could mean that1432 * there are two names for the path that the user1433 * may know the file by.1434 */1435if(!alt_path) {1436if(!old_path) {1437output(opt,1,_("CONFLICT (%s/delete):%sdeleted in%s"1438"and%sin%s. Version%sof%sleft in tree."),1439 change, path, delete_branch, change_past,1440 change_branch, change_branch, path);1441}else{1442output(opt,1,_("CONFLICT (%s/delete):%sdeleted in%s"1443"and%sto%sin%s. Version%sof%sleft in tree."),1444 change, old_path, delete_branch, change_past, path,1445 change_branch, change_branch, path);1446}1447}else{1448if(!old_path) {1449output(opt,1,_("CONFLICT (%s/delete):%sdeleted in%s"1450"and%sin%s. Version%sof%sleft in tree at%s."),1451 change, path, delete_branch, change_past,1452 change_branch, change_branch, path, alt_path);1453}else{1454output(opt,1,_("CONFLICT (%s/delete):%sdeleted in%s"1455"and%sto%sin%s. Version%sof%sleft in tree at%s."),1456 change, old_path, delete_branch, change_past, path,1457 change_branch, change_branch, path, alt_path);1458}1459}1460/*1461 * No need to call update_file() on path when change_branch ==1462 * opt->branch1 && !alt_path, since that would needlessly touch1463 * path. We could call update_file_flags() with update_cache=01464 * and update_wd=0, but that's a no-op.1465 */1466if(change_branch != opt->branch1 || alt_path)1467 ret =update_file(opt,0, changed, update_path);1468}1469free(alt_path);14701471return ret;1472}14731474static inthandle_rename_delete(struct merge_options *opt,1475struct rename_conflict_info *ci)1476{1477const struct rename *ren = ci->ren1;1478const struct diff_filespec *orig = ren->pair->one;1479const struct diff_filespec *dest = ren->pair->two;1480const char*rename_branch = ren->branch;1481const char*delete_branch = (opt->branch1 == ren->branch ?1482 opt->branch2 : opt->branch1);14831484if(handle_change_delete(opt,1485 opt->call_depth ? orig->path : dest->path,1486 opt->call_depth ? NULL : orig->path,1487 orig, dest,1488 rename_branch, delete_branch,1489_("rename"),_("renamed")))1490return-1;14911492if(opt->call_depth)1493returnremove_file_from_index(opt->repo->index, dest->path);1494else1495returnupdate_stages(opt, dest->path, NULL,1496 rename_branch == opt->branch1 ? dest : NULL,1497 rename_branch == opt->branch1 ? NULL : dest);1498}14991500static inthandle_file_collision(struct merge_options *opt,1501const char*collide_path,1502const char*prev_path1,1503const char*prev_path2,1504const char*branch1,const char*branch2,1505struct diff_filespec *a,1506struct diff_filespec *b)1507{1508struct merge_file_info mfi;1509struct diff_filespec null;1510char*alt_path = NULL;1511const char*update_path = collide_path;15121513/*1514 * It's easiest to get the correct things into stage 2 and 3, and1515 * to make sure that the content merge puts HEAD before the other1516 * branch if we just ensure that branch1 == opt->branch1. So, simply1517 * flip arguments around if we don't have that.1518 */1519if(branch1 != opt->branch1) {1520returnhandle_file_collision(opt, collide_path,1521 prev_path2, prev_path1,1522 branch2, branch1,1523 b, a);1524}15251526/*1527 * In the recursive case, we just opt to undo renames1528 */1529if(opt->call_depth && (prev_path1 || prev_path2)) {1530/* Put first file (a->oid, a->mode) in its original spot */1531if(prev_path1) {1532if(update_file(opt,1, a, prev_path1))1533return-1;1534}else{1535if(update_file(opt,1, a, collide_path))1536return-1;1537}15381539/* Put second file (b->oid, b->mode) in its original spot */1540if(prev_path2) {1541if(update_file(opt,1, b, prev_path2))1542return-1;1543}else{1544if(update_file(opt,1, b, collide_path))1545return-1;1546}15471548/* Don't leave something at collision path if unrenaming both */1549if(prev_path1 && prev_path2)1550remove_file(opt,1, collide_path,0);15511552return0;1553}15541555/* Remove rename sources if rename/add or rename/rename(2to1) */1556if(prev_path1)1557remove_file(opt,1, prev_path1,1558 opt->call_depth ||would_lose_untracked(opt, prev_path1));1559if(prev_path2)1560remove_file(opt,1, prev_path2,1561 opt->call_depth ||would_lose_untracked(opt, prev_path2));15621563/*1564 * Remove the collision path, if it wouldn't cause dirty contents1565 * or an untracked file to get lost. We'll either overwrite with1566 * merged contents, or just write out to differently named files.1567 */1568if(was_dirty(opt, collide_path)) {1569output(opt,1,_("Refusing to lose dirty file at%s"),1570 collide_path);1571 update_path = alt_path =unique_path(opt, collide_path,"merged");1572}else if(would_lose_untracked(opt, collide_path)) {1573/*1574 * Only way we get here is if both renames were from1575 * a directory rename AND user had an untracked file1576 * at the location where both files end up after the1577 * two directory renames. See testcase 10d of t6043.1578 */1579output(opt,1,_("Refusing to lose untracked file at "1580"%s, even though it's in the way."),1581 collide_path);1582 update_path = alt_path =unique_path(opt, collide_path,"merged");1583}else{1584/*1585 * FIXME: It's possible that the two files are identical1586 * and that the current working copy happens to match, in1587 * which case we are unnecessarily touching the working1588 * tree file. It's not a likely enough scenario that I1589 * want to code up the checks for it and a better fix is1590 * available if we restructure how unpack_trees() and1591 * merge-recursive interoperate anyway, so punting for1592 * now...1593 */1594remove_file(opt,0, collide_path,0);1595}15961597/* Store things in diff_filespecs for functions that need it */1598 null.path = (char*)collide_path;1599oidcpy(&null.oid, &null_oid);1600 null.mode =0;16011602if(merge_mode_and_contents(opt, &null, a, b, collide_path,1603 branch1, branch2, opt->call_depth *2, &mfi))1604return-1;1605 mfi.clean &= !alt_path;1606if(update_file(opt, mfi.clean, &mfi.blob, update_path))1607return-1;1608if(!mfi.clean && !opt->call_depth &&1609update_stages(opt, collide_path, NULL, a, b))1610return-1;1611free(alt_path);1612/*1613 * FIXME: If both a & b both started with conflicts (only possible1614 * if they came from a rename/rename(2to1)), but had IDENTICAL1615 * contents including those conflicts, then in the next line we claim1616 * it was clean. If someone cares about this case, we should have the1617 * caller notify us if we started with conflicts.1618 */1619return mfi.clean;1620}16211622static inthandle_rename_add(struct merge_options *opt,1623struct rename_conflict_info *ci)1624{1625/* a was renamed to c, and a separate c was added. */1626struct diff_filespec *a = ci->ren1->pair->one;1627struct diff_filespec *c = ci->ren1->pair->two;1628char*path = c->path;1629char*prev_path_desc;1630struct merge_file_info mfi;16311632const char*rename_branch = ci->ren1->branch;1633const char*add_branch = (opt->branch1 == rename_branch ?1634 opt->branch2 : opt->branch1);1635int other_stage = (ci->ren1->branch == opt->branch1 ?3:2);16361637output(opt,1,_("CONFLICT (rename/add): "1638"Rename%s->%sin%s. Added%sin%s"),1639 a->path, c->path, rename_branch,1640 c->path, add_branch);16411642 prev_path_desc =xstrfmt("version of%sfrom%s", path, a->path);1643if(merge_mode_and_contents(opt, a, c,1644&ci->ren1->src_entry->stages[other_stage],1645 prev_path_desc,1646 opt->branch1, opt->branch2,16471+ opt->call_depth *2, &mfi))1648return-1;1649free(prev_path_desc);16501651 ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;1652returnhandle_file_collision(opt,1653 c->path, a->path, NULL,1654 rename_branch, add_branch,1655&mfi.blob,1656&ci->ren1->dst_entry->stages[other_stage]);1657}16581659static char*find_path_for_conflict(struct merge_options *opt,1660const char*path,1661const char*branch1,1662const char*branch2)1663{1664char*new_path = NULL;1665if(dir_in_way(opt->repo->index, path, !opt->call_depth,0)) {1666 new_path =unique_path(opt, path, branch1);1667output(opt,1,_("%sis a directory in%sadding "1668"as%sinstead"),1669 path, branch2, new_path);1670}else if(would_lose_untracked(opt, path)) {1671 new_path =unique_path(opt, path, branch1);1672output(opt,1,_("Refusing to lose untracked file"1673" at%s; adding as%sinstead"),1674 path, new_path);1675}16761677return new_path;1678}16791680static inthandle_rename_rename_1to2(struct merge_options *opt,1681struct rename_conflict_info *ci)1682{1683/* One file was renamed in both branches, but to different names. */1684struct merge_file_info mfi;1685struct diff_filespec *add;1686struct diff_filespec *o = ci->ren1->pair->one;1687struct diff_filespec *a = ci->ren1->pair->two;1688struct diff_filespec *b = ci->ren2->pair->two;1689char*path_desc;16901691output(opt,1,_("CONFLICT (rename/rename): "1692"Rename\"%s\"->\"%s\"in branch\"%s\""1693"rename\"%s\"->\"%s\"in\"%s\"%s"),1694 o->path, a->path, ci->ren1->branch,1695 o->path, b->path, ci->ren2->branch,1696 opt->call_depth ?_(" (left unresolved)") :"");16971698 path_desc =xstrfmt("%sand%s, both renamed from%s",1699 a->path, b->path, o->path);1700if(merge_mode_and_contents(opt, o, a, b, path_desc,1701 ci->ren1->branch, ci->ren2->branch,1702 opt->call_depth *2, &mfi))1703return-1;1704free(path_desc);17051706if(opt->call_depth) {1707/*1708 * FIXME: For rename/add-source conflicts (if we could detect1709 * such), this is wrong. We should instead find a unique1710 * pathname and then either rename the add-source file to that1711 * unique path, or use that unique path instead of src here.1712 */1713if(update_file(opt,0, &mfi.blob, o->path))1714return-1;17151716/*1717 * Above, we put the merged content at the merge-base's1718 * path. Now we usually need to delete both a->path and1719 * b->path. However, the rename on each side of the merge1720 * could also be involved in a rename/add conflict. In1721 * such cases, we should keep the added file around,1722 * resolving the conflict at that path in its favor.1723 */1724 add = &ci->ren1->dst_entry->stages[2^1];1725if(is_valid(add)) {1726if(update_file(opt,0, add, a->path))1727return-1;1728}1729else1730remove_file_from_index(opt->repo->index, a->path);1731 add = &ci->ren2->dst_entry->stages[3^1];1732if(is_valid(add)) {1733if(update_file(opt,0, add, b->path))1734return-1;1735}1736else1737remove_file_from_index(opt->repo->index, b->path);1738}else{1739/*1740 * For each destination path, we need to see if there is a1741 * rename/add collision. If not, we can write the file out1742 * to the specified location.1743 */1744 add = &ci->ren1->dst_entry->stages[2^1];1745if(is_valid(add)) {1746 add->path = mfi.blob.path = a->path;1747if(handle_file_collision(opt, a->path,1748 NULL, NULL,1749 ci->ren1->branch,1750 ci->ren2->branch,1751&mfi.blob, add) <0)1752return-1;1753}else{1754char*new_path =find_path_for_conflict(opt, a->path,1755 ci->ren1->branch,1756 ci->ren2->branch);1757if(update_file(opt,0, &mfi.blob,1758 new_path ? new_path : a->path))1759return-1;1760free(new_path);1761if(update_stages(opt, a->path, NULL, a, NULL))1762return-1;1763}17641765 add = &ci->ren2->dst_entry->stages[3^1];1766if(is_valid(add)) {1767 add->path = mfi.blob.path = b->path;1768if(handle_file_collision(opt, b->path,1769 NULL, NULL,1770 ci->ren1->branch,1771 ci->ren2->branch,1772 add, &mfi.blob) <0)1773return-1;1774}else{1775char*new_path =find_path_for_conflict(opt, b->path,1776 ci->ren2->branch,1777 ci->ren1->branch);1778if(update_file(opt,0, &mfi.blob,1779 new_path ? new_path : b->path))1780return-1;1781free(new_path);1782if(update_stages(opt, b->path, NULL, NULL, b))1783return-1;1784}1785}17861787return0;1788}17891790static inthandle_rename_rename_2to1(struct merge_options *opt,1791struct rename_conflict_info *ci)1792{1793/* Two files, a & b, were renamed to the same thing, c. */1794struct diff_filespec *a = ci->ren1->pair->one;1795struct diff_filespec *b = ci->ren2->pair->one;1796struct diff_filespec *c1 = ci->ren1->pair->two;1797struct diff_filespec *c2 = ci->ren2->pair->two;1798char*path = c1->path;/* == c2->path */1799char*path_side_1_desc;1800char*path_side_2_desc;1801struct merge_file_info mfi_c1;1802struct merge_file_info mfi_c2;1803int ostage1, ostage2;18041805output(opt,1,_("CONFLICT (rename/rename): "1806"Rename%s->%sin%s. "1807"Rename%s->%sin%s"),1808 a->path, c1->path, ci->ren1->branch,1809 b->path, c2->path, ci->ren2->branch);18101811 path_side_1_desc =xstrfmt("version of%sfrom%s", path, a->path);1812 path_side_2_desc =xstrfmt("version of%sfrom%s", path, b->path);1813 ostage1 = ci->ren1->branch == opt->branch1 ?3:2;1814 ostage2 = ostage1 ^1;1815 ci->ren1->src_entry->stages[ostage1].path = a->path;1816 ci->ren2->src_entry->stages[ostage2].path = b->path;1817if(merge_mode_and_contents(opt, a, c1,1818&ci->ren1->src_entry->stages[ostage1],1819 path_side_1_desc,1820 opt->branch1, opt->branch2,18211+ opt->call_depth *2, &mfi_c1) ||1822merge_mode_and_contents(opt, b,1823&ci->ren2->src_entry->stages[ostage2],1824 c2, path_side_2_desc,1825 opt->branch1, opt->branch2,18261+ opt->call_depth *2, &mfi_c2))1827return-1;1828free(path_side_1_desc);1829free(path_side_2_desc);1830 mfi_c1.blob.path = path;1831 mfi_c2.blob.path = path;18321833returnhandle_file_collision(opt, path, a->path, b->path,1834 ci->ren1->branch, ci->ren2->branch,1835&mfi_c1.blob, &mfi_c2.blob);1836}18371838/*1839 * Get the diff_filepairs changed between o_tree and tree.1840 */1841static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,1842struct tree *o_tree,1843struct tree *tree)1844{1845struct diff_queue_struct *ret;1846struct diff_options opts;18471848repo_diff_setup(opt->repo, &opts);1849 opts.flags.recursive =1;1850 opts.flags.rename_empty =0;1851 opts.detect_rename =merge_detect_rename(opt);1852/*1853 * We do not have logic to handle the detection of copies. In1854 * fact, it may not even make sense to add such logic: would we1855 * really want a change to a base file to be propagated through1856 * multiple other files by a merge?1857 */1858if(opts.detect_rename > DIFF_DETECT_RENAME)1859 opts.detect_rename = DIFF_DETECT_RENAME;1860 opts.rename_limit = opt->merge_rename_limit >=0? opt->merge_rename_limit :1861 opt->diff_rename_limit >=0? opt->diff_rename_limit :18621000;1863 opts.rename_score = opt->rename_score;1864 opts.show_rename_progress = opt->show_rename_progress;1865 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1866diff_setup_done(&opts);1867diff_tree_oid(&o_tree->object.oid, &tree->object.oid,"", &opts);1868diffcore_std(&opts);1869if(opts.needed_rename_limit > opt->needed_rename_limit)1870 opt->needed_rename_limit = opts.needed_rename_limit;18711872 ret =xmalloc(sizeof(*ret));1873*ret = diff_queued_diff;18741875 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1876 diff_queued_diff.nr =0;1877 diff_queued_diff.queue = NULL;1878diff_flush(&opts);1879return ret;1880}18811882static inttree_has_path(struct tree *tree,const char*path)1883{1884struct object_id hashy;1885unsigned short mode_o;18861887return!get_tree_entry(&tree->object.oid, path,1888&hashy, &mode_o);1889}18901891/*1892 * Return a new string that replaces the beginning portion (which matches1893 * entry->dir), with entry->new_dir. In perl-speak:1894 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);1895 * NOTE:1896 * Caller must ensure that old_path starts with entry->dir + '/'.1897 */1898static char*apply_dir_rename(struct dir_rename_entry *entry,1899const char*old_path)1900{1901struct strbuf new_path = STRBUF_INIT;1902int oldlen, newlen;19031904if(entry->non_unique_new_dir)1905return NULL;19061907 oldlen =strlen(entry->dir);1908 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) +1;1909strbuf_grow(&new_path, newlen);1910strbuf_addbuf(&new_path, &entry->new_dir);1911strbuf_addstr(&new_path, &old_path[oldlen]);19121913returnstrbuf_detach(&new_path, NULL);1914}19151916static voidget_renamed_dir_portion(const char*old_path,const char*new_path,1917char**old_dir,char**new_dir)1918{1919char*end_of_old, *end_of_new;1920int old_len, new_len;19211922*old_dir = NULL;1923*new_dir = NULL;19241925/*1926 * For1927 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"1928 * the "e/foo.c" part is the same, we just want to know that1929 * "a/b/c/d" was renamed to "a/b/some/thing/else"1930 * so, for this example, this function returns "a/b/c/d" in1931 * *old_dir and "a/b/some/thing/else" in *new_dir.1932 *1933 * Also, if the basename of the file changed, we don't care. We1934 * want to know which portion of the directory, if any, changed.1935 */1936 end_of_old =strrchr(old_path,'/');1937 end_of_new =strrchr(new_path,'/');19381939if(end_of_old == NULL || end_of_new == NULL)1940return;1941while(*--end_of_new == *--end_of_old &&1942 end_of_old != old_path &&1943 end_of_new != new_path)1944;/* Do nothing; all in the while loop */1945/*1946 * We've found the first non-matching character in the directory1947 * paths. That means the current directory we were comparing1948 * represents the rename. Move end_of_old and end_of_new back1949 * to the full directory name.1950 */1951if(*end_of_old =='/')1952 end_of_old++;1953if(*end_of_old !='/')1954 end_of_new++;1955 end_of_old =strchr(end_of_old,'/');1956 end_of_new =strchr(end_of_new,'/');19571958/*1959 * It may have been the case that old_path and new_path were the same1960 * directory all along. Don't claim a rename if they're the same.1961 */1962 old_len = end_of_old - old_path;1963 new_len = end_of_new - new_path;19641965if(old_len != new_len ||strncmp(old_path, new_path, old_len)) {1966*old_dir =xstrndup(old_path, old_len);1967*new_dir =xstrndup(new_path, new_len);1968}1969}19701971static voidremove_hashmap_entries(struct hashmap *dir_renames,1972struct string_list *items_to_remove)1973{1974int i;1975struct dir_rename_entry *entry;19761977for(i =0; i < items_to_remove->nr; i++) {1978 entry = items_to_remove->items[i].util;1979hashmap_remove(dir_renames, entry, NULL);1980}1981string_list_clear(items_to_remove,0);1982}19831984/*1985 * See if there is a directory rename for path, and if there are any file1986 * level conflicts for the renamed location. If there is a rename and1987 * there are no conflicts, return the new name. Otherwise, return NULL.1988 */1989static char*handle_path_level_conflicts(struct merge_options *opt,1990const char*path,1991struct dir_rename_entry *entry,1992struct hashmap *collisions,1993struct tree *tree)1994{1995char*new_path = NULL;1996struct collision_entry *collision_ent;1997int clean =1;1998struct strbuf collision_paths = STRBUF_INIT;19992000/*2001 * entry has the mapping of old directory name to new directory name2002 * that we want to apply to path.2003 */2004 new_path =apply_dir_rename(entry, path);20052006if(!new_path) {2007/* This should only happen when entry->non_unique_new_dir set */2008if(!entry->non_unique_new_dir)2009BUG("entry->non_unqiue_dir not set and !new_path");2010output(opt,1,_("CONFLICT (directory rename split): "2011"Unclear where to place%sbecause directory "2012"%swas renamed to multiple other directories, "2013"with no destination getting a majority of the "2014"files."),2015 path, entry->dir);2016 clean =0;2017return NULL;2018}20192020/*2021 * The caller needs to have ensured that it has pre-populated2022 * collisions with all paths that map to new_path. Do a quick check2023 * to ensure that's the case.2024 */2025 collision_ent =collision_find_entry(collisions, new_path);2026if(collision_ent == NULL)2027BUG("collision_ent is NULL");20282029/*2030 * Check for one-sided add/add/.../add conflicts, i.e.2031 * where implicit renames from the other side doing2032 * directory rename(s) can affect this side of history2033 * to put multiple paths into the same location. Warn2034 * and bail on directory renames for such paths.2035 */2036if(collision_ent->reported_already) {2037 clean =0;2038}else if(tree_has_path(tree, new_path)) {2039 collision_ent->reported_already =1;2040strbuf_add_separated_string_list(&collision_paths,", ",2041&collision_ent->source_files);2042output(opt,1,_("CONFLICT (implicit dir rename): Existing "2043"file/dir at%sin the way of implicit "2044"directory rename(s) putting the following "2045"path(s) there:%s."),2046 new_path, collision_paths.buf);2047 clean =0;2048}else if(collision_ent->source_files.nr >1) {2049 collision_ent->reported_already =1;2050strbuf_add_separated_string_list(&collision_paths,", ",2051&collision_ent->source_files);2052output(opt,1,_("CONFLICT (implicit dir rename): Cannot map "2053"more than one path to%s; implicit directory "2054"renames tried to put these paths there:%s"),2055 new_path, collision_paths.buf);2056 clean =0;2057}20582059/* Free memory we no longer need */2060strbuf_release(&collision_paths);2061if(!clean && new_path) {2062free(new_path);2063return NULL;2064}20652066return new_path;2067}20682069/*2070 * There are a couple things we want to do at the directory level:2071 * 1. Check for both sides renaming to the same thing, in order to avoid2072 * implicit renaming of files that should be left in place. (See2073 * testcase 6b in t6043 for details.)2074 * 2. Prune directory renames if there are still files left in the2075 * the original directory. These represent a partial directory rename,2076 * i.e. a rename where only some of the files within the directory2077 * were renamed elsewhere. (Technically, this could be done earlier2078 * in get_directory_renames(), except that would prevent us from2079 * doing the previous check and thus failing testcase 6b.)2080 * 3. Check for rename/rename(1to2) conflicts (at the directory level).2081 * In the future, we could potentially record this info as well and2082 * omit reporting rename/rename(1to2) conflicts for each path within2083 * the affected directories, thus cleaning up the merge output.2084 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the2085 * directory level, because merging directories is fine. If it2086 * causes conflicts for files within those merged directories, then2087 * that should be detected at the individual path level.2088 */2089static voidhandle_directory_level_conflicts(struct merge_options *opt,2090struct hashmap *dir_re_head,2091struct tree *head,2092struct hashmap *dir_re_merge,2093struct tree *merge)2094{2095struct hashmap_iter iter;2096struct dir_rename_entry *head_ent;2097struct dir_rename_entry *merge_ent;20982099struct string_list remove_from_head = STRING_LIST_INIT_NODUP;2100struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;21012102hashmap_iter_init(dir_re_head, &iter);2103while((head_ent =hashmap_iter_next(&iter))) {2104 merge_ent =dir_rename_find_entry(dir_re_merge, head_ent->dir);2105if(merge_ent &&2106!head_ent->non_unique_new_dir &&2107!merge_ent->non_unique_new_dir &&2108!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {2109/* 1. Renamed identically; remove it from both sides */2110string_list_append(&remove_from_head,2111 head_ent->dir)->util = head_ent;2112strbuf_release(&head_ent->new_dir);2113string_list_append(&remove_from_merge,2114 merge_ent->dir)->util = merge_ent;2115strbuf_release(&merge_ent->new_dir);2116}else if(tree_has_path(head, head_ent->dir)) {2117/* 2. This wasn't a directory rename after all */2118string_list_append(&remove_from_head,2119 head_ent->dir)->util = head_ent;2120strbuf_release(&head_ent->new_dir);2121}2122}21232124remove_hashmap_entries(dir_re_head, &remove_from_head);2125remove_hashmap_entries(dir_re_merge, &remove_from_merge);21262127hashmap_iter_init(dir_re_merge, &iter);2128while((merge_ent =hashmap_iter_next(&iter))) {2129 head_ent =dir_rename_find_entry(dir_re_head, merge_ent->dir);2130if(tree_has_path(merge, merge_ent->dir)) {2131/* 2. This wasn't a directory rename after all */2132string_list_append(&remove_from_merge,2133 merge_ent->dir)->util = merge_ent;2134}else if(head_ent &&2135!head_ent->non_unique_new_dir &&2136!merge_ent->non_unique_new_dir) {2137/* 3. rename/rename(1to2) */2138/*2139 * We can assume it's not rename/rename(1to1) because2140 * that was case (1), already checked above. So we2141 * know that head_ent->new_dir and merge_ent->new_dir2142 * are different strings.2143 */2144output(opt,1,_("CONFLICT (rename/rename): "2145"Rename directory%s->%sin%s. "2146"Rename directory%s->%sin%s"),2147 head_ent->dir, head_ent->new_dir.buf, opt->branch1,2148 head_ent->dir, merge_ent->new_dir.buf, opt->branch2);2149string_list_append(&remove_from_head,2150 head_ent->dir)->util = head_ent;2151strbuf_release(&head_ent->new_dir);2152string_list_append(&remove_from_merge,2153 merge_ent->dir)->util = merge_ent;2154strbuf_release(&merge_ent->new_dir);2155}2156}21572158remove_hashmap_entries(dir_re_head, &remove_from_head);2159remove_hashmap_entries(dir_re_merge, &remove_from_merge);2160}21612162static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)2163{2164struct hashmap *dir_renames;2165struct hashmap_iter iter;2166struct dir_rename_entry *entry;2167int i;21682169/*2170 * Typically, we think of a directory rename as all files from a2171 * certain directory being moved to a target directory. However,2172 * what if someone first moved two files from the original2173 * directory in one commit, and then renamed the directory2174 * somewhere else in a later commit? At merge time, we just know2175 * that files from the original directory went to two different2176 * places, and that the bulk of them ended up in the same place.2177 * We want each directory rename to represent where the bulk of the2178 * files from that directory end up; this function exists to find2179 * where the bulk of the files went.2180 *2181 * The first loop below simply iterates through the list of file2182 * renames, finding out how often each directory rename pair2183 * possibility occurs.2184 */2185 dir_renames =xmalloc(sizeof(*dir_renames));2186dir_rename_init(dir_renames);2187for(i =0; i < pairs->nr; ++i) {2188struct string_list_item *item;2189int*count;2190struct diff_filepair *pair = pairs->queue[i];2191char*old_dir, *new_dir;21922193/* File not part of directory rename if it wasn't renamed */2194if(pair->status !='R')2195continue;21962197get_renamed_dir_portion(pair->one->path, pair->two->path,2198&old_dir, &new_dir);2199if(!old_dir)2200/* Directory didn't change at all; ignore this one. */2201continue;22022203 entry =dir_rename_find_entry(dir_renames, old_dir);2204if(!entry) {2205 entry =xmalloc(sizeof(*entry));2206dir_rename_entry_init(entry, old_dir);2207hashmap_put(dir_renames, entry);2208}else{2209free(old_dir);2210}2211 item =string_list_lookup(&entry->possible_new_dirs, new_dir);2212if(!item) {2213 item =string_list_insert(&entry->possible_new_dirs,2214 new_dir);2215 item->util =xcalloc(1,sizeof(int));2216}else{2217free(new_dir);2218}2219 count = item->util;2220*count +=1;2221}22222223/*2224 * For each directory with files moved out of it, we find out which2225 * target directory received the most files so we can declare it to2226 * be the "winning" target location for the directory rename. This2227 * winner gets recorded in new_dir. If there is no winner2228 * (multiple target directories received the same number of files),2229 * we set non_unique_new_dir. Once we've determined the winner (or2230 * that there is no winner), we no longer need possible_new_dirs.2231 */2232hashmap_iter_init(dir_renames, &iter);2233while((entry =hashmap_iter_next(&iter))) {2234int max =0;2235int bad_max =0;2236char*best = NULL;22372238for(i =0; i < entry->possible_new_dirs.nr; i++) {2239int*count = entry->possible_new_dirs.items[i].util;22402241if(*count == max)2242 bad_max = max;2243else if(*count > max) {2244 max = *count;2245 best = entry->possible_new_dirs.items[i].string;2246}2247}2248if(bad_max == max)2249 entry->non_unique_new_dir =1;2250else{2251assert(entry->new_dir.len ==0);2252strbuf_addstr(&entry->new_dir, best);2253}2254/*2255 * The relevant directory sub-portion of the original full2256 * filepaths were xstrndup'ed before inserting into2257 * possible_new_dirs, and instead of manually iterating the2258 * list and free'ing each, just lie and tell2259 * possible_new_dirs that it did the strdup'ing so that it2260 * will free them for us.2261 */2262 entry->possible_new_dirs.strdup_strings =1;2263string_list_clear(&entry->possible_new_dirs,1);2264}22652266return dir_renames;2267}22682269static struct dir_rename_entry *check_dir_renamed(const char*path,2270struct hashmap *dir_renames)2271{2272char*temp =xstrdup(path);2273char*end;2274struct dir_rename_entry *entry = NULL;22752276while((end =strrchr(temp,'/'))) {2277*end ='\0';2278 entry =dir_rename_find_entry(dir_renames, temp);2279if(entry)2280break;2281}2282free(temp);2283return entry;2284}22852286static voidcompute_collisions(struct hashmap *collisions,2287struct hashmap *dir_renames,2288struct diff_queue_struct *pairs)2289{2290int i;22912292/*2293 * Multiple files can be mapped to the same path due to directory2294 * renames done by the other side of history. Since that other2295 * side of history could have merged multiple directories into one,2296 * if our side of history added the same file basename to each of2297 * those directories, then all N of them would get implicitly2298 * renamed by the directory rename detection into the same path,2299 * and we'd get an add/add/.../add conflict, and all those adds2300 * from *this* side of history. This is not representable in the2301 * index, and users aren't going to easily be able to make sense of2302 * it. So we need to provide a good warning about what's2303 * happening, and fall back to no-directory-rename detection2304 * behavior for those paths.2305 *2306 * See testcases 9e and all of section 5 from t6043 for examples.2307 */2308collision_init(collisions);23092310for(i =0; i < pairs->nr; ++i) {2311struct dir_rename_entry *dir_rename_ent;2312struct collision_entry *collision_ent;2313char*new_path;2314struct diff_filepair *pair = pairs->queue[i];23152316if(pair->status !='A'&& pair->status !='R')2317continue;2318 dir_rename_ent =check_dir_renamed(pair->two->path,2319 dir_renames);2320if(!dir_rename_ent)2321continue;23222323 new_path =apply_dir_rename(dir_rename_ent, pair->two->path);2324if(!new_path)2325/*2326 * dir_rename_ent->non_unique_new_path is true, which2327 * means there is no directory rename for us to use,2328 * which means it won't cause us any additional2329 * collisions.2330 */2331continue;2332 collision_ent =collision_find_entry(collisions, new_path);2333if(!collision_ent) {2334 collision_ent =xcalloc(1,2335sizeof(struct collision_entry));2336hashmap_entry_init(collision_ent,strhash(new_path));2337hashmap_put(collisions, collision_ent);2338 collision_ent->target_file = new_path;2339}else{2340free(new_path);2341}2342string_list_insert(&collision_ent->source_files,2343 pair->two->path);2344}2345}23462347static char*check_for_directory_rename(struct merge_options *opt,2348const char*path,2349struct tree *tree,2350struct hashmap *dir_renames,2351struct hashmap *dir_rename_exclusions,2352struct hashmap *collisions,2353int*clean_merge)2354{2355char*new_path = NULL;2356struct dir_rename_entry *entry =check_dir_renamed(path, dir_renames);2357struct dir_rename_entry *oentry = NULL;23582359if(!entry)2360return new_path;23612362/*2363 * This next part is a little weird. We do not want to do an2364 * implicit rename into a directory we renamed on our side, because2365 * that will result in a spurious rename/rename(1to2) conflict. An2366 * example:2367 * Base commit: dumbdir/afile, otherdir/bfile2368 * Side 1: smrtdir/afile, otherdir/bfile2369 * Side 2: dumbdir/afile, dumbdir/bfile2370 * Here, while working on Side 1, we could notice that otherdir was2371 * renamed/merged to dumbdir, and change the diff_filepair for2372 * otherdir/bfile into a rename into dumbdir/bfile. However, Side2373 * 2 will notice the rename from dumbdir to smrtdir, and do the2374 * transitive rename to move it from dumbdir/bfile to2375 * smrtdir/bfile. That gives us bfile in dumbdir vs being in2376 * smrtdir, a rename/rename(1to2) conflict. We really just want2377 * the file to end up in smrtdir. And the way to achieve that is2378 * to not let Side1 do the rename to dumbdir, since we know that is2379 * the source of one of our directory renames.2380 *2381 * That's why oentry and dir_rename_exclusions is here.2382 *2383 * As it turns out, this also prevents N-way transient rename2384 * confusion; See testcases 9c and 9d of t6043.2385 */2386 oentry =dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);2387if(oentry) {2388output(opt,1,_("WARNING: Avoiding applying%s->%srename "2389"to%s, because%sitself was renamed."),2390 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);2391}else{2392 new_path =handle_path_level_conflicts(opt, path, entry,2393 collisions, tree);2394*clean_merge &= (new_path != NULL);2395}23962397return new_path;2398}23992400static voidapply_directory_rename_modifications(struct merge_options *opt,2401struct diff_filepair *pair,2402char*new_path,2403struct rename *re,2404struct tree *tree,2405struct tree *o_tree,2406struct tree *a_tree,2407struct tree *b_tree,2408struct string_list *entries)2409{2410struct string_list_item *item;2411int stage = (tree == a_tree ?2:3);2412int update_wd;24132414/*2415 * In all cases where we can do directory rename detection,2416 * unpack_trees() will have read pair->two->path into the2417 * index and the working copy. We need to remove it so that2418 * we can instead place it at new_path. It is guaranteed to2419 * not be untracked (unpack_trees() would have errored out2420 * saying the file would have been overwritten), but it might2421 * be dirty, though.2422 */2423 update_wd = !was_dirty(opt, pair->two->path);2424if(!update_wd)2425output(opt,1,_("Refusing to lose dirty file at%s"),2426 pair->two->path);2427remove_file(opt,1, pair->two->path, !update_wd);24282429/* Find or create a new re->dst_entry */2430 item =string_list_lookup(entries, new_path);2431if(item) {2432/*2433 * Since we're renaming on this side of history, and it's2434 * due to a directory rename on the other side of history2435 * (which we only allow when the directory in question no2436 * longer exists on the other side of history), the2437 * original entry for re->dst_entry is no longer2438 * necessary...2439 */2440 re->dst_entry->processed =1;24412442/*2443 * ...because we'll be using this new one.2444 */2445 re->dst_entry = item->util;2446}else{2447/*2448 * re->dst_entry is for the before-dir-rename path, and we2449 * need it to hold information for the after-dir-rename2450 * path. Before creating a new entry, we need to mark the2451 * old one as unnecessary (...unless it is shared by2452 * src_entry, i.e. this didn't use to be a rename, in which2453 * case we can just allow the normal processing to happen2454 * for it).2455 */2456if(pair->status =='R')2457 re->dst_entry->processed =1;24582459 re->dst_entry =insert_stage_data(new_path,2460 o_tree, a_tree, b_tree,2461 entries);2462 item =string_list_insert(entries, new_path);2463 item->util = re->dst_entry;2464}24652466/*2467 * Update the stage_data with the information about the path we are2468 * moving into place. That slot will be empty and available for us2469 * to write to because of the collision checks in2470 * handle_path_level_conflicts(). In other words,2471 * re->dst_entry->stages[stage].oid will be the null_oid, so it's2472 * open for us to write to.2473 *2474 * It may be tempting to actually update the index at this point as2475 * well, using update_stages_for_stage_data(), but as per the big2476 * "NOTE" in update_stages(), doing so will modify the current2477 * in-memory index which will break calls to would_lose_untracked()2478 * that we need to make. Instead, we need to just make sure that2479 * the various handle_rename_*() functions update the index2480 * explicitly rather than relying on unpack_trees() to have done it.2481 */2482get_tree_entry(&tree->object.oid,2483 pair->two->path,2484&re->dst_entry->stages[stage].oid,2485&re->dst_entry->stages[stage].mode);24862487/* Update pair status */2488if(pair->status =='A') {2489/*2490 * Recording rename information for this add makes it look2491 * like a rename/delete conflict. Make sure we can2492 * correctly handle this as an add that was moved to a new2493 * directory instead of reporting a rename/delete conflict.2494 */2495 re->add_turned_into_rename =1;2496}2497/*2498 * We don't actually look at pair->status again, but it seems2499 * pedagogically correct to adjust it.2500 */2501 pair->status ='R';25022503/*2504 * Finally, record the new location.2505 */2506 pair->two->path = new_path;2507}25082509/*2510 * Get information of all renames which occurred in 'pairs', making use of2511 * any implicit directory renames inferred from the other side of history.2512 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')2513 * to be able to associate the correct cache entries with the rename2514 * information; tree is always equal to either a_tree or b_tree.2515 */2516static struct string_list *get_renames(struct merge_options *opt,2517const char*branch,2518struct diff_queue_struct *pairs,2519struct hashmap *dir_renames,2520struct hashmap *dir_rename_exclusions,2521struct tree *tree,2522struct tree *o_tree,2523struct tree *a_tree,2524struct tree *b_tree,2525struct string_list *entries,2526int*clean_merge)2527{2528int i;2529struct hashmap collisions;2530struct hashmap_iter iter;2531struct collision_entry *e;2532struct string_list *renames;25332534compute_collisions(&collisions, dir_renames, pairs);2535 renames =xcalloc(1,sizeof(struct string_list));25362537for(i =0; i < pairs->nr; ++i) {2538struct string_list_item *item;2539struct rename *re;2540struct diff_filepair *pair = pairs->queue[i];2541char*new_path;/* non-NULL only with directory renames */25422543if(pair->status !='A'&& pair->status !='R') {2544diff_free_filepair(pair);2545continue;2546}2547 new_path =check_for_directory_rename(opt, pair->two->path, tree,2548 dir_renames,2549 dir_rename_exclusions,2550&collisions,2551 clean_merge);2552if(pair->status !='R'&& !new_path) {2553diff_free_filepair(pair);2554continue;2555}25562557 re =xmalloc(sizeof(*re));2558 re->processed =0;2559 re->add_turned_into_rename =0;2560 re->pair = pair;2561 re->branch = branch;2562 item =string_list_lookup(entries, re->pair->one->path);2563if(!item)2564 re->src_entry =insert_stage_data(re->pair->one->path,2565 o_tree, a_tree, b_tree, entries);2566else2567 re->src_entry = item->util;25682569 item =string_list_lookup(entries, re->pair->two->path);2570if(!item)2571 re->dst_entry =insert_stage_data(re->pair->two->path,2572 o_tree, a_tree, b_tree, entries);2573else2574 re->dst_entry = item->util;2575 item =string_list_insert(renames, pair->one->path);2576 item->util = re;2577if(new_path)2578apply_directory_rename_modifications(opt, pair, new_path,2579 re, tree, o_tree,2580 a_tree, b_tree,2581 entries);2582}25832584hashmap_iter_init(&collisions, &iter);2585while((e =hashmap_iter_next(&iter))) {2586free(e->target_file);2587string_list_clear(&e->source_files,0);2588}2589hashmap_free(&collisions,1);2590return renames;2591}25922593static intprocess_renames(struct merge_options *opt,2594struct string_list *a_renames,2595struct string_list *b_renames)2596{2597int clean_merge =1, i, j;2598struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2599struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2600const struct rename *sre;26012602for(i =0; i < a_renames->nr; i++) {2603 sre = a_renames->items[i].util;2604string_list_insert(&a_by_dst, sre->pair->two->path)->util2605= (void*)sre;2606}2607for(i =0; i < b_renames->nr; i++) {2608 sre = b_renames->items[i].util;2609string_list_insert(&b_by_dst, sre->pair->two->path)->util2610= (void*)sre;2611}26122613for(i =0, j =0; i < a_renames->nr || j < b_renames->nr;) {2614struct string_list *renames1, *renames2Dst;2615struct rename *ren1 = NULL, *ren2 = NULL;2616const char*ren1_src, *ren1_dst;2617struct string_list_item *lookup;26182619if(i >= a_renames->nr) {2620 ren2 = b_renames->items[j++].util;2621}else if(j >= b_renames->nr) {2622 ren1 = a_renames->items[i++].util;2623}else{2624int compare =strcmp(a_renames->items[i].string,2625 b_renames->items[j].string);2626if(compare <=0)2627 ren1 = a_renames->items[i++].util;2628if(compare >=0)2629 ren2 = b_renames->items[j++].util;2630}26312632/* TODO: refactor, so that 1/2 are not needed */2633if(ren1) {2634 renames1 = a_renames;2635 renames2Dst = &b_by_dst;2636}else{2637 renames1 = b_renames;2638 renames2Dst = &a_by_dst;2639SWAP(ren2, ren1);2640}26412642if(ren1->processed)2643continue;2644 ren1->processed =1;2645 ren1->dst_entry->processed =1;2646/* BUG: We should only mark src_entry as processed if we2647 * are not dealing with a rename + add-source case.2648 */2649 ren1->src_entry->processed =1;26502651 ren1_src = ren1->pair->one->path;2652 ren1_dst = ren1->pair->two->path;26532654if(ren2) {2655/* One file renamed on both sides */2656const char*ren2_src = ren2->pair->one->path;2657const char*ren2_dst = ren2->pair->two->path;2658enum rename_type rename_type;2659if(strcmp(ren1_src, ren2_src) !=0)2660BUG("ren1_src != ren2_src");2661 ren2->dst_entry->processed =1;2662 ren2->processed =1;2663if(strcmp(ren1_dst, ren2_dst) !=0) {2664 rename_type = RENAME_ONE_FILE_TO_TWO;2665 clean_merge =0;2666}else{2667 rename_type = RENAME_ONE_FILE_TO_ONE;2668/* BUG: We should only remove ren1_src in2669 * the base stage (think of rename +2670 * add-source cases).2671 */2672remove_file(opt,1, ren1_src,1);2673update_entry(ren1->dst_entry,2674 ren1->pair->one,2675 ren1->pair->two,2676 ren2->pair->two);2677}2678setup_rename_conflict_info(rename_type, opt, ren1, ren2);2679}else if((lookup =string_list_lookup(renames2Dst, ren1_dst))) {2680/* Two different files renamed to the same thing */2681char*ren2_dst;2682 ren2 = lookup->util;2683 ren2_dst = ren2->pair->two->path;2684if(strcmp(ren1_dst, ren2_dst) !=0)2685BUG("ren1_dst != ren2_dst");26862687 clean_merge =0;2688 ren2->processed =1;2689/*2690 * BUG: We should only mark src_entry as processed2691 * if we are not dealing with a rename + add-source2692 * case.2693 */2694 ren2->src_entry->processed =1;26952696setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2697 opt, ren1, ren2);2698}else{2699/* Renamed in 1, maybe changed in 2 */2700/* we only use sha1 and mode of these */2701struct diff_filespec src_other, dst_other;2702int try_merge;27032704/*2705 * unpack_trees loads entries from common-commit2706 * into stage 1, from head-commit into stage 2, and2707 * from merge-commit into stage 3. We keep track2708 * of which side corresponds to the rename.2709 */2710int renamed_stage = a_renames == renames1 ?2:3;2711int other_stage = a_renames == renames1 ?3:2;27122713/* BUG: We should only remove ren1_src in the base2714 * stage and in other_stage (think of rename +2715 * add-source case).2716 */2717remove_file(opt,1, ren1_src,2718 renamed_stage ==2|| !was_tracked(opt, ren1_src));27192720oidcpy(&src_other.oid,2721&ren1->src_entry->stages[other_stage].oid);2722 src_other.mode = ren1->src_entry->stages[other_stage].mode;2723oidcpy(&dst_other.oid,2724&ren1->dst_entry->stages[other_stage].oid);2725 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2726 try_merge =0;27272728if(oid_eq(&src_other.oid, &null_oid) &&2729 ren1->add_turned_into_rename) {2730setup_rename_conflict_info(RENAME_VIA_DIR,2731 opt, ren1, NULL);2732}else if(oid_eq(&src_other.oid, &null_oid)) {2733setup_rename_conflict_info(RENAME_DELETE,2734 opt, ren1, NULL);2735}else if((dst_other.mode == ren1->pair->two->mode) &&2736oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {2737/*2738 * Added file on the other side identical to2739 * the file being renamed: clean merge.2740 * Also, there is no need to overwrite the2741 * file already in the working copy, so call2742 * update_file_flags() instead of2743 * update_file().2744 */2745if(update_file_flags(opt,2746 ren1->pair->two,2747 ren1_dst,27481,/* update_cache */27490/* update_wd */))2750 clean_merge = -1;2751}else if(!oid_eq(&dst_other.oid, &null_oid)) {2752/*2753 * Probably not a clean merge, but it's2754 * premature to set clean_merge to 0 here,2755 * because if the rename merges cleanly and2756 * the merge exactly matches the newly added2757 * file, then the merge will be clean.2758 */2759setup_rename_conflict_info(RENAME_ADD,2760 opt, ren1, NULL);2761}else2762 try_merge =1;27632764if(clean_merge <0)2765goto cleanup_and_return;2766if(try_merge) {2767struct diff_filespec *o, *a, *b;2768 src_other.path = (char*)ren1_src;27692770 o = ren1->pair->one;2771if(a_renames == renames1) {2772 a = ren1->pair->two;2773 b = &src_other;2774}else{2775 b = ren1->pair->two;2776 a = &src_other;2777}2778update_entry(ren1->dst_entry, o, a, b);2779setup_rename_conflict_info(RENAME_NORMAL,2780 opt, ren1, NULL);2781}2782}2783}2784cleanup_and_return:2785string_list_clear(&a_by_dst,0);2786string_list_clear(&b_by_dst,0);27872788return clean_merge;2789}27902791struct rename_info {2792struct string_list *head_renames;2793struct string_list *merge_renames;2794};27952796static voidinitial_cleanup_rename(struct diff_queue_struct *pairs,2797struct hashmap *dir_renames)2798{2799struct hashmap_iter iter;2800struct dir_rename_entry *e;28012802hashmap_iter_init(dir_renames, &iter);2803while((e =hashmap_iter_next(&iter))) {2804free(e->dir);2805strbuf_release(&e->new_dir);2806/* possible_new_dirs already cleared in get_directory_renames */2807}2808hashmap_free(dir_renames,1);2809free(dir_renames);28102811free(pairs->queue);2812free(pairs);2813}28142815static intdetect_and_process_renames(struct merge_options *opt,2816struct tree *common,2817struct tree *head,2818struct tree *merge,2819struct string_list *entries,2820struct rename_info *ri)2821{2822struct diff_queue_struct *head_pairs, *merge_pairs;2823struct hashmap *dir_re_head, *dir_re_merge;2824int clean =1;28252826 ri->head_renames = NULL;2827 ri->merge_renames = NULL;28282829if(!merge_detect_rename(opt))2830return1;28312832 head_pairs =get_diffpairs(opt, common, head);2833 merge_pairs =get_diffpairs(opt, common, merge);28342835if(opt->detect_directory_renames) {2836 dir_re_head =get_directory_renames(head_pairs);2837 dir_re_merge =get_directory_renames(merge_pairs);28382839handle_directory_level_conflicts(opt,2840 dir_re_head, head,2841 dir_re_merge, merge);2842}else{2843 dir_re_head =xmalloc(sizeof(*dir_re_head));2844 dir_re_merge =xmalloc(sizeof(*dir_re_merge));2845dir_rename_init(dir_re_head);2846dir_rename_init(dir_re_merge);2847}28482849 ri->head_renames =get_renames(opt, opt->branch1, head_pairs,2850 dir_re_merge, dir_re_head, head,2851 common, head, merge, entries,2852&clean);2853if(clean <0)2854goto cleanup;2855 ri->merge_renames =get_renames(opt, opt->branch2, merge_pairs,2856 dir_re_head, dir_re_merge, merge,2857 common, head, merge, entries,2858&clean);2859if(clean <0)2860goto cleanup;2861 clean &=process_renames(opt, ri->head_renames, ri->merge_renames);28622863cleanup:2864/*2865 * Some cleanup is deferred until cleanup_renames() because the2866 * data structures are still needed and referenced in2867 * process_entry(). But there are a few things we can free now.2868 */2869initial_cleanup_rename(head_pairs, dir_re_head);2870initial_cleanup_rename(merge_pairs, dir_re_merge);28712872return clean;2873}28742875static voidfinal_cleanup_rename(struct string_list *rename)2876{2877const struct rename *re;2878int i;28792880if(rename == NULL)2881return;28822883for(i =0; i < rename->nr; i++) {2884 re = rename->items[i].util;2885diff_free_filepair(re->pair);2886}2887string_list_clear(rename,1);2888free(rename);2889}28902891static voidfinal_cleanup_renames(struct rename_info *re_info)2892{2893final_cleanup_rename(re_info->head_renames);2894final_cleanup_rename(re_info->merge_renames);2895}28962897static intread_oid_strbuf(struct merge_options *opt,2898const struct object_id *oid,2899struct strbuf *dst)2900{2901void*buf;2902enum object_type type;2903unsigned long size;2904 buf =read_object_file(oid, &type, &size);2905if(!buf)2906returnerr(opt,_("cannot read object%s"),oid_to_hex(oid));2907if(type != OBJ_BLOB) {2908free(buf);2909returnerr(opt,_("object%sis not a blob"),oid_to_hex(oid));2910}2911strbuf_attach(dst, buf, size, size +1);2912return0;2913}29142915static intblob_unchanged(struct merge_options *opt,2916const struct diff_filespec *o,2917const struct diff_filespec *a,2918int renormalize,const char*path)2919{2920struct strbuf obuf = STRBUF_INIT;2921struct strbuf abuf = STRBUF_INIT;2922int ret =0;/* assume changed for safety */2923const struct index_state *idx = opt->repo->index;29242925if(a->mode != o->mode)2926return0;2927if(oid_eq(&o->oid, &a->oid))2928return1;2929if(!renormalize)2930return0;29312932if(read_oid_strbuf(opt, &o->oid, &obuf) ||2933read_oid_strbuf(opt, &a->oid, &abuf))2934goto error_return;2935/*2936 * Note: binary | is used so that both renormalizations are2937 * performed. Comparison can be skipped if both files are2938 * unchanged since their sha1s have already been compared.2939 */2940if(renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |2941renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))2942 ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));29432944error_return:2945strbuf_release(&obuf);2946strbuf_release(&abuf);2947return ret;2948}29492950static inthandle_modify_delete(struct merge_options *opt,2951const char*path,2952const struct diff_filespec *o,2953const struct diff_filespec *a,2954const struct diff_filespec *b)2955{2956const char*modify_branch, *delete_branch;2957const struct diff_filespec *changed;29582959if(is_valid(a)) {2960 modify_branch = opt->branch1;2961 delete_branch = opt->branch2;2962 changed = a;2963}else{2964 modify_branch = opt->branch2;2965 delete_branch = opt->branch1;2966 changed = b;2967}29682969returnhandle_change_delete(opt,2970 path, NULL,2971 o, changed,2972 modify_branch, delete_branch,2973_("modify"),_("modified"));2974}29752976static inthandle_content_merge(struct merge_options *opt,2977const char*path,2978int is_dirty,2979const struct diff_filespec *o,2980const struct diff_filespec *a,2981const struct diff_filespec *b,2982struct rename_conflict_info *ci)2983{2984const char*reason =_("content");2985struct merge_file_info mfi;2986unsigned df_conflict_remains =0;29872988if(!is_valid(o))2989 reason =_("add/add");29902991assert(o->path && a->path && b->path);2992if(ci &&dir_in_way(opt->repo->index, path, !opt->call_depth,2993S_ISGITLINK(ci->ren1->pair->two->mode)))2994 df_conflict_remains =1;29952996if(merge_mode_and_contents(opt, o, a, b, path,2997 opt->branch1, opt->branch2,2998 opt->call_depth *2, &mfi))2999return-1;30003001/*3002 * We can skip updating the working tree file iff:3003 * a) The merge is clean3004 * b) The merge matches what was in HEAD (content, mode, pathname)3005 * c) The target path is usable (i.e. not involved in D/F conflict)3006 */3007if(mfi.clean &&was_tracked_and_matches(opt, path, &mfi.blob) &&3008!df_conflict_remains) {3009int pos;3010struct cache_entry *ce;30113012output(opt,3,_("Skipped%s(merged same as existing)"), path);3013if(add_cacheinfo(opt, &mfi.blob, path,30140, (!opt->call_depth && !is_dirty),0))3015return-1;3016/*3017 * However, add_cacheinfo() will delete the old cache entry3018 * and add a new one. We need to copy over any skip_worktree3019 * flag to avoid making the file appear as if it were3020 * deleted by the user.3021 */3022 pos =index_name_pos(&opt->orig_index, path,strlen(path));3023 ce = opt->orig_index.cache[pos];3024if(ce_skip_worktree(ce)) {3025 pos =index_name_pos(opt->repo->index, path,strlen(path));3026 ce = opt->repo->index->cache[pos];3027 ce->ce_flags |= CE_SKIP_WORKTREE;3028}3029return mfi.clean;3030}30313032if(!mfi.clean) {3033if(S_ISGITLINK(mfi.blob.mode))3034 reason =_("submodule");3035output(opt,1,_("CONFLICT (%s): Merge conflict in%s"),3036 reason, path);3037if(ci && !df_conflict_remains)3038if(update_stages(opt, path, o, a, b))3039return-1;3040}30413042if(df_conflict_remains || is_dirty) {3043char*new_path;3044if(opt->call_depth) {3045remove_file_from_index(opt->repo->index, path);3046}else{3047if(!mfi.clean) {3048if(update_stages(opt, path, o, a, b))3049return-1;3050}else{3051int file_from_stage2 =was_tracked(opt, path);30523053if(update_stages(opt, path, NULL,3054 file_from_stage2 ? &mfi.blob : NULL,3055 file_from_stage2 ? NULL : &mfi.blob))3056return-1;3057}30583059}3060 new_path =unique_path(opt, path, ci->ren1->branch);3061if(is_dirty) {3062output(opt,1,_("Refusing to lose dirty file at%s"),3063 path);3064}3065output(opt,1,_("Adding as%sinstead"), new_path);3066if(update_file(opt,0, &mfi.blob, new_path)) {3067free(new_path);3068return-1;3069}3070free(new_path);3071 mfi.clean =0;3072}else if(update_file(opt, mfi.clean, &mfi.blob, path))3073return-1;3074return!is_dirty && mfi.clean;3075}30763077static inthandle_rename_normal(struct merge_options *opt,3078const char*path,3079const struct diff_filespec *o,3080const struct diff_filespec *a,3081const struct diff_filespec *b,3082struct rename_conflict_info *ci)3083{3084/* Merge the content and write it out */3085returnhandle_content_merge(opt, path,was_dirty(opt, path),3086 o, a, b, ci);3087}30883089/* Per entry merge function */3090static intprocess_entry(struct merge_options *opt,3091const char*path,struct stage_data *entry)3092{3093int clean_merge =1;3094int normalize = opt->renormalize;30953096struct diff_filespec *o = &entry->stages[1];3097struct diff_filespec *a = &entry->stages[2];3098struct diff_filespec *b = &entry->stages[3];3099int o_valid =is_valid(o);3100int a_valid =is_valid(a);3101int b_valid =is_valid(b);3102 o->path = a->path = b->path = (char*)path;31033104 entry->processed =1;3105if(entry->rename_conflict_info) {3106struct rename_conflict_info *ci = entry->rename_conflict_info;3107struct diff_filespec *temp;31083109/*3110 * For cases with a single rename, {o,a,b}->path have all been3111 * set to the rename target path; we need to set two of these3112 * back to the rename source.3113 * For rename/rename conflicts, we'll manually fix paths below.3114 */3115 temp = (opt->branch1 == ci->ren1->branch) ? b : a;3116 o->path = temp->path = ci->ren1->pair->one->path;3117if(ci->ren2) {3118assert(opt->branch1 == ci->ren1->branch);3119}31203121switch(ci->rename_type) {3122case RENAME_NORMAL:3123case RENAME_ONE_FILE_TO_ONE:3124 clean_merge =handle_rename_normal(opt, path, o, a, b,3125 ci);3126break;3127case RENAME_VIA_DIR:3128 clean_merge =1;3129if(handle_rename_via_dir(opt, ci))3130 clean_merge = -1;3131break;3132case RENAME_ADD:3133/*3134 * Probably unclean merge, but if the renamed file3135 * merges cleanly and the result can then be3136 * two-way merged cleanly with the added file, I3137 * guess it's a clean merge?3138 */3139 clean_merge =handle_rename_add(opt, ci);3140break;3141case RENAME_DELETE:3142 clean_merge =0;3143if(handle_rename_delete(opt, ci))3144 clean_merge = -1;3145break;3146case RENAME_ONE_FILE_TO_TWO:3147/*3148 * Manually fix up paths; note:3149 * ren[12]->pair->one->path are equal.3150 */3151 o->path = ci->ren1->pair->one->path;3152 a->path = ci->ren1->pair->two->path;3153 b->path = ci->ren2->pair->two->path;31543155 clean_merge =0;3156if(handle_rename_rename_1to2(opt, ci))3157 clean_merge = -1;3158break;3159case RENAME_TWO_FILES_TO_ONE:3160/*3161 * Manually fix up paths; note,3162 * ren[12]->pair->two->path are actually equal.3163 */3164 o->path = NULL;3165 a->path = ci->ren1->pair->two->path;3166 b->path = ci->ren2->pair->two->path;31673168/*3169 * Probably unclean merge, but if the two renamed3170 * files merge cleanly and the two resulting files3171 * can then be two-way merged cleanly, I guess it's3172 * a clean merge?3173 */3174 clean_merge =handle_rename_rename_2to1(opt, ci);3175break;3176default:3177 entry->processed =0;3178break;3179}3180}else if(o_valid && (!a_valid || !b_valid)) {3181/* Case A: Deleted in one */3182if((!a_valid && !b_valid) ||3183(!b_valid &&blob_unchanged(opt, o, a, normalize, path)) ||3184(!a_valid &&blob_unchanged(opt, o, b, normalize, path))) {3185/* Deleted in both or deleted in one and3186 * unchanged in the other */3187if(a_valid)3188output(opt,2,_("Removing%s"), path);3189/* do not touch working file if it did not exist */3190remove_file(opt,1, path, !a_valid);3191}else{3192/* Modify/delete; deleted side may have put a directory in the way */3193 clean_merge =0;3194if(handle_modify_delete(opt, path, o, a, b))3195 clean_merge = -1;3196}3197}else if((!o_valid && a_valid && !b_valid) ||3198(!o_valid && !a_valid && b_valid)) {3199/* Case B: Added in one. */3200/* [nothing|directory] -> ([nothing|directory], file) */32013202const char*add_branch;3203const char*other_branch;3204const char*conf;3205const struct diff_filespec *contents;32063207if(a_valid) {3208 add_branch = opt->branch1;3209 other_branch = opt->branch2;3210 contents = a;3211 conf =_("file/directory");3212}else{3213 add_branch = opt->branch2;3214 other_branch = opt->branch1;3215 contents = b;3216 conf =_("directory/file");3217}3218if(dir_in_way(opt->repo->index, path,3219!opt->call_depth && !S_ISGITLINK(a->mode),32200)) {3221char*new_path =unique_path(opt, path, add_branch);3222 clean_merge =0;3223output(opt,1,_("CONFLICT (%s): There is a directory with name%sin%s. "3224"Adding%sas%s"),3225 conf, path, other_branch, path, new_path);3226if(update_file(opt,0, contents, new_path))3227 clean_merge = -1;3228else if(opt->call_depth)3229remove_file_from_index(opt->repo->index, path);3230free(new_path);3231}else{3232output(opt,2,_("Adding%s"), path);3233/* do not overwrite file if already present */3234if(update_file_flags(opt, contents, path,1, !a_valid))3235 clean_merge = -1;3236}3237}else if(a_valid && b_valid) {3238if(!o_valid) {3239/* Case C: Added in both (check for same permissions) */3240output(opt,1,3241_("CONFLICT (add/add): Merge conflict in%s"),3242 path);3243 clean_merge =handle_file_collision(opt,3244 path, NULL, NULL,3245 opt->branch1,3246 opt->branch2,3247 a, b);3248}else{3249/* case D: Modified in both, but differently. */3250int is_dirty =0;/* unpack_trees would have bailed if dirty */3251 clean_merge =handle_content_merge(opt, path, is_dirty,3252 o, a, b, NULL);3253}3254}else if(!o_valid && !a_valid && !b_valid) {3255/*3256 * this entry was deleted altogether. a_mode == 0 means3257 * we had that path and want to actively remove it.3258 */3259remove_file(opt,1, path, !a->mode);3260}else3261BUG("fatal merge failure, shouldn't happen.");32623263return clean_merge;3264}32653266intmerge_trees(struct merge_options *opt,3267struct tree *head,3268struct tree *merge,3269struct tree *common,3270struct tree **result)3271{3272struct index_state *istate = opt->repo->index;3273int code, clean;3274struct strbuf sb = STRBUF_INIT;32753276if(!opt->call_depth &&repo_index_has_changes(opt->repo, head, &sb)) {3277err(opt,_("Your local changes to the following files would be overwritten by merge:\n%s"),3278 sb.buf);3279return-1;3280}32813282if(opt->subtree_shift) {3283 merge =shift_tree_object(opt->repo, head, merge, opt->subtree_shift);3284 common =shift_tree_object(opt->repo, head, common, opt->subtree_shift);3285}32863287if(oid_eq(&common->object.oid, &merge->object.oid)) {3288output(opt,0,_("Already up to date!"));3289*result = head;3290return1;3291}32923293 code =unpack_trees_start(opt, common, head, merge);32943295if(code !=0) {3296if(show(opt,4) || opt->call_depth)3297err(opt,_("merging of trees%sand%sfailed"),3298oid_to_hex(&head->object.oid),3299oid_to_hex(&merge->object.oid));3300unpack_trees_finish(opt);3301return-1;3302}33033304if(unmerged_index(istate)) {3305struct string_list *entries;3306struct rename_info re_info;3307int i;3308/*3309 * Only need the hashmap while processing entries, so3310 * initialize it here and free it when we are done running3311 * through the entries. Keeping it in the merge_options as3312 * opposed to decaring a local hashmap is for convenience3313 * so that we don't have to pass it to around.3314 */3315hashmap_init(&opt->current_file_dir_set, path_hashmap_cmp, NULL,512);3316get_files_dirs(opt, head);3317get_files_dirs(opt, merge);33183319 entries =get_unmerged(opt->repo->index);3320 clean =detect_and_process_renames(opt, common, head, merge,3321 entries, &re_info);3322record_df_conflict_files(opt, entries);3323if(clean <0)3324goto cleanup;3325for(i = entries->nr-1;0<= i; i--) {3326const char*path = entries->items[i].string;3327struct stage_data *e = entries->items[i].util;3328if(!e->processed) {3329int ret =process_entry(opt, path, e);3330if(!ret)3331 clean =0;3332else if(ret <0) {3333 clean = ret;3334goto cleanup;3335}3336}3337}3338for(i =0; i < entries->nr; i++) {3339struct stage_data *e = entries->items[i].util;3340if(!e->processed)3341BUG("unprocessed path???%s",3342 entries->items[i].string);3343}33443345 cleanup:3346final_cleanup_renames(&re_info);33473348string_list_clear(entries,1);3349free(entries);33503351hashmap_free(&opt->current_file_dir_set,1);33523353if(clean <0) {3354unpack_trees_finish(opt);3355return clean;3356}3357}3358else3359 clean =1;33603361unpack_trees_finish(opt);33623363if(opt->call_depth && !(*result =write_tree_from_memory(opt)))3364return-1;33653366return clean;3367}33683369static struct commit_list *reverse_commit_list(struct commit_list *list)3370{3371struct commit_list *next = NULL, *current, *backup;3372for(current = list; current; current = backup) {3373 backup = current->next;3374 current->next = next;3375 next = current;3376}3377return next;3378}33793380/*3381 * Merge the commits h1 and h2, return the resulting virtual3382 * commit object and a flag indicating the cleanness of the merge.3383 */3384intmerge_recursive(struct merge_options *opt,3385struct commit *h1,3386struct commit *h2,3387struct commit_list *ca,3388struct commit **result)3389{3390struct commit_list *iter;3391struct commit *merged_common_ancestors;3392struct tree *mrtree;3393int clean;33943395if(show(opt,4)) {3396output(opt,4,_("Merging:"));3397output_commit_title(opt, h1);3398output_commit_title(opt, h2);3399}34003401if(!ca) {3402 ca =get_merge_bases(h1, h2);3403 ca =reverse_commit_list(ca);3404}34053406if(show(opt,5)) {3407unsigned cnt =commit_list_count(ca);34083409output(opt,5,Q_("found%ucommon ancestor:",3410"found%ucommon ancestors:", cnt), cnt);3411for(iter = ca; iter; iter = iter->next)3412output_commit_title(opt, iter->item);3413}34143415 merged_common_ancestors =pop_commit(&ca);3416if(merged_common_ancestors == NULL) {3417/* if there is no common ancestor, use an empty tree */3418struct tree *tree;34193420 tree =lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);3421 merged_common_ancestors =make_virtual_commit(opt->repo, tree,"ancestor");3422}34233424for(iter = ca; iter; iter = iter->next) {3425const char*saved_b1, *saved_b2;3426 opt->call_depth++;3427/*3428 * When the merge fails, the result contains files3429 * with conflict markers. The cleanness flag is3430 * ignored (unless indicating an error), it was never3431 * actually used, as result of merge_trees has always3432 * overwritten it: the committed "conflicts" were3433 * already resolved.3434 */3435discard_index(opt->repo->index);3436 saved_b1 = opt->branch1;3437 saved_b2 = opt->branch2;3438 opt->branch1 ="Temporary merge branch 1";3439 opt->branch2 ="Temporary merge branch 2";3440if(merge_recursive(opt, merged_common_ancestors, iter->item,3441 NULL, &merged_common_ancestors) <0)3442return-1;3443 opt->branch1 = saved_b1;3444 opt->branch2 = saved_b2;3445 opt->call_depth--;34463447if(!merged_common_ancestors)3448returnerr(opt,_("merge returned no commit"));3449}34503451discard_index(opt->repo->index);3452if(!opt->call_depth)3453repo_read_index(opt->repo);34543455 opt->ancestor ="merged common ancestors";3456 clean =merge_trees(opt,get_commit_tree(h1),get_commit_tree(h2),3457get_commit_tree(merged_common_ancestors),3458&mrtree);3459if(clean <0) {3460flush_output(opt);3461return clean;3462}34633464if(opt->call_depth) {3465*result =make_virtual_commit(opt->repo, mrtree,"merged tree");3466commit_list_insert(h1, &(*result)->parents);3467commit_list_insert(h2, &(*result)->parents->next);3468}3469flush_output(opt);3470if(!opt->call_depth && opt->buffer_output <2)3471strbuf_release(&opt->obuf);3472if(show(opt,2))3473diff_warn_rename_limit("merge.renamelimit",3474 opt->needed_rename_limit,0);3475return clean;3476}34773478static struct commit *get_ref(struct repository *repo,const struct object_id *oid,3479const char*name)3480{3481struct object *object;34823483 object =deref_tag(repo,parse_object(repo, oid),3484 name,strlen(name));3485if(!object)3486return NULL;3487if(object->type == OBJ_TREE)3488returnmake_virtual_commit(repo, (struct tree*)object, name);3489if(object->type != OBJ_COMMIT)3490return NULL;3491if(parse_commit((struct commit *)object))3492return NULL;3493return(struct commit *)object;3494}34953496intmerge_recursive_generic(struct merge_options *opt,3497const struct object_id *head,3498const struct object_id *merge,3499int num_base_list,3500const struct object_id **base_list,3501struct commit **result)3502{3503int clean;3504struct lock_file lock = LOCK_INIT;3505struct commit *head_commit =get_ref(opt->repo, head, opt->branch1);3506struct commit *next_commit =get_ref(opt->repo, merge, opt->branch2);3507struct commit_list *ca = NULL;35083509if(base_list) {3510int i;3511for(i =0; i < num_base_list; ++i) {3512struct commit *base;3513if(!(base =get_ref(opt->repo, base_list[i],oid_to_hex(base_list[i]))))3514returnerr(opt,_("Could not parse object '%s'"),3515oid_to_hex(base_list[i]));3516commit_list_insert(base, &ca);3517}3518}35193520repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);3521 clean =merge_recursive(opt, head_commit, next_commit, ca,3522 result);3523if(clean <0) {3524rollback_lock_file(&lock);3525return clean;3526}35273528if(write_locked_index(opt->repo->index, &lock,3529 COMMIT_LOCK | SKIP_IF_UNCHANGED))3530returnerr(opt,_("Unable to write index."));35313532return clean ?0:1;3533}35343535static voidmerge_recursive_config(struct merge_options *opt)3536{3537char*value = NULL;3538git_config_get_int("merge.verbosity", &opt->verbosity);3539git_config_get_int("diff.renamelimit", &opt->diff_rename_limit);3540git_config_get_int("merge.renamelimit", &opt->merge_rename_limit);3541if(!git_config_get_string("diff.renames", &value)) {3542 opt->diff_detect_rename =git_config_rename("diff.renames", value);3543free(value);3544}3545if(!git_config_get_string("merge.renames", &value)) {3546 opt->merge_detect_rename =git_config_rename("merge.renames", value);3547free(value);3548}3549git_config(git_xmerge_config, NULL);3550}35513552voidinit_merge_options(struct merge_options *opt,3553struct repository *repo)3554{3555const char*merge_verbosity;3556memset(opt,0,sizeof(struct merge_options));3557 opt->repo = repo;3558 opt->verbosity =2;3559 opt->buffer_output =1;3560 opt->diff_rename_limit = -1;3561 opt->merge_rename_limit = -1;3562 opt->renormalize =0;3563 opt->diff_detect_rename = -1;3564 opt->merge_detect_rename = -1;3565 opt->detect_directory_renames =1;3566merge_recursive_config(opt);3567 merge_verbosity =getenv("GIT_MERGE_VERBOSITY");3568if(merge_verbosity)3569 opt->verbosity =strtol(merge_verbosity, NULL,10);3570if(opt->verbosity >=5)3571 opt->buffer_output =0;3572strbuf_init(&opt->obuf,0);3573string_list_init(&opt->df_conflict_file_set,1);3574}35753576intparse_merge_opt(struct merge_options *opt,const char*s)3577{3578const char*arg;35793580if(!s || !*s)3581return-1;3582if(!strcmp(s,"ours"))3583 opt->recursive_variant = MERGE_RECURSIVE_OURS;3584else if(!strcmp(s,"theirs"))3585 opt->recursive_variant = MERGE_RECURSIVE_THEIRS;3586else if(!strcmp(s,"subtree"))3587 opt->subtree_shift ="";3588else if(skip_prefix(s,"subtree=", &arg))3589 opt->subtree_shift = arg;3590else if(!strcmp(s,"patience"))3591 opt->xdl_opts =DIFF_WITH_ALG(opt, PATIENCE_DIFF);3592else if(!strcmp(s,"histogram"))3593 opt->xdl_opts =DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);3594else if(skip_prefix(s,"diff-algorithm=", &arg)) {3595long value =parse_algorithm_value(arg);3596if(value <0)3597return-1;3598/* clear out previous settings */3599DIFF_XDL_CLR(opt, NEED_MINIMAL);3600 opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;3601 opt->xdl_opts |= value;3602}3603else if(!strcmp(s,"ignore-space-change"))3604DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);3605else if(!strcmp(s,"ignore-all-space"))3606DIFF_XDL_SET(opt, IGNORE_WHITESPACE);3607else if(!strcmp(s,"ignore-space-at-eol"))3608DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);3609else if(!strcmp(s,"ignore-cr-at-eol"))3610DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);3611else if(!strcmp(s,"renormalize"))3612 opt->renormalize =1;3613else if(!strcmp(s,"no-renormalize"))3614 opt->renormalize =0;3615else if(!strcmp(s,"no-renames"))3616 opt->merge_detect_rename =0;3617else if(!strcmp(s,"find-renames")) {3618 opt->merge_detect_rename =1;3619 opt->rename_score =0;3620}3621else if(skip_prefix(s,"find-renames=", &arg) ||3622skip_prefix(s,"rename-threshold=", &arg)) {3623if((opt->rename_score =parse_rename_score(&arg)) == -1|| *arg !=0)3624return-1;3625 opt->merge_detect_rename =1;3626}3627/*3628 * Please update $__git_merge_strategy_options in3629 * git-completion.bash when you add new options3630 */3631else3632return-1;3633return0;3634}