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"commit.h" 12#include"blob.h" 13#include"builtin.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"diffcore.h" 17#include"tag.h" 18#include"unpack-trees.h" 19#include"string-list.h" 20#include"xdiff-interface.h" 21#include"ll-merge.h" 22#include"attr.h" 23#include"merge-recursive.h" 24#include"dir.h" 25#include"submodule.h" 26 27struct path_hashmap_entry { 28struct hashmap_entry e; 29char path[FLEX_ARRAY]; 30}; 31 32static intpath_hashmap_cmp(const void*cmp_data, 33const void*entry, 34const void*entry_or_key, 35const void*keydata) 36{ 37const struct path_hashmap_entry *a = entry; 38const struct path_hashmap_entry *b = entry_or_key; 39const char*key = keydata; 40 41if(ignore_case) 42returnstrcasecmp(a->path, key ? key : b->path); 43else 44returnstrcmp(a->path, key ? key : b->path); 45} 46 47static unsigned intpath_hash(const char*path) 48{ 49return ignore_case ?strihash(path) :strhash(path); 50} 51 52static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap, 53char*dir) 54{ 55struct dir_rename_entry key; 56 57if(dir == NULL) 58return NULL; 59hashmap_entry_init(&key,strhash(dir)); 60 key.dir = dir; 61returnhashmap_get(hashmap, &key, NULL); 62} 63 64static intdir_rename_cmp(const void*unused_cmp_data, 65const void*entry, 66const void*entry_or_key, 67const void*unused_keydata) 68{ 69const struct dir_rename_entry *e1 = entry; 70const struct dir_rename_entry *e2 = entry_or_key; 71 72returnstrcmp(e1->dir, e2->dir); 73} 74 75static voiddir_rename_init(struct hashmap *map) 76{ 77hashmap_init(map, dir_rename_cmp, NULL,0); 78} 79 80static voiddir_rename_entry_init(struct dir_rename_entry *entry, 81char*directory) 82{ 83hashmap_entry_init(entry,strhash(directory)); 84 entry->dir = directory; 85 entry->non_unique_new_dir =0; 86strbuf_init(&entry->new_dir,0); 87string_list_init(&entry->possible_new_dirs,0); 88} 89 90static struct collision_entry *collision_find_entry(struct hashmap *hashmap, 91char*target_file) 92{ 93struct collision_entry key; 94 95hashmap_entry_init(&key,strhash(target_file)); 96 key.target_file = target_file; 97returnhashmap_get(hashmap, &key, NULL); 98} 99 100static intcollision_cmp(void*unused_cmp_data, 101const struct collision_entry *e1, 102const struct collision_entry *e2, 103const void*unused_keydata) 104{ 105returnstrcmp(e1->target_file, e2->target_file); 106} 107 108static voidcollision_init(struct hashmap *map) 109{ 110hashmap_init(map, (hashmap_cmp_fn) collision_cmp, NULL,0); 111} 112 113static voidflush_output(struct merge_options *o) 114{ 115if(o->buffer_output <2&& o->obuf.len) { 116fputs(o->obuf.buf, stdout); 117strbuf_reset(&o->obuf); 118} 119} 120 121static interr(struct merge_options *o,const char*err, ...) 122{ 123va_list params; 124 125if(o->buffer_output <2) 126flush_output(o); 127else{ 128strbuf_complete(&o->obuf,'\n'); 129strbuf_addstr(&o->obuf,"error: "); 130} 131va_start(params, err); 132strbuf_vaddf(&o->obuf, err, params); 133va_end(params); 134if(o->buffer_output >1) 135strbuf_addch(&o->obuf,'\n'); 136else{ 137error("%s", o->obuf.buf); 138strbuf_reset(&o->obuf); 139} 140 141return-1; 142} 143 144static struct tree *shift_tree_object(struct tree *one,struct tree *two, 145const char*subtree_shift) 146{ 147struct object_id shifted; 148 149if(!*subtree_shift) { 150shift_tree(&one->object.oid, &two->object.oid, &shifted,0); 151}else{ 152shift_tree_by(&one->object.oid, &two->object.oid, &shifted, 153 subtree_shift); 154} 155if(!oidcmp(&two->object.oid, &shifted)) 156return two; 157returnlookup_tree(&shifted); 158} 159 160static struct commit *make_virtual_commit(struct tree *tree,const char*comment) 161{ 162struct commit *commit =alloc_commit_node(); 163 164set_merge_remote_desc(commit, comment, (struct object *)commit); 165 commit->maybe_tree = tree; 166 commit->object.parsed =1; 167return commit; 168} 169 170/* 171 * Since we use get_tree_entry(), which does not put the read object into 172 * the object pool, we cannot rely on a == b. 173 */ 174static intoid_eq(const struct object_id *a,const struct object_id *b) 175{ 176if(!a && !b) 177return2; 178return a && b &&oidcmp(a, b) ==0; 179} 180 181enum rename_type { 182 RENAME_NORMAL =0, 183 RENAME_DIR, 184 RENAME_DELETE, 185 RENAME_ONE_FILE_TO_ONE, 186 RENAME_ONE_FILE_TO_TWO, 187 RENAME_TWO_FILES_TO_ONE 188}; 189 190struct rename_conflict_info { 191enum rename_type rename_type; 192struct diff_filepair *pair1; 193struct diff_filepair *pair2; 194const char*branch1; 195const char*branch2; 196struct stage_data *dst_entry1; 197struct stage_data *dst_entry2; 198struct diff_filespec ren1_other; 199struct diff_filespec ren2_other; 200}; 201 202/* 203 * Since we want to write the index eventually, we cannot reuse the index 204 * for these (temporary) data. 205 */ 206struct stage_data { 207struct{ 208unsigned mode; 209struct object_id oid; 210} stages[4]; 211struct rename_conflict_info *rename_conflict_info; 212unsigned processed:1; 213}; 214 215staticinlinevoidsetup_rename_conflict_info(enum rename_type rename_type, 216struct diff_filepair *pair1, 217struct diff_filepair *pair2, 218const char*branch1, 219const char*branch2, 220struct stage_data *dst_entry1, 221struct stage_data *dst_entry2, 222struct merge_options *o, 223struct stage_data *src_entry1, 224struct stage_data *src_entry2) 225{ 226struct rename_conflict_info *ci =xcalloc(1,sizeof(struct rename_conflict_info)); 227 ci->rename_type = rename_type; 228 ci->pair1 = pair1; 229 ci->branch1 = branch1; 230 ci->branch2 = branch2; 231 232 ci->dst_entry1 = dst_entry1; 233 dst_entry1->rename_conflict_info = ci; 234 dst_entry1->processed =0; 235 236assert(!pair2 == !dst_entry2); 237if(dst_entry2) { 238 ci->dst_entry2 = dst_entry2; 239 ci->pair2 = pair2; 240 dst_entry2->rename_conflict_info = ci; 241} 242 243if(rename_type == RENAME_TWO_FILES_TO_ONE) { 244/* 245 * For each rename, there could have been 246 * modifications on the side of history where that 247 * file was not renamed. 248 */ 249int ostage1 = o->branch1 == branch1 ?3:2; 250int ostage2 = ostage1 ^1; 251 252 ci->ren1_other.path = pair1->one->path; 253oidcpy(&ci->ren1_other.oid, &src_entry1->stages[ostage1].oid); 254 ci->ren1_other.mode = src_entry1->stages[ostage1].mode; 255 256 ci->ren2_other.path = pair2->one->path; 257oidcpy(&ci->ren2_other.oid, &src_entry2->stages[ostage2].oid); 258 ci->ren2_other.mode = src_entry2->stages[ostage2].mode; 259} 260} 261 262static intshow(struct merge_options *o,int v) 263{ 264return(!o->call_depth && o->verbosity >= v) || o->verbosity >=5; 265} 266 267__attribute__((format(printf,3,4))) 268static voidoutput(struct merge_options *o,int v,const char*fmt, ...) 269{ 270va_list ap; 271 272if(!show(o, v)) 273return; 274 275strbuf_addchars(&o->obuf,' ', o->call_depth *2); 276 277va_start(ap, fmt); 278strbuf_vaddf(&o->obuf, fmt, ap); 279va_end(ap); 280 281strbuf_addch(&o->obuf,'\n'); 282if(!o->buffer_output) 283flush_output(o); 284} 285 286static voidoutput_commit_title(struct merge_options *o,struct commit *commit) 287{ 288strbuf_addchars(&o->obuf,' ', o->call_depth *2); 289if(commit->util) 290strbuf_addf(&o->obuf,"virtual%s\n", 291merge_remote_util(commit)->name); 292else{ 293strbuf_add_unique_abbrev(&o->obuf, &commit->object.oid, 294 DEFAULT_ABBREV); 295strbuf_addch(&o->obuf,' '); 296if(parse_commit(commit) !=0) 297strbuf_addstr(&o->obuf,_("(bad commit)\n")); 298else{ 299const char*title; 300const char*msg =get_commit_buffer(commit, NULL); 301int len =find_commit_subject(msg, &title); 302if(len) 303strbuf_addf(&o->obuf,"%.*s\n", len, title); 304unuse_commit_buffer(commit, msg); 305} 306} 307flush_output(o); 308} 309 310static intadd_cacheinfo(struct merge_options *o, 311unsigned int mode,const struct object_id *oid, 312const char*path,int stage,int refresh,int options) 313{ 314struct cache_entry *ce; 315int ret; 316 317 ce =make_cache_entry(mode, oid ? oid->hash : null_sha1, path, stage,0); 318if(!ce) 319returnerr(o,_("add_cacheinfo failed for path '%s'; merge aborting."), path); 320 321 ret =add_cache_entry(ce, options); 322if(refresh) { 323struct cache_entry *nce; 324 325 nce =refresh_cache_entry(ce, CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING); 326if(!nce) 327returnerr(o,_("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path); 328if(nce != ce) 329 ret =add_cache_entry(nce, options); 330} 331return ret; 332} 333 334static voidinit_tree_desc_from_tree(struct tree_desc *desc,struct tree *tree) 335{ 336parse_tree(tree); 337init_tree_desc(desc, tree->buffer, tree->size); 338} 339 340static intgit_merge_trees(struct merge_options *o, 341struct tree *common, 342struct tree *head, 343struct tree *merge) 344{ 345int rc; 346struct tree_desc t[3]; 347struct index_state tmp_index = { NULL }; 348 349memset(&o->unpack_opts,0,sizeof(o->unpack_opts)); 350if(o->call_depth) 351 o->unpack_opts.index_only =1; 352else 353 o->unpack_opts.update =1; 354 o->unpack_opts.merge =1; 355 o->unpack_opts.head_idx =2; 356 o->unpack_opts.fn = threeway_merge; 357 o->unpack_opts.src_index = &the_index; 358 o->unpack_opts.dst_index = &tmp_index; 359 o->unpack_opts.aggressive = !merge_detect_rename(o); 360setup_unpack_trees_porcelain(&o->unpack_opts,"merge"); 361 362init_tree_desc_from_tree(t+0, common); 363init_tree_desc_from_tree(t+1, head); 364init_tree_desc_from_tree(t+2, merge); 365 366 rc =unpack_trees(3, t, &o->unpack_opts); 367cache_tree_free(&active_cache_tree); 368 369/* 370 * Update the_index to match the new results, AFTER saving a copy 371 * in o->orig_index. Update src_index to point to the saved copy. 372 * (verify_uptodate() checks src_index, and the original index is 373 * the one that had the necessary modification timestamps.) 374 */ 375 o->orig_index = the_index; 376 the_index = tmp_index; 377 o->unpack_opts.src_index = &o->orig_index; 378 379return rc; 380} 381 382struct tree *write_tree_from_memory(struct merge_options *o) 383{ 384struct tree *result = NULL; 385 386if(unmerged_cache()) { 387int i; 388fprintf(stderr,"BUG: There are unmerged index entries:\n"); 389for(i =0; i < active_nr; i++) { 390const struct cache_entry *ce = active_cache[i]; 391if(ce_stage(ce)) 392fprintf(stderr,"BUG:%d%.*s\n",ce_stage(ce), 393(int)ce_namelen(ce), ce->name); 394} 395BUG("unmerged index entries in merge-recursive.c"); 396} 397 398if(!active_cache_tree) 399 active_cache_tree =cache_tree(); 400 401if(!cache_tree_fully_valid(active_cache_tree) && 402cache_tree_update(&the_index,0) <0) { 403err(o,_("error building trees")); 404return NULL; 405} 406 407 result =lookup_tree(&active_cache_tree->oid); 408 409return result; 410} 411 412static intsave_files_dirs(const struct object_id *oid, 413struct strbuf *base,const char*path, 414unsigned int mode,int stage,void*context) 415{ 416struct path_hashmap_entry *entry; 417int baselen = base->len; 418struct merge_options *o = context; 419 420strbuf_addstr(base, path); 421 422FLEX_ALLOC_MEM(entry, path, base->buf, base->len); 423hashmap_entry_init(entry,path_hash(entry->path)); 424hashmap_add(&o->current_file_dir_set, entry); 425 426strbuf_setlen(base, baselen); 427return(S_ISDIR(mode) ? READ_TREE_RECURSIVE :0); 428} 429 430static voidget_files_dirs(struct merge_options *o,struct tree *tree) 431{ 432struct pathspec match_all; 433memset(&match_all,0,sizeof(match_all)); 434read_tree_recursive(tree,"",0,0, &match_all, save_files_dirs, o); 435} 436 437static intget_tree_entry_if_blob(const struct object_id *tree, 438const char*path, 439struct object_id *hashy, 440unsigned int*mode_o) 441{ 442int ret; 443 444 ret =get_tree_entry(tree, path, hashy, mode_o); 445if(S_ISDIR(*mode_o)) { 446oidcpy(hashy, &null_oid); 447*mode_o =0; 448} 449return ret; 450} 451 452/* 453 * Returns an index_entry instance which doesn't have to correspond to 454 * a real cache entry in Git's index. 455 */ 456static struct stage_data *insert_stage_data(const char*path, 457struct tree *o,struct tree *a,struct tree *b, 458struct string_list *entries) 459{ 460struct string_list_item *item; 461struct stage_data *e =xcalloc(1,sizeof(struct stage_data)); 462get_tree_entry_if_blob(&o->object.oid, path, 463&e->stages[1].oid, &e->stages[1].mode); 464get_tree_entry_if_blob(&a->object.oid, path, 465&e->stages[2].oid, &e->stages[2].mode); 466get_tree_entry_if_blob(&b->object.oid, path, 467&e->stages[3].oid, &e->stages[3].mode); 468 item =string_list_insert(entries, path); 469 item->util = e; 470return e; 471} 472 473/* 474 * Create a dictionary mapping file names to stage_data objects. The 475 * dictionary contains one entry for every path with a non-zero stage entry. 476 */ 477static struct string_list *get_unmerged(void) 478{ 479struct string_list *unmerged =xcalloc(1,sizeof(struct string_list)); 480int i; 481 482 unmerged->strdup_strings =1; 483 484for(i =0; i < active_nr; i++) { 485struct string_list_item *item; 486struct stage_data *e; 487const struct cache_entry *ce = active_cache[i]; 488if(!ce_stage(ce)) 489continue; 490 491 item =string_list_lookup(unmerged, ce->name); 492if(!item) { 493 item =string_list_insert(unmerged, ce->name); 494 item->util =xcalloc(1,sizeof(struct stage_data)); 495} 496 e = item->util; 497 e->stages[ce_stage(ce)].mode = ce->ce_mode; 498oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid); 499} 500 501return unmerged; 502} 503 504static intstring_list_df_name_compare(const char*one,const char*two) 505{ 506int onelen =strlen(one); 507int twolen =strlen(two); 508/* 509 * Here we only care that entries for D/F conflicts are 510 * adjacent, in particular with the file of the D/F conflict 511 * appearing before files below the corresponding directory. 512 * The order of the rest of the list is irrelevant for us. 513 * 514 * To achieve this, we sort with df_name_compare and provide 515 * the mode S_IFDIR so that D/F conflicts will sort correctly. 516 * We use the mode S_IFDIR for everything else for simplicity, 517 * since in other cases any changes in their order due to 518 * sorting cause no problems for us. 519 */ 520int cmp =df_name_compare(one, onelen, S_IFDIR, 521 two, twolen, S_IFDIR); 522/* 523 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure 524 * that 'foo' comes before 'foo/bar'. 525 */ 526if(cmp) 527return cmp; 528return onelen - twolen; 529} 530 531static voidrecord_df_conflict_files(struct merge_options *o, 532struct string_list *entries) 533{ 534/* If there is a D/F conflict and the file for such a conflict 535 * currently exist in the working tree, we want to allow it to be 536 * removed to make room for the corresponding directory if needed. 537 * The files underneath the directories of such D/F conflicts will 538 * be processed before the corresponding file involved in the D/F 539 * conflict. If the D/F directory ends up being removed by the 540 * merge, then we won't have to touch the D/F file. If the D/F 541 * directory needs to be written to the working copy, then the D/F 542 * file will simply be removed (in make_room_for_path()) to make 543 * room for the necessary paths. Note that if both the directory 544 * and the file need to be present, then the D/F file will be 545 * reinstated with a new unique name at the time it is processed. 546 */ 547struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP; 548const char*last_file = NULL; 549int last_len =0; 550int i; 551 552/* 553 * If we're merging merge-bases, we don't want to bother with 554 * any working directory changes. 555 */ 556if(o->call_depth) 557return; 558 559/* Ensure D/F conflicts are adjacent in the entries list. */ 560for(i =0; i < entries->nr; i++) { 561struct string_list_item *next = &entries->items[i]; 562string_list_append(&df_sorted_entries, next->string)->util = 563 next->util; 564} 565 df_sorted_entries.cmp = string_list_df_name_compare; 566string_list_sort(&df_sorted_entries); 567 568string_list_clear(&o->df_conflict_file_set,1); 569for(i =0; i < df_sorted_entries.nr; i++) { 570const char*path = df_sorted_entries.items[i].string; 571int len =strlen(path); 572struct stage_data *e = df_sorted_entries.items[i].util; 573 574/* 575 * Check if last_file & path correspond to a D/F conflict; 576 * i.e. whether path is last_file+'/'+<something>. 577 * If so, record that it's okay to remove last_file to make 578 * room for path and friends if needed. 579 */ 580if(last_file && 581 len > last_len && 582memcmp(path, last_file, last_len) ==0&& 583 path[last_len] =='/') { 584string_list_insert(&o->df_conflict_file_set, last_file); 585} 586 587/* 588 * Determine whether path could exist as a file in the 589 * working directory as a possible D/F conflict. This 590 * will only occur when it exists in stage 2 as a 591 * file. 592 */ 593if(S_ISREG(e->stages[2].mode) ||S_ISLNK(e->stages[2].mode)) { 594 last_file = path; 595 last_len = len; 596}else{ 597 last_file = NULL; 598} 599} 600string_list_clear(&df_sorted_entries,0); 601} 602 603struct rename { 604struct diff_filepair *pair; 605/* 606 * Purpose of src_entry and dst_entry: 607 * 608 * If 'before' is renamed to 'after' then src_entry will contain 609 * the versions of 'before' from the merge_base, HEAD, and MERGE in 610 * stages 1, 2, and 3; dst_entry will contain the respective 611 * versions of 'after' in corresponding locations. Thus, we have a 612 * total of six modes and oids, though some will be null. (Stage 0 613 * is ignored; we're interested in handling conflicts.) 614 * 615 * Since we don't turn on break-rewrites by default, neither 616 * src_entry nor dst_entry can have all three of their stages have 617 * non-null oids, meaning at most four of the six will be non-null. 618 * Also, since this is a rename, both src_entry and dst_entry will 619 * have at least one non-null oid, meaning at least two will be 620 * non-null. Of the six oids, a typical rename will have three be 621 * non-null. Only two implies a rename/delete, and four implies a 622 * rename/add. 623 */ 624struct stage_data *src_entry; 625struct stage_data *dst_entry; 626unsigned add_turned_into_rename:1; 627unsigned processed:1; 628}; 629 630static intupdate_stages(struct merge_options *opt,const char*path, 631const struct diff_filespec *o, 632const struct diff_filespec *a, 633const struct diff_filespec *b) 634{ 635 636/* 637 * NOTE: It is usually a bad idea to call update_stages on a path 638 * before calling update_file on that same path, since it can 639 * sometimes lead to spurious "refusing to lose untracked file..." 640 * messages from update_file (via make_room_for path via 641 * would_lose_untracked). Instead, reverse the order of the calls 642 * (executing update_file first and then update_stages). 643 */ 644int clear =1; 645int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK; 646if(clear) 647if(remove_file_from_cache(path)) 648return-1; 649if(o) 650if(add_cacheinfo(opt, o->mode, &o->oid, path,1,0, options)) 651return-1; 652if(a) 653if(add_cacheinfo(opt, a->mode, &a->oid, path,2,0, options)) 654return-1; 655if(b) 656if(add_cacheinfo(opt, b->mode, &b->oid, path,3,0, options)) 657return-1; 658return0; 659} 660 661static intupdate_stages_for_stage_data(struct merge_options *opt, 662const char*path, 663const struct stage_data *stage_data) 664{ 665struct diff_filespec o, a, b; 666 667 o.mode = stage_data->stages[1].mode; 668oidcpy(&o.oid, &stage_data->stages[1].oid); 669 670 a.mode = stage_data->stages[2].mode; 671oidcpy(&a.oid, &stage_data->stages[2].oid); 672 673 b.mode = stage_data->stages[3].mode; 674oidcpy(&b.oid, &stage_data->stages[3].oid); 675 676returnupdate_stages(opt, path, 677is_null_oid(&o.oid) ? NULL : &o, 678is_null_oid(&a.oid) ? NULL : &a, 679is_null_oid(&b.oid) ? NULL : &b); 680} 681 682static voidupdate_entry(struct stage_data *entry, 683struct diff_filespec *o, 684struct diff_filespec *a, 685struct diff_filespec *b) 686{ 687 entry->processed =0; 688 entry->stages[1].mode = o->mode; 689 entry->stages[2].mode = a->mode; 690 entry->stages[3].mode = b->mode; 691oidcpy(&entry->stages[1].oid, &o->oid); 692oidcpy(&entry->stages[2].oid, &a->oid); 693oidcpy(&entry->stages[3].oid, &b->oid); 694} 695 696static intremove_file(struct merge_options *o,int clean, 697const char*path,int no_wd) 698{ 699int update_cache = o->call_depth || clean; 700int update_working_directory = !o->call_depth && !no_wd; 701 702if(update_cache) { 703if(remove_file_from_cache(path)) 704return-1; 705} 706if(update_working_directory) { 707if(ignore_case) { 708struct cache_entry *ce; 709 ce =cache_file_exists(path,strlen(path), ignore_case); 710if(ce &&ce_stage(ce) ==0&&strcmp(path, ce->name)) 711return0; 712} 713if(remove_path(path)) 714return-1; 715} 716return0; 717} 718 719/* add a string to a strbuf, but converting "/" to "_" */ 720static voidadd_flattened_path(struct strbuf *out,const char*s) 721{ 722size_t i = out->len; 723strbuf_addstr(out, s); 724for(; i < out->len; i++) 725if(out->buf[i] =='/') 726 out->buf[i] ='_'; 727} 728 729static char*unique_path(struct merge_options *o,const char*path,const char*branch) 730{ 731struct path_hashmap_entry *entry; 732struct strbuf newpath = STRBUF_INIT; 733int suffix =0; 734size_t base_len; 735 736strbuf_addf(&newpath,"%s~", path); 737add_flattened_path(&newpath, branch); 738 739 base_len = newpath.len; 740while(hashmap_get_from_hash(&o->current_file_dir_set, 741path_hash(newpath.buf), newpath.buf) || 742(!o->call_depth &&file_exists(newpath.buf))) { 743strbuf_setlen(&newpath, base_len); 744strbuf_addf(&newpath,"_%d", suffix++); 745} 746 747FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len); 748hashmap_entry_init(entry,path_hash(entry->path)); 749hashmap_add(&o->current_file_dir_set, entry); 750returnstrbuf_detach(&newpath, NULL); 751} 752 753/** 754 * Check whether a directory in the index is in the way of an incoming 755 * file. Return 1 if so. If check_working_copy is non-zero, also 756 * check the working directory. If empty_ok is non-zero, also return 757 * 0 in the case where the working-tree dir exists but is empty. 758 */ 759static intdir_in_way(const char*path,int check_working_copy,int empty_ok) 760{ 761int pos; 762struct strbuf dirpath = STRBUF_INIT; 763struct stat st; 764 765strbuf_addstr(&dirpath, path); 766strbuf_addch(&dirpath,'/'); 767 768 pos =cache_name_pos(dirpath.buf, dirpath.len); 769 770if(pos <0) 771 pos = -1- pos; 772if(pos < active_nr && 773!strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) { 774strbuf_release(&dirpath); 775return1; 776} 777 778strbuf_release(&dirpath); 779return check_working_copy && !lstat(path, &st) &&S_ISDIR(st.st_mode) && 780!(empty_ok &&is_empty_dir(path)); 781} 782 783/* 784 * Returns whether path was tracked in the index before the merge started, 785 * and its oid and mode match the specified values 786 */ 787static intwas_tracked_and_matches(struct merge_options *o,const char*path, 788const struct object_id *oid,unsigned mode) 789{ 790int pos =index_name_pos(&o->orig_index, path,strlen(path)); 791struct cache_entry *ce; 792 793if(0> pos) 794/* we were not tracking this path before the merge */ 795return0; 796 797/* See if the file we were tracking before matches */ 798 ce = o->orig_index.cache[pos]; 799return(oid_eq(&ce->oid, oid) && ce->ce_mode == mode); 800} 801 802/* 803 * Returns whether path was tracked in the index before the merge started 804 */ 805static intwas_tracked(struct merge_options *o,const char*path) 806{ 807int pos =index_name_pos(&o->orig_index, path,strlen(path)); 808 809if(0<= pos) 810/* we were tracking this path before the merge */ 811return1; 812 813return0; 814} 815 816static intwould_lose_untracked(const char*path) 817{ 818/* 819 * This may look like it can be simplified to: 820 * return !was_tracked(o, path) && file_exists(path) 821 * but it can't. This function needs to know whether path was in 822 * the working tree due to EITHER having been tracked in the index 823 * before the merge OR having been put into the working copy and 824 * index by unpack_trees(). Due to that either-or requirement, we 825 * check the current index instead of the original one. 826 * 827 * Note that we do not need to worry about merge-recursive itself 828 * updating the index after unpack_trees() and before calling this 829 * function, because we strictly require all code paths in 830 * merge-recursive to update the working tree first and the index 831 * second. Doing otherwise would break 832 * update_file()/would_lose_untracked(); see every comment in this 833 * file which mentions "update_stages". 834 */ 835int pos =cache_name_pos(path,strlen(path)); 836 837if(pos <0) 838 pos = -1- pos; 839while(pos < active_nr && 840!strcmp(path, active_cache[pos]->name)) { 841/* 842 * If stage #0, it is definitely tracked. 843 * If it has stage #2 then it was tracked 844 * before this merge started. All other 845 * cases the path was not tracked. 846 */ 847switch(ce_stage(active_cache[pos])) { 848case0: 849case2: 850return0; 851} 852 pos++; 853} 854returnfile_exists(path); 855} 856 857static intwas_dirty(struct merge_options *o,const char*path) 858{ 859struct cache_entry *ce; 860int dirty =1; 861 862if(o->call_depth || !was_tracked(o, path)) 863return!dirty; 864 865 ce =index_file_exists(o->unpack_opts.src_index, 866 path,strlen(path), ignore_case); 867 dirty =verify_uptodate(ce, &o->unpack_opts) !=0; 868return dirty; 869} 870 871static intmake_room_for_path(struct merge_options *o,const char*path) 872{ 873int status, i; 874const char*msg =_("failed to create path '%s'%s"); 875 876/* Unlink any D/F conflict files that are in the way */ 877for(i =0; i < o->df_conflict_file_set.nr; i++) { 878const char*df_path = o->df_conflict_file_set.items[i].string; 879size_t pathlen =strlen(path); 880size_t df_pathlen =strlen(df_path); 881if(df_pathlen < pathlen && 882 path[df_pathlen] =='/'&& 883strncmp(path, df_path, df_pathlen) ==0) { 884output(o,3, 885_("Removing%sto make room for subdirectory\n"), 886 df_path); 887unlink(df_path); 888unsorted_string_list_delete_item(&o->df_conflict_file_set, 889 i,0); 890break; 891} 892} 893 894/* Make sure leading directories are created */ 895 status =safe_create_leading_directories_const(path); 896if(status) { 897if(status == SCLD_EXISTS) 898/* something else exists */ 899returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 900returnerr(o, msg, path,""); 901} 902 903/* 904 * Do not unlink a file in the work tree if we are not 905 * tracking it. 906 */ 907if(would_lose_untracked(path)) 908returnerr(o,_("refusing to lose untracked file at '%s'"), 909 path); 910 911/* Successful unlink is good.. */ 912if(!unlink(path)) 913return0; 914/* .. and so is no existing file */ 915if(errno == ENOENT) 916return0; 917/* .. but not some other error (who really cares what?) */ 918returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 919} 920 921static intupdate_file_flags(struct merge_options *o, 922const struct object_id *oid, 923unsigned mode, 924const char*path, 925int update_cache, 926int update_wd) 927{ 928int ret =0; 929 930if(o->call_depth) 931 update_wd =0; 932 933if(update_wd) { 934enum object_type type; 935void*buf; 936unsigned long size; 937 938if(S_ISGITLINK(mode)) { 939/* 940 * We may later decide to recursively descend into 941 * the submodule directory and update its index 942 * and/or work tree, but we do not do that now. 943 */ 944 update_wd =0; 945goto update_index; 946} 947 948 buf =read_object_file(oid, &type, &size); 949if(!buf) 950returnerr(o,_("cannot read object%s'%s'"),oid_to_hex(oid), path); 951if(type != OBJ_BLOB) { 952 ret =err(o,_("blob expected for%s'%s'"),oid_to_hex(oid), path); 953goto free_buf; 954} 955if(S_ISREG(mode)) { 956struct strbuf strbuf = STRBUF_INIT; 957if(convert_to_working_tree(path, buf, size, &strbuf)) { 958free(buf); 959 size = strbuf.len; 960 buf =strbuf_detach(&strbuf, NULL); 961} 962} 963 964if(make_room_for_path(o, path) <0) { 965 update_wd =0; 966goto free_buf; 967} 968if(S_ISREG(mode) || (!has_symlinks &&S_ISLNK(mode))) { 969int fd; 970if(mode &0100) 971 mode =0777; 972else 973 mode =0666; 974 fd =open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); 975if(fd <0) { 976 ret =err(o,_("failed to open '%s':%s"), 977 path,strerror(errno)); 978goto free_buf; 979} 980write_in_full(fd, buf, size); 981close(fd); 982}else if(S_ISLNK(mode)) { 983char*lnk =xmemdupz(buf, size); 984safe_create_leading_directories_const(path); 985unlink(path); 986if(symlink(lnk, path)) 987 ret =err(o,_("failed to symlink '%s':%s"), 988 path,strerror(errno)); 989free(lnk); 990}else 991 ret =err(o, 992_("do not know what to do with%06o%s'%s'"), 993 mode,oid_to_hex(oid), path); 994 free_buf: 995free(buf); 996} 997 update_index: 998if(!ret && update_cache) 999if(add_cacheinfo(o, mode, oid, path,0, update_wd,1000 ADD_CACHE_OK_TO_ADD))1001return-1;1002return ret;1003}10041005static intupdate_file(struct merge_options *o,1006int clean,1007const struct object_id *oid,1008unsigned mode,1009const char*path)1010{1011returnupdate_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);1012}10131014/* Low level file merging, update and removal */10151016struct merge_file_info {1017struct object_id oid;1018unsigned mode;1019unsigned clean:1,1020 merge:1;1021};10221023static intmerge_3way(struct merge_options *o,1024 mmbuffer_t *result_buf,1025const struct diff_filespec *one,1026const struct diff_filespec *a,1027const struct diff_filespec *b,1028const char*branch1,1029const char*branch2)1030{1031 mmfile_t orig, src1, src2;1032struct ll_merge_options ll_opts = {0};1033char*base_name, *name1, *name2;1034int merge_status;10351036 ll_opts.renormalize = o->renormalize;1037 ll_opts.xdl_opts = o->xdl_opts;10381039if(o->call_depth) {1040 ll_opts.virtual_ancestor =1;1041 ll_opts.variant =0;1042}else{1043switch(o->recursive_variant) {1044case MERGE_RECURSIVE_OURS:1045 ll_opts.variant = XDL_MERGE_FAVOR_OURS;1046break;1047case MERGE_RECURSIVE_THEIRS:1048 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;1049break;1050default:1051 ll_opts.variant =0;1052break;1053}1054}10551056if(strcmp(a->path, b->path) ||1057(o->ancestor != NULL &&strcmp(a->path, one->path) !=0)) {1058 base_name = o->ancestor == NULL ? NULL :1059mkpathdup("%s:%s", o->ancestor, one->path);1060 name1 =mkpathdup("%s:%s", branch1, a->path);1061 name2 =mkpathdup("%s:%s", branch2, b->path);1062}else{1063 base_name = o->ancestor == NULL ? NULL :1064mkpathdup("%s", o->ancestor);1065 name1 =mkpathdup("%s", branch1);1066 name2 =mkpathdup("%s", branch2);1067}10681069read_mmblob(&orig, &one->oid);1070read_mmblob(&src1, &a->oid);1071read_mmblob(&src2, &b->oid);10721073 merge_status =ll_merge(result_buf, a->path, &orig, base_name,1074&src1, name1, &src2, name2, &ll_opts);10751076free(base_name);1077free(name1);1078free(name2);1079free(orig.ptr);1080free(src1.ptr);1081free(src2.ptr);1082return merge_status;1083}10841085static intmerge_file_1(struct merge_options *o,1086const struct diff_filespec *one,1087const struct diff_filespec *a,1088const struct diff_filespec *b,1089const char*filename,1090const char*branch1,1091const char*branch2,1092struct merge_file_info *result)1093{1094 result->merge =0;1095 result->clean =1;10961097if((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1098 result->clean =0;1099if(S_ISREG(a->mode)) {1100 result->mode = a->mode;1101oidcpy(&result->oid, &a->oid);1102}else{1103 result->mode = b->mode;1104oidcpy(&result->oid, &b->oid);1105}1106}else{1107if(!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))1108 result->merge =1;11091110/*1111 * Merge modes1112 */1113if(a->mode == b->mode || a->mode == one->mode)1114 result->mode = b->mode;1115else{1116 result->mode = a->mode;1117if(b->mode != one->mode) {1118 result->clean =0;1119 result->merge =1;1120}1121}11221123if(oid_eq(&a->oid, &b->oid) ||oid_eq(&a->oid, &one->oid))1124oidcpy(&result->oid, &b->oid);1125else if(oid_eq(&b->oid, &one->oid))1126oidcpy(&result->oid, &a->oid);1127else if(S_ISREG(a->mode)) {1128 mmbuffer_t result_buf;1129int ret =0, merge_status;11301131 merge_status =merge_3way(o, &result_buf, one, a, b,1132 branch1, branch2);11331134if((merge_status <0) || !result_buf.ptr)1135 ret =err(o,_("Failed to execute internal merge"));11361137if(!ret &&1138write_object_file(result_buf.ptr, result_buf.size,1139 blob_type, &result->oid))1140 ret =err(o,_("Unable to add%sto database"),1141 a->path);11421143free(result_buf.ptr);1144if(ret)1145return ret;1146 result->clean = (merge_status ==0);1147}else if(S_ISGITLINK(a->mode)) {1148 result->clean =merge_submodule(&result->oid,1149 one->path,1150&one->oid,1151&a->oid,1152&b->oid,1153!o->call_depth);1154}else if(S_ISLNK(a->mode)) {1155switch(o->recursive_variant) {1156case MERGE_RECURSIVE_NORMAL:1157oidcpy(&result->oid, &a->oid);1158if(!oid_eq(&a->oid, &b->oid))1159 result->clean =0;1160break;1161case MERGE_RECURSIVE_OURS:1162oidcpy(&result->oid, &a->oid);1163break;1164case MERGE_RECURSIVE_THEIRS:1165oidcpy(&result->oid, &b->oid);1166break;1167}1168}else1169BUG("unsupported object type in the tree");1170}11711172if(result->merge)1173output(o,2,_("Auto-merging%s"), filename);11741175return0;1176}11771178static intmerge_file_special_markers(struct merge_options *o,1179const struct diff_filespec *one,1180const struct diff_filespec *a,1181const struct diff_filespec *b,1182const char*target_filename,1183const char*branch1,1184const char*filename1,1185const char*branch2,1186const char*filename2,1187struct merge_file_info *mfi)1188{1189char*side1 = NULL;1190char*side2 = NULL;1191int ret;11921193if(filename1)1194 side1 =xstrfmt("%s:%s", branch1, filename1);1195if(filename2)1196 side2 =xstrfmt("%s:%s", branch2, filename2);11971198 ret =merge_file_1(o, one, a, b, target_filename,1199 side1 ? side1 : branch1,1200 side2 ? side2 : branch2, mfi);12011202free(side1);1203free(side2);1204return ret;1205}12061207static intmerge_file_one(struct merge_options *o,1208const char*path,1209const struct object_id *o_oid,int o_mode,1210const struct object_id *a_oid,int a_mode,1211const struct object_id *b_oid,int b_mode,1212const char*branch1,1213const char*branch2,1214struct merge_file_info *mfi)1215{1216struct diff_filespec one, a, b;12171218 one.path = a.path = b.path = (char*)path;1219oidcpy(&one.oid, o_oid);1220 one.mode = o_mode;1221oidcpy(&a.oid, a_oid);1222 a.mode = a_mode;1223oidcpy(&b.oid, b_oid);1224 b.mode = b_mode;1225returnmerge_file_1(o, &one, &a, &b, path, branch1, branch2, mfi);1226}12271228static intconflict_rename_dir(struct merge_options *o,1229struct diff_filepair *pair,1230const char*rename_branch,1231const char*other_branch)1232{1233const struct diff_filespec *dest = pair->two;12341235if(!o->call_depth &&would_lose_untracked(dest->path)) {1236char*alt_path =unique_path(o, dest->path, rename_branch);12371238output(o,1,_("Error: Refusing to lose untracked file at%s; "1239"writing to%sinstead."),1240 dest->path, alt_path);1241/*1242 * Write the file in worktree at alt_path, but not in the1243 * index. Instead, write to dest->path for the index but1244 * only at the higher appropriate stage.1245 */1246if(update_file(o,0, &dest->oid, dest->mode, alt_path))1247return-1;1248free(alt_path);1249returnupdate_stages(o, dest->path, NULL,1250 rename_branch == o->branch1 ? dest : NULL,1251 rename_branch == o->branch1 ? NULL : dest);1252}12531254/* Update dest->path both in index and in worktree */1255if(update_file(o,1, &dest->oid, dest->mode, dest->path))1256return-1;1257return0;1258}12591260static inthandle_change_delete(struct merge_options *o,1261const char*path,const char*old_path,1262const struct object_id *o_oid,int o_mode,1263const struct object_id *changed_oid,1264int changed_mode,1265const char*change_branch,1266const char*delete_branch,1267const char*change,const char*change_past)1268{1269char*alt_path = NULL;1270const char*update_path = path;1271int ret =0;12721273if(dir_in_way(path, !o->call_depth,0) ||1274(!o->call_depth &&would_lose_untracked(path))) {1275 update_path = alt_path =unique_path(o, path, change_branch);1276}12771278if(o->call_depth) {1279/*1280 * We cannot arbitrarily accept either a_sha or b_sha as1281 * correct; since there is no true "middle point" between1282 * them, simply reuse the base version for virtual merge base.1283 */1284 ret =remove_file_from_cache(path);1285if(!ret)1286 ret =update_file(o,0, o_oid, o_mode, update_path);1287}else{1288if(!alt_path) {1289if(!old_path) {1290output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1291"and%sin%s. Version%sof%sleft in tree."),1292 change, path, delete_branch, change_past,1293 change_branch, change_branch, path);1294}else{1295output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1296"and%sto%sin%s. Version%sof%sleft in tree."),1297 change, old_path, delete_branch, change_past, path,1298 change_branch, change_branch, path);1299}1300}else{1301if(!old_path) {1302output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1303"and%sin%s. Version%sof%sleft in tree at%s."),1304 change, path, delete_branch, change_past,1305 change_branch, change_branch, path, alt_path);1306}else{1307output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1308"and%sto%sin%s. Version%sof%sleft in tree at%s."),1309 change, old_path, delete_branch, change_past, path,1310 change_branch, change_branch, path, alt_path);1311}1312}1313/*1314 * No need to call update_file() on path when change_branch ==1315 * o->branch1 && !alt_path, since that would needlessly touch1316 * path. We could call update_file_flags() with update_cache=01317 * and update_wd=0, but that's a no-op.1318 */1319if(change_branch != o->branch1 || alt_path)1320 ret =update_file(o,0, changed_oid, changed_mode, update_path);1321}1322free(alt_path);13231324return ret;1325}13261327static intconflict_rename_delete(struct merge_options *o,1328struct diff_filepair *pair,1329const char*rename_branch,1330const char*delete_branch)1331{1332const struct diff_filespec *orig = pair->one;1333const struct diff_filespec *dest = pair->two;13341335if(handle_change_delete(o,1336 o->call_depth ? orig->path : dest->path,1337 o->call_depth ? NULL : orig->path,1338&orig->oid, orig->mode,1339&dest->oid, dest->mode,1340 rename_branch, delete_branch,1341_("rename"),_("renamed")))1342return-1;13431344if(o->call_depth)1345returnremove_file_from_cache(dest->path);1346else1347returnupdate_stages(o, dest->path, NULL,1348 rename_branch == o->branch1 ? dest : NULL,1349 rename_branch == o->branch1 ? NULL : dest);1350}13511352static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,1353struct stage_data *entry,1354int stage)1355{1356struct object_id *oid = &entry->stages[stage].oid;1357unsigned mode = entry->stages[stage].mode;1358if(mode ==0||is_null_oid(oid))1359return NULL;1360oidcpy(&target->oid, oid);1361 target->mode = mode;1362return target;1363}13641365static inthandle_file(struct merge_options *o,1366struct diff_filespec *rename,1367int stage,1368struct rename_conflict_info *ci)1369{1370char*dst_name = rename->path;1371struct stage_data *dst_entry;1372const char*cur_branch, *other_branch;1373struct diff_filespec other;1374struct diff_filespec *add;1375int ret;13761377if(stage ==2) {1378 dst_entry = ci->dst_entry1;1379 cur_branch = ci->branch1;1380 other_branch = ci->branch2;1381}else{1382 dst_entry = ci->dst_entry2;1383 cur_branch = ci->branch2;1384 other_branch = ci->branch1;1385}13861387 add =filespec_from_entry(&other, dst_entry, stage ^1);1388if(add) {1389int ren_src_was_dirty =was_dirty(o, rename->path);1390char*add_name =unique_path(o, rename->path, other_branch);1391if(update_file(o,0, &add->oid, add->mode, add_name))1392return-1;13931394if(ren_src_was_dirty) {1395output(o,1,_("Refusing to lose dirty file at%s"),1396 rename->path);1397}1398/*1399 * Because the double negatives somehow keep confusing me...1400 * 1) update_wd iff !ren_src_was_dirty.1401 * 2) no_wd iff !update_wd1402 * 3) so, no_wd == !!ren_src_was_dirty == ren_src_was_dirty1403 */1404remove_file(o,0, rename->path, ren_src_was_dirty);1405 dst_name =unique_path(o, rename->path, cur_branch);1406}else{1407if(dir_in_way(rename->path, !o->call_depth,0)) {1408 dst_name =unique_path(o, rename->path, cur_branch);1409output(o,1,_("%sis a directory in%sadding as%sinstead"),1410 rename->path, other_branch, dst_name);1411}else if(!o->call_depth &&1412would_lose_untracked(rename->path)) {1413 dst_name =unique_path(o, rename->path, cur_branch);1414output(o,1,_("Refusing to lose untracked file at%s; "1415"adding as%sinstead"),1416 rename->path, dst_name);1417}1418}1419if((ret =update_file(o,0, &rename->oid, rename->mode, dst_name)))1420;/* fall through, do allow dst_name to be released */1421else if(stage ==2)1422 ret =update_stages(o, rename->path, NULL, rename, add);1423else1424 ret =update_stages(o, rename->path, NULL, add, rename);14251426if(dst_name != rename->path)1427free(dst_name);14281429return ret;1430}14311432static intconflict_rename_rename_1to2(struct merge_options *o,1433struct rename_conflict_info *ci)1434{1435/* One file was renamed in both branches, but to different names. */1436struct diff_filespec *one = ci->pair1->one;1437struct diff_filespec *a = ci->pair1->two;1438struct diff_filespec *b = ci->pair2->two;14391440output(o,1,_("CONFLICT (rename/rename): "1441"Rename\"%s\"->\"%s\"in branch\"%s\""1442"rename\"%s\"->\"%s\"in\"%s\"%s"),1443 one->path, a->path, ci->branch1,1444 one->path, b->path, ci->branch2,1445 o->call_depth ?_(" (left unresolved)") :"");1446if(o->call_depth) {1447struct merge_file_info mfi;1448struct diff_filespec other;1449struct diff_filespec *add;1450if(merge_file_one(o, one->path,1451&one->oid, one->mode,1452&a->oid, a->mode,1453&b->oid, b->mode,1454 ci->branch1, ci->branch2, &mfi))1455return-1;14561457/*1458 * FIXME: For rename/add-source conflicts (if we could detect1459 * such), this is wrong. We should instead find a unique1460 * pathname and then either rename the add-source file to that1461 * unique path, or use that unique path instead of src here.1462 */1463if(update_file(o,0, &mfi.oid, mfi.mode, one->path))1464return-1;14651466/*1467 * Above, we put the merged content at the merge-base's1468 * path. Now we usually need to delete both a->path and1469 * b->path. However, the rename on each side of the merge1470 * could also be involved in a rename/add conflict. In1471 * such cases, we should keep the added file around,1472 * resolving the conflict at that path in its favor.1473 */1474 add =filespec_from_entry(&other, ci->dst_entry1,2^1);1475if(add) {1476if(update_file(o,0, &add->oid, add->mode, a->path))1477return-1;1478}1479else1480remove_file_from_cache(a->path);1481 add =filespec_from_entry(&other, ci->dst_entry2,3^1);1482if(add) {1483if(update_file(o,0, &add->oid, add->mode, b->path))1484return-1;1485}1486else1487remove_file_from_cache(b->path);1488}else if(handle_file(o, a,2, ci) ||handle_file(o, b,3, ci))1489return-1;14901491return0;1492}14931494static intconflict_rename_rename_2to1(struct merge_options *o,1495struct rename_conflict_info *ci)1496{1497/* Two files, a & b, were renamed to the same thing, c. */1498struct diff_filespec *a = ci->pair1->one;1499struct diff_filespec *b = ci->pair2->one;1500struct diff_filespec *c1 = ci->pair1->two;1501struct diff_filespec *c2 = ci->pair2->two;1502char*path = c1->path;/* == c2->path */1503char*path_side_1_desc;1504char*path_side_2_desc;1505struct merge_file_info mfi_c1;1506struct merge_file_info mfi_c2;1507int ret;15081509output(o,1,_("CONFLICT (rename/rename): "1510"Rename%s->%sin%s. "1511"Rename%s->%sin%s"),1512 a->path, c1->path, ci->branch1,1513 b->path, c2->path, ci->branch2);15141515remove_file(o,1, a->path, o->call_depth ||would_lose_untracked(a->path));1516remove_file(o,1, b->path, o->call_depth ||would_lose_untracked(b->path));15171518 path_side_1_desc =xstrfmt("%s(was%s)", path, a->path);1519 path_side_2_desc =xstrfmt("%s(was%s)", path, b->path);1520if(merge_file_special_markers(o, a, c1, &ci->ren1_other,1521 path_side_1_desc,1522 o->branch1, c1->path,1523 o->branch2, ci->ren1_other.path, &mfi_c1) ||1524merge_file_special_markers(o, b, &ci->ren2_other, c2,1525 path_side_2_desc,1526 o->branch1, ci->ren2_other.path,1527 o->branch2, c2->path, &mfi_c2))1528return-1;1529free(path_side_1_desc);1530free(path_side_2_desc);15311532if(o->call_depth) {1533/*1534 * If mfi_c1.clean && mfi_c2.clean, then it might make1535 * sense to do a two-way merge of those results. But, I1536 * think in all cases, it makes sense to have the virtual1537 * merge base just undo the renames; they can be detected1538 * again later for the non-recursive merge.1539 */1540remove_file(o,0, path,0);1541 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, a->path);1542if(!ret)1543 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1544 b->path);1545}else{1546char*new_path1 =unique_path(o, path, ci->branch1);1547char*new_path2 =unique_path(o, path, ci->branch2);1548output(o,1,_("Renaming%sto%sand%sto%sinstead"),1549 a->path, new_path1, b->path, new_path2);1550if(was_dirty(o, path))1551output(o,1,_("Refusing to lose dirty file at%s"),1552 path);1553else if(would_lose_untracked(path))1554/*1555 * Only way we get here is if both renames were from1556 * a directory rename AND user had an untracked file1557 * at the location where both files end up after the1558 * two directory renames. See testcase 10d of t6043.1559 */1560output(o,1,_("Refusing to lose untracked file at "1561"%s, even though it's in the way."),1562 path);1563else1564remove_file(o,0, path,0);1565 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, new_path1);1566if(!ret)1567 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1568 new_path2);1569/*1570 * unpack_trees() actually populates the index for us for1571 * "normal" rename/rename(2to1) situtations so that the1572 * correct entries are at the higher stages, which would1573 * make the call below to update_stages_for_stage_data1574 * unnecessary. However, if either of the renames came1575 * from a directory rename, then unpack_trees() will not1576 * have gotten the right data loaded into the index, so we1577 * need to do so now. (While it'd be tempting to move this1578 * call to update_stages_for_stage_data() to1579 * apply_directory_rename_modifications(), that would break1580 * our intermediate calls to would_lose_untracked() since1581 * those rely on the current in-memory index. See also the1582 * big "NOTE" in update_stages()).1583 */1584if(update_stages_for_stage_data(o, path, ci->dst_entry1))1585 ret = -1;15861587free(new_path2);1588free(new_path1);1589}15901591return ret;1592}15931594/*1595 * Get the diff_filepairs changed between o_tree and tree.1596 */1597static struct diff_queue_struct *get_diffpairs(struct merge_options *o,1598struct tree *o_tree,1599struct tree *tree)1600{1601struct diff_queue_struct *ret;1602struct diff_options opts;16031604diff_setup(&opts);1605 opts.flags.recursive =1;1606 opts.flags.rename_empty =0;1607 opts.detect_rename =merge_detect_rename(o);1608/*1609 * We do not have logic to handle the detection of copies. In1610 * fact, it may not even make sense to add such logic: would we1611 * really want a change to a base file to be propagated through1612 * multiple other files by a merge?1613 */1614if(opts.detect_rename > DIFF_DETECT_RENAME)1615 opts.detect_rename = DIFF_DETECT_RENAME;1616 opts.rename_limit = o->merge_rename_limit >=0? o->merge_rename_limit :1617 o->diff_rename_limit >=0? o->diff_rename_limit :16181000;1619 opts.rename_score = o->rename_score;1620 opts.show_rename_progress = o->show_rename_progress;1621 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1622diff_setup_done(&opts);1623diff_tree_oid(&o_tree->object.oid, &tree->object.oid,"", &opts);1624diffcore_std(&opts);1625if(opts.needed_rename_limit > o->needed_rename_limit)1626 o->needed_rename_limit = opts.needed_rename_limit;16271628 ret =xmalloc(sizeof(*ret));1629*ret = diff_queued_diff;16301631 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1632 diff_queued_diff.nr =0;1633 diff_queued_diff.queue = NULL;1634diff_flush(&opts);1635return ret;1636}16371638static inttree_has_path(struct tree *tree,const char*path)1639{1640struct object_id hashy;1641unsigned int mode_o;16421643return!get_tree_entry(&tree->object.oid, path,1644&hashy, &mode_o);1645}16461647/*1648 * Return a new string that replaces the beginning portion (which matches1649 * entry->dir), with entry->new_dir. In perl-speak:1650 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);1651 * NOTE:1652 * Caller must ensure that old_path starts with entry->dir + '/'.1653 */1654static char*apply_dir_rename(struct dir_rename_entry *entry,1655const char*old_path)1656{1657struct strbuf new_path = STRBUF_INIT;1658int oldlen, newlen;16591660if(entry->non_unique_new_dir)1661return NULL;16621663 oldlen =strlen(entry->dir);1664 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) +1;1665strbuf_grow(&new_path, newlen);1666strbuf_addbuf(&new_path, &entry->new_dir);1667strbuf_addstr(&new_path, &old_path[oldlen]);16681669returnstrbuf_detach(&new_path, NULL);1670}16711672static voidget_renamed_dir_portion(const char*old_path,const char*new_path,1673char**old_dir,char**new_dir)1674{1675char*end_of_old, *end_of_new;1676int old_len, new_len;16771678*old_dir = NULL;1679*new_dir = NULL;16801681/*1682 * For1683 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"1684 * the "e/foo.c" part is the same, we just want to know that1685 * "a/b/c/d" was renamed to "a/b/some/thing/else"1686 * so, for this example, this function returns "a/b/c/d" in1687 * *old_dir and "a/b/some/thing/else" in *new_dir.1688 *1689 * Also, if the basename of the file changed, we don't care. We1690 * want to know which portion of the directory, if any, changed.1691 */1692 end_of_old =strrchr(old_path,'/');1693 end_of_new =strrchr(new_path,'/');16941695if(end_of_old == NULL || end_of_new == NULL)1696return;1697while(*--end_of_new == *--end_of_old &&1698 end_of_old != old_path &&1699 end_of_new != new_path)1700;/* Do nothing; all in the while loop */1701/*1702 * We've found the first non-matching character in the directory1703 * paths. That means the current directory we were comparing1704 * represents the rename. Move end_of_old and end_of_new back1705 * to the full directory name.1706 */1707if(*end_of_old =='/')1708 end_of_old++;1709if(*end_of_old !='/')1710 end_of_new++;1711 end_of_old =strchr(end_of_old,'/');1712 end_of_new =strchr(end_of_new,'/');17131714/*1715 * It may have been the case that old_path and new_path were the same1716 * directory all along. Don't claim a rename if they're the same.1717 */1718 old_len = end_of_old - old_path;1719 new_len = end_of_new - new_path;17201721if(old_len != new_len ||strncmp(old_path, new_path, old_len)) {1722*old_dir =xstrndup(old_path, old_len);1723*new_dir =xstrndup(new_path, new_len);1724}1725}17261727static voidremove_hashmap_entries(struct hashmap *dir_renames,1728struct string_list *items_to_remove)1729{1730int i;1731struct dir_rename_entry *entry;17321733for(i =0; i < items_to_remove->nr; i++) {1734 entry = items_to_remove->items[i].util;1735hashmap_remove(dir_renames, entry, NULL);1736}1737string_list_clear(items_to_remove,0);1738}17391740/*1741 * See if there is a directory rename for path, and if there are any file1742 * level conflicts for the renamed location. If there is a rename and1743 * there are no conflicts, return the new name. Otherwise, return NULL.1744 */1745static char*handle_path_level_conflicts(struct merge_options *o,1746const char*path,1747struct dir_rename_entry *entry,1748struct hashmap *collisions,1749struct tree *tree)1750{1751char*new_path = NULL;1752struct collision_entry *collision_ent;1753int clean =1;1754struct strbuf collision_paths = STRBUF_INIT;17551756/*1757 * entry has the mapping of old directory name to new directory name1758 * that we want to apply to path.1759 */1760 new_path =apply_dir_rename(entry, path);17611762if(!new_path) {1763/* This should only happen when entry->non_unique_new_dir set */1764if(!entry->non_unique_new_dir)1765BUG("entry->non_unqiue_dir not set and !new_path");1766output(o,1,_("CONFLICT (directory rename split): "1767"Unclear where to place%sbecause directory "1768"%swas renamed to multiple other directories, "1769"with no destination getting a majority of the "1770"files."),1771 path, entry->dir);1772 clean =0;1773return NULL;1774}17751776/*1777 * The caller needs to have ensured that it has pre-populated1778 * collisions with all paths that map to new_path. Do a quick check1779 * to ensure that's the case.1780 */1781 collision_ent =collision_find_entry(collisions, new_path);1782if(collision_ent == NULL)1783BUG("collision_ent is NULL");17841785/*1786 * Check for one-sided add/add/.../add conflicts, i.e.1787 * where implicit renames from the other side doing1788 * directory rename(s) can affect this side of history1789 * to put multiple paths into the same location. Warn1790 * and bail on directory renames for such paths.1791 */1792if(collision_ent->reported_already) {1793 clean =0;1794}else if(tree_has_path(tree, new_path)) {1795 collision_ent->reported_already =1;1796strbuf_add_separated_string_list(&collision_paths,", ",1797&collision_ent->source_files);1798output(o,1,_("CONFLICT (implicit dir rename): Existing "1799"file/dir at%sin the way of implicit "1800"directory rename(s) putting the following "1801"path(s) there:%s."),1802 new_path, collision_paths.buf);1803 clean =0;1804}else if(collision_ent->source_files.nr >1) {1805 collision_ent->reported_already =1;1806strbuf_add_separated_string_list(&collision_paths,", ",1807&collision_ent->source_files);1808output(o,1,_("CONFLICT (implicit dir rename): Cannot map "1809"more than one path to%s; implicit directory "1810"renames tried to put these paths there:%s"),1811 new_path, collision_paths.buf);1812 clean =0;1813}18141815/* Free memory we no longer need */1816strbuf_release(&collision_paths);1817if(!clean && new_path) {1818free(new_path);1819return NULL;1820}18211822return new_path;1823}18241825/*1826 * There are a couple things we want to do at the directory level:1827 * 1. Check for both sides renaming to the same thing, in order to avoid1828 * implicit renaming of files that should be left in place. (See1829 * testcase 6b in t6043 for details.)1830 * 2. Prune directory renames if there are still files left in the1831 * the original directory. These represent a partial directory rename,1832 * i.e. a rename where only some of the files within the directory1833 * were renamed elsewhere. (Technically, this could be done earlier1834 * in get_directory_renames(), except that would prevent us from1835 * doing the previous check and thus failing testcase 6b.)1836 * 3. Check for rename/rename(1to2) conflicts (at the directory level).1837 * In the future, we could potentially record this info as well and1838 * omit reporting rename/rename(1to2) conflicts for each path within1839 * the affected directories, thus cleaning up the merge output.1840 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the1841 * directory level, because merging directories is fine. If it1842 * causes conflicts for files within those merged directories, then1843 * that should be detected at the individual path level.1844 */1845static voidhandle_directory_level_conflicts(struct merge_options *o,1846struct hashmap *dir_re_head,1847struct tree *head,1848struct hashmap *dir_re_merge,1849struct tree *merge)1850{1851struct hashmap_iter iter;1852struct dir_rename_entry *head_ent;1853struct dir_rename_entry *merge_ent;18541855struct string_list remove_from_head = STRING_LIST_INIT_NODUP;1856struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;18571858hashmap_iter_init(dir_re_head, &iter);1859while((head_ent =hashmap_iter_next(&iter))) {1860 merge_ent =dir_rename_find_entry(dir_re_merge, head_ent->dir);1861if(merge_ent &&1862!head_ent->non_unique_new_dir &&1863!merge_ent->non_unique_new_dir &&1864!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {1865/* 1. Renamed identically; remove it from both sides */1866string_list_append(&remove_from_head,1867 head_ent->dir)->util = head_ent;1868strbuf_release(&head_ent->new_dir);1869string_list_append(&remove_from_merge,1870 merge_ent->dir)->util = merge_ent;1871strbuf_release(&merge_ent->new_dir);1872}else if(tree_has_path(head, head_ent->dir)) {1873/* 2. This wasn't a directory rename after all */1874string_list_append(&remove_from_head,1875 head_ent->dir)->util = head_ent;1876strbuf_release(&head_ent->new_dir);1877}1878}18791880remove_hashmap_entries(dir_re_head, &remove_from_head);1881remove_hashmap_entries(dir_re_merge, &remove_from_merge);18821883hashmap_iter_init(dir_re_merge, &iter);1884while((merge_ent =hashmap_iter_next(&iter))) {1885 head_ent =dir_rename_find_entry(dir_re_head, merge_ent->dir);1886if(tree_has_path(merge, merge_ent->dir)) {1887/* 2. This wasn't a directory rename after all */1888string_list_append(&remove_from_merge,1889 merge_ent->dir)->util = merge_ent;1890}else if(head_ent &&1891!head_ent->non_unique_new_dir &&1892!merge_ent->non_unique_new_dir) {1893/* 3. rename/rename(1to2) */1894/*1895 * We can assume it's not rename/rename(1to1) because1896 * that was case (1), already checked above. So we1897 * know that head_ent->new_dir and merge_ent->new_dir1898 * are different strings.1899 */1900output(o,1,_("CONFLICT (rename/rename): "1901"Rename directory%s->%sin%s. "1902"Rename directory%s->%sin%s"),1903 head_ent->dir, head_ent->new_dir.buf, o->branch1,1904 head_ent->dir, merge_ent->new_dir.buf, o->branch2);1905string_list_append(&remove_from_head,1906 head_ent->dir)->util = head_ent;1907strbuf_release(&head_ent->new_dir);1908string_list_append(&remove_from_merge,1909 merge_ent->dir)->util = merge_ent;1910strbuf_release(&merge_ent->new_dir);1911}1912}19131914remove_hashmap_entries(dir_re_head, &remove_from_head);1915remove_hashmap_entries(dir_re_merge, &remove_from_merge);1916}19171918static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs,1919struct tree *tree)1920{1921struct hashmap *dir_renames;1922struct hashmap_iter iter;1923struct dir_rename_entry *entry;1924int i;19251926/*1927 * Typically, we think of a directory rename as all files from a1928 * certain directory being moved to a target directory. However,1929 * what if someone first moved two files from the original1930 * directory in one commit, and then renamed the directory1931 * somewhere else in a later commit? At merge time, we just know1932 * that files from the original directory went to two different1933 * places, and that the bulk of them ended up in the same place.1934 * We want each directory rename to represent where the bulk of the1935 * files from that directory end up; this function exists to find1936 * where the bulk of the files went.1937 *1938 * The first loop below simply iterates through the list of file1939 * renames, finding out how often each directory rename pair1940 * possibility occurs.1941 */1942 dir_renames =xmalloc(sizeof(*dir_renames));1943dir_rename_init(dir_renames);1944for(i =0; i < pairs->nr; ++i) {1945struct string_list_item *item;1946int*count;1947struct diff_filepair *pair = pairs->queue[i];1948char*old_dir, *new_dir;19491950/* File not part of directory rename if it wasn't renamed */1951if(pair->status !='R')1952continue;19531954get_renamed_dir_portion(pair->one->path, pair->two->path,1955&old_dir, &new_dir);1956if(!old_dir)1957/* Directory didn't change at all; ignore this one. */1958continue;19591960 entry =dir_rename_find_entry(dir_renames, old_dir);1961if(!entry) {1962 entry =xmalloc(sizeof(*entry));1963dir_rename_entry_init(entry, old_dir);1964hashmap_put(dir_renames, entry);1965}else{1966free(old_dir);1967}1968 item =string_list_lookup(&entry->possible_new_dirs, new_dir);1969if(!item) {1970 item =string_list_insert(&entry->possible_new_dirs,1971 new_dir);1972 item->util =xcalloc(1,sizeof(int));1973}else{1974free(new_dir);1975}1976 count = item->util;1977*count +=1;1978}19791980/*1981 * For each directory with files moved out of it, we find out which1982 * target directory received the most files so we can declare it to1983 * be the "winning" target location for the directory rename. This1984 * winner gets recorded in new_dir. If there is no winner1985 * (multiple target directories received the same number of files),1986 * we set non_unique_new_dir. Once we've determined the winner (or1987 * that there is no winner), we no longer need possible_new_dirs.1988 */1989hashmap_iter_init(dir_renames, &iter);1990while((entry =hashmap_iter_next(&iter))) {1991int max =0;1992int bad_max =0;1993char*best = NULL;19941995for(i =0; i < entry->possible_new_dirs.nr; i++) {1996int*count = entry->possible_new_dirs.items[i].util;19971998if(*count == max)1999 bad_max = max;2000else if(*count > max) {2001 max = *count;2002 best = entry->possible_new_dirs.items[i].string;2003}2004}2005if(bad_max == max)2006 entry->non_unique_new_dir =1;2007else{2008assert(entry->new_dir.len ==0);2009strbuf_addstr(&entry->new_dir, best);2010}2011/*2012 * The relevant directory sub-portion of the original full2013 * filepaths were xstrndup'ed before inserting into2014 * possible_new_dirs, and instead of manually iterating the2015 * list and free'ing each, just lie and tell2016 * possible_new_dirs that it did the strdup'ing so that it2017 * will free them for us.2018 */2019 entry->possible_new_dirs.strdup_strings =1;2020string_list_clear(&entry->possible_new_dirs,1);2021}20222023return dir_renames;2024}20252026static struct dir_rename_entry *check_dir_renamed(const char*path,2027struct hashmap *dir_renames)2028{2029char temp[PATH_MAX];2030char*end;2031struct dir_rename_entry *entry;20322033strcpy(temp, path);2034while((end =strrchr(temp,'/'))) {2035*end ='\0';2036 entry =dir_rename_find_entry(dir_renames, temp);2037if(entry)2038return entry;2039}2040return NULL;2041}20422043static voidcompute_collisions(struct hashmap *collisions,2044struct hashmap *dir_renames,2045struct diff_queue_struct *pairs)2046{2047int i;20482049/*2050 * Multiple files can be mapped to the same path due to directory2051 * renames done by the other side of history. Since that other2052 * side of history could have merged multiple directories into one,2053 * if our side of history added the same file basename to each of2054 * those directories, then all N of them would get implicitly2055 * renamed by the directory rename detection into the same path,2056 * and we'd get an add/add/.../add conflict, and all those adds2057 * from *this* side of history. This is not representable in the2058 * index, and users aren't going to easily be able to make sense of2059 * it. So we need to provide a good warning about what's2060 * happening, and fall back to no-directory-rename detection2061 * behavior for those paths.2062 *2063 * See testcases 9e and all of section 5 from t6043 for examples.2064 */2065collision_init(collisions);20662067for(i =0; i < pairs->nr; ++i) {2068struct dir_rename_entry *dir_rename_ent;2069struct collision_entry *collision_ent;2070char*new_path;2071struct diff_filepair *pair = pairs->queue[i];20722073if(pair->status !='A'&& pair->status !='R')2074continue;2075 dir_rename_ent =check_dir_renamed(pair->two->path,2076 dir_renames);2077if(!dir_rename_ent)2078continue;20792080 new_path =apply_dir_rename(dir_rename_ent, pair->two->path);2081if(!new_path)2082/*2083 * dir_rename_ent->non_unique_new_path is true, which2084 * means there is no directory rename for us to use,2085 * which means it won't cause us any additional2086 * collisions.2087 */2088continue;2089 collision_ent =collision_find_entry(collisions, new_path);2090if(!collision_ent) {2091 collision_ent =xcalloc(1,2092sizeof(struct collision_entry));2093hashmap_entry_init(collision_ent,strhash(new_path));2094hashmap_put(collisions, collision_ent);2095 collision_ent->target_file = new_path;2096}else{2097free(new_path);2098}2099string_list_insert(&collision_ent->source_files,2100 pair->two->path);2101}2102}21032104static char*check_for_directory_rename(struct merge_options *o,2105const char*path,2106struct tree *tree,2107struct hashmap *dir_renames,2108struct hashmap *dir_rename_exclusions,2109struct hashmap *collisions,2110int*clean_merge)2111{2112char*new_path = NULL;2113struct dir_rename_entry *entry =check_dir_renamed(path, dir_renames);2114struct dir_rename_entry *oentry = NULL;21152116if(!entry)2117return new_path;21182119/*2120 * This next part is a little weird. We do not want to do an2121 * implicit rename into a directory we renamed on our side, because2122 * that will result in a spurious rename/rename(1to2) conflict. An2123 * example:2124 * Base commit: dumbdir/afile, otherdir/bfile2125 * Side 1: smrtdir/afile, otherdir/bfile2126 * Side 2: dumbdir/afile, dumbdir/bfile2127 * Here, while working on Side 1, we could notice that otherdir was2128 * renamed/merged to dumbdir, and change the diff_filepair for2129 * otherdir/bfile into a rename into dumbdir/bfile. However, Side2130 * 2 will notice the rename from dumbdir to smrtdir, and do the2131 * transitive rename to move it from dumbdir/bfile to2132 * smrtdir/bfile. That gives us bfile in dumbdir vs being in2133 * smrtdir, a rename/rename(1to2) conflict. We really just want2134 * the file to end up in smrtdir. And the way to achieve that is2135 * to not let Side1 do the rename to dumbdir, since we know that is2136 * the source of one of our directory renames.2137 *2138 * That's why oentry and dir_rename_exclusions is here.2139 *2140 * As it turns out, this also prevents N-way transient rename2141 * confusion; See testcases 9c and 9d of t6043.2142 */2143 oentry =dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);2144if(oentry) {2145output(o,1,_("WARNING: Avoiding applying%s->%srename "2146"to%s, because%sitself was renamed."),2147 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);2148}else{2149 new_path =handle_path_level_conflicts(o, path, entry,2150 collisions, tree);2151*clean_merge &= (new_path != NULL);2152}21532154return new_path;2155}21562157static voidapply_directory_rename_modifications(struct merge_options *o,2158struct diff_filepair *pair,2159char*new_path,2160struct rename *re,2161struct tree *tree,2162struct tree *o_tree,2163struct tree *a_tree,2164struct tree *b_tree,2165struct string_list *entries,2166int*clean)2167{2168struct string_list_item *item;2169int stage = (tree == a_tree ?2:3);2170int update_wd;21712172/*2173 * In all cases where we can do directory rename detection,2174 * unpack_trees() will have read pair->two->path into the2175 * index and the working copy. We need to remove it so that2176 * we can instead place it at new_path. It is guaranteed to2177 * not be untracked (unpack_trees() would have errored out2178 * saying the file would have been overwritten), but it might2179 * be dirty, though.2180 */2181 update_wd = !was_dirty(o, pair->two->path);2182if(!update_wd)2183output(o,1,_("Refusing to lose dirty file at%s"),2184 pair->two->path);2185remove_file(o,1, pair->two->path, !update_wd);21862187/* Find or create a new re->dst_entry */2188 item =string_list_lookup(entries, new_path);2189if(item) {2190/*2191 * Since we're renaming on this side of history, and it's2192 * due to a directory rename on the other side of history2193 * (which we only allow when the directory in question no2194 * longer exists on the other side of history), the2195 * original entry for re->dst_entry is no longer2196 * necessary...2197 */2198 re->dst_entry->processed =1;21992200/*2201 * ...because we'll be using this new one.2202 */2203 re->dst_entry = item->util;2204}else{2205/*2206 * re->dst_entry is for the before-dir-rename path, and we2207 * need it to hold information for the after-dir-rename2208 * path. Before creating a new entry, we need to mark the2209 * old one as unnecessary (...unless it is shared by2210 * src_entry, i.e. this didn't use to be a rename, in which2211 * case we can just allow the normal processing to happen2212 * for it).2213 */2214if(pair->status =='R')2215 re->dst_entry->processed =1;22162217 re->dst_entry =insert_stage_data(new_path,2218 o_tree, a_tree, b_tree,2219 entries);2220 item =string_list_insert(entries, new_path);2221 item->util = re->dst_entry;2222}22232224/*2225 * Update the stage_data with the information about the path we are2226 * moving into place. That slot will be empty and available for us2227 * to write to because of the collision checks in2228 * handle_path_level_conflicts(). In other words,2229 * re->dst_entry->stages[stage].oid will be the null_oid, so it's2230 * open for us to write to.2231 *2232 * It may be tempting to actually update the index at this point as2233 * well, using update_stages_for_stage_data(), but as per the big2234 * "NOTE" in update_stages(), doing so will modify the current2235 * in-memory index which will break calls to would_lose_untracked()2236 * that we need to make. Instead, we need to just make sure that2237 * the various conflict_rename_*() functions update the index2238 * explicitly rather than relying on unpack_trees() to have done it.2239 */2240get_tree_entry(&tree->object.oid,2241 pair->two->path,2242&re->dst_entry->stages[stage].oid,2243&re->dst_entry->stages[stage].mode);22442245/* Update pair status */2246if(pair->status =='A') {2247/*2248 * Recording rename information for this add makes it look2249 * like a rename/delete conflict. Make sure we can2250 * correctly handle this as an add that was moved to a new2251 * directory instead of reporting a rename/delete conflict.2252 */2253 re->add_turned_into_rename =1;2254}2255/*2256 * We don't actually look at pair->status again, but it seems2257 * pedagogically correct to adjust it.2258 */2259 pair->status ='R';22602261/*2262 * Finally, record the new location.2263 */2264 pair->two->path = new_path;2265}22662267/*2268 * Get information of all renames which occurred in 'pairs', making use of2269 * any implicit directory renames inferred from the other side of history.2270 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')2271 * to be able to associate the correct cache entries with the rename2272 * information; tree is always equal to either a_tree or b_tree.2273 */2274static struct string_list *get_renames(struct merge_options *o,2275struct diff_queue_struct *pairs,2276struct hashmap *dir_renames,2277struct hashmap *dir_rename_exclusions,2278struct tree *tree,2279struct tree *o_tree,2280struct tree *a_tree,2281struct tree *b_tree,2282struct string_list *entries,2283int*clean_merge)2284{2285int i;2286struct hashmap collisions;2287struct hashmap_iter iter;2288struct collision_entry *e;2289struct string_list *renames;22902291compute_collisions(&collisions, dir_renames, pairs);2292 renames =xcalloc(1,sizeof(struct string_list));22932294for(i =0; i < pairs->nr; ++i) {2295struct string_list_item *item;2296struct rename *re;2297struct diff_filepair *pair = pairs->queue[i];2298char*new_path;/* non-NULL only with directory renames */22992300if(pair->status !='A'&& pair->status !='R') {2301diff_free_filepair(pair);2302continue;2303}2304 new_path =check_for_directory_rename(o, pair->two->path, tree,2305 dir_renames,2306 dir_rename_exclusions,2307&collisions,2308 clean_merge);2309if(pair->status !='R'&& !new_path) {2310diff_free_filepair(pair);2311continue;2312}23132314 re =xmalloc(sizeof(*re));2315 re->processed =0;2316 re->add_turned_into_rename =0;2317 re->pair = pair;2318 item =string_list_lookup(entries, re->pair->one->path);2319if(!item)2320 re->src_entry =insert_stage_data(re->pair->one->path,2321 o_tree, a_tree, b_tree, entries);2322else2323 re->src_entry = item->util;23242325 item =string_list_lookup(entries, re->pair->two->path);2326if(!item)2327 re->dst_entry =insert_stage_data(re->pair->two->path,2328 o_tree, a_tree, b_tree, entries);2329else2330 re->dst_entry = item->util;2331 item =string_list_insert(renames, pair->one->path);2332 item->util = re;2333if(new_path)2334apply_directory_rename_modifications(o, pair, new_path,2335 re, tree, o_tree,2336 a_tree, b_tree,2337 entries,2338 clean_merge);2339}23402341hashmap_iter_init(&collisions, &iter);2342while((e =hashmap_iter_next(&iter))) {2343free(e->target_file);2344string_list_clear(&e->source_files,0);2345}2346hashmap_free(&collisions,1);2347return renames;2348}23492350static intprocess_renames(struct merge_options *o,2351struct string_list *a_renames,2352struct string_list *b_renames)2353{2354int clean_merge =1, i, j;2355struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2356struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2357const struct rename *sre;23582359for(i =0; i < a_renames->nr; i++) {2360 sre = a_renames->items[i].util;2361string_list_insert(&a_by_dst, sre->pair->two->path)->util2362= (void*)sre;2363}2364for(i =0; i < b_renames->nr; i++) {2365 sre = b_renames->items[i].util;2366string_list_insert(&b_by_dst, sre->pair->two->path)->util2367= (void*)sre;2368}23692370for(i =0, j =0; i < a_renames->nr || j < b_renames->nr;) {2371struct string_list *renames1, *renames2Dst;2372struct rename *ren1 = NULL, *ren2 = NULL;2373const char*branch1, *branch2;2374const char*ren1_src, *ren1_dst;2375struct string_list_item *lookup;23762377if(i >= a_renames->nr) {2378 ren2 = b_renames->items[j++].util;2379}else if(j >= b_renames->nr) {2380 ren1 = a_renames->items[i++].util;2381}else{2382int compare =strcmp(a_renames->items[i].string,2383 b_renames->items[j].string);2384if(compare <=0)2385 ren1 = a_renames->items[i++].util;2386if(compare >=0)2387 ren2 = b_renames->items[j++].util;2388}23892390/* TODO: refactor, so that 1/2 are not needed */2391if(ren1) {2392 renames1 = a_renames;2393 renames2Dst = &b_by_dst;2394 branch1 = o->branch1;2395 branch2 = o->branch2;2396}else{2397 renames1 = b_renames;2398 renames2Dst = &a_by_dst;2399 branch1 = o->branch2;2400 branch2 = o->branch1;2401SWAP(ren2, ren1);2402}24032404if(ren1->processed)2405continue;2406 ren1->processed =1;2407 ren1->dst_entry->processed =1;2408/* BUG: We should only mark src_entry as processed if we2409 * are not dealing with a rename + add-source case.2410 */2411 ren1->src_entry->processed =1;24122413 ren1_src = ren1->pair->one->path;2414 ren1_dst = ren1->pair->two->path;24152416if(ren2) {2417/* One file renamed on both sides */2418const char*ren2_src = ren2->pair->one->path;2419const char*ren2_dst = ren2->pair->two->path;2420enum rename_type rename_type;2421if(strcmp(ren1_src, ren2_src) !=0)2422BUG("ren1_src != ren2_src");2423 ren2->dst_entry->processed =1;2424 ren2->processed =1;2425if(strcmp(ren1_dst, ren2_dst) !=0) {2426 rename_type = RENAME_ONE_FILE_TO_TWO;2427 clean_merge =0;2428}else{2429 rename_type = RENAME_ONE_FILE_TO_ONE;2430/* BUG: We should only remove ren1_src in2431 * the base stage (think of rename +2432 * add-source cases).2433 */2434remove_file(o,1, ren1_src,1);2435update_entry(ren1->dst_entry,2436 ren1->pair->one,2437 ren1->pair->two,2438 ren2->pair->two);2439}2440setup_rename_conflict_info(rename_type,2441 ren1->pair,2442 ren2->pair,2443 branch1,2444 branch2,2445 ren1->dst_entry,2446 ren2->dst_entry,2447 o,2448 NULL,2449 NULL);2450}else if((lookup =string_list_lookup(renames2Dst, ren1_dst))) {2451/* Two different files renamed to the same thing */2452char*ren2_dst;2453 ren2 = lookup->util;2454 ren2_dst = ren2->pair->two->path;2455if(strcmp(ren1_dst, ren2_dst) !=0)2456BUG("ren1_dst != ren2_dst");24572458 clean_merge =0;2459 ren2->processed =1;2460/*2461 * BUG: We should only mark src_entry as processed2462 * if we are not dealing with a rename + add-source2463 * case.2464 */2465 ren2->src_entry->processed =1;24662467setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2468 ren1->pair,2469 ren2->pair,2470 branch1,2471 branch2,2472 ren1->dst_entry,2473 ren2->dst_entry,2474 o,2475 ren1->src_entry,2476 ren2->src_entry);24772478}else{2479/* Renamed in 1, maybe changed in 2 */2480/* we only use sha1 and mode of these */2481struct diff_filespec src_other, dst_other;2482int try_merge;24832484/*2485 * unpack_trees loads entries from common-commit2486 * into stage 1, from head-commit into stage 2, and2487 * from merge-commit into stage 3. We keep track2488 * of which side corresponds to the rename.2489 */2490int renamed_stage = a_renames == renames1 ?2:3;2491int other_stage = a_renames == renames1 ?3:2;24922493/* BUG: We should only remove ren1_src in the base2494 * stage and in other_stage (think of rename +2495 * add-source case).2496 */2497remove_file(o,1, ren1_src,2498 renamed_stage ==2|| !was_tracked(o, ren1_src));24992500oidcpy(&src_other.oid,2501&ren1->src_entry->stages[other_stage].oid);2502 src_other.mode = ren1->src_entry->stages[other_stage].mode;2503oidcpy(&dst_other.oid,2504&ren1->dst_entry->stages[other_stage].oid);2505 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2506 try_merge =0;25072508if(oid_eq(&src_other.oid, &null_oid) &&2509 ren1->add_turned_into_rename) {2510setup_rename_conflict_info(RENAME_DIR,2511 ren1->pair,2512 NULL,2513 branch1,2514 branch2,2515 ren1->dst_entry,2516 NULL,2517 o,2518 NULL,2519 NULL);2520}else if(oid_eq(&src_other.oid, &null_oid)) {2521setup_rename_conflict_info(RENAME_DELETE,2522 ren1->pair,2523 NULL,2524 branch1,2525 branch2,2526 ren1->dst_entry,2527 NULL,2528 o,2529 NULL,2530 NULL);2531}else if((dst_other.mode == ren1->pair->two->mode) &&2532oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {2533/*2534 * Added file on the other side identical to2535 * the file being renamed: clean merge.2536 * Also, there is no need to overwrite the2537 * file already in the working copy, so call2538 * update_file_flags() instead of2539 * update_file().2540 */2541if(update_file_flags(o,2542&ren1->pair->two->oid,2543 ren1->pair->two->mode,2544 ren1_dst,25451,/* update_cache */25460/* update_wd */))2547 clean_merge = -1;2548}else if(!oid_eq(&dst_other.oid, &null_oid)) {2549 clean_merge =0;2550 try_merge =1;2551output(o,1,_("CONFLICT (rename/add): Rename%s->%sin%s. "2552"%sadded in%s"),2553 ren1_src, ren1_dst, branch1,2554 ren1_dst, branch2);2555if(o->call_depth) {2556struct merge_file_info mfi;2557if(merge_file_one(o, ren1_dst, &null_oid,0,2558&ren1->pair->two->oid,2559 ren1->pair->two->mode,2560&dst_other.oid,2561 dst_other.mode,2562 branch1, branch2, &mfi)) {2563 clean_merge = -1;2564goto cleanup_and_return;2565}2566output(o,1,_("Adding merged%s"), ren1_dst);2567if(update_file(o,0, &mfi.oid,2568 mfi.mode, ren1_dst))2569 clean_merge = -1;2570 try_merge =0;2571}else{2572char*new_path =unique_path(o, ren1_dst, branch2);2573output(o,1,_("Adding as%sinstead"), new_path);2574if(update_file(o,0, &dst_other.oid,2575 dst_other.mode, new_path))2576 clean_merge = -1;2577free(new_path);2578}2579}else2580 try_merge =1;25812582if(clean_merge <0)2583goto cleanup_and_return;2584if(try_merge) {2585struct diff_filespec *one, *a, *b;2586 src_other.path = (char*)ren1_src;25872588 one = ren1->pair->one;2589if(a_renames == renames1) {2590 a = ren1->pair->two;2591 b = &src_other;2592}else{2593 b = ren1->pair->two;2594 a = &src_other;2595}2596update_entry(ren1->dst_entry, one, a, b);2597setup_rename_conflict_info(RENAME_NORMAL,2598 ren1->pair,2599 NULL,2600 branch1,2601 NULL,2602 ren1->dst_entry,2603 NULL,2604 o,2605 NULL,2606 NULL);2607}2608}2609}2610cleanup_and_return:2611string_list_clear(&a_by_dst,0);2612string_list_clear(&b_by_dst,0);26132614return clean_merge;2615}26162617struct rename_info {2618struct string_list *head_renames;2619struct string_list *merge_renames;2620};26212622static voidinitial_cleanup_rename(struct diff_queue_struct *pairs,2623struct hashmap *dir_renames)2624{2625struct hashmap_iter iter;2626struct dir_rename_entry *e;26272628hashmap_iter_init(dir_renames, &iter);2629while((e =hashmap_iter_next(&iter))) {2630free(e->dir);2631strbuf_release(&e->new_dir);2632/* possible_new_dirs already cleared in get_directory_renames */2633}2634hashmap_free(dir_renames,1);2635free(dir_renames);26362637free(pairs->queue);2638free(pairs);2639}26402641static inthandle_renames(struct merge_options *o,2642struct tree *common,2643struct tree *head,2644struct tree *merge,2645struct string_list *entries,2646struct rename_info *ri)2647{2648struct diff_queue_struct *head_pairs, *merge_pairs;2649struct hashmap *dir_re_head, *dir_re_merge;2650int clean =1;26512652 ri->head_renames = NULL;2653 ri->merge_renames = NULL;26542655if(!merge_detect_rename(o))2656return1;26572658 head_pairs =get_diffpairs(o, common, head);2659 merge_pairs =get_diffpairs(o, common, merge);26602661 dir_re_head =get_directory_renames(head_pairs, head);2662 dir_re_merge =get_directory_renames(merge_pairs, merge);26632664handle_directory_level_conflicts(o,2665 dir_re_head, head,2666 dir_re_merge, merge);26672668 ri->head_renames =get_renames(o, head_pairs,2669 dir_re_merge, dir_re_head, head,2670 common, head, merge, entries,2671&clean);2672if(clean <0)2673goto cleanup;2674 ri->merge_renames =get_renames(o, merge_pairs,2675 dir_re_head, dir_re_merge, merge,2676 common, head, merge, entries,2677&clean);2678if(clean <0)2679goto cleanup;2680 clean &=process_renames(o, ri->head_renames, ri->merge_renames);26812682cleanup:2683/*2684 * Some cleanup is deferred until cleanup_renames() because the2685 * data structures are still needed and referenced in2686 * process_entry(). But there are a few things we can free now.2687 */2688initial_cleanup_rename(head_pairs, dir_re_head);2689initial_cleanup_rename(merge_pairs, dir_re_merge);26902691return clean;2692}26932694static voidfinal_cleanup_rename(struct string_list *rename)2695{2696const struct rename *re;2697int i;26982699if(rename == NULL)2700return;27012702for(i =0; i < rename->nr; i++) {2703 re = rename->items[i].util;2704diff_free_filepair(re->pair);2705}2706string_list_clear(rename,1);2707free(rename);2708}27092710static voidfinal_cleanup_renames(struct rename_info *re_info)2711{2712final_cleanup_rename(re_info->head_renames);2713final_cleanup_rename(re_info->merge_renames);2714}27152716static struct object_id *stage_oid(const struct object_id *oid,unsigned mode)2717{2718return(is_null_oid(oid) || mode ==0) ? NULL: (struct object_id *)oid;2719}27202721static intread_oid_strbuf(struct merge_options *o,2722const struct object_id *oid,struct strbuf *dst)2723{2724void*buf;2725enum object_type type;2726unsigned long size;2727 buf =read_object_file(oid, &type, &size);2728if(!buf)2729returnerr(o,_("cannot read object%s"),oid_to_hex(oid));2730if(type != OBJ_BLOB) {2731free(buf);2732returnerr(o,_("object%sis not a blob"),oid_to_hex(oid));2733}2734strbuf_attach(dst, buf, size, size +1);2735return0;2736}27372738static intblob_unchanged(struct merge_options *opt,2739const struct object_id *o_oid,2740unsigned o_mode,2741const struct object_id *a_oid,2742unsigned a_mode,2743int renormalize,const char*path)2744{2745struct strbuf o = STRBUF_INIT;2746struct strbuf a = STRBUF_INIT;2747int ret =0;/* assume changed for safety */27482749if(a_mode != o_mode)2750return0;2751if(oid_eq(o_oid, a_oid))2752return1;2753if(!renormalize)2754return0;27552756assert(o_oid && a_oid);2757if(read_oid_strbuf(opt, o_oid, &o) ||read_oid_strbuf(opt, a_oid, &a))2758goto error_return;2759/*2760 * Note: binary | is used so that both renormalizations are2761 * performed. Comparison can be skipped if both files are2762 * unchanged since their sha1s have already been compared.2763 */2764if(renormalize_buffer(&the_index, path, o.buf, o.len, &o) |2765renormalize_buffer(&the_index, path, a.buf, a.len, &a))2766 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));27672768error_return:2769strbuf_release(&o);2770strbuf_release(&a);2771return ret;2772}27732774static inthandle_modify_delete(struct merge_options *o,2775const char*path,2776struct object_id *o_oid,int o_mode,2777struct object_id *a_oid,int a_mode,2778struct object_id *b_oid,int b_mode)2779{2780const char*modify_branch, *delete_branch;2781struct object_id *changed_oid;2782int changed_mode;27832784if(a_oid) {2785 modify_branch = o->branch1;2786 delete_branch = o->branch2;2787 changed_oid = a_oid;2788 changed_mode = a_mode;2789}else{2790 modify_branch = o->branch2;2791 delete_branch = o->branch1;2792 changed_oid = b_oid;2793 changed_mode = b_mode;2794}27952796returnhandle_change_delete(o,2797 path, NULL,2798 o_oid, o_mode,2799 changed_oid, changed_mode,2800 modify_branch, delete_branch,2801_("modify"),_("modified"));2802}28032804static intmerge_content(struct merge_options *o,2805const char*path,2806int is_dirty,2807struct object_id *o_oid,int o_mode,2808struct object_id *a_oid,int a_mode,2809struct object_id *b_oid,int b_mode,2810struct rename_conflict_info *rename_conflict_info)2811{2812const char*reason =_("content");2813const char*path1 = NULL, *path2 = NULL;2814struct merge_file_info mfi;2815struct diff_filespec one, a, b;2816unsigned df_conflict_remains =0;28172818if(!o_oid) {2819 reason =_("add/add");2820 o_oid = (struct object_id *)&null_oid;2821}2822 one.path = a.path = b.path = (char*)path;2823oidcpy(&one.oid, o_oid);2824 one.mode = o_mode;2825oidcpy(&a.oid, a_oid);2826 a.mode = a_mode;2827oidcpy(&b.oid, b_oid);2828 b.mode = b_mode;28292830if(rename_conflict_info) {2831struct diff_filepair *pair1 = rename_conflict_info->pair1;28322833 path1 = (o->branch1 == rename_conflict_info->branch1) ?2834 pair1->two->path : pair1->one->path;2835/* If rename_conflict_info->pair2 != NULL, we are in2836 * RENAME_ONE_FILE_TO_ONE case. Otherwise, we have a2837 * normal rename.2838 */2839 path2 = (rename_conflict_info->pair2 ||2840 o->branch2 == rename_conflict_info->branch1) ?2841 pair1->two->path : pair1->one->path;28422843if(dir_in_way(path, !o->call_depth,2844S_ISGITLINK(pair1->two->mode)))2845 df_conflict_remains =1;2846}2847if(merge_file_special_markers(o, &one, &a, &b, path,2848 o->branch1, path1,2849 o->branch2, path2, &mfi))2850return-1;28512852/*2853 * We can skip updating the working tree file iff:2854 * a) The merge is clean2855 * b) The merge matches what was in HEAD (content, mode, pathname)2856 * c) The target path is usable (i.e. not involved in D/F conflict)2857 */2858if(mfi.clean &&2859was_tracked_and_matches(o, path, &mfi.oid, mfi.mode) &&2860!df_conflict_remains) {2861output(o,3,_("Skipped%s(merged same as existing)"), path);2862if(add_cacheinfo(o, mfi.mode, &mfi.oid, path,28630, (!o->call_depth && !is_dirty),0))2864return-1;2865return mfi.clean;2866}28672868if(!mfi.clean) {2869if(S_ISGITLINK(mfi.mode))2870 reason =_("submodule");2871output(o,1,_("CONFLICT (%s): Merge conflict in%s"),2872 reason, path);2873if(rename_conflict_info && !df_conflict_remains)2874if(update_stages(o, path, &one, &a, &b))2875return-1;2876}28772878if(df_conflict_remains || is_dirty) {2879char*new_path;2880if(o->call_depth) {2881remove_file_from_cache(path);2882}else{2883if(!mfi.clean) {2884if(update_stages(o, path, &one, &a, &b))2885return-1;2886}else{2887int file_from_stage2 =was_tracked(o, path);2888struct diff_filespec merged;2889oidcpy(&merged.oid, &mfi.oid);2890 merged.mode = mfi.mode;28912892if(update_stages(o, path, NULL,2893 file_from_stage2 ? &merged : NULL,2894 file_from_stage2 ? NULL : &merged))2895return-1;2896}28972898}2899 new_path =unique_path(o, path, rename_conflict_info->branch1);2900if(is_dirty) {2901output(o,1,_("Refusing to lose dirty file at%s"),2902 path);2903}2904output(o,1,_("Adding as%sinstead"), new_path);2905if(update_file(o,0, &mfi.oid, mfi.mode, new_path)) {2906free(new_path);2907return-1;2908}2909free(new_path);2910 mfi.clean =0;2911}else if(update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))2912return-1;2913return!is_dirty && mfi.clean;2914}29152916static intconflict_rename_normal(struct merge_options *o,2917const char*path,2918struct object_id *o_oid,unsigned int o_mode,2919struct object_id *a_oid,unsigned int a_mode,2920struct object_id *b_oid,unsigned int b_mode,2921struct rename_conflict_info *ci)2922{2923/* Merge the content and write it out */2924returnmerge_content(o, path,was_dirty(o, path),2925 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,2926 ci);2927}29282929/* Per entry merge function */2930static intprocess_entry(struct merge_options *o,2931const char*path,struct stage_data *entry)2932{2933int clean_merge =1;2934int normalize = o->renormalize;2935unsigned o_mode = entry->stages[1].mode;2936unsigned a_mode = entry->stages[2].mode;2937unsigned b_mode = entry->stages[3].mode;2938struct object_id *o_oid =stage_oid(&entry->stages[1].oid, o_mode);2939struct object_id *a_oid =stage_oid(&entry->stages[2].oid, a_mode);2940struct object_id *b_oid =stage_oid(&entry->stages[3].oid, b_mode);29412942 entry->processed =1;2943if(entry->rename_conflict_info) {2944struct rename_conflict_info *conflict_info = entry->rename_conflict_info;2945switch(conflict_info->rename_type) {2946case RENAME_NORMAL:2947case RENAME_ONE_FILE_TO_ONE:2948 clean_merge =conflict_rename_normal(o,2949 path,2950 o_oid, o_mode,2951 a_oid, a_mode,2952 b_oid, b_mode,2953 conflict_info);2954break;2955case RENAME_DIR:2956 clean_merge =1;2957if(conflict_rename_dir(o,2958 conflict_info->pair1,2959 conflict_info->branch1,2960 conflict_info->branch2))2961 clean_merge = -1;2962break;2963case RENAME_DELETE:2964 clean_merge =0;2965if(conflict_rename_delete(o,2966 conflict_info->pair1,2967 conflict_info->branch1,2968 conflict_info->branch2))2969 clean_merge = -1;2970break;2971case RENAME_ONE_FILE_TO_TWO:2972 clean_merge =0;2973if(conflict_rename_rename_1to2(o, conflict_info))2974 clean_merge = -1;2975break;2976case RENAME_TWO_FILES_TO_ONE:2977 clean_merge =0;2978if(conflict_rename_rename_2to1(o, conflict_info))2979 clean_merge = -1;2980break;2981default:2982 entry->processed =0;2983break;2984}2985}else if(o_oid && (!a_oid || !b_oid)) {2986/* Case A: Deleted in one */2987if((!a_oid && !b_oid) ||2988(!b_oid &&blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||2989(!a_oid &&blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {2990/* Deleted in both or deleted in one and2991 * unchanged in the other */2992if(a_oid)2993output(o,2,_("Removing%s"), path);2994/* do not touch working file if it did not exist */2995remove_file(o,1, path, !a_oid);2996}else{2997/* Modify/delete; deleted side may have put a directory in the way */2998 clean_merge =0;2999if(handle_modify_delete(o, path, o_oid, o_mode,3000 a_oid, a_mode, b_oid, b_mode))3001 clean_merge = -1;3002}3003}else if((!o_oid && a_oid && !b_oid) ||3004(!o_oid && !a_oid && b_oid)) {3005/* Case B: Added in one. */3006/* [nothing|directory] -> ([nothing|directory], file) */30073008const char*add_branch;3009const char*other_branch;3010unsigned mode;3011const struct object_id *oid;3012const char*conf;30133014if(a_oid) {3015 add_branch = o->branch1;3016 other_branch = o->branch2;3017 mode = a_mode;3018 oid = a_oid;3019 conf =_("file/directory");3020}else{3021 add_branch = o->branch2;3022 other_branch = o->branch1;3023 mode = b_mode;3024 oid = b_oid;3025 conf =_("directory/file");3026}3027if(dir_in_way(path,3028!o->call_depth && !S_ISGITLINK(a_mode),30290)) {3030char*new_path =unique_path(o, path, add_branch);3031 clean_merge =0;3032output(o,1,_("CONFLICT (%s): There is a directory with name%sin%s. "3033"Adding%sas%s"),3034 conf, path, other_branch, path, new_path);3035if(update_file(o,0, oid, mode, new_path))3036 clean_merge = -1;3037else if(o->call_depth)3038remove_file_from_cache(path);3039free(new_path);3040}else{3041output(o,2,_("Adding%s"), path);3042/* do not overwrite file if already present */3043if(update_file_flags(o, oid, mode, path,1, !a_oid))3044 clean_merge = -1;3045}3046}else if(a_oid && b_oid) {3047/* Case C: Added in both (check for same permissions) and */3048/* case D: Modified in both, but differently. */3049int is_dirty =0;/* unpack_trees would have bailed if dirty */3050 clean_merge =merge_content(o, path, is_dirty,3051 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,3052 NULL);3053}else if(!o_oid && !a_oid && !b_oid) {3054/*3055 * this entry was deleted altogether. a_mode == 0 means3056 * we had that path and want to actively remove it.3057 */3058remove_file(o,1, path, !a_mode);3059}else3060BUG("fatal merge failure, shouldn't happen.");30613062return clean_merge;3063}30643065intmerge_trees(struct merge_options *o,3066struct tree *head,3067struct tree *merge,3068struct tree *common,3069struct tree **result)3070{3071int code, clean;30723073if(o->subtree_shift) {3074 merge =shift_tree_object(head, merge, o->subtree_shift);3075 common =shift_tree_object(head, common, o->subtree_shift);3076}30773078if(oid_eq(&common->object.oid, &merge->object.oid)) {3079struct strbuf sb = STRBUF_INIT;30803081if(!o->call_depth &&index_has_changes(&sb)) {3082err(o,_("Dirty index: cannot merge (dirty:%s)"),3083 sb.buf);3084return0;3085}3086output(o,0,_("Already up to date!"));3087*result = head;3088return1;3089}30903091 code =git_merge_trees(o, common, head, merge);30923093if(code !=0) {3094if(show(o,4) || o->call_depth)3095err(o,_("merging of trees%sand%sfailed"),3096oid_to_hex(&head->object.oid),3097oid_to_hex(&merge->object.oid));3098return-1;3099}31003101if(unmerged_cache()) {3102struct string_list *entries;3103struct rename_info re_info;3104int i;3105/*3106 * Only need the hashmap while processing entries, so3107 * initialize it here and free it when we are done running3108 * through the entries. Keeping it in the merge_options as3109 * opposed to decaring a local hashmap is for convenience3110 * so that we don't have to pass it to around.3111 */3112hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL,512);3113get_files_dirs(o, head);3114get_files_dirs(o, merge);31153116 entries =get_unmerged();3117 clean =handle_renames(o, common, head, merge, entries,3118&re_info);3119record_df_conflict_files(o, entries);3120if(clean <0)3121goto cleanup;3122for(i = entries->nr-1;0<= i; i--) {3123const char*path = entries->items[i].string;3124struct stage_data *e = entries->items[i].util;3125if(!e->processed) {3126int ret =process_entry(o, path, e);3127if(!ret)3128 clean =0;3129else if(ret <0) {3130 clean = ret;3131goto cleanup;3132}3133}3134}3135for(i =0; i < entries->nr; i++) {3136struct stage_data *e = entries->items[i].util;3137if(!e->processed)3138BUG("unprocessed path???%s",3139 entries->items[i].string);3140}31413142cleanup:3143final_cleanup_renames(&re_info);31443145string_list_clear(entries,1);3146free(entries);31473148hashmap_free(&o->current_file_dir_set,1);31493150if(clean <0)3151return clean;3152}3153else3154 clean =1;31553156/* Free the extra index left from git_merge_trees() */3157/*3158 * FIXME: Need to also free data allocated by3159 * setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs,3160 * but the problem is that only half of it refers to dynamically3161 * allocated data, while the other half points at static strings.3162 */3163discard_index(&o->orig_index);31643165if(o->call_depth && !(*result =write_tree_from_memory(o)))3166return-1;31673168return clean;3169}31703171static struct commit_list *reverse_commit_list(struct commit_list *list)3172{3173struct commit_list *next = NULL, *current, *backup;3174for(current = list; current; current = backup) {3175 backup = current->next;3176 current->next = next;3177 next = current;3178}3179return next;3180}31813182/*3183 * Merge the commits h1 and h2, return the resulting virtual3184 * commit object and a flag indicating the cleanness of the merge.3185 */3186intmerge_recursive(struct merge_options *o,3187struct commit *h1,3188struct commit *h2,3189struct commit_list *ca,3190struct commit **result)3191{3192struct commit_list *iter;3193struct commit *merged_common_ancestors;3194struct tree *mrtree;3195int clean;31963197if(show(o,4)) {3198output(o,4,_("Merging:"));3199output_commit_title(o, h1);3200output_commit_title(o, h2);3201}32023203if(!ca) {3204 ca =get_merge_bases(h1, h2);3205 ca =reverse_commit_list(ca);3206}32073208if(show(o,5)) {3209unsigned cnt =commit_list_count(ca);32103211output(o,5,Q_("found%ucommon ancestor:",3212"found%ucommon ancestors:", cnt), cnt);3213for(iter = ca; iter; iter = iter->next)3214output_commit_title(o, iter->item);3215}32163217 merged_common_ancestors =pop_commit(&ca);3218if(merged_common_ancestors == NULL) {3219/* if there is no common ancestor, use an empty tree */3220struct tree *tree;32213222 tree =lookup_tree(the_hash_algo->empty_tree);3223 merged_common_ancestors =make_virtual_commit(tree,"ancestor");3224}32253226for(iter = ca; iter; iter = iter->next) {3227const char*saved_b1, *saved_b2;3228 o->call_depth++;3229/*3230 * When the merge fails, the result contains files3231 * with conflict markers. The cleanness flag is3232 * ignored (unless indicating an error), it was never3233 * actually used, as result of merge_trees has always3234 * overwritten it: the committed "conflicts" were3235 * already resolved.3236 */3237discard_cache();3238 saved_b1 = o->branch1;3239 saved_b2 = o->branch2;3240 o->branch1 ="Temporary merge branch 1";3241 o->branch2 ="Temporary merge branch 2";3242if(merge_recursive(o, merged_common_ancestors, iter->item,3243 NULL, &merged_common_ancestors) <0)3244return-1;3245 o->branch1 = saved_b1;3246 o->branch2 = saved_b2;3247 o->call_depth--;32483249if(!merged_common_ancestors)3250returnerr(o,_("merge returned no commit"));3251}32523253discard_cache();3254if(!o->call_depth)3255read_cache();32563257 o->ancestor ="merged common ancestors";3258 clean =merge_trees(o,get_commit_tree(h1),get_commit_tree(h2),3259get_commit_tree(merged_common_ancestors),3260&mrtree);3261if(clean <0) {3262flush_output(o);3263return clean;3264}32653266if(o->call_depth) {3267*result =make_virtual_commit(mrtree,"merged tree");3268commit_list_insert(h1, &(*result)->parents);3269commit_list_insert(h2, &(*result)->parents->next);3270}3271flush_output(o);3272if(!o->call_depth && o->buffer_output <2)3273strbuf_release(&o->obuf);3274if(show(o,2))3275diff_warn_rename_limit("merge.renamelimit",3276 o->needed_rename_limit,0);3277return clean;3278}32793280static struct commit *get_ref(const struct object_id *oid,const char*name)3281{3282struct object *object;32833284 object =deref_tag(parse_object(oid), name,strlen(name));3285if(!object)3286return NULL;3287if(object->type == OBJ_TREE)3288returnmake_virtual_commit((struct tree*)object, name);3289if(object->type != OBJ_COMMIT)3290return NULL;3291if(parse_commit((struct commit *)object))3292return NULL;3293return(struct commit *)object;3294}32953296intmerge_recursive_generic(struct merge_options *o,3297const struct object_id *head,3298const struct object_id *merge,3299int num_base_list,3300const struct object_id **base_list,3301struct commit **result)3302{3303int clean;3304struct lock_file lock = LOCK_INIT;3305struct commit *head_commit =get_ref(head, o->branch1);3306struct commit *next_commit =get_ref(merge, o->branch2);3307struct commit_list *ca = NULL;33083309if(base_list) {3310int i;3311for(i =0; i < num_base_list; ++i) {3312struct commit *base;3313if(!(base =get_ref(base_list[i],oid_to_hex(base_list[i]))))3314returnerr(o,_("Could not parse object '%s'"),3315oid_to_hex(base_list[i]));3316commit_list_insert(base, &ca);3317}3318}33193320hold_locked_index(&lock, LOCK_DIE_ON_ERROR);3321 clean =merge_recursive(o, head_commit, next_commit, ca,3322 result);3323if(clean <0) {3324rollback_lock_file(&lock);3325return clean;3326}33273328if(write_locked_index(&the_index, &lock,3329 COMMIT_LOCK | SKIP_IF_UNCHANGED))3330returnerr(o,_("Unable to write index."));33313332return clean ?0:1;3333}33343335static voidmerge_recursive_config(struct merge_options *o)3336{3337char*value = NULL;3338git_config_get_int("merge.verbosity", &o->verbosity);3339git_config_get_int("diff.renamelimit", &o->diff_rename_limit);3340git_config_get_int("merge.renamelimit", &o->merge_rename_limit);3341if(!git_config_get_string("diff.renames", &value)) {3342 o->diff_detect_rename =git_config_rename("diff.renames", value);3343free(value);3344}3345if(!git_config_get_string("merge.renames", &value)) {3346 o->merge_detect_rename =git_config_rename("merge.renames", value);3347free(value);3348}3349git_config(git_xmerge_config, NULL);3350}33513352voidinit_merge_options(struct merge_options *o)3353{3354const char*merge_verbosity;3355memset(o,0,sizeof(struct merge_options));3356 o->verbosity =2;3357 o->buffer_output =1;3358 o->diff_rename_limit = -1;3359 o->merge_rename_limit = -1;3360 o->renormalize =0;3361 o->diff_detect_rename = -1;3362 o->merge_detect_rename = -1;3363merge_recursive_config(o);3364 merge_verbosity =getenv("GIT_MERGE_VERBOSITY");3365if(merge_verbosity)3366 o->verbosity =strtol(merge_verbosity, NULL,10);3367if(o->verbosity >=5)3368 o->buffer_output =0;3369strbuf_init(&o->obuf,0);3370string_list_init(&o->df_conflict_file_set,1);3371}33723373intparse_merge_opt(struct merge_options *o,const char*s)3374{3375const char*arg;33763377if(!s || !*s)3378return-1;3379if(!strcmp(s,"ours"))3380 o->recursive_variant = MERGE_RECURSIVE_OURS;3381else if(!strcmp(s,"theirs"))3382 o->recursive_variant = MERGE_RECURSIVE_THEIRS;3383else if(!strcmp(s,"subtree"))3384 o->subtree_shift ="";3385else if(skip_prefix(s,"subtree=", &arg))3386 o->subtree_shift = arg;3387else if(!strcmp(s,"patience"))3388 o->xdl_opts =DIFF_WITH_ALG(o, PATIENCE_DIFF);3389else if(!strcmp(s,"histogram"))3390 o->xdl_opts =DIFF_WITH_ALG(o, HISTOGRAM_DIFF);3391else if(skip_prefix(s,"diff-algorithm=", &arg)) {3392long value =parse_algorithm_value(arg);3393if(value <0)3394return-1;3395/* clear out previous settings */3396DIFF_XDL_CLR(o, NEED_MINIMAL);3397 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;3398 o->xdl_opts |= value;3399}3400else if(!strcmp(s,"ignore-space-change"))3401DIFF_XDL_SET(o, IGNORE_WHITESPACE_CHANGE);3402else if(!strcmp(s,"ignore-all-space"))3403DIFF_XDL_SET(o, IGNORE_WHITESPACE);3404else if(!strcmp(s,"ignore-space-at-eol"))3405DIFF_XDL_SET(o, IGNORE_WHITESPACE_AT_EOL);3406else if(!strcmp(s,"ignore-cr-at-eol"))3407DIFF_XDL_SET(o, IGNORE_CR_AT_EOL);3408else if(!strcmp(s,"renormalize"))3409 o->renormalize =1;3410else if(!strcmp(s,"no-renormalize"))3411 o->renormalize =0;3412else if(!strcmp(s,"no-renames"))3413 o->merge_detect_rename =0;3414else if(!strcmp(s,"find-renames")) {3415 o->merge_detect_rename =1;3416 o->rename_score =0;3417}3418else if(skip_prefix(s,"find-renames=", &arg) ||3419skip_prefix(s,"rename-threshold=", &arg)) {3420if((o->rename_score =parse_rename_score(&arg)) == -1|| *arg !=0)3421return-1;3422 o->merge_detect_rename =1;3423}3424else3425return-1;3426return0;3427}