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 *o) 119{ 120if(o->buffer_output <2&& o->obuf.len) { 121fputs(o->obuf.buf, stdout); 122strbuf_reset(&o->obuf); 123} 124} 125 126static interr(struct merge_options *o,const char*err, ...) 127{ 128va_list params; 129 130if(o->buffer_output <2) 131flush_output(o); 132else{ 133strbuf_complete(&o->obuf,'\n'); 134strbuf_addstr(&o->obuf,"error: "); 135} 136va_start(params, err); 137strbuf_vaddf(&o->obuf, err, params); 138va_end(params); 139if(o->buffer_output >1) 140strbuf_addch(&o->obuf,'\n'); 141else{ 142error("%s", o->obuf.buf); 143strbuf_reset(&o->obuf); 144} 145 146return-1; 147} 148 149static struct tree *shift_tree_object(struct tree *one,struct tree *two, 150const char*subtree_shift) 151{ 152struct object_id shifted; 153 154if(!*subtree_shift) { 155shift_tree(&one->object.oid, &two->object.oid, &shifted,0); 156}else{ 157shift_tree_by(&one->object.oid, &two->object.oid, &shifted, 158 subtree_shift); 159} 160if(oideq(&two->object.oid, &shifted)) 161return two; 162returnlookup_tree(the_repository, &shifted); 163} 164 165static struct commit *make_virtual_commit(struct tree *tree,const char*comment) 166{ 167struct commit *commit =alloc_commit_node(the_repository); 168 169set_merge_remote_desc(commit, comment, (struct object *)commit); 170 commit->maybe_tree = tree; 171 commit->object.parsed =1; 172return commit; 173} 174 175/* 176 * Since we use get_tree_entry(), which does not put the read object into 177 * the object pool, we cannot rely on a == b. 178 */ 179static intoid_eq(const struct object_id *a,const struct object_id *b) 180{ 181if(!a && !b) 182return2; 183return a && b &&oideq(a, b); 184} 185 186enum rename_type { 187 RENAME_NORMAL =0, 188 RENAME_VIA_DIR, 189 RENAME_DELETE, 190 RENAME_ONE_FILE_TO_ONE, 191 RENAME_ONE_FILE_TO_TWO, 192 RENAME_TWO_FILES_TO_ONE 193}; 194 195struct rename_conflict_info { 196enum rename_type rename_type; 197struct diff_filepair *pair1; 198struct diff_filepair *pair2; 199const char*branch1; 200const char*branch2; 201struct stage_data *dst_entry1; 202struct stage_data *dst_entry2; 203struct diff_filespec ren1_other; 204struct diff_filespec ren2_other; 205}; 206 207/* 208 * Since we want to write the index eventually, we cannot reuse the index 209 * for these (temporary) data. 210 */ 211struct stage_data { 212struct{ 213unsigned mode; 214struct object_id oid; 215} stages[4]; 216struct rename_conflict_info *rename_conflict_info; 217unsigned processed:1; 218}; 219 220staticinlinevoidsetup_rename_conflict_info(enum rename_type rename_type, 221struct diff_filepair *pair1, 222struct diff_filepair *pair2, 223const char*branch1, 224const char*branch2, 225struct stage_data *dst_entry1, 226struct stage_data *dst_entry2, 227struct merge_options *o, 228struct stage_data *src_entry1, 229struct stage_data *src_entry2) 230{ 231struct rename_conflict_info *ci; 232 233/* 234 * When we have two renames involved, it's easiest to get the 235 * correct things into stage 2 and 3, and to make sure that the 236 * content merge puts HEAD before the other branch if we just 237 * ensure that branch1 == o->branch1. So, simply flip arguments 238 * around if we don't have that. 239 */ 240if(dst_entry2 && branch1 != o->branch1) { 241setup_rename_conflict_info(rename_type, 242 pair2, pair1, 243 branch2, branch1, 244 dst_entry2, dst_entry1, 245 o, 246 src_entry2, src_entry1); 247return; 248} 249 250 ci =xcalloc(1,sizeof(struct rename_conflict_info)); 251 ci->rename_type = rename_type; 252 ci->pair1 = pair1; 253 ci->branch1 = branch1; 254 ci->branch2 = branch2; 255 256 ci->dst_entry1 = dst_entry1; 257 dst_entry1->rename_conflict_info = ci; 258 dst_entry1->processed =0; 259 260assert(!pair2 == !dst_entry2); 261if(dst_entry2) { 262 ci->dst_entry2 = dst_entry2; 263 ci->pair2 = pair2; 264 dst_entry2->rename_conflict_info = ci; 265} 266 267if(rename_type == RENAME_TWO_FILES_TO_ONE) { 268/* 269 * For each rename, there could have been 270 * modifications on the side of history where that 271 * file was not renamed. 272 */ 273int ostage1 = o->branch1 == branch1 ?3:2; 274int ostage2 = ostage1 ^1; 275 276 ci->ren1_other.path = pair1->one->path; 277oidcpy(&ci->ren1_other.oid, &src_entry1->stages[ostage1].oid); 278 ci->ren1_other.mode = src_entry1->stages[ostage1].mode; 279 280 ci->ren2_other.path = pair2->one->path; 281oidcpy(&ci->ren2_other.oid, &src_entry2->stages[ostage2].oid); 282 ci->ren2_other.mode = src_entry2->stages[ostage2].mode; 283} 284} 285 286static intshow(struct merge_options *o,int v) 287{ 288return(!o->call_depth && o->verbosity >= v) || o->verbosity >=5; 289} 290 291__attribute__((format(printf,3,4))) 292static voidoutput(struct merge_options *o,int v,const char*fmt, ...) 293{ 294va_list ap; 295 296if(!show(o, v)) 297return; 298 299strbuf_addchars(&o->obuf,' ', o->call_depth *2); 300 301va_start(ap, fmt); 302strbuf_vaddf(&o->obuf, fmt, ap); 303va_end(ap); 304 305strbuf_addch(&o->obuf,'\n'); 306if(!o->buffer_output) 307flush_output(o); 308} 309 310static voidoutput_commit_title(struct merge_options *o,struct commit *commit) 311{ 312struct merge_remote_desc *desc; 313 314strbuf_addchars(&o->obuf,' ', o->call_depth *2); 315 desc =merge_remote_util(commit); 316if(desc) 317strbuf_addf(&o->obuf,"virtual%s\n", desc->name); 318else{ 319strbuf_add_unique_abbrev(&o->obuf, &commit->object.oid, 320 DEFAULT_ABBREV); 321strbuf_addch(&o->obuf,' '); 322if(parse_commit(commit) !=0) 323strbuf_addstr(&o->obuf,_("(bad commit)\n")); 324else{ 325const char*title; 326const char*msg =get_commit_buffer(commit, NULL); 327int len =find_commit_subject(msg, &title); 328if(len) 329strbuf_addf(&o->obuf,"%.*s\n", len, title); 330unuse_commit_buffer(commit, msg); 331} 332} 333flush_output(o); 334} 335 336static intadd_cacheinfo(struct merge_options *o, 337unsigned int mode,const struct object_id *oid, 338const char*path,int stage,int refresh,int options) 339{ 340struct cache_entry *ce; 341int ret; 342 343 ce =make_cache_entry(&the_index, mode, oid ? oid : &null_oid, path, stage,0); 344if(!ce) 345returnerr(o,_("add_cacheinfo failed for path '%s'; merge aborting."), path); 346 347 ret =add_cache_entry(ce, options); 348if(refresh) { 349struct cache_entry *nce; 350 351 nce =refresh_cache_entry(&the_index, ce, CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING); 352if(!nce) 353returnerr(o,_("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path); 354if(nce != ce) 355 ret =add_cache_entry(nce, options); 356} 357return ret; 358} 359 360static voidinit_tree_desc_from_tree(struct tree_desc *desc,struct tree *tree) 361{ 362parse_tree(tree); 363init_tree_desc(desc, tree->buffer, tree->size); 364} 365 366static intunpack_trees_start(struct merge_options *o, 367struct tree *common, 368struct tree *head, 369struct tree *merge) 370{ 371int rc; 372struct tree_desc t[3]; 373struct index_state tmp_index = { NULL }; 374 375memset(&o->unpack_opts,0,sizeof(o->unpack_opts)); 376if(o->call_depth) 377 o->unpack_opts.index_only =1; 378else 379 o->unpack_opts.update =1; 380 o->unpack_opts.merge =1; 381 o->unpack_opts.head_idx =2; 382 o->unpack_opts.fn = threeway_merge; 383 o->unpack_opts.src_index = &the_index; 384 o->unpack_opts.dst_index = &tmp_index; 385 o->unpack_opts.aggressive = !merge_detect_rename(o); 386setup_unpack_trees_porcelain(&o->unpack_opts,"merge"); 387 388init_tree_desc_from_tree(t+0, common); 389init_tree_desc_from_tree(t+1, head); 390init_tree_desc_from_tree(t+2, merge); 391 392 rc =unpack_trees(3, t, &o->unpack_opts); 393cache_tree_free(&active_cache_tree); 394 395/* 396 * Update the_index to match the new results, AFTER saving a copy 397 * in o->orig_index. Update src_index to point to the saved copy. 398 * (verify_uptodate() checks src_index, and the original index is 399 * the one that had the necessary modification timestamps.) 400 */ 401 o->orig_index = the_index; 402 the_index = tmp_index; 403 o->unpack_opts.src_index = &o->orig_index; 404 405return rc; 406} 407 408static voidunpack_trees_finish(struct merge_options *o) 409{ 410discard_index(&o->orig_index); 411clear_unpack_trees_porcelain(&o->unpack_opts); 412} 413 414struct tree *write_tree_from_memory(struct merge_options *o) 415{ 416struct tree *result = NULL; 417 418if(unmerged_cache()) { 419int i; 420fprintf(stderr,"BUG: There are unmerged index entries:\n"); 421for(i =0; i < active_nr; i++) { 422const struct cache_entry *ce = active_cache[i]; 423if(ce_stage(ce)) 424fprintf(stderr,"BUG:%d%.*s\n",ce_stage(ce), 425(int)ce_namelen(ce), ce->name); 426} 427BUG("unmerged index entries in merge-recursive.c"); 428} 429 430if(!active_cache_tree) 431 active_cache_tree =cache_tree(); 432 433if(!cache_tree_fully_valid(active_cache_tree) && 434cache_tree_update(&the_index,0) <0) { 435err(o,_("error building trees")); 436return NULL; 437} 438 439 result =lookup_tree(the_repository, &active_cache_tree->oid); 440 441return result; 442} 443 444static intsave_files_dirs(const struct object_id *oid, 445struct strbuf *base,const char*path, 446unsigned int mode,int stage,void*context) 447{ 448struct path_hashmap_entry *entry; 449int baselen = base->len; 450struct merge_options *o = context; 451 452strbuf_addstr(base, path); 453 454FLEX_ALLOC_MEM(entry, path, base->buf, base->len); 455hashmap_entry_init(entry,path_hash(entry->path)); 456hashmap_add(&o->current_file_dir_set, entry); 457 458strbuf_setlen(base, baselen); 459return(S_ISDIR(mode) ? READ_TREE_RECURSIVE :0); 460} 461 462static voidget_files_dirs(struct merge_options *o,struct tree *tree) 463{ 464struct pathspec match_all; 465memset(&match_all,0,sizeof(match_all)); 466read_tree_recursive(tree,"",0,0, &match_all, save_files_dirs, o); 467} 468 469static intget_tree_entry_if_blob(const struct object_id *tree, 470const char*path, 471struct object_id *hashy, 472unsigned int*mode_o) 473{ 474int ret; 475 476 ret =get_tree_entry(tree, path, hashy, mode_o); 477if(S_ISDIR(*mode_o)) { 478oidcpy(hashy, &null_oid); 479*mode_o =0; 480} 481return ret; 482} 483 484/* 485 * Returns an index_entry instance which doesn't have to correspond to 486 * a real cache entry in Git's index. 487 */ 488static struct stage_data *insert_stage_data(const char*path, 489struct tree *o,struct tree *a,struct tree *b, 490struct string_list *entries) 491{ 492struct string_list_item *item; 493struct stage_data *e =xcalloc(1,sizeof(struct stage_data)); 494get_tree_entry_if_blob(&o->object.oid, path, 495&e->stages[1].oid, &e->stages[1].mode); 496get_tree_entry_if_blob(&a->object.oid, path, 497&e->stages[2].oid, &e->stages[2].mode); 498get_tree_entry_if_blob(&b->object.oid, path, 499&e->stages[3].oid, &e->stages[3].mode); 500 item =string_list_insert(entries, path); 501 item->util = e; 502return e; 503} 504 505/* 506 * Create a dictionary mapping file names to stage_data objects. The 507 * dictionary contains one entry for every path with a non-zero stage entry. 508 */ 509static struct string_list *get_unmerged(void) 510{ 511struct string_list *unmerged =xcalloc(1,sizeof(struct string_list)); 512int i; 513 514 unmerged->strdup_strings =1; 515 516for(i =0; i < active_nr; i++) { 517struct string_list_item *item; 518struct stage_data *e; 519const struct cache_entry *ce = active_cache[i]; 520if(!ce_stage(ce)) 521continue; 522 523 item =string_list_lookup(unmerged, ce->name); 524if(!item) { 525 item =string_list_insert(unmerged, ce->name); 526 item->util =xcalloc(1,sizeof(struct stage_data)); 527} 528 e = item->util; 529 e->stages[ce_stage(ce)].mode = ce->ce_mode; 530oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid); 531} 532 533return unmerged; 534} 535 536static intstring_list_df_name_compare(const char*one,const char*two) 537{ 538int onelen =strlen(one); 539int twolen =strlen(two); 540/* 541 * Here we only care that entries for D/F conflicts are 542 * adjacent, in particular with the file of the D/F conflict 543 * appearing before files below the corresponding directory. 544 * The order of the rest of the list is irrelevant for us. 545 * 546 * To achieve this, we sort with df_name_compare and provide 547 * the mode S_IFDIR so that D/F conflicts will sort correctly. 548 * We use the mode S_IFDIR for everything else for simplicity, 549 * since in other cases any changes in their order due to 550 * sorting cause no problems for us. 551 */ 552int cmp =df_name_compare(one, onelen, S_IFDIR, 553 two, twolen, S_IFDIR); 554/* 555 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure 556 * that 'foo' comes before 'foo/bar'. 557 */ 558if(cmp) 559return cmp; 560return onelen - twolen; 561} 562 563static voidrecord_df_conflict_files(struct merge_options *o, 564struct string_list *entries) 565{ 566/* If there is a D/F conflict and the file for such a conflict 567 * currently exists in the working tree, we want to allow it to be 568 * removed to make room for the corresponding directory if needed. 569 * The files underneath the directories of such D/F conflicts will 570 * be processed before the corresponding file involved in the D/F 571 * conflict. If the D/F directory ends up being removed by the 572 * merge, then we won't have to touch the D/F file. If the D/F 573 * directory needs to be written to the working copy, then the D/F 574 * file will simply be removed (in make_room_for_path()) to make 575 * room for the necessary paths. Note that if both the directory 576 * and the file need to be present, then the D/F file will be 577 * reinstated with a new unique name at the time it is processed. 578 */ 579struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP; 580const char*last_file = NULL; 581int last_len =0; 582int i; 583 584/* 585 * If we're merging merge-bases, we don't want to bother with 586 * any working directory changes. 587 */ 588if(o->call_depth) 589return; 590 591/* Ensure D/F conflicts are adjacent in the entries list. */ 592for(i =0; i < entries->nr; i++) { 593struct string_list_item *next = &entries->items[i]; 594string_list_append(&df_sorted_entries, next->string)->util = 595 next->util; 596} 597 df_sorted_entries.cmp = string_list_df_name_compare; 598string_list_sort(&df_sorted_entries); 599 600string_list_clear(&o->df_conflict_file_set,1); 601for(i =0; i < df_sorted_entries.nr; i++) { 602const char*path = df_sorted_entries.items[i].string; 603int len =strlen(path); 604struct stage_data *e = df_sorted_entries.items[i].util; 605 606/* 607 * Check if last_file & path correspond to a D/F conflict; 608 * i.e. whether path is last_file+'/'+<something>. 609 * If so, record that it's okay to remove last_file to make 610 * room for path and friends if needed. 611 */ 612if(last_file && 613 len > last_len && 614memcmp(path, last_file, last_len) ==0&& 615 path[last_len] =='/') { 616string_list_insert(&o->df_conflict_file_set, last_file); 617} 618 619/* 620 * Determine whether path could exist as a file in the 621 * working directory as a possible D/F conflict. This 622 * will only occur when it exists in stage 2 as a 623 * file. 624 */ 625if(S_ISREG(e->stages[2].mode) ||S_ISLNK(e->stages[2].mode)) { 626 last_file = path; 627 last_len = len; 628}else{ 629 last_file = NULL; 630} 631} 632string_list_clear(&df_sorted_entries,0); 633} 634 635struct rename { 636struct diff_filepair *pair; 637/* 638 * Purpose of src_entry and dst_entry: 639 * 640 * If 'before' is renamed to 'after' then src_entry will contain 641 * the versions of 'before' from the merge_base, HEAD, and MERGE in 642 * stages 1, 2, and 3; dst_entry will contain the respective 643 * versions of 'after' in corresponding locations. Thus, we have a 644 * total of six modes and oids, though some will be null. (Stage 0 645 * is ignored; we're interested in handling conflicts.) 646 * 647 * Since we don't turn on break-rewrites by default, neither 648 * src_entry nor dst_entry can have all three of their stages have 649 * non-null oids, meaning at most four of the six will be non-null. 650 * Also, since this is a rename, both src_entry and dst_entry will 651 * have at least one non-null oid, meaning at least two will be 652 * non-null. Of the six oids, a typical rename will have three be 653 * non-null. Only two implies a rename/delete, and four implies a 654 * rename/add. 655 */ 656struct stage_data *src_entry; 657struct stage_data *dst_entry; 658unsigned add_turned_into_rename:1; 659unsigned processed:1; 660}; 661 662static intupdate_stages(struct merge_options *opt,const char*path, 663const struct diff_filespec *o, 664const struct diff_filespec *a, 665const struct diff_filespec *b) 666{ 667 668/* 669 * NOTE: It is usually a bad idea to call update_stages on a path 670 * before calling update_file on that same path, since it can 671 * sometimes lead to spurious "refusing to lose untracked file..." 672 * messages from update_file (via make_room_for path via 673 * would_lose_untracked). Instead, reverse the order of the calls 674 * (executing update_file first and then update_stages). 675 */ 676int clear =1; 677int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK; 678if(clear) 679if(remove_file_from_cache(path)) 680return-1; 681if(o) 682if(add_cacheinfo(opt, o->mode, &o->oid, path,1,0, options)) 683return-1; 684if(a) 685if(add_cacheinfo(opt, a->mode, &a->oid, path,2,0, options)) 686return-1; 687if(b) 688if(add_cacheinfo(opt, b->mode, &b->oid, path,3,0, options)) 689return-1; 690return0; 691} 692 693static intupdate_stages_for_stage_data(struct merge_options *opt, 694const char*path, 695const struct stage_data *stage_data) 696{ 697struct diff_filespec o, a, b; 698 699 o.mode = stage_data->stages[1].mode; 700oidcpy(&o.oid, &stage_data->stages[1].oid); 701 702 a.mode = stage_data->stages[2].mode; 703oidcpy(&a.oid, &stage_data->stages[2].oid); 704 705 b.mode = stage_data->stages[3].mode; 706oidcpy(&b.oid, &stage_data->stages[3].oid); 707 708returnupdate_stages(opt, path, 709is_null_oid(&o.oid) ? NULL : &o, 710is_null_oid(&a.oid) ? NULL : &a, 711is_null_oid(&b.oid) ? NULL : &b); 712} 713 714static voidupdate_entry(struct stage_data *entry, 715struct diff_filespec *o, 716struct diff_filespec *a, 717struct diff_filespec *b) 718{ 719 entry->processed =0; 720 entry->stages[1].mode = o->mode; 721 entry->stages[2].mode = a->mode; 722 entry->stages[3].mode = b->mode; 723oidcpy(&entry->stages[1].oid, &o->oid); 724oidcpy(&entry->stages[2].oid, &a->oid); 725oidcpy(&entry->stages[3].oid, &b->oid); 726} 727 728static intremove_file(struct merge_options *o,int clean, 729const char*path,int no_wd) 730{ 731int update_cache = o->call_depth || clean; 732int update_working_directory = !o->call_depth && !no_wd; 733 734if(update_cache) { 735if(remove_file_from_cache(path)) 736return-1; 737} 738if(update_working_directory) { 739if(ignore_case) { 740struct cache_entry *ce; 741 ce =cache_file_exists(path,strlen(path), ignore_case); 742if(ce &&ce_stage(ce) ==0&&strcmp(path, ce->name)) 743return0; 744} 745if(remove_path(path)) 746return-1; 747} 748return0; 749} 750 751/* add a string to a strbuf, but converting "/" to "_" */ 752static voidadd_flattened_path(struct strbuf *out,const char*s) 753{ 754size_t i = out->len; 755strbuf_addstr(out, s); 756for(; i < out->len; i++) 757if(out->buf[i] =='/') 758 out->buf[i] ='_'; 759} 760 761static char*unique_path(struct merge_options *o,const char*path,const char*branch) 762{ 763struct path_hashmap_entry *entry; 764struct strbuf newpath = STRBUF_INIT; 765int suffix =0; 766size_t base_len; 767 768strbuf_addf(&newpath,"%s~", path); 769add_flattened_path(&newpath, branch); 770 771 base_len = newpath.len; 772while(hashmap_get_from_hash(&o->current_file_dir_set, 773path_hash(newpath.buf), newpath.buf) || 774(!o->call_depth &&file_exists(newpath.buf))) { 775strbuf_setlen(&newpath, base_len); 776strbuf_addf(&newpath,"_%d", suffix++); 777} 778 779FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len); 780hashmap_entry_init(entry,path_hash(entry->path)); 781hashmap_add(&o->current_file_dir_set, entry); 782returnstrbuf_detach(&newpath, NULL); 783} 784 785/** 786 * Check whether a directory in the index is in the way of an incoming 787 * file. Return 1 if so. If check_working_copy is non-zero, also 788 * check the working directory. If empty_ok is non-zero, also return 789 * 0 in the case where the working-tree dir exists but is empty. 790 */ 791static intdir_in_way(const char*path,int check_working_copy,int empty_ok) 792{ 793int pos; 794struct strbuf dirpath = STRBUF_INIT; 795struct stat st; 796 797strbuf_addstr(&dirpath, path); 798strbuf_addch(&dirpath,'/'); 799 800 pos =cache_name_pos(dirpath.buf, dirpath.len); 801 802if(pos <0) 803 pos = -1- pos; 804if(pos < active_nr && 805!strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) { 806strbuf_release(&dirpath); 807return1; 808} 809 810strbuf_release(&dirpath); 811return check_working_copy && !lstat(path, &st) &&S_ISDIR(st.st_mode) && 812!(empty_ok &&is_empty_dir(path)); 813} 814 815/* 816 * Returns whether path was tracked in the index before the merge started, 817 * and its oid and mode match the specified values 818 */ 819static intwas_tracked_and_matches(struct merge_options *o,const char*path, 820const struct object_id *oid,unsigned mode) 821{ 822int pos =index_name_pos(&o->orig_index, path,strlen(path)); 823struct cache_entry *ce; 824 825if(0> pos) 826/* we were not tracking this path before the merge */ 827return0; 828 829/* See if the file we were tracking before matches */ 830 ce = o->orig_index.cache[pos]; 831return(oid_eq(&ce->oid, oid) && ce->ce_mode == mode); 832} 833 834/* 835 * Returns whether path was tracked in the index before the merge started 836 */ 837static intwas_tracked(struct merge_options *o,const char*path) 838{ 839int pos =index_name_pos(&o->orig_index, path,strlen(path)); 840 841if(0<= pos) 842/* we were tracking this path before the merge */ 843return1; 844 845return0; 846} 847 848static intwould_lose_untracked(const char*path) 849{ 850/* 851 * This may look like it can be simplified to: 852 * return !was_tracked(o, path) && file_exists(path) 853 * but it can't. This function needs to know whether path was in 854 * the working tree due to EITHER having been tracked in the index 855 * before the merge OR having been put into the working copy and 856 * index by unpack_trees(). Due to that either-or requirement, we 857 * check the current index instead of the original one. 858 * 859 * Note that we do not need to worry about merge-recursive itself 860 * updating the index after unpack_trees() and before calling this 861 * function, because we strictly require all code paths in 862 * merge-recursive to update the working tree first and the index 863 * second. Doing otherwise would break 864 * update_file()/would_lose_untracked(); see every comment in this 865 * file which mentions "update_stages". 866 */ 867int pos =cache_name_pos(path,strlen(path)); 868 869if(pos <0) 870 pos = -1- pos; 871while(pos < active_nr && 872!strcmp(path, active_cache[pos]->name)) { 873/* 874 * If stage #0, it is definitely tracked. 875 * If it has stage #2 then it was tracked 876 * before this merge started. All other 877 * cases the path was not tracked. 878 */ 879switch(ce_stage(active_cache[pos])) { 880case0: 881case2: 882return0; 883} 884 pos++; 885} 886returnfile_exists(path); 887} 888 889static intwas_dirty(struct merge_options *o,const char*path) 890{ 891struct cache_entry *ce; 892int dirty =1; 893 894if(o->call_depth || !was_tracked(o, path)) 895return!dirty; 896 897 ce =index_file_exists(o->unpack_opts.src_index, 898 path,strlen(path), ignore_case); 899 dirty =verify_uptodate(ce, &o->unpack_opts) !=0; 900return dirty; 901} 902 903static intmake_room_for_path(struct merge_options *o,const char*path) 904{ 905int status, i; 906const char*msg =_("failed to create path '%s'%s"); 907 908/* Unlink any D/F conflict files that are in the way */ 909for(i =0; i < o->df_conflict_file_set.nr; i++) { 910const char*df_path = o->df_conflict_file_set.items[i].string; 911size_t pathlen =strlen(path); 912size_t df_pathlen =strlen(df_path); 913if(df_pathlen < pathlen && 914 path[df_pathlen] =='/'&& 915strncmp(path, df_path, df_pathlen) ==0) { 916output(o,3, 917_("Removing%sto make room for subdirectory\n"), 918 df_path); 919unlink(df_path); 920unsorted_string_list_delete_item(&o->df_conflict_file_set, 921 i,0); 922break; 923} 924} 925 926/* Make sure leading directories are created */ 927 status =safe_create_leading_directories_const(path); 928if(status) { 929if(status == SCLD_EXISTS) 930/* something else exists */ 931returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 932returnerr(o, msg, path,""); 933} 934 935/* 936 * Do not unlink a file in the work tree if we are not 937 * tracking it. 938 */ 939if(would_lose_untracked(path)) 940returnerr(o,_("refusing to lose untracked file at '%s'"), 941 path); 942 943/* Successful unlink is good.. */ 944if(!unlink(path)) 945return0; 946/* .. and so is no existing file */ 947if(errno == ENOENT) 948return0; 949/* .. but not some other error (who really cares what?) */ 950returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 951} 952 953static intupdate_file_flags(struct merge_options *o, 954const struct object_id *oid, 955unsigned mode, 956const char*path, 957int update_cache, 958int update_wd) 959{ 960int ret =0; 961 962if(o->call_depth) 963 update_wd =0; 964 965if(update_wd) { 966enum object_type type; 967void*buf; 968unsigned long size; 969 970if(S_ISGITLINK(mode)) { 971/* 972 * We may later decide to recursively descend into 973 * the submodule directory and update its index 974 * and/or work tree, but we do not do that now. 975 */ 976 update_wd =0; 977goto update_index; 978} 979 980 buf =read_object_file(oid, &type, &size); 981if(!buf) 982returnerr(o,_("cannot read object%s'%s'"),oid_to_hex(oid), path); 983if(type != OBJ_BLOB) { 984 ret =err(o,_("blob expected for%s'%s'"),oid_to_hex(oid), path); 985goto free_buf; 986} 987if(S_ISREG(mode)) { 988struct strbuf strbuf = STRBUF_INIT; 989if(convert_to_working_tree(&the_index, path, buf, size, &strbuf)) { 990free(buf); 991 size = strbuf.len; 992 buf =strbuf_detach(&strbuf, NULL); 993} 994} 995 996if(make_room_for_path(o, path) <0) { 997 update_wd =0; 998goto free_buf; 999}1000if(S_ISREG(mode) || (!has_symlinks &&S_ISLNK(mode))) {1001int fd;1002if(mode &0100)1003 mode =0777;1004else1005 mode =0666;1006 fd =open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);1007if(fd <0) {1008 ret =err(o,_("failed to open '%s':%s"),1009 path,strerror(errno));1010goto free_buf;1011}1012write_in_full(fd, buf, size);1013close(fd);1014}else if(S_ISLNK(mode)) {1015char*lnk =xmemdupz(buf, size);1016safe_create_leading_directories_const(path);1017unlink(path);1018if(symlink(lnk, path))1019 ret =err(o,_("failed to symlink '%s':%s"),1020 path,strerror(errno));1021free(lnk);1022}else1023 ret =err(o,1024_("do not know what to do with%06o%s'%s'"),1025 mode,oid_to_hex(oid), path);1026 free_buf:1027free(buf);1028}1029update_index:1030if(!ret && update_cache)1031if(add_cacheinfo(o, mode, oid, path,0, update_wd,1032 ADD_CACHE_OK_TO_ADD))1033return-1;1034return ret;1035}10361037static intupdate_file(struct merge_options *o,1038int clean,1039const struct object_id *oid,1040unsigned mode,1041const char*path)1042{1043returnupdate_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);1044}10451046/* Low level file merging, update and removal */10471048struct merge_file_info {1049struct object_id oid;1050unsigned mode;1051unsigned clean:1,1052 merge:1;1053};10541055static intmerge_3way(struct merge_options *o,1056 mmbuffer_t *result_buf,1057const struct diff_filespec *one,1058const struct diff_filespec *a,1059const struct diff_filespec *b,1060const char*branch1,1061const char*branch2)1062{1063 mmfile_t orig, src1, src2;1064struct ll_merge_options ll_opts = {0};1065char*base_name, *name1, *name2;1066int merge_status;10671068 ll_opts.renormalize = o->renormalize;1069 ll_opts.xdl_opts = o->xdl_opts;10701071if(o->call_depth) {1072 ll_opts.virtual_ancestor =1;1073 ll_opts.variant =0;1074}else{1075switch(o->recursive_variant) {1076case MERGE_RECURSIVE_OURS:1077 ll_opts.variant = XDL_MERGE_FAVOR_OURS;1078break;1079case MERGE_RECURSIVE_THEIRS:1080 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;1081break;1082default:1083 ll_opts.variant =0;1084break;1085}1086}10871088if(strcmp(a->path, b->path) ||1089(o->ancestor != NULL &&strcmp(a->path, one->path) !=0)) {1090 base_name = o->ancestor == NULL ? NULL :1091mkpathdup("%s:%s", o->ancestor, one->path);1092 name1 =mkpathdup("%s:%s", branch1, a->path);1093 name2 =mkpathdup("%s:%s", branch2, b->path);1094}else{1095 base_name = o->ancestor == NULL ? NULL :1096mkpathdup("%s", o->ancestor);1097 name1 =mkpathdup("%s", branch1);1098 name2 =mkpathdup("%s", branch2);1099}11001101read_mmblob(&orig, &one->oid);1102read_mmblob(&src1, &a->oid);1103read_mmblob(&src2, &b->oid);11041105 merge_status =ll_merge(result_buf, a->path, &orig, base_name,1106&src1, name1, &src2, name2,1107&the_index, &ll_opts);11081109free(base_name);1110free(name1);1111free(name2);1112free(orig.ptr);1113free(src1.ptr);1114free(src2.ptr);1115return merge_status;1116}11171118static intfind_first_merges(struct object_array *result,const char*path,1119struct commit *a,struct commit *b)1120{1121int i, j;1122struct object_array merges = OBJECT_ARRAY_INIT;1123struct commit *commit;1124int contains_another;11251126char merged_revision[42];1127const char*rev_args[] = {"rev-list","--merges","--ancestry-path",1128"--all", merged_revision, NULL };1129struct rev_info revs;1130struct setup_revision_opt rev_opts;11311132memset(result,0,sizeof(struct object_array));1133memset(&rev_opts,0,sizeof(rev_opts));11341135/* get all revisions that merge commit a */1136xsnprintf(merged_revision,sizeof(merged_revision),"^%s",1137oid_to_hex(&a->object.oid));1138repo_init_revisions(the_repository, &revs, NULL);1139 rev_opts.submodule = path;1140/* FIXME: can't handle linked worktrees in submodules yet */1141 revs.single_worktree = path != NULL;1142setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);11431144/* save all revisions from the above list that contain b */1145if(prepare_revision_walk(&revs))1146die("revision walk setup failed");1147while((commit =get_revision(&revs)) != NULL) {1148struct object *o = &(commit->object);1149if(in_merge_bases(b, commit))1150add_object_array(o, NULL, &merges);1151}1152reset_revision_walk();11531154/* Now we've got all merges that contain a and b. Prune all1155 * merges that contain another found merge and save them in1156 * result.1157 */1158for(i =0; i < merges.nr; i++) {1159struct commit *m1 = (struct commit *) merges.objects[i].item;11601161 contains_another =0;1162for(j =0; j < merges.nr; j++) {1163struct commit *m2 = (struct commit *) merges.objects[j].item;1164if(i != j &&in_merge_bases(m2, m1)) {1165 contains_another =1;1166break;1167}1168}11691170if(!contains_another)1171add_object_array(merges.objects[i].item, NULL, result);1172}11731174object_array_clear(&merges);1175return result->nr;1176}11771178static voidprint_commit(struct commit *commit)1179{1180struct strbuf sb = STRBUF_INIT;1181struct pretty_print_context ctx = {0};1182 ctx.date_mode.type = DATE_NORMAL;1183format_commit_message(commit,"%h:%m %s", &sb, &ctx);1184fprintf(stderr,"%s\n", sb.buf);1185strbuf_release(&sb);1186}11871188static intmerge_submodule(struct merge_options *o,1189struct object_id *result,const char*path,1190const struct object_id *base,const struct object_id *a,1191const struct object_id *b)1192{1193struct commit *commit_base, *commit_a, *commit_b;1194int parent_count;1195struct object_array merges;11961197int i;1198int search = !o->call_depth;11991200/* store a in result in case we fail */1201oidcpy(result, a);12021203/* we can not handle deletion conflicts */1204if(is_null_oid(base))1205return0;1206if(is_null_oid(a))1207return0;1208if(is_null_oid(b))1209return0;12101211if(add_submodule_odb(path)) {1212output(o,1,_("Failed to merge submodule%s(not checked out)"), path);1213return0;1214}12151216if(!(commit_base =lookup_commit_reference(the_repository, base)) ||1217!(commit_a =lookup_commit_reference(the_repository, a)) ||1218!(commit_b =lookup_commit_reference(the_repository, b))) {1219output(o,1,_("Failed to merge submodule%s(commits not present)"), path);1220return0;1221}12221223/* check whether both changes are forward */1224if(!in_merge_bases(commit_base, commit_a) ||1225!in_merge_bases(commit_base, commit_b)) {1226output(o,1,_("Failed to merge submodule%s(commits don't follow merge-base)"), path);1227return0;1228}12291230/* Case #1: a is contained in b or vice versa */1231if(in_merge_bases(commit_a, commit_b)) {1232oidcpy(result, b);1233if(show(o,3)) {1234output(o,3,_("Fast-forwarding submodule%sto the following commit:"), path);1235output_commit_title(o, commit_b);1236}else if(show(o,2))1237output(o,2,_("Fast-forwarding submodule%s"), path);1238else1239;/* no output */12401241return1;1242}1243if(in_merge_bases(commit_b, commit_a)) {1244oidcpy(result, a);1245if(show(o,3)) {1246output(o,3,_("Fast-forwarding submodule%sto the following commit:"), path);1247output_commit_title(o, commit_a);1248}else if(show(o,2))1249output(o,2,_("Fast-forwarding submodule%s"), path);1250else1251;/* no output */12521253return1;1254}12551256/*1257 * Case #2: There are one or more merges that contain a and b in1258 * the submodule. If there is only one, then present it as a1259 * suggestion to the user, but leave it marked unmerged so the1260 * user needs to confirm the resolution.1261 */12621263/* Skip the search if makes no sense to the calling context. */1264if(!search)1265return0;12661267/* find commit which merges them */1268 parent_count =find_first_merges(&merges, path, commit_a, commit_b);1269switch(parent_count) {1270case0:1271output(o,1,_("Failed to merge submodule%s(merge following commits not found)"), path);1272break;12731274case1:1275output(o,1,_("Failed to merge submodule%s(not fast-forward)"), path);1276output(o,2,_("Found a possible merge resolution for the submodule:\n"));1277print_commit((struct commit *) merges.objects[0].item);1278output(o,2,_(1279"If this is correct simply add it to the index "1280"for example\n"1281"by using:\n\n"1282" git update-index --cacheinfo 160000%s\"%s\"\n\n"1283"which will accept this suggestion.\n"),1284oid_to_hex(&merges.objects[0].item->oid), path);1285break;12861287default:1288output(o,1,_("Failed to merge submodule%s(multiple merges found)"), path);1289for(i =0; i < merges.nr; i++)1290print_commit((struct commit *) merges.objects[i].item);1291}12921293object_array_clear(&merges);1294return0;1295}12961297static intmerge_mode_and_contents(struct merge_options *o,1298const struct diff_filespec *one,1299const struct diff_filespec *a,1300const struct diff_filespec *b,1301const char*filename,1302const char*branch1,1303const char*branch2,1304struct merge_file_info *result)1305{1306if(o->branch1 != branch1) {1307/*1308 * It's weird getting a reverse merge with HEAD on the bottom1309 * side of the conflict markers and the other branch on the1310 * top. Fix that.1311 */1312returnmerge_mode_and_contents(o, one, b, a,1313 filename,1314 branch2, branch1, result);1315}13161317 result->merge =0;1318 result->clean =1;13191320if((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1321 result->clean =0;1322if(S_ISREG(a->mode)) {1323 result->mode = a->mode;1324oidcpy(&result->oid, &a->oid);1325}else{1326 result->mode = b->mode;1327oidcpy(&result->oid, &b->oid);1328}1329}else{1330if(!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))1331 result->merge =1;13321333/*1334 * Merge modes1335 */1336if(a->mode == b->mode || a->mode == one->mode)1337 result->mode = b->mode;1338else{1339 result->mode = a->mode;1340if(b->mode != one->mode) {1341 result->clean =0;1342 result->merge =1;1343}1344}13451346if(oid_eq(&a->oid, &b->oid) ||oid_eq(&a->oid, &one->oid))1347oidcpy(&result->oid, &b->oid);1348else if(oid_eq(&b->oid, &one->oid))1349oidcpy(&result->oid, &a->oid);1350else if(S_ISREG(a->mode)) {1351 mmbuffer_t result_buf;1352int ret =0, merge_status;13531354 merge_status =merge_3way(o, &result_buf, one, a, b,1355 branch1, branch2);13561357if((merge_status <0) || !result_buf.ptr)1358 ret =err(o,_("Failed to execute internal merge"));13591360if(!ret &&1361write_object_file(result_buf.ptr, result_buf.size,1362 blob_type, &result->oid))1363 ret =err(o,_("Unable to add%sto database"),1364 a->path);13651366free(result_buf.ptr);1367if(ret)1368return ret;1369 result->clean = (merge_status ==0);1370}else if(S_ISGITLINK(a->mode)) {1371 result->clean =merge_submodule(o, &result->oid,1372 one->path,1373&one->oid,1374&a->oid,1375&b->oid);1376}else if(S_ISLNK(a->mode)) {1377switch(o->recursive_variant) {1378case MERGE_RECURSIVE_NORMAL:1379oidcpy(&result->oid, &a->oid);1380if(!oid_eq(&a->oid, &b->oid))1381 result->clean =0;1382break;1383case MERGE_RECURSIVE_OURS:1384oidcpy(&result->oid, &a->oid);1385break;1386case MERGE_RECURSIVE_THEIRS:1387oidcpy(&result->oid, &b->oid);1388break;1389}1390}else1391BUG("unsupported object type in the tree");1392}13931394if(result->merge)1395output(o,2,_("Auto-merging%s"), filename);13961397return0;1398}13991400static inthandle_rename_via_dir(struct merge_options *o,1401struct diff_filepair *pair,1402const char*rename_branch,1403const char*other_branch)1404{1405/*1406 * Handle file adds that need to be renamed due to directory rename1407 * detection. This differs from handle_rename_normal, because1408 * there is no content merge to do; just move the file into the1409 * desired final location.1410 */1411const struct diff_filespec *dest = pair->two;14121413if(!o->call_depth &&would_lose_untracked(dest->path)) {1414char*alt_path =unique_path(o, dest->path, rename_branch);14151416output(o,1,_("Error: Refusing to lose untracked file at%s; "1417"writing to%sinstead."),1418 dest->path, alt_path);1419/*1420 * Write the file in worktree at alt_path, but not in the1421 * index. Instead, write to dest->path for the index but1422 * only at the higher appropriate stage.1423 */1424if(update_file(o,0, &dest->oid, dest->mode, alt_path))1425return-1;1426free(alt_path);1427returnupdate_stages(o, dest->path, NULL,1428 rename_branch == o->branch1 ? dest : NULL,1429 rename_branch == o->branch1 ? NULL : dest);1430}14311432/* Update dest->path both in index and in worktree */1433if(update_file(o,1, &dest->oid, dest->mode, dest->path))1434return-1;1435return0;1436}14371438static inthandle_change_delete(struct merge_options *o,1439const char*path,const char*old_path,1440const struct object_id *o_oid,int o_mode,1441const struct object_id *changed_oid,1442int changed_mode,1443const char*change_branch,1444const char*delete_branch,1445const char*change,const char*change_past)1446{1447char*alt_path = NULL;1448const char*update_path = path;1449int ret =0;14501451if(dir_in_way(path, !o->call_depth,0) ||1452(!o->call_depth &&would_lose_untracked(path))) {1453 update_path = alt_path =unique_path(o, path, change_branch);1454}14551456if(o->call_depth) {1457/*1458 * We cannot arbitrarily accept either a_sha or b_sha as1459 * correct; since there is no true "middle point" between1460 * them, simply reuse the base version for virtual merge base.1461 */1462 ret =remove_file_from_cache(path);1463if(!ret)1464 ret =update_file(o,0, o_oid, o_mode, update_path);1465}else{1466/*1467 * Despite the four nearly duplicate messages and argument1468 * lists below and the ugliness of the nested if-statements,1469 * having complete messages makes the job easier for1470 * translators.1471 *1472 * The slight variance among the cases is due to the fact1473 * that:1474 * 1) directory/file conflicts (in effect if1475 * !alt_path) could cause us to need to write the1476 * file to a different path.1477 * 2) renames (in effect if !old_path) could mean that1478 * there are two names for the path that the user1479 * may know the file by.1480 */1481if(!alt_path) {1482if(!old_path) {1483output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1484"and%sin%s. Version%sof%sleft in tree."),1485 change, path, delete_branch, change_past,1486 change_branch, change_branch, path);1487}else{1488output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1489"and%sto%sin%s. Version%sof%sleft in tree."),1490 change, old_path, delete_branch, change_past, path,1491 change_branch, change_branch, path);1492}1493}else{1494if(!old_path) {1495output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1496"and%sin%s. Version%sof%sleft in tree at%s."),1497 change, path, delete_branch, change_past,1498 change_branch, change_branch, path, alt_path);1499}else{1500output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1501"and%sto%sin%s. Version%sof%sleft in tree at%s."),1502 change, old_path, delete_branch, change_past, path,1503 change_branch, change_branch, path, alt_path);1504}1505}1506/*1507 * No need to call update_file() on path when change_branch ==1508 * o->branch1 && !alt_path, since that would needlessly touch1509 * path. We could call update_file_flags() with update_cache=01510 * and update_wd=0, but that's a no-op.1511 */1512if(change_branch != o->branch1 || alt_path)1513 ret =update_file(o,0, changed_oid, changed_mode, update_path);1514}1515free(alt_path);15161517return ret;1518}15191520static inthandle_rename_delete(struct merge_options *o,1521struct diff_filepair *pair,1522const char*rename_branch,1523const char*delete_branch)1524{1525const struct diff_filespec *orig = pair->one;1526const struct diff_filespec *dest = pair->two;15271528if(handle_change_delete(o,1529 o->call_depth ? orig->path : dest->path,1530 o->call_depth ? NULL : orig->path,1531&orig->oid, orig->mode,1532&dest->oid, dest->mode,1533 rename_branch, delete_branch,1534_("rename"),_("renamed")))1535return-1;15361537if(o->call_depth)1538returnremove_file_from_cache(dest->path);1539else1540returnupdate_stages(o, dest->path, NULL,1541 rename_branch == o->branch1 ? dest : NULL,1542 rename_branch == o->branch1 ? NULL : dest);1543}15441545static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,1546struct stage_data *entry,1547int stage)1548{1549struct object_id *oid = &entry->stages[stage].oid;1550unsigned mode = entry->stages[stage].mode;1551if(mode ==0||is_null_oid(oid))1552return NULL;1553oidcpy(&target->oid, oid);1554 target->mode = mode;1555return target;1556}15571558static inthandle_file(struct merge_options *o,1559struct diff_filespec *rename,1560int stage,1561struct rename_conflict_info *ci)1562{1563char*dst_name = rename->path;1564struct stage_data *dst_entry;1565const char*cur_branch, *other_branch;1566struct diff_filespec other;1567struct diff_filespec *add;1568int ret;15691570if(stage ==2) {1571 dst_entry = ci->dst_entry1;1572 cur_branch = ci->branch1;1573 other_branch = ci->branch2;1574}else{1575 dst_entry = ci->dst_entry2;1576 cur_branch = ci->branch2;1577 other_branch = ci->branch1;1578}15791580 add =filespec_from_entry(&other, dst_entry, stage ^1);1581if(add) {1582int ren_src_was_dirty =was_dirty(o, rename->path);1583char*add_name =unique_path(o, rename->path, other_branch);1584if(update_file(o,0, &add->oid, add->mode, add_name))1585return-1;15861587if(ren_src_was_dirty) {1588output(o,1,_("Refusing to lose dirty file at%s"),1589 rename->path);1590}1591/*1592 * Because the double negatives somehow keep confusing me...1593 * 1) update_wd iff !ren_src_was_dirty.1594 * 2) no_wd iff !update_wd1595 * 3) so, no_wd == !!ren_src_was_dirty == ren_src_was_dirty1596 */1597remove_file(o,0, rename->path, ren_src_was_dirty);1598 dst_name =unique_path(o, rename->path, cur_branch);1599}else{1600if(dir_in_way(rename->path, !o->call_depth,0)) {1601 dst_name =unique_path(o, rename->path, cur_branch);1602output(o,1,_("%sis a directory in%sadding as%sinstead"),1603 rename->path, other_branch, dst_name);1604}else if(!o->call_depth &&1605would_lose_untracked(rename->path)) {1606 dst_name =unique_path(o, rename->path, cur_branch);1607output(o,1,_("Refusing to lose untracked file at%s; "1608"adding as%sinstead"),1609 rename->path, dst_name);1610}1611}1612if((ret =update_file(o,0, &rename->oid, rename->mode, dst_name)))1613;/* fall through, do allow dst_name to be released */1614else if(stage ==2)1615 ret =update_stages(o, rename->path, NULL, rename, add);1616else1617 ret =update_stages(o, rename->path, NULL, add, rename);16181619if(dst_name != rename->path)1620free(dst_name);16211622return ret;1623}16241625static inthandle_rename_rename_1to2(struct merge_options *o,1626struct rename_conflict_info *ci)1627{1628/* One file was renamed in both branches, but to different names. */1629struct diff_filespec *one = ci->pair1->one;1630struct diff_filespec *a = ci->pair1->two;1631struct diff_filespec *b = ci->pair2->two;16321633output(o,1,_("CONFLICT (rename/rename): "1634"Rename\"%s\"->\"%s\"in branch\"%s\""1635"rename\"%s\"->\"%s\"in\"%s\"%s"),1636 one->path, a->path, ci->branch1,1637 one->path, b->path, ci->branch2,1638 o->call_depth ?_(" (left unresolved)") :"");1639if(o->call_depth) {1640struct merge_file_info mfi;1641struct diff_filespec other;1642struct diff_filespec *add;1643if(merge_mode_and_contents(o, one, a, b, one->path,1644 ci->branch1, ci->branch2, &mfi))1645return-1;16461647/*1648 * FIXME: For rename/add-source conflicts (if we could detect1649 * such), this is wrong. We should instead find a unique1650 * pathname and then either rename the add-source file to that1651 * unique path, or use that unique path instead of src here.1652 */1653if(update_file(o,0, &mfi.oid, mfi.mode, one->path))1654return-1;16551656/*1657 * Above, we put the merged content at the merge-base's1658 * path. Now we usually need to delete both a->path and1659 * b->path. However, the rename on each side of the merge1660 * could also be involved in a rename/add conflict. In1661 * such cases, we should keep the added file around,1662 * resolving the conflict at that path in its favor.1663 */1664 add =filespec_from_entry(&other, ci->dst_entry1,2^1);1665if(add) {1666if(update_file(o,0, &add->oid, add->mode, a->path))1667return-1;1668}1669else1670remove_file_from_cache(a->path);1671 add =filespec_from_entry(&other, ci->dst_entry2,3^1);1672if(add) {1673if(update_file(o,0, &add->oid, add->mode, b->path))1674return-1;1675}1676else1677remove_file_from_cache(b->path);1678}else if(handle_file(o, a,2, ci) ||handle_file(o, b,3, ci))1679return-1;16801681return0;1682}16831684static inthandle_rename_rename_2to1(struct merge_options *o,1685struct rename_conflict_info *ci)1686{1687/* Two files, a & b, were renamed to the same thing, c. */1688struct diff_filespec *a = ci->pair1->one;1689struct diff_filespec *b = ci->pair2->one;1690struct diff_filespec *c1 = ci->pair1->two;1691struct diff_filespec *c2 = ci->pair2->two;1692char*path = c1->path;/* == c2->path */1693char*path_side_1_desc;1694char*path_side_2_desc;1695struct merge_file_info mfi_c1;1696struct merge_file_info mfi_c2;1697int ret;16981699output(o,1,_("CONFLICT (rename/rename): "1700"Rename%s->%sin%s. "1701"Rename%s->%sin%s"),1702 a->path, c1->path, ci->branch1,1703 b->path, c2->path, ci->branch2);17041705remove_file(o,1, a->path, o->call_depth ||would_lose_untracked(a->path));1706remove_file(o,1, b->path, o->call_depth ||would_lose_untracked(b->path));17071708 path_side_1_desc =xstrfmt("version of%sfrom%s", path, a->path);1709 path_side_2_desc =xstrfmt("version of%sfrom%s", path, b->path);1710if(merge_mode_and_contents(o, a, c1, &ci->ren1_other, path_side_1_desc,1711 o->branch1, o->branch2, &mfi_c1) ||1712merge_mode_and_contents(o, b, &ci->ren2_other, c2, path_side_2_desc,1713 o->branch1, o->branch2, &mfi_c2))1714return-1;1715free(path_side_1_desc);1716free(path_side_2_desc);17171718if(o->call_depth) {1719/*1720 * If mfi_c1.clean && mfi_c2.clean, then it might make1721 * sense to do a two-way merge of those results. But, I1722 * think in all cases, it makes sense to have the virtual1723 * merge base just undo the renames; they can be detected1724 * again later for the non-recursive merge.1725 */1726remove_file(o,0, path,0);1727 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, a->path);1728if(!ret)1729 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1730 b->path);1731}else{1732char*new_path1 =unique_path(o, path, ci->branch1);1733char*new_path2 =unique_path(o, path, ci->branch2);1734output(o,1,_("Renaming%sto%sand%sto%sinstead"),1735 a->path, new_path1, b->path, new_path2);1736if(was_dirty(o, path))1737output(o,1,_("Refusing to lose dirty file at%s"),1738 path);1739else if(would_lose_untracked(path))1740/*1741 * Only way we get here is if both renames were from1742 * a directory rename AND user had an untracked file1743 * at the location where both files end up after the1744 * two directory renames. See testcase 10d of t6043.1745 */1746output(o,1,_("Refusing to lose untracked file at "1747"%s, even though it's in the way."),1748 path);1749else1750remove_file(o,0, path,0);1751 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, new_path1);1752if(!ret)1753 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1754 new_path2);1755/*1756 * unpack_trees() actually populates the index for us for1757 * "normal" rename/rename(2to1) situtations so that the1758 * correct entries are at the higher stages, which would1759 * make the call below to update_stages_for_stage_data1760 * unnecessary. However, if either of the renames came1761 * from a directory rename, then unpack_trees() will not1762 * have gotten the right data loaded into the index, so we1763 * need to do so now. (While it'd be tempting to move this1764 * call to update_stages_for_stage_data() to1765 * apply_directory_rename_modifications(), that would break1766 * our intermediate calls to would_lose_untracked() since1767 * those rely on the current in-memory index. See also the1768 * big "NOTE" in update_stages()).1769 */1770if(update_stages_for_stage_data(o, path, ci->dst_entry1))1771 ret = -1;17721773free(new_path2);1774free(new_path1);1775}17761777return ret;1778}17791780/*1781 * Get the diff_filepairs changed between o_tree and tree.1782 */1783static struct diff_queue_struct *get_diffpairs(struct merge_options *o,1784struct tree *o_tree,1785struct tree *tree)1786{1787struct diff_queue_struct *ret;1788struct diff_options opts;17891790repo_diff_setup(the_repository, &opts);1791 opts.flags.recursive =1;1792 opts.flags.rename_empty =0;1793 opts.detect_rename =merge_detect_rename(o);1794/*1795 * We do not have logic to handle the detection of copies. In1796 * fact, it may not even make sense to add such logic: would we1797 * really want a change to a base file to be propagated through1798 * multiple other files by a merge?1799 */1800if(opts.detect_rename > DIFF_DETECT_RENAME)1801 opts.detect_rename = DIFF_DETECT_RENAME;1802 opts.rename_limit = o->merge_rename_limit >=0? o->merge_rename_limit :1803 o->diff_rename_limit >=0? o->diff_rename_limit :18041000;1805 opts.rename_score = o->rename_score;1806 opts.show_rename_progress = o->show_rename_progress;1807 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1808diff_setup_done(&opts);1809diff_tree_oid(&o_tree->object.oid, &tree->object.oid,"", &opts);1810diffcore_std(&opts);1811if(opts.needed_rename_limit > o->needed_rename_limit)1812 o->needed_rename_limit = opts.needed_rename_limit;18131814 ret =xmalloc(sizeof(*ret));1815*ret = diff_queued_diff;18161817 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1818 diff_queued_diff.nr =0;1819 diff_queued_diff.queue = NULL;1820diff_flush(&opts);1821return ret;1822}18231824static inttree_has_path(struct tree *tree,const char*path)1825{1826struct object_id hashy;1827unsigned int mode_o;18281829return!get_tree_entry(&tree->object.oid, path,1830&hashy, &mode_o);1831}18321833/*1834 * Return a new string that replaces the beginning portion (which matches1835 * entry->dir), with entry->new_dir. In perl-speak:1836 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);1837 * NOTE:1838 * Caller must ensure that old_path starts with entry->dir + '/'.1839 */1840static char*apply_dir_rename(struct dir_rename_entry *entry,1841const char*old_path)1842{1843struct strbuf new_path = STRBUF_INIT;1844int oldlen, newlen;18451846if(entry->non_unique_new_dir)1847return NULL;18481849 oldlen =strlen(entry->dir);1850 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) +1;1851strbuf_grow(&new_path, newlen);1852strbuf_addbuf(&new_path, &entry->new_dir);1853strbuf_addstr(&new_path, &old_path[oldlen]);18541855returnstrbuf_detach(&new_path, NULL);1856}18571858static voidget_renamed_dir_portion(const char*old_path,const char*new_path,1859char**old_dir,char**new_dir)1860{1861char*end_of_old, *end_of_new;1862int old_len, new_len;18631864*old_dir = NULL;1865*new_dir = NULL;18661867/*1868 * For1869 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"1870 * the "e/foo.c" part is the same, we just want to know that1871 * "a/b/c/d" was renamed to "a/b/some/thing/else"1872 * so, for this example, this function returns "a/b/c/d" in1873 * *old_dir and "a/b/some/thing/else" in *new_dir.1874 *1875 * Also, if the basename of the file changed, we don't care. We1876 * want to know which portion of the directory, if any, changed.1877 */1878 end_of_old =strrchr(old_path,'/');1879 end_of_new =strrchr(new_path,'/');18801881if(end_of_old == NULL || end_of_new == NULL)1882return;1883while(*--end_of_new == *--end_of_old &&1884 end_of_old != old_path &&1885 end_of_new != new_path)1886;/* Do nothing; all in the while loop */1887/*1888 * We've found the first non-matching character in the directory1889 * paths. That means the current directory we were comparing1890 * represents the rename. Move end_of_old and end_of_new back1891 * to the full directory name.1892 */1893if(*end_of_old =='/')1894 end_of_old++;1895if(*end_of_old !='/')1896 end_of_new++;1897 end_of_old =strchr(end_of_old,'/');1898 end_of_new =strchr(end_of_new,'/');18991900/*1901 * It may have been the case that old_path and new_path were the same1902 * directory all along. Don't claim a rename if they're the same.1903 */1904 old_len = end_of_old - old_path;1905 new_len = end_of_new - new_path;19061907if(old_len != new_len ||strncmp(old_path, new_path, old_len)) {1908*old_dir =xstrndup(old_path, old_len);1909*new_dir =xstrndup(new_path, new_len);1910}1911}19121913static voidremove_hashmap_entries(struct hashmap *dir_renames,1914struct string_list *items_to_remove)1915{1916int i;1917struct dir_rename_entry *entry;19181919for(i =0; i < items_to_remove->nr; i++) {1920 entry = items_to_remove->items[i].util;1921hashmap_remove(dir_renames, entry, NULL);1922}1923string_list_clear(items_to_remove,0);1924}19251926/*1927 * See if there is a directory rename for path, and if there are any file1928 * level conflicts for the renamed location. If there is a rename and1929 * there are no conflicts, return the new name. Otherwise, return NULL.1930 */1931static char*handle_path_level_conflicts(struct merge_options *o,1932const char*path,1933struct dir_rename_entry *entry,1934struct hashmap *collisions,1935struct tree *tree)1936{1937char*new_path = NULL;1938struct collision_entry *collision_ent;1939int clean =1;1940struct strbuf collision_paths = STRBUF_INIT;19411942/*1943 * entry has the mapping of old directory name to new directory name1944 * that we want to apply to path.1945 */1946 new_path =apply_dir_rename(entry, path);19471948if(!new_path) {1949/* This should only happen when entry->non_unique_new_dir set */1950if(!entry->non_unique_new_dir)1951BUG("entry->non_unqiue_dir not set and !new_path");1952output(o,1,_("CONFLICT (directory rename split): "1953"Unclear where to place%sbecause directory "1954"%swas renamed to multiple other directories, "1955"with no destination getting a majority of the "1956"files."),1957 path, entry->dir);1958 clean =0;1959return NULL;1960}19611962/*1963 * The caller needs to have ensured that it has pre-populated1964 * collisions with all paths that map to new_path. Do a quick check1965 * to ensure that's the case.1966 */1967 collision_ent =collision_find_entry(collisions, new_path);1968if(collision_ent == NULL)1969BUG("collision_ent is NULL");19701971/*1972 * Check for one-sided add/add/.../add conflicts, i.e.1973 * where implicit renames from the other side doing1974 * directory rename(s) can affect this side of history1975 * to put multiple paths into the same location. Warn1976 * and bail on directory renames for such paths.1977 */1978if(collision_ent->reported_already) {1979 clean =0;1980}else if(tree_has_path(tree, new_path)) {1981 collision_ent->reported_already =1;1982strbuf_add_separated_string_list(&collision_paths,", ",1983&collision_ent->source_files);1984output(o,1,_("CONFLICT (implicit dir rename): Existing "1985"file/dir at%sin the way of implicit "1986"directory rename(s) putting the following "1987"path(s) there:%s."),1988 new_path, collision_paths.buf);1989 clean =0;1990}else if(collision_ent->source_files.nr >1) {1991 collision_ent->reported_already =1;1992strbuf_add_separated_string_list(&collision_paths,", ",1993&collision_ent->source_files);1994output(o,1,_("CONFLICT (implicit dir rename): Cannot map "1995"more than one path to%s; implicit directory "1996"renames tried to put these paths there:%s"),1997 new_path, collision_paths.buf);1998 clean =0;1999}20002001/* Free memory we no longer need */2002strbuf_release(&collision_paths);2003if(!clean && new_path) {2004free(new_path);2005return NULL;2006}20072008return new_path;2009}20102011/*2012 * There are a couple things we want to do at the directory level:2013 * 1. Check for both sides renaming to the same thing, in order to avoid2014 * implicit renaming of files that should be left in place. (See2015 * testcase 6b in t6043 for details.)2016 * 2. Prune directory renames if there are still files left in the2017 * the original directory. These represent a partial directory rename,2018 * i.e. a rename where only some of the files within the directory2019 * were renamed elsewhere. (Technically, this could be done earlier2020 * in get_directory_renames(), except that would prevent us from2021 * doing the previous check and thus failing testcase 6b.)2022 * 3. Check for rename/rename(1to2) conflicts (at the directory level).2023 * In the future, we could potentially record this info as well and2024 * omit reporting rename/rename(1to2) conflicts for each path within2025 * the affected directories, thus cleaning up the merge output.2026 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the2027 * directory level, because merging directories is fine. If it2028 * causes conflicts for files within those merged directories, then2029 * that should be detected at the individual path level.2030 */2031static voidhandle_directory_level_conflicts(struct merge_options *o,2032struct hashmap *dir_re_head,2033struct tree *head,2034struct hashmap *dir_re_merge,2035struct tree *merge)2036{2037struct hashmap_iter iter;2038struct dir_rename_entry *head_ent;2039struct dir_rename_entry *merge_ent;20402041struct string_list remove_from_head = STRING_LIST_INIT_NODUP;2042struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;20432044hashmap_iter_init(dir_re_head, &iter);2045while((head_ent =hashmap_iter_next(&iter))) {2046 merge_ent =dir_rename_find_entry(dir_re_merge, head_ent->dir);2047if(merge_ent &&2048!head_ent->non_unique_new_dir &&2049!merge_ent->non_unique_new_dir &&2050!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {2051/* 1. Renamed identically; remove it from both sides */2052string_list_append(&remove_from_head,2053 head_ent->dir)->util = head_ent;2054strbuf_release(&head_ent->new_dir);2055string_list_append(&remove_from_merge,2056 merge_ent->dir)->util = merge_ent;2057strbuf_release(&merge_ent->new_dir);2058}else if(tree_has_path(head, head_ent->dir)) {2059/* 2. This wasn't a directory rename after all */2060string_list_append(&remove_from_head,2061 head_ent->dir)->util = head_ent;2062strbuf_release(&head_ent->new_dir);2063}2064}20652066remove_hashmap_entries(dir_re_head, &remove_from_head);2067remove_hashmap_entries(dir_re_merge, &remove_from_merge);20682069hashmap_iter_init(dir_re_merge, &iter);2070while((merge_ent =hashmap_iter_next(&iter))) {2071 head_ent =dir_rename_find_entry(dir_re_head, merge_ent->dir);2072if(tree_has_path(merge, merge_ent->dir)) {2073/* 2. This wasn't a directory rename after all */2074string_list_append(&remove_from_merge,2075 merge_ent->dir)->util = merge_ent;2076}else if(head_ent &&2077!head_ent->non_unique_new_dir &&2078!merge_ent->non_unique_new_dir) {2079/* 3. rename/rename(1to2) */2080/*2081 * We can assume it's not rename/rename(1to1) because2082 * that was case (1), already checked above. So we2083 * know that head_ent->new_dir and merge_ent->new_dir2084 * are different strings.2085 */2086output(o,1,_("CONFLICT (rename/rename): "2087"Rename directory%s->%sin%s. "2088"Rename directory%s->%sin%s"),2089 head_ent->dir, head_ent->new_dir.buf, o->branch1,2090 head_ent->dir, merge_ent->new_dir.buf, o->branch2);2091string_list_append(&remove_from_head,2092 head_ent->dir)->util = head_ent;2093strbuf_release(&head_ent->new_dir);2094string_list_append(&remove_from_merge,2095 merge_ent->dir)->util = merge_ent;2096strbuf_release(&merge_ent->new_dir);2097}2098}20992100remove_hashmap_entries(dir_re_head, &remove_from_head);2101remove_hashmap_entries(dir_re_merge, &remove_from_merge);2102}21032104static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs,2105struct tree *tree)2106{2107struct hashmap *dir_renames;2108struct hashmap_iter iter;2109struct dir_rename_entry *entry;2110int i;21112112/*2113 * Typically, we think of a directory rename as all files from a2114 * certain directory being moved to a target directory. However,2115 * what if someone first moved two files from the original2116 * directory in one commit, and then renamed the directory2117 * somewhere else in a later commit? At merge time, we just know2118 * that files from the original directory went to two different2119 * places, and that the bulk of them ended up in the same place.2120 * We want each directory rename to represent where the bulk of the2121 * files from that directory end up; this function exists to find2122 * where the bulk of the files went.2123 *2124 * The first loop below simply iterates through the list of file2125 * renames, finding out how often each directory rename pair2126 * possibility occurs.2127 */2128 dir_renames =xmalloc(sizeof(*dir_renames));2129dir_rename_init(dir_renames);2130for(i =0; i < pairs->nr; ++i) {2131struct string_list_item *item;2132int*count;2133struct diff_filepair *pair = pairs->queue[i];2134char*old_dir, *new_dir;21352136/* File not part of directory rename if it wasn't renamed */2137if(pair->status !='R')2138continue;21392140get_renamed_dir_portion(pair->one->path, pair->two->path,2141&old_dir, &new_dir);2142if(!old_dir)2143/* Directory didn't change at all; ignore this one. */2144continue;21452146 entry =dir_rename_find_entry(dir_renames, old_dir);2147if(!entry) {2148 entry =xmalloc(sizeof(*entry));2149dir_rename_entry_init(entry, old_dir);2150hashmap_put(dir_renames, entry);2151}else{2152free(old_dir);2153}2154 item =string_list_lookup(&entry->possible_new_dirs, new_dir);2155if(!item) {2156 item =string_list_insert(&entry->possible_new_dirs,2157 new_dir);2158 item->util =xcalloc(1,sizeof(int));2159}else{2160free(new_dir);2161}2162 count = item->util;2163*count +=1;2164}21652166/*2167 * For each directory with files moved out of it, we find out which2168 * target directory received the most files so we can declare it to2169 * be the "winning" target location for the directory rename. This2170 * winner gets recorded in new_dir. If there is no winner2171 * (multiple target directories received the same number of files),2172 * we set non_unique_new_dir. Once we've determined the winner (or2173 * that there is no winner), we no longer need possible_new_dirs.2174 */2175hashmap_iter_init(dir_renames, &iter);2176while((entry =hashmap_iter_next(&iter))) {2177int max =0;2178int bad_max =0;2179char*best = NULL;21802181for(i =0; i < entry->possible_new_dirs.nr; i++) {2182int*count = entry->possible_new_dirs.items[i].util;21832184if(*count == max)2185 bad_max = max;2186else if(*count > max) {2187 max = *count;2188 best = entry->possible_new_dirs.items[i].string;2189}2190}2191if(bad_max == max)2192 entry->non_unique_new_dir =1;2193else{2194assert(entry->new_dir.len ==0);2195strbuf_addstr(&entry->new_dir, best);2196}2197/*2198 * The relevant directory sub-portion of the original full2199 * filepaths were xstrndup'ed before inserting into2200 * possible_new_dirs, and instead of manually iterating the2201 * list and free'ing each, just lie and tell2202 * possible_new_dirs that it did the strdup'ing so that it2203 * will free them for us.2204 */2205 entry->possible_new_dirs.strdup_strings =1;2206string_list_clear(&entry->possible_new_dirs,1);2207}22082209return dir_renames;2210}22112212static struct dir_rename_entry *check_dir_renamed(const char*path,2213struct hashmap *dir_renames)2214{2215char*temp =xstrdup(path);2216char*end;2217struct dir_rename_entry *entry = NULL;22182219while((end =strrchr(temp,'/'))) {2220*end ='\0';2221 entry =dir_rename_find_entry(dir_renames, temp);2222if(entry)2223break;2224}2225free(temp);2226return entry;2227}22282229static voidcompute_collisions(struct hashmap *collisions,2230struct hashmap *dir_renames,2231struct diff_queue_struct *pairs)2232{2233int i;22342235/*2236 * Multiple files can be mapped to the same path due to directory2237 * renames done by the other side of history. Since that other2238 * side of history could have merged multiple directories into one,2239 * if our side of history added the same file basename to each of2240 * those directories, then all N of them would get implicitly2241 * renamed by the directory rename detection into the same path,2242 * and we'd get an add/add/.../add conflict, and all those adds2243 * from *this* side of history. This is not representable in the2244 * index, and users aren't going to easily be able to make sense of2245 * it. So we need to provide a good warning about what's2246 * happening, and fall back to no-directory-rename detection2247 * behavior for those paths.2248 *2249 * See testcases 9e and all of section 5 from t6043 for examples.2250 */2251collision_init(collisions);22522253for(i =0; i < pairs->nr; ++i) {2254struct dir_rename_entry *dir_rename_ent;2255struct collision_entry *collision_ent;2256char*new_path;2257struct diff_filepair *pair = pairs->queue[i];22582259if(pair->status !='A'&& pair->status !='R')2260continue;2261 dir_rename_ent =check_dir_renamed(pair->two->path,2262 dir_renames);2263if(!dir_rename_ent)2264continue;22652266 new_path =apply_dir_rename(dir_rename_ent, pair->two->path);2267if(!new_path)2268/*2269 * dir_rename_ent->non_unique_new_path is true, which2270 * means there is no directory rename for us to use,2271 * which means it won't cause us any additional2272 * collisions.2273 */2274continue;2275 collision_ent =collision_find_entry(collisions, new_path);2276if(!collision_ent) {2277 collision_ent =xcalloc(1,2278sizeof(struct collision_entry));2279hashmap_entry_init(collision_ent,strhash(new_path));2280hashmap_put(collisions, collision_ent);2281 collision_ent->target_file = new_path;2282}else{2283free(new_path);2284}2285string_list_insert(&collision_ent->source_files,2286 pair->two->path);2287}2288}22892290static char*check_for_directory_rename(struct merge_options *o,2291const char*path,2292struct tree *tree,2293struct hashmap *dir_renames,2294struct hashmap *dir_rename_exclusions,2295struct hashmap *collisions,2296int*clean_merge)2297{2298char*new_path = NULL;2299struct dir_rename_entry *entry =check_dir_renamed(path, dir_renames);2300struct dir_rename_entry *oentry = NULL;23012302if(!entry)2303return new_path;23042305/*2306 * This next part is a little weird. We do not want to do an2307 * implicit rename into a directory we renamed on our side, because2308 * that will result in a spurious rename/rename(1to2) conflict. An2309 * example:2310 * Base commit: dumbdir/afile, otherdir/bfile2311 * Side 1: smrtdir/afile, otherdir/bfile2312 * Side 2: dumbdir/afile, dumbdir/bfile2313 * Here, while working on Side 1, we could notice that otherdir was2314 * renamed/merged to dumbdir, and change the diff_filepair for2315 * otherdir/bfile into a rename into dumbdir/bfile. However, Side2316 * 2 will notice the rename from dumbdir to smrtdir, and do the2317 * transitive rename to move it from dumbdir/bfile to2318 * smrtdir/bfile. That gives us bfile in dumbdir vs being in2319 * smrtdir, a rename/rename(1to2) conflict. We really just want2320 * the file to end up in smrtdir. And the way to achieve that is2321 * to not let Side1 do the rename to dumbdir, since we know that is2322 * the source of one of our directory renames.2323 *2324 * That's why oentry and dir_rename_exclusions is here.2325 *2326 * As it turns out, this also prevents N-way transient rename2327 * confusion; See testcases 9c and 9d of t6043.2328 */2329 oentry =dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);2330if(oentry) {2331output(o,1,_("WARNING: Avoiding applying%s->%srename "2332"to%s, because%sitself was renamed."),2333 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);2334}else{2335 new_path =handle_path_level_conflicts(o, path, entry,2336 collisions, tree);2337*clean_merge &= (new_path != NULL);2338}23392340return new_path;2341}23422343static voidapply_directory_rename_modifications(struct merge_options *o,2344struct diff_filepair *pair,2345char*new_path,2346struct rename *re,2347struct tree *tree,2348struct tree *o_tree,2349struct tree *a_tree,2350struct tree *b_tree,2351struct string_list *entries,2352int*clean)2353{2354struct string_list_item *item;2355int stage = (tree == a_tree ?2:3);2356int update_wd;23572358/*2359 * In all cases where we can do directory rename detection,2360 * unpack_trees() will have read pair->two->path into the2361 * index and the working copy. We need to remove it so that2362 * we can instead place it at new_path. It is guaranteed to2363 * not be untracked (unpack_trees() would have errored out2364 * saying the file would have been overwritten), but it might2365 * be dirty, though.2366 */2367 update_wd = !was_dirty(o, pair->two->path);2368if(!update_wd)2369output(o,1,_("Refusing to lose dirty file at%s"),2370 pair->two->path);2371remove_file(o,1, pair->two->path, !update_wd);23722373/* Find or create a new re->dst_entry */2374 item =string_list_lookup(entries, new_path);2375if(item) {2376/*2377 * Since we're renaming on this side of history, and it's2378 * due to a directory rename on the other side of history2379 * (which we only allow when the directory in question no2380 * longer exists on the other side of history), the2381 * original entry for re->dst_entry is no longer2382 * necessary...2383 */2384 re->dst_entry->processed =1;23852386/*2387 * ...because we'll be using this new one.2388 */2389 re->dst_entry = item->util;2390}else{2391/*2392 * re->dst_entry is for the before-dir-rename path, and we2393 * need it to hold information for the after-dir-rename2394 * path. Before creating a new entry, we need to mark the2395 * old one as unnecessary (...unless it is shared by2396 * src_entry, i.e. this didn't use to be a rename, in which2397 * case we can just allow the normal processing to happen2398 * for it).2399 */2400if(pair->status =='R')2401 re->dst_entry->processed =1;24022403 re->dst_entry =insert_stage_data(new_path,2404 o_tree, a_tree, b_tree,2405 entries);2406 item =string_list_insert(entries, new_path);2407 item->util = re->dst_entry;2408}24092410/*2411 * Update the stage_data with the information about the path we are2412 * moving into place. That slot will be empty and available for us2413 * to write to because of the collision checks in2414 * handle_path_level_conflicts(). In other words,2415 * re->dst_entry->stages[stage].oid will be the null_oid, so it's2416 * open for us to write to.2417 *2418 * It may be tempting to actually update the index at this point as2419 * well, using update_stages_for_stage_data(), but as per the big2420 * "NOTE" in update_stages(), doing so will modify the current2421 * in-memory index which will break calls to would_lose_untracked()2422 * that we need to make. Instead, we need to just make sure that2423 * the various handle_rename_*() functions update the index2424 * explicitly rather than relying on unpack_trees() to have done it.2425 */2426get_tree_entry(&tree->object.oid,2427 pair->two->path,2428&re->dst_entry->stages[stage].oid,2429&re->dst_entry->stages[stage].mode);24302431/* Update pair status */2432if(pair->status =='A') {2433/*2434 * Recording rename information for this add makes it look2435 * like a rename/delete conflict. Make sure we can2436 * correctly handle this as an add that was moved to a new2437 * directory instead of reporting a rename/delete conflict.2438 */2439 re->add_turned_into_rename =1;2440}2441/*2442 * We don't actually look at pair->status again, but it seems2443 * pedagogically correct to adjust it.2444 */2445 pair->status ='R';24462447/*2448 * Finally, record the new location.2449 */2450 pair->two->path = new_path;2451}24522453/*2454 * Get information of all renames which occurred in 'pairs', making use of2455 * any implicit directory renames inferred from the other side of history.2456 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')2457 * to be able to associate the correct cache entries with the rename2458 * information; tree is always equal to either a_tree or b_tree.2459 */2460static struct string_list *get_renames(struct merge_options *o,2461struct diff_queue_struct *pairs,2462struct hashmap *dir_renames,2463struct hashmap *dir_rename_exclusions,2464struct tree *tree,2465struct tree *o_tree,2466struct tree *a_tree,2467struct tree *b_tree,2468struct string_list *entries,2469int*clean_merge)2470{2471int i;2472struct hashmap collisions;2473struct hashmap_iter iter;2474struct collision_entry *e;2475struct string_list *renames;24762477compute_collisions(&collisions, dir_renames, pairs);2478 renames =xcalloc(1,sizeof(struct string_list));24792480for(i =0; i < pairs->nr; ++i) {2481struct string_list_item *item;2482struct rename *re;2483struct diff_filepair *pair = pairs->queue[i];2484char*new_path;/* non-NULL only with directory renames */24852486if(pair->status !='A'&& pair->status !='R') {2487diff_free_filepair(pair);2488continue;2489}2490 new_path =check_for_directory_rename(o, pair->two->path, tree,2491 dir_renames,2492 dir_rename_exclusions,2493&collisions,2494 clean_merge);2495if(pair->status !='R'&& !new_path) {2496diff_free_filepair(pair);2497continue;2498}24992500 re =xmalloc(sizeof(*re));2501 re->processed =0;2502 re->add_turned_into_rename =0;2503 re->pair = pair;2504 item =string_list_lookup(entries, re->pair->one->path);2505if(!item)2506 re->src_entry =insert_stage_data(re->pair->one->path,2507 o_tree, a_tree, b_tree, entries);2508else2509 re->src_entry = item->util;25102511 item =string_list_lookup(entries, re->pair->two->path);2512if(!item)2513 re->dst_entry =insert_stage_data(re->pair->two->path,2514 o_tree, a_tree, b_tree, entries);2515else2516 re->dst_entry = item->util;2517 item =string_list_insert(renames, pair->one->path);2518 item->util = re;2519if(new_path)2520apply_directory_rename_modifications(o, pair, new_path,2521 re, tree, o_tree,2522 a_tree, b_tree,2523 entries,2524 clean_merge);2525}25262527hashmap_iter_init(&collisions, &iter);2528while((e =hashmap_iter_next(&iter))) {2529free(e->target_file);2530string_list_clear(&e->source_files,0);2531}2532hashmap_free(&collisions,1);2533return renames;2534}25352536static intprocess_renames(struct merge_options *o,2537struct string_list *a_renames,2538struct string_list *b_renames)2539{2540int clean_merge =1, i, j;2541struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2542struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2543const struct rename *sre;25442545for(i =0; i < a_renames->nr; i++) {2546 sre = a_renames->items[i].util;2547string_list_insert(&a_by_dst, sre->pair->two->path)->util2548= (void*)sre;2549}2550for(i =0; i < b_renames->nr; i++) {2551 sre = b_renames->items[i].util;2552string_list_insert(&b_by_dst, sre->pair->two->path)->util2553= (void*)sre;2554}25552556for(i =0, j =0; i < a_renames->nr || j < b_renames->nr;) {2557struct string_list *renames1, *renames2Dst;2558struct rename *ren1 = NULL, *ren2 = NULL;2559const char*branch1, *branch2;2560const char*ren1_src, *ren1_dst;2561struct string_list_item *lookup;25622563if(i >= a_renames->nr) {2564 ren2 = b_renames->items[j++].util;2565}else if(j >= b_renames->nr) {2566 ren1 = a_renames->items[i++].util;2567}else{2568int compare =strcmp(a_renames->items[i].string,2569 b_renames->items[j].string);2570if(compare <=0)2571 ren1 = a_renames->items[i++].util;2572if(compare >=0)2573 ren2 = b_renames->items[j++].util;2574}25752576/* TODO: refactor, so that 1/2 are not needed */2577if(ren1) {2578 renames1 = a_renames;2579 renames2Dst = &b_by_dst;2580 branch1 = o->branch1;2581 branch2 = o->branch2;2582}else{2583 renames1 = b_renames;2584 renames2Dst = &a_by_dst;2585 branch1 = o->branch2;2586 branch2 = o->branch1;2587SWAP(ren2, ren1);2588}25892590if(ren1->processed)2591continue;2592 ren1->processed =1;2593 ren1->dst_entry->processed =1;2594/* BUG: We should only mark src_entry as processed if we2595 * are not dealing with a rename + add-source case.2596 */2597 ren1->src_entry->processed =1;25982599 ren1_src = ren1->pair->one->path;2600 ren1_dst = ren1->pair->two->path;26012602if(ren2) {2603/* One file renamed on both sides */2604const char*ren2_src = ren2->pair->one->path;2605const char*ren2_dst = ren2->pair->two->path;2606enum rename_type rename_type;2607if(strcmp(ren1_src, ren2_src) !=0)2608BUG("ren1_src != ren2_src");2609 ren2->dst_entry->processed =1;2610 ren2->processed =1;2611if(strcmp(ren1_dst, ren2_dst) !=0) {2612 rename_type = RENAME_ONE_FILE_TO_TWO;2613 clean_merge =0;2614}else{2615 rename_type = RENAME_ONE_FILE_TO_ONE;2616/* BUG: We should only remove ren1_src in2617 * the base stage (think of rename +2618 * add-source cases).2619 */2620remove_file(o,1, ren1_src,1);2621update_entry(ren1->dst_entry,2622 ren1->pair->one,2623 ren1->pair->two,2624 ren2->pair->two);2625}2626setup_rename_conflict_info(rename_type,2627 ren1->pair,2628 ren2->pair,2629 branch1,2630 branch2,2631 ren1->dst_entry,2632 ren2->dst_entry,2633 o,2634 NULL,2635 NULL);2636}else if((lookup =string_list_lookup(renames2Dst, ren1_dst))) {2637/* Two different files renamed to the same thing */2638char*ren2_dst;2639 ren2 = lookup->util;2640 ren2_dst = ren2->pair->two->path;2641if(strcmp(ren1_dst, ren2_dst) !=0)2642BUG("ren1_dst != ren2_dst");26432644 clean_merge =0;2645 ren2->processed =1;2646/*2647 * BUG: We should only mark src_entry as processed2648 * if we are not dealing with a rename + add-source2649 * case.2650 */2651 ren2->src_entry->processed =1;26522653setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2654 ren1->pair,2655 ren2->pair,2656 branch1,2657 branch2,2658 ren1->dst_entry,2659 ren2->dst_entry,2660 o,2661 ren1->src_entry,2662 ren2->src_entry);26632664}else{2665/* Renamed in 1, maybe changed in 2 */2666/* we only use sha1 and mode of these */2667struct diff_filespec src_other, dst_other;2668int try_merge;26692670/*2671 * unpack_trees loads entries from common-commit2672 * into stage 1, from head-commit into stage 2, and2673 * from merge-commit into stage 3. We keep track2674 * of which side corresponds to the rename.2675 */2676int renamed_stage = a_renames == renames1 ?2:3;2677int other_stage = a_renames == renames1 ?3:2;26782679/* BUG: We should only remove ren1_src in the base2680 * stage and in other_stage (think of rename +2681 * add-source case).2682 */2683remove_file(o,1, ren1_src,2684 renamed_stage ==2|| !was_tracked(o, ren1_src));26852686oidcpy(&src_other.oid,2687&ren1->src_entry->stages[other_stage].oid);2688 src_other.mode = ren1->src_entry->stages[other_stage].mode;2689oidcpy(&dst_other.oid,2690&ren1->dst_entry->stages[other_stage].oid);2691 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2692 try_merge =0;26932694if(oid_eq(&src_other.oid, &null_oid) &&2695 ren1->add_turned_into_rename) {2696setup_rename_conflict_info(RENAME_VIA_DIR,2697 ren1->pair,2698 NULL,2699 branch1,2700 branch2,2701 ren1->dst_entry,2702 NULL,2703 o,2704 NULL,2705 NULL);2706}else if(oid_eq(&src_other.oid, &null_oid)) {2707setup_rename_conflict_info(RENAME_DELETE,2708 ren1->pair,2709 NULL,2710 branch1,2711 branch2,2712 ren1->dst_entry,2713 NULL,2714 o,2715 NULL,2716 NULL);2717}else if((dst_other.mode == ren1->pair->two->mode) &&2718oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {2719/*2720 * Added file on the other side identical to2721 * the file being renamed: clean merge.2722 * Also, there is no need to overwrite the2723 * file already in the working copy, so call2724 * update_file_flags() instead of2725 * update_file().2726 */2727if(update_file_flags(o,2728&ren1->pair->two->oid,2729 ren1->pair->two->mode,2730 ren1_dst,27311,/* update_cache */27320/* update_wd */))2733 clean_merge = -1;2734}else if(!oid_eq(&dst_other.oid, &null_oid)) {2735 clean_merge =0;2736 try_merge =1;2737output(o,1,_("CONFLICT (rename/add): Rename%s->%sin%s. "2738"%sadded in%s"),2739 ren1_src, ren1_dst, branch1,2740 ren1_dst, branch2);2741if(o->call_depth) {2742struct merge_file_info mfi;2743struct diff_filespec one, a, b;27442745oidcpy(&one.oid, &null_oid);2746 one.mode =0;2747 one.path = ren1->pair->two->path;27482749oidcpy(&a.oid, &ren1->pair->two->oid);2750 a.mode = ren1->pair->two->mode;2751 a.path = one.path;27522753oidcpy(&b.oid, &dst_other.oid);2754 b.mode = dst_other.mode;2755 b.path = one.path;27562757if(merge_mode_and_contents(o, &one, &a, &b, ren1_dst,2758 branch1, branch2,2759&mfi)) {2760 clean_merge = -1;2761goto cleanup_and_return;2762}2763output(o,1,_("Adding merged%s"), ren1_dst);2764if(update_file(o,0, &mfi.oid,2765 mfi.mode, ren1_dst))2766 clean_merge = -1;2767 try_merge =0;2768}else{2769char*new_path =unique_path(o, ren1_dst, branch2);2770output(o,1,_("Adding as%sinstead"), new_path);2771if(update_file(o,0, &dst_other.oid,2772 dst_other.mode, new_path))2773 clean_merge = -1;2774free(new_path);2775}2776}else2777 try_merge =1;27782779if(clean_merge <0)2780goto cleanup_and_return;2781if(try_merge) {2782struct diff_filespec *one, *a, *b;2783 src_other.path = (char*)ren1_src;27842785 one = ren1->pair->one;2786if(a_renames == renames1) {2787 a = ren1->pair->two;2788 b = &src_other;2789}else{2790 b = ren1->pair->two;2791 a = &src_other;2792}2793update_entry(ren1->dst_entry, one, a, b);2794setup_rename_conflict_info(RENAME_NORMAL,2795 ren1->pair,2796 NULL,2797 branch1,2798 NULL,2799 ren1->dst_entry,2800 NULL,2801 o,2802 NULL,2803 NULL);2804}2805}2806}2807cleanup_and_return:2808string_list_clear(&a_by_dst,0);2809string_list_clear(&b_by_dst,0);28102811return clean_merge;2812}28132814struct rename_info {2815struct string_list *head_renames;2816struct string_list *merge_renames;2817};28182819static voidinitial_cleanup_rename(struct diff_queue_struct *pairs,2820struct hashmap *dir_renames)2821{2822struct hashmap_iter iter;2823struct dir_rename_entry *e;28242825hashmap_iter_init(dir_renames, &iter);2826while((e =hashmap_iter_next(&iter))) {2827free(e->dir);2828strbuf_release(&e->new_dir);2829/* possible_new_dirs already cleared in get_directory_renames */2830}2831hashmap_free(dir_renames,1);2832free(dir_renames);28332834free(pairs->queue);2835free(pairs);2836}28372838static intdetect_and_process_renames(struct merge_options *o,2839struct tree *common,2840struct tree *head,2841struct tree *merge,2842struct string_list *entries,2843struct rename_info *ri)2844{2845struct diff_queue_struct *head_pairs, *merge_pairs;2846struct hashmap *dir_re_head, *dir_re_merge;2847int clean =1;28482849 ri->head_renames = NULL;2850 ri->merge_renames = NULL;28512852if(!merge_detect_rename(o))2853return1;28542855 head_pairs =get_diffpairs(o, common, head);2856 merge_pairs =get_diffpairs(o, common, merge);28572858if(o->detect_directory_renames) {2859 dir_re_head =get_directory_renames(head_pairs, head);2860 dir_re_merge =get_directory_renames(merge_pairs, merge);28612862handle_directory_level_conflicts(o,2863 dir_re_head, head,2864 dir_re_merge, merge);2865}else{2866 dir_re_head =xmalloc(sizeof(*dir_re_head));2867 dir_re_merge =xmalloc(sizeof(*dir_re_merge));2868dir_rename_init(dir_re_head);2869dir_rename_init(dir_re_merge);2870}28712872 ri->head_renames =get_renames(o, head_pairs,2873 dir_re_merge, dir_re_head, head,2874 common, head, merge, entries,2875&clean);2876if(clean <0)2877goto cleanup;2878 ri->merge_renames =get_renames(o, merge_pairs,2879 dir_re_head, dir_re_merge, merge,2880 common, head, merge, entries,2881&clean);2882if(clean <0)2883goto cleanup;2884 clean &=process_renames(o, ri->head_renames, ri->merge_renames);28852886cleanup:2887/*2888 * Some cleanup is deferred until cleanup_renames() because the2889 * data structures are still needed and referenced in2890 * process_entry(). But there are a few things we can free now.2891 */2892initial_cleanup_rename(head_pairs, dir_re_head);2893initial_cleanup_rename(merge_pairs, dir_re_merge);28942895return clean;2896}28972898static voidfinal_cleanup_rename(struct string_list *rename)2899{2900const struct rename *re;2901int i;29022903if(rename == NULL)2904return;29052906for(i =0; i < rename->nr; i++) {2907 re = rename->items[i].util;2908diff_free_filepair(re->pair);2909}2910string_list_clear(rename,1);2911free(rename);2912}29132914static voidfinal_cleanup_renames(struct rename_info *re_info)2915{2916final_cleanup_rename(re_info->head_renames);2917final_cleanup_rename(re_info->merge_renames);2918}29192920static struct object_id *stage_oid(const struct object_id *oid,unsigned mode)2921{2922return(is_null_oid(oid) || mode ==0) ? NULL: (struct object_id *)oid;2923}29242925static intread_oid_strbuf(struct merge_options *o,2926const struct object_id *oid,2927struct strbuf *dst)2928{2929void*buf;2930enum object_type type;2931unsigned long size;2932 buf =read_object_file(oid, &type, &size);2933if(!buf)2934returnerr(o,_("cannot read object%s"),oid_to_hex(oid));2935if(type != OBJ_BLOB) {2936free(buf);2937returnerr(o,_("object%sis not a blob"),oid_to_hex(oid));2938}2939strbuf_attach(dst, buf, size, size +1);2940return0;2941}29422943static intblob_unchanged(struct merge_options *opt,2944const struct object_id *o_oid,2945unsigned o_mode,2946const struct object_id *a_oid,2947unsigned a_mode,2948int renormalize,const char*path)2949{2950struct strbuf o = STRBUF_INIT;2951struct strbuf a = STRBUF_INIT;2952int ret =0;/* assume changed for safety */29532954if(a_mode != o_mode)2955return0;2956if(oid_eq(o_oid, a_oid))2957return1;2958if(!renormalize)2959return0;29602961assert(o_oid && a_oid);2962if(read_oid_strbuf(opt, o_oid, &o) ||read_oid_strbuf(opt, a_oid, &a))2963goto error_return;2964/*2965 * Note: binary | is used so that both renormalizations are2966 * performed. Comparison can be skipped if both files are2967 * unchanged since their sha1s have already been compared.2968 */2969if(renormalize_buffer(&the_index, path, o.buf, o.len, &o) |2970renormalize_buffer(&the_index, path, a.buf, a.len, &a))2971 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));29722973error_return:2974strbuf_release(&o);2975strbuf_release(&a);2976return ret;2977}29782979static inthandle_modify_delete(struct merge_options *o,2980const char*path,2981struct object_id *o_oid,int o_mode,2982struct object_id *a_oid,int a_mode,2983struct object_id *b_oid,int b_mode)2984{2985const char*modify_branch, *delete_branch;2986struct object_id *changed_oid;2987int changed_mode;29882989if(a_oid) {2990 modify_branch = o->branch1;2991 delete_branch = o->branch2;2992 changed_oid = a_oid;2993 changed_mode = a_mode;2994}else{2995 modify_branch = o->branch2;2996 delete_branch = o->branch1;2997 changed_oid = b_oid;2998 changed_mode = b_mode;2999}30003001returnhandle_change_delete(o,3002 path, NULL,3003 o_oid, o_mode,3004 changed_oid, changed_mode,3005 modify_branch, delete_branch,3006_("modify"),_("modified"));3007}30083009static inthandle_content_merge(struct merge_options *o,3010const char*path,3011int is_dirty,3012struct object_id *o_oid,int o_mode,3013struct object_id *a_oid,int a_mode,3014struct object_id *b_oid,int b_mode,3015struct rename_conflict_info *rename_conflict_info)3016{3017const char*reason =_("content");3018const char*path1 = NULL, *path2 = NULL;3019struct merge_file_info mfi;3020struct diff_filespec one, a, b;3021unsigned df_conflict_remains =0;30223023if(!o_oid) {3024 reason =_("add/add");3025 o_oid = (struct object_id *)&null_oid;3026}3027 one.path = a.path = b.path = (char*)path;3028oidcpy(&one.oid, o_oid);3029 one.mode = o_mode;3030oidcpy(&a.oid, a_oid);3031 a.mode = a_mode;3032oidcpy(&b.oid, b_oid);3033 b.mode = b_mode;30343035if(rename_conflict_info) {3036struct diff_filepair *pair1 = rename_conflict_info->pair1;30373038 path1 = (o->branch1 == rename_conflict_info->branch1) ?3039 pair1->two->path : pair1->one->path;3040/* If rename_conflict_info->pair2 != NULL, we are in3041 * RENAME_ONE_FILE_TO_ONE case. Otherwise, we have a3042 * normal rename.3043 */3044 path2 = (rename_conflict_info->pair2 ||3045 o->branch2 == rename_conflict_info->branch1) ?3046 pair1->two->path : pair1->one->path;3047 one.path = pair1->one->path;3048 a.path = (char*)path1;3049 b.path = (char*)path2;30503051if(dir_in_way(path, !o->call_depth,3052S_ISGITLINK(pair1->two->mode)))3053 df_conflict_remains =1;3054}3055if(merge_mode_and_contents(o, &one, &a, &b, path,3056 o->branch1, o->branch2, &mfi))3057return-1;30583059/*3060 * We can skip updating the working tree file iff:3061 * a) The merge is clean3062 * b) The merge matches what was in HEAD (content, mode, pathname)3063 * c) The target path is usable (i.e. not involved in D/F conflict)3064 */3065if(mfi.clean &&3066was_tracked_and_matches(o, path, &mfi.oid, mfi.mode) &&3067!df_conflict_remains) {3068int pos;3069struct cache_entry *ce;30703071output(o,3,_("Skipped%s(merged same as existing)"), path);3072if(add_cacheinfo(o, mfi.mode, &mfi.oid, path,30730, (!o->call_depth && !is_dirty),0))3074return-1;3075/*3076 * However, add_cacheinfo() will delete the old cache entry3077 * and add a new one. We need to copy over any skip_worktree3078 * flag to avoid making the file appear as if it were3079 * deleted by the user.3080 */3081 pos =index_name_pos(&o->orig_index, path,strlen(path));3082 ce = o->orig_index.cache[pos];3083if(ce_skip_worktree(ce)) {3084 pos =index_name_pos(&the_index, path,strlen(path));3085 ce = the_index.cache[pos];3086 ce->ce_flags |= CE_SKIP_WORKTREE;3087}3088return mfi.clean;3089}30903091if(!mfi.clean) {3092if(S_ISGITLINK(mfi.mode))3093 reason =_("submodule");3094output(o,1,_("CONFLICT (%s): Merge conflict in%s"),3095 reason, path);3096if(rename_conflict_info && !df_conflict_remains)3097if(update_stages(o, path, &one, &a, &b))3098return-1;3099}31003101if(df_conflict_remains || is_dirty) {3102char*new_path;3103if(o->call_depth) {3104remove_file_from_cache(path);3105}else{3106if(!mfi.clean) {3107if(update_stages(o, path, &one, &a, &b))3108return-1;3109}else{3110int file_from_stage2 =was_tracked(o, path);3111struct diff_filespec merged;3112oidcpy(&merged.oid, &mfi.oid);3113 merged.mode = mfi.mode;31143115if(update_stages(o, path, NULL,3116 file_from_stage2 ? &merged : NULL,3117 file_from_stage2 ? NULL : &merged))3118return-1;3119}31203121}3122 new_path =unique_path(o, path, rename_conflict_info->branch1);3123if(is_dirty) {3124output(o,1,_("Refusing to lose dirty file at%s"),3125 path);3126}3127output(o,1,_("Adding as%sinstead"), new_path);3128if(update_file(o,0, &mfi.oid, mfi.mode, new_path)) {3129free(new_path);3130return-1;3131}3132free(new_path);3133 mfi.clean =0;3134}else if(update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))3135return-1;3136return!is_dirty && mfi.clean;3137}31383139static inthandle_rename_normal(struct merge_options *o,3140const char*path,3141struct object_id *o_oid,unsigned int o_mode,3142struct object_id *a_oid,unsigned int a_mode,3143struct object_id *b_oid,unsigned int b_mode,3144struct rename_conflict_info *ci)3145{3146/* Merge the content and write it out */3147returnhandle_content_merge(o, path,was_dirty(o, path),3148 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,3149 ci);3150}31513152/* Per entry merge function */3153static intprocess_entry(struct merge_options *o,3154const char*path,struct stage_data *entry)3155{3156int clean_merge =1;3157int normalize = o->renormalize;3158unsigned o_mode = entry->stages[1].mode;3159unsigned a_mode = entry->stages[2].mode;3160unsigned b_mode = entry->stages[3].mode;3161struct object_id *o_oid =stage_oid(&entry->stages[1].oid, o_mode);3162struct object_id *a_oid =stage_oid(&entry->stages[2].oid, a_mode);3163struct object_id *b_oid =stage_oid(&entry->stages[3].oid, b_mode);31643165 entry->processed =1;3166if(entry->rename_conflict_info) {3167struct rename_conflict_info *conflict_info = entry->rename_conflict_info;3168switch(conflict_info->rename_type) {3169case RENAME_NORMAL:3170case RENAME_ONE_FILE_TO_ONE:3171 clean_merge =handle_rename_normal(o,3172 path,3173 o_oid, o_mode,3174 a_oid, a_mode,3175 b_oid, b_mode,3176 conflict_info);3177break;3178case RENAME_VIA_DIR:3179 clean_merge =1;3180if(handle_rename_via_dir(o,3181 conflict_info->pair1,3182 conflict_info->branch1,3183 conflict_info->branch2))3184 clean_merge = -1;3185break;3186case RENAME_DELETE:3187 clean_merge =0;3188if(handle_rename_delete(o,3189 conflict_info->pair1,3190 conflict_info->branch1,3191 conflict_info->branch2))3192 clean_merge = -1;3193break;3194case RENAME_ONE_FILE_TO_TWO:3195 clean_merge =0;3196if(handle_rename_rename_1to2(o, conflict_info))3197 clean_merge = -1;3198break;3199case RENAME_TWO_FILES_TO_ONE:3200 clean_merge =0;3201if(handle_rename_rename_2to1(o, conflict_info))3202 clean_merge = -1;3203break;3204default:3205 entry->processed =0;3206break;3207}3208}else if(o_oid && (!a_oid || !b_oid)) {3209/* Case A: Deleted in one */3210if((!a_oid && !b_oid) ||3211(!b_oid &&blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||3212(!a_oid &&blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {3213/* Deleted in both or deleted in one and3214 * unchanged in the other */3215if(a_oid)3216output(o,2,_("Removing%s"), path);3217/* do not touch working file if it did not exist */3218remove_file(o,1, path, !a_oid);3219}else{3220/* Modify/delete; deleted side may have put a directory in the way */3221 clean_merge =0;3222if(handle_modify_delete(o, path, o_oid, o_mode,3223 a_oid, a_mode, b_oid, b_mode))3224 clean_merge = -1;3225}3226}else if((!o_oid && a_oid && !b_oid) ||3227(!o_oid && !a_oid && b_oid)) {3228/* Case B: Added in one. */3229/* [nothing|directory] -> ([nothing|directory], file) */32303231const char*add_branch;3232const char*other_branch;3233unsigned mode;3234const struct object_id *oid;3235const char*conf;32363237if(a_oid) {3238 add_branch = o->branch1;3239 other_branch = o->branch2;3240 mode = a_mode;3241 oid = a_oid;3242 conf =_("file/directory");3243}else{3244 add_branch = o->branch2;3245 other_branch = o->branch1;3246 mode = b_mode;3247 oid = b_oid;3248 conf =_("directory/file");3249}3250if(dir_in_way(path,3251!o->call_depth && !S_ISGITLINK(a_mode),32520)) {3253char*new_path =unique_path(o, path, add_branch);3254 clean_merge =0;3255output(o,1,_("CONFLICT (%s): There is a directory with name%sin%s. "3256"Adding%sas%s"),3257 conf, path, other_branch, path, new_path);3258if(update_file(o,0, oid, mode, new_path))3259 clean_merge = -1;3260else if(o->call_depth)3261remove_file_from_cache(path);3262free(new_path);3263}else{3264output(o,2,_("Adding%s"), path);3265/* do not overwrite file if already present */3266if(update_file_flags(o, oid, mode, path,1, !a_oid))3267 clean_merge = -1;3268}3269}else if(a_oid && b_oid) {3270/* Case C: Added in both (check for same permissions) and */3271/* case D: Modified in both, but differently. */3272int is_dirty =0;/* unpack_trees would have bailed if dirty */3273 clean_merge =handle_content_merge(o, path, is_dirty,3274 o_oid, o_mode,3275 a_oid, a_mode,3276 b_oid, b_mode,3277 NULL);3278}else if(!o_oid && !a_oid && !b_oid) {3279/*3280 * this entry was deleted altogether. a_mode == 0 means3281 * we had that path and want to actively remove it.3282 */3283remove_file(o,1, path, !a_mode);3284}else3285BUG("fatal merge failure, shouldn't happen.");32863287return clean_merge;3288}32893290intmerge_trees(struct merge_options *o,3291struct tree *head,3292struct tree *merge,3293struct tree *common,3294struct tree **result)3295{3296int code, clean;3297struct strbuf sb = STRBUF_INIT;32983299if(!o->call_depth &&index_has_changes(&the_index, head, &sb)) {3300err(o,_("Your local changes to the following files would be overwritten by merge:\n%s"),3301 sb.buf);3302return-1;3303}33043305if(o->subtree_shift) {3306 merge =shift_tree_object(head, merge, o->subtree_shift);3307 common =shift_tree_object(head, common, o->subtree_shift);3308}33093310if(oid_eq(&common->object.oid, &merge->object.oid)) {3311output(o,0,_("Already up to date!"));3312*result = head;3313return1;3314}33153316 code =unpack_trees_start(o, common, head, merge);33173318if(code !=0) {3319if(show(o,4) || o->call_depth)3320err(o,_("merging of trees%sand%sfailed"),3321oid_to_hex(&head->object.oid),3322oid_to_hex(&merge->object.oid));3323unpack_trees_finish(o);3324return-1;3325}33263327if(unmerged_cache()) {3328struct string_list *entries;3329struct rename_info re_info;3330int i;3331/*3332 * Only need the hashmap while processing entries, so3333 * initialize it here and free it when we are done running3334 * through the entries. Keeping it in the merge_options as3335 * opposed to decaring a local hashmap is for convenience3336 * so that we don't have to pass it to around.3337 */3338hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL,512);3339get_files_dirs(o, head);3340get_files_dirs(o, merge);33413342 entries =get_unmerged();3343 clean =detect_and_process_renames(o, common, head, merge,3344 entries, &re_info);3345record_df_conflict_files(o, entries);3346if(clean <0)3347goto cleanup;3348for(i = entries->nr-1;0<= i; i--) {3349const char*path = entries->items[i].string;3350struct stage_data *e = entries->items[i].util;3351if(!e->processed) {3352int ret =process_entry(o, path, e);3353if(!ret)3354 clean =0;3355else if(ret <0) {3356 clean = ret;3357goto cleanup;3358}3359}3360}3361for(i =0; i < entries->nr; i++) {3362struct stage_data *e = entries->items[i].util;3363if(!e->processed)3364BUG("unprocessed path???%s",3365 entries->items[i].string);3366}33673368 cleanup:3369final_cleanup_renames(&re_info);33703371string_list_clear(entries,1);3372free(entries);33733374hashmap_free(&o->current_file_dir_set,1);33753376if(clean <0) {3377unpack_trees_finish(o);3378return clean;3379}3380}3381else3382 clean =1;33833384unpack_trees_finish(o);33853386if(o->call_depth && !(*result =write_tree_from_memory(o)))3387return-1;33883389return clean;3390}33913392static struct commit_list *reverse_commit_list(struct commit_list *list)3393{3394struct commit_list *next = NULL, *current, *backup;3395for(current = list; current; current = backup) {3396 backup = current->next;3397 current->next = next;3398 next = current;3399}3400return next;3401}34023403/*3404 * Merge the commits h1 and h2, return the resulting virtual3405 * commit object and a flag indicating the cleanness of the merge.3406 */3407intmerge_recursive(struct merge_options *o,3408struct commit *h1,3409struct commit *h2,3410struct commit_list *ca,3411struct commit **result)3412{3413struct commit_list *iter;3414struct commit *merged_common_ancestors;3415struct tree *mrtree;3416int clean;34173418if(show(o,4)) {3419output(o,4,_("Merging:"));3420output_commit_title(o, h1);3421output_commit_title(o, h2);3422}34233424if(!ca) {3425 ca =get_merge_bases(h1, h2);3426 ca =reverse_commit_list(ca);3427}34283429if(show(o,5)) {3430unsigned cnt =commit_list_count(ca);34313432output(o,5,Q_("found%ucommon ancestor:",3433"found%ucommon ancestors:", cnt), cnt);3434for(iter = ca; iter; iter = iter->next)3435output_commit_title(o, iter->item);3436}34373438 merged_common_ancestors =pop_commit(&ca);3439if(merged_common_ancestors == NULL) {3440/* if there is no common ancestor, use an empty tree */3441struct tree *tree;34423443 tree =lookup_tree(the_repository, the_repository->hash_algo->empty_tree);3444 merged_common_ancestors =make_virtual_commit(tree,"ancestor");3445}34463447for(iter = ca; iter; iter = iter->next) {3448const char*saved_b1, *saved_b2;3449 o->call_depth++;3450/*3451 * When the merge fails, the result contains files3452 * with conflict markers. The cleanness flag is3453 * ignored (unless indicating an error), it was never3454 * actually used, as result of merge_trees has always3455 * overwritten it: the committed "conflicts" were3456 * already resolved.3457 */3458discard_cache();3459 saved_b1 = o->branch1;3460 saved_b2 = o->branch2;3461 o->branch1 ="Temporary merge branch 1";3462 o->branch2 ="Temporary merge branch 2";3463if(merge_recursive(o, merged_common_ancestors, iter->item,3464 NULL, &merged_common_ancestors) <0)3465return-1;3466 o->branch1 = saved_b1;3467 o->branch2 = saved_b2;3468 o->call_depth--;34693470if(!merged_common_ancestors)3471returnerr(o,_("merge returned no commit"));3472}34733474discard_cache();3475if(!o->call_depth)3476read_cache();34773478 o->ancestor ="merged common ancestors";3479 clean =merge_trees(o,get_commit_tree(h1),get_commit_tree(h2),3480get_commit_tree(merged_common_ancestors),3481&mrtree);3482if(clean <0) {3483flush_output(o);3484return clean;3485}34863487if(o->call_depth) {3488*result =make_virtual_commit(mrtree,"merged tree");3489commit_list_insert(h1, &(*result)->parents);3490commit_list_insert(h2, &(*result)->parents->next);3491}3492flush_output(o);3493if(!o->call_depth && o->buffer_output <2)3494strbuf_release(&o->obuf);3495if(show(o,2))3496diff_warn_rename_limit("merge.renamelimit",3497 o->needed_rename_limit,0);3498return clean;3499}35003501static struct commit *get_ref(const struct object_id *oid,const char*name)3502{3503struct object *object;35043505 object =deref_tag(the_repository,parse_object(the_repository, oid),3506 name,3507strlen(name));3508if(!object)3509return NULL;3510if(object->type == OBJ_TREE)3511returnmake_virtual_commit((struct tree*)object, name);3512if(object->type != OBJ_COMMIT)3513return NULL;3514if(parse_commit((struct commit *)object))3515return NULL;3516return(struct commit *)object;3517}35183519intmerge_recursive_generic(struct merge_options *o,3520const struct object_id *head,3521const struct object_id *merge,3522int num_base_list,3523const struct object_id **base_list,3524struct commit **result)3525{3526int clean;3527struct lock_file lock = LOCK_INIT;3528struct commit *head_commit =get_ref(head, o->branch1);3529struct commit *next_commit =get_ref(merge, o->branch2);3530struct commit_list *ca = NULL;35313532if(base_list) {3533int i;3534for(i =0; i < num_base_list; ++i) {3535struct commit *base;3536if(!(base =get_ref(base_list[i],oid_to_hex(base_list[i]))))3537returnerr(o,_("Could not parse object '%s'"),3538oid_to_hex(base_list[i]));3539commit_list_insert(base, &ca);3540}3541}35423543hold_locked_index(&lock, LOCK_DIE_ON_ERROR);3544 clean =merge_recursive(o, head_commit, next_commit, ca,3545 result);3546if(clean <0) {3547rollback_lock_file(&lock);3548return clean;3549}35503551if(write_locked_index(&the_index, &lock,3552 COMMIT_LOCK | SKIP_IF_UNCHANGED))3553returnerr(o,_("Unable to write index."));35543555return clean ?0:1;3556}35573558static voidmerge_recursive_config(struct merge_options *o)3559{3560char*value = NULL;3561git_config_get_int("merge.verbosity", &o->verbosity);3562git_config_get_int("diff.renamelimit", &o->diff_rename_limit);3563git_config_get_int("merge.renamelimit", &o->merge_rename_limit);3564if(!git_config_get_string("diff.renames", &value)) {3565 o->diff_detect_rename =git_config_rename("diff.renames", value);3566free(value);3567}3568if(!git_config_get_string("merge.renames", &value)) {3569 o->merge_detect_rename =git_config_rename("merge.renames", value);3570free(value);3571}3572git_config(git_xmerge_config, NULL);3573}35743575voidinit_merge_options(struct merge_options *o)3576{3577const char*merge_verbosity;3578memset(o,0,sizeof(struct merge_options));3579 o->verbosity =2;3580 o->buffer_output =1;3581 o->diff_rename_limit = -1;3582 o->merge_rename_limit = -1;3583 o->renormalize =0;3584 o->diff_detect_rename = -1;3585 o->merge_detect_rename = -1;3586 o->detect_directory_renames =1;3587merge_recursive_config(o);3588 merge_verbosity =getenv("GIT_MERGE_VERBOSITY");3589if(merge_verbosity)3590 o->verbosity =strtol(merge_verbosity, NULL,10);3591if(o->verbosity >=5)3592 o->buffer_output =0;3593strbuf_init(&o->obuf,0);3594string_list_init(&o->df_conflict_file_set,1);3595}35963597intparse_merge_opt(struct merge_options *o,const char*s)3598{3599const char*arg;36003601if(!s || !*s)3602return-1;3603if(!strcmp(s,"ours"))3604 o->recursive_variant = MERGE_RECURSIVE_OURS;3605else if(!strcmp(s,"theirs"))3606 o->recursive_variant = MERGE_RECURSIVE_THEIRS;3607else if(!strcmp(s,"subtree"))3608 o->subtree_shift ="";3609else if(skip_prefix(s,"subtree=", &arg))3610 o->subtree_shift = arg;3611else if(!strcmp(s,"patience"))3612 o->xdl_opts =DIFF_WITH_ALG(o, PATIENCE_DIFF);3613else if(!strcmp(s,"histogram"))3614 o->xdl_opts =DIFF_WITH_ALG(o, HISTOGRAM_DIFF);3615else if(skip_prefix(s,"diff-algorithm=", &arg)) {3616long value =parse_algorithm_value(arg);3617if(value <0)3618return-1;3619/* clear out previous settings */3620DIFF_XDL_CLR(o, NEED_MINIMAL);3621 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;3622 o->xdl_opts |= value;3623}3624else if(!strcmp(s,"ignore-space-change"))3625DIFF_XDL_SET(o, IGNORE_WHITESPACE_CHANGE);3626else if(!strcmp(s,"ignore-all-space"))3627DIFF_XDL_SET(o, IGNORE_WHITESPACE);3628else if(!strcmp(s,"ignore-space-at-eol"))3629DIFF_XDL_SET(o, IGNORE_WHITESPACE_AT_EOL);3630else if(!strcmp(s,"ignore-cr-at-eol"))3631DIFF_XDL_SET(o, IGNORE_CR_AT_EOL);3632else if(!strcmp(s,"renormalize"))3633 o->renormalize =1;3634else if(!strcmp(s,"no-renormalize"))3635 o->renormalize =0;3636else if(!strcmp(s,"no-renames"))3637 o->merge_detect_rename =0;3638else if(!strcmp(s,"find-renames")) {3639 o->merge_detect_rename =1;3640 o->rename_score =0;3641}3642else if(skip_prefix(s,"find-renames=", &arg) ||3643skip_prefix(s,"rename-threshold=", &arg)) {3644if((o->rename_score =parse_rename_score(&arg)) == -1|| *arg !=0)3645return-1;3646 o->merge_detect_rename =1;3647}3648else3649return-1;3650return0;3651}