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->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 intunpack_trees_start(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 382static voidunpack_trees_finish(struct merge_options *o) 383{ 384discard_index(&o->orig_index); 385} 386 387struct tree *write_tree_from_memory(struct merge_options *o) 388{ 389struct tree *result = NULL; 390 391if(unmerged_cache()) { 392int i; 393fprintf(stderr,"BUG: There are unmerged index entries:\n"); 394for(i =0; i < active_nr; i++) { 395const struct cache_entry *ce = active_cache[i]; 396if(ce_stage(ce)) 397fprintf(stderr,"BUG:%d%.*s\n",ce_stage(ce), 398(int)ce_namelen(ce), ce->name); 399} 400die("BUG: unmerged index entries in merge-recursive.c"); 401} 402 403if(!active_cache_tree) 404 active_cache_tree =cache_tree(); 405 406if(!cache_tree_fully_valid(active_cache_tree) && 407cache_tree_update(&the_index,0) <0) { 408err(o,_("error building trees")); 409return NULL; 410} 411 412 result =lookup_tree(&active_cache_tree->oid); 413 414return result; 415} 416 417static intsave_files_dirs(const struct object_id *oid, 418struct strbuf *base,const char*path, 419unsigned int mode,int stage,void*context) 420{ 421struct path_hashmap_entry *entry; 422int baselen = base->len; 423struct merge_options *o = context; 424 425strbuf_addstr(base, path); 426 427FLEX_ALLOC_MEM(entry, path, base->buf, base->len); 428hashmap_entry_init(entry,path_hash(entry->path)); 429hashmap_add(&o->current_file_dir_set, entry); 430 431strbuf_setlen(base, baselen); 432return(S_ISDIR(mode) ? READ_TREE_RECURSIVE :0); 433} 434 435static voidget_files_dirs(struct merge_options *o,struct tree *tree) 436{ 437struct pathspec match_all; 438memset(&match_all,0,sizeof(match_all)); 439read_tree_recursive(tree,"",0,0, &match_all, save_files_dirs, o); 440} 441 442static intget_tree_entry_if_blob(const struct object_id *tree, 443const char*path, 444struct object_id *hashy, 445unsigned int*mode_o) 446{ 447int ret; 448 449 ret =get_tree_entry(tree, path, hashy, mode_o); 450if(S_ISDIR(*mode_o)) { 451oidcpy(hashy, &null_oid); 452*mode_o =0; 453} 454return ret; 455} 456 457/* 458 * Returns an index_entry instance which doesn't have to correspond to 459 * a real cache entry in Git's index. 460 */ 461static struct stage_data *insert_stage_data(const char*path, 462struct tree *o,struct tree *a,struct tree *b, 463struct string_list *entries) 464{ 465struct string_list_item *item; 466struct stage_data *e =xcalloc(1,sizeof(struct stage_data)); 467get_tree_entry_if_blob(&o->object.oid, path, 468&e->stages[1].oid, &e->stages[1].mode); 469get_tree_entry_if_blob(&a->object.oid, path, 470&e->stages[2].oid, &e->stages[2].mode); 471get_tree_entry_if_blob(&b->object.oid, path, 472&e->stages[3].oid, &e->stages[3].mode); 473 item =string_list_insert(entries, path); 474 item->util = e; 475return e; 476} 477 478/* 479 * Create a dictionary mapping file names to stage_data objects. The 480 * dictionary contains one entry for every path with a non-zero stage entry. 481 */ 482static struct string_list *get_unmerged(void) 483{ 484struct string_list *unmerged =xcalloc(1,sizeof(struct string_list)); 485int i; 486 487 unmerged->strdup_strings =1; 488 489for(i =0; i < active_nr; i++) { 490struct string_list_item *item; 491struct stage_data *e; 492const struct cache_entry *ce = active_cache[i]; 493if(!ce_stage(ce)) 494continue; 495 496 item =string_list_lookup(unmerged, ce->name); 497if(!item) { 498 item =string_list_insert(unmerged, ce->name); 499 item->util =xcalloc(1,sizeof(struct stage_data)); 500} 501 e = item->util; 502 e->stages[ce_stage(ce)].mode = ce->ce_mode; 503oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid); 504} 505 506return unmerged; 507} 508 509static intstring_list_df_name_compare(const char*one,const char*two) 510{ 511int onelen =strlen(one); 512int twolen =strlen(two); 513/* 514 * Here we only care that entries for D/F conflicts are 515 * adjacent, in particular with the file of the D/F conflict 516 * appearing before files below the corresponding directory. 517 * The order of the rest of the list is irrelevant for us. 518 * 519 * To achieve this, we sort with df_name_compare and provide 520 * the mode S_IFDIR so that D/F conflicts will sort correctly. 521 * We use the mode S_IFDIR for everything else for simplicity, 522 * since in other cases any changes in their order due to 523 * sorting cause no problems for us. 524 */ 525int cmp =df_name_compare(one, onelen, S_IFDIR, 526 two, twolen, S_IFDIR); 527/* 528 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure 529 * that 'foo' comes before 'foo/bar'. 530 */ 531if(cmp) 532return cmp; 533return onelen - twolen; 534} 535 536static voidrecord_df_conflict_files(struct merge_options *o, 537struct string_list *entries) 538{ 539/* If there is a D/F conflict and the file for such a conflict 540 * currently exist in the working tree, we want to allow it to be 541 * removed to make room for the corresponding directory if needed. 542 * The files underneath the directories of such D/F conflicts will 543 * be processed before the corresponding file involved in the D/F 544 * conflict. If the D/F directory ends up being removed by the 545 * merge, then we won't have to touch the D/F file. If the D/F 546 * directory needs to be written to the working copy, then the D/F 547 * file will simply be removed (in make_room_for_path()) to make 548 * room for the necessary paths. Note that if both the directory 549 * and the file need to be present, then the D/F file will be 550 * reinstated with a new unique name at the time it is processed. 551 */ 552struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP; 553const char*last_file = NULL; 554int last_len =0; 555int i; 556 557/* 558 * If we're merging merge-bases, we don't want to bother with 559 * any working directory changes. 560 */ 561if(o->call_depth) 562return; 563 564/* Ensure D/F conflicts are adjacent in the entries list. */ 565for(i =0; i < entries->nr; i++) { 566struct string_list_item *next = &entries->items[i]; 567string_list_append(&df_sorted_entries, next->string)->util = 568 next->util; 569} 570 df_sorted_entries.cmp = string_list_df_name_compare; 571string_list_sort(&df_sorted_entries); 572 573string_list_clear(&o->df_conflict_file_set,1); 574for(i =0; i < df_sorted_entries.nr; i++) { 575const char*path = df_sorted_entries.items[i].string; 576int len =strlen(path); 577struct stage_data *e = df_sorted_entries.items[i].util; 578 579/* 580 * Check if last_file & path correspond to a D/F conflict; 581 * i.e. whether path is last_file+'/'+<something>. 582 * If so, record that it's okay to remove last_file to make 583 * room for path and friends if needed. 584 */ 585if(last_file && 586 len > last_len && 587memcmp(path, last_file, last_len) ==0&& 588 path[last_len] =='/') { 589string_list_insert(&o->df_conflict_file_set, last_file); 590} 591 592/* 593 * Determine whether path could exist as a file in the 594 * working directory as a possible D/F conflict. This 595 * will only occur when it exists in stage 2 as a 596 * file. 597 */ 598if(S_ISREG(e->stages[2].mode) ||S_ISLNK(e->stages[2].mode)) { 599 last_file = path; 600 last_len = len; 601}else{ 602 last_file = NULL; 603} 604} 605string_list_clear(&df_sorted_entries,0); 606} 607 608struct rename { 609struct diff_filepair *pair; 610/* 611 * Purpose of src_entry and dst_entry: 612 * 613 * If 'before' is renamed to 'after' then src_entry will contain 614 * the versions of 'before' from the merge_base, HEAD, and MERGE in 615 * stages 1, 2, and 3; dst_entry will contain the respective 616 * versions of 'after' in corresponding locations. Thus, we have a 617 * total of six modes and oids, though some will be null. (Stage 0 618 * is ignored; we're interested in handling conflicts.) 619 * 620 * Since we don't turn on break-rewrites by default, neither 621 * src_entry nor dst_entry can have all three of their stages have 622 * non-null oids, meaning at most four of the six will be non-null. 623 * Also, since this is a rename, both src_entry and dst_entry will 624 * have at least one non-null oid, meaning at least two will be 625 * non-null. Of the six oids, a typical rename will have three be 626 * non-null. Only two implies a rename/delete, and four implies a 627 * rename/add. 628 */ 629struct stage_data *src_entry; 630struct stage_data *dst_entry; 631unsigned add_turned_into_rename:1; 632unsigned processed:1; 633}; 634 635static intupdate_stages(struct merge_options *opt,const char*path, 636const struct diff_filespec *o, 637const struct diff_filespec *a, 638const struct diff_filespec *b) 639{ 640 641/* 642 * NOTE: It is usually a bad idea to call update_stages on a path 643 * before calling update_file on that same path, since it can 644 * sometimes lead to spurious "refusing to lose untracked file..." 645 * messages from update_file (via make_room_for path via 646 * would_lose_untracked). Instead, reverse the order of the calls 647 * (executing update_file first and then update_stages). 648 */ 649int clear =1; 650int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK; 651if(clear) 652if(remove_file_from_cache(path)) 653return-1; 654if(o) 655if(add_cacheinfo(opt, o->mode, &o->oid, path,1,0, options)) 656return-1; 657if(a) 658if(add_cacheinfo(opt, a->mode, &a->oid, path,2,0, options)) 659return-1; 660if(b) 661if(add_cacheinfo(opt, b->mode, &b->oid, path,3,0, options)) 662return-1; 663return0; 664} 665 666static intupdate_stages_for_stage_data(struct merge_options *opt, 667const char*path, 668const struct stage_data *stage_data) 669{ 670struct diff_filespec o, a, b; 671 672 o.mode = stage_data->stages[1].mode; 673oidcpy(&o.oid, &stage_data->stages[1].oid); 674 675 a.mode = stage_data->stages[2].mode; 676oidcpy(&a.oid, &stage_data->stages[2].oid); 677 678 b.mode = stage_data->stages[3].mode; 679oidcpy(&b.oid, &stage_data->stages[3].oid); 680 681returnupdate_stages(opt, path, 682is_null_oid(&o.oid) ? NULL : &o, 683is_null_oid(&a.oid) ? NULL : &a, 684is_null_oid(&b.oid) ? NULL : &b); 685} 686 687static voidupdate_entry(struct stage_data *entry, 688struct diff_filespec *o, 689struct diff_filespec *a, 690struct diff_filespec *b) 691{ 692 entry->processed =0; 693 entry->stages[1].mode = o->mode; 694 entry->stages[2].mode = a->mode; 695 entry->stages[3].mode = b->mode; 696oidcpy(&entry->stages[1].oid, &o->oid); 697oidcpy(&entry->stages[2].oid, &a->oid); 698oidcpy(&entry->stages[3].oid, &b->oid); 699} 700 701static intremove_file(struct merge_options *o,int clean, 702const char*path,int no_wd) 703{ 704int update_cache = o->call_depth || clean; 705int update_working_directory = !o->call_depth && !no_wd; 706 707if(update_cache) { 708if(remove_file_from_cache(path)) 709return-1; 710} 711if(update_working_directory) { 712if(ignore_case) { 713struct cache_entry *ce; 714 ce =cache_file_exists(path,strlen(path), ignore_case); 715if(ce &&ce_stage(ce) ==0&&strcmp(path, ce->name)) 716return0; 717} 718if(remove_path(path)) 719return-1; 720} 721return0; 722} 723 724/* add a string to a strbuf, but converting "/" to "_" */ 725static voidadd_flattened_path(struct strbuf *out,const char*s) 726{ 727size_t i = out->len; 728strbuf_addstr(out, s); 729for(; i < out->len; i++) 730if(out->buf[i] =='/') 731 out->buf[i] ='_'; 732} 733 734static char*unique_path(struct merge_options *o,const char*path,const char*branch) 735{ 736struct path_hashmap_entry *entry; 737struct strbuf newpath = STRBUF_INIT; 738int suffix =0; 739size_t base_len; 740 741strbuf_addf(&newpath,"%s~", path); 742add_flattened_path(&newpath, branch); 743 744 base_len = newpath.len; 745while(hashmap_get_from_hash(&o->current_file_dir_set, 746path_hash(newpath.buf), newpath.buf) || 747(!o->call_depth &&file_exists(newpath.buf))) { 748strbuf_setlen(&newpath, base_len); 749strbuf_addf(&newpath,"_%d", suffix++); 750} 751 752FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len); 753hashmap_entry_init(entry,path_hash(entry->path)); 754hashmap_add(&o->current_file_dir_set, entry); 755returnstrbuf_detach(&newpath, NULL); 756} 757 758/** 759 * Check whether a directory in the index is in the way of an incoming 760 * file. Return 1 if so. If check_working_copy is non-zero, also 761 * check the working directory. If empty_ok is non-zero, also return 762 * 0 in the case where the working-tree dir exists but is empty. 763 */ 764static intdir_in_way(const char*path,int check_working_copy,int empty_ok) 765{ 766int pos; 767struct strbuf dirpath = STRBUF_INIT; 768struct stat st; 769 770strbuf_addstr(&dirpath, path); 771strbuf_addch(&dirpath,'/'); 772 773 pos =cache_name_pos(dirpath.buf, dirpath.len); 774 775if(pos <0) 776 pos = -1- pos; 777if(pos < active_nr && 778!strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) { 779strbuf_release(&dirpath); 780return1; 781} 782 783strbuf_release(&dirpath); 784return check_working_copy && !lstat(path, &st) &&S_ISDIR(st.st_mode) && 785!(empty_ok &&is_empty_dir(path)); 786} 787 788/* 789 * Returns whether path was tracked in the index before the merge started, 790 * and its oid and mode match the specified values 791 */ 792static intwas_tracked_and_matches(struct merge_options *o,const char*path, 793const struct object_id *oid,unsigned mode) 794{ 795int pos =index_name_pos(&o->orig_index, path,strlen(path)); 796struct cache_entry *ce; 797 798if(0> pos) 799/* we were not tracking this path before the merge */ 800return0; 801 802/* See if the file we were tracking before matches */ 803 ce = o->orig_index.cache[pos]; 804return(oid_eq(&ce->oid, oid) && ce->ce_mode == mode); 805} 806 807/* 808 * Returns whether path was tracked in the index before the merge started 809 */ 810static intwas_tracked(struct merge_options *o,const char*path) 811{ 812int pos =index_name_pos(&o->orig_index, path,strlen(path)); 813 814if(0<= pos) 815/* we were tracking this path before the merge */ 816return1; 817 818return0; 819} 820 821static intwould_lose_untracked(const char*path) 822{ 823/* 824 * This may look like it can be simplified to: 825 * return !was_tracked(o, path) && file_exists(path) 826 * but it can't. This function needs to know whether path was in 827 * the working tree due to EITHER having been tracked in the index 828 * before the merge OR having been put into the working copy and 829 * index by unpack_trees(). Due to that either-or requirement, we 830 * check the current index instead of the original one. 831 * 832 * Note that we do not need to worry about merge-recursive itself 833 * updating the index after unpack_trees() and before calling this 834 * function, because we strictly require all code paths in 835 * merge-recursive to update the working tree first and the index 836 * second. Doing otherwise would break 837 * update_file()/would_lose_untracked(); see every comment in this 838 * file which mentions "update_stages". 839 */ 840int pos =cache_name_pos(path,strlen(path)); 841 842if(pos <0) 843 pos = -1- pos; 844while(pos < active_nr && 845!strcmp(path, active_cache[pos]->name)) { 846/* 847 * If stage #0, it is definitely tracked. 848 * If it has stage #2 then it was tracked 849 * before this merge started. All other 850 * cases the path was not tracked. 851 */ 852switch(ce_stage(active_cache[pos])) { 853case0: 854case2: 855return0; 856} 857 pos++; 858} 859returnfile_exists(path); 860} 861 862static intwas_dirty(struct merge_options *o,const char*path) 863{ 864struct cache_entry *ce; 865int dirty =1; 866 867if(o->call_depth || !was_tracked(o, path)) 868return!dirty; 869 870 ce =index_file_exists(o->unpack_opts.src_index, 871 path,strlen(path), ignore_case); 872 dirty =verify_uptodate(ce, &o->unpack_opts) !=0; 873return dirty; 874} 875 876static intmake_room_for_path(struct merge_options *o,const char*path) 877{ 878int status, i; 879const char*msg =_("failed to create path '%s'%s"); 880 881/* Unlink any D/F conflict files that are in the way */ 882for(i =0; i < o->df_conflict_file_set.nr; i++) { 883const char*df_path = o->df_conflict_file_set.items[i].string; 884size_t pathlen =strlen(path); 885size_t df_pathlen =strlen(df_path); 886if(df_pathlen < pathlen && 887 path[df_pathlen] =='/'&& 888strncmp(path, df_path, df_pathlen) ==0) { 889output(o,3, 890_("Removing%sto make room for subdirectory\n"), 891 df_path); 892unlink(df_path); 893unsorted_string_list_delete_item(&o->df_conflict_file_set, 894 i,0); 895break; 896} 897} 898 899/* Make sure leading directories are created */ 900 status =safe_create_leading_directories_const(path); 901if(status) { 902if(status == SCLD_EXISTS) 903/* something else exists */ 904returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 905returnerr(o, msg, path,""); 906} 907 908/* 909 * Do not unlink a file in the work tree if we are not 910 * tracking it. 911 */ 912if(would_lose_untracked(path)) 913returnerr(o,_("refusing to lose untracked file at '%s'"), 914 path); 915 916/* Successful unlink is good.. */ 917if(!unlink(path)) 918return0; 919/* .. and so is no existing file */ 920if(errno == ENOENT) 921return0; 922/* .. but not some other error (who really cares what?) */ 923returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 924} 925 926static intupdate_file_flags(struct merge_options *o, 927const struct object_id *oid, 928unsigned mode, 929const char*path, 930int update_cache, 931int update_wd) 932{ 933int ret =0; 934 935if(o->call_depth) 936 update_wd =0; 937 938if(update_wd) { 939enum object_type type; 940void*buf; 941unsigned long size; 942 943if(S_ISGITLINK(mode)) { 944/* 945 * We may later decide to recursively descend into 946 * the submodule directory and update its index 947 * and/or work tree, but we do not do that now. 948 */ 949 update_wd =0; 950goto update_index; 951} 952 953 buf =read_object_file(oid, &type, &size); 954if(!buf) 955returnerr(o,_("cannot read object%s'%s'"),oid_to_hex(oid), path); 956if(type != OBJ_BLOB) { 957 ret =err(o,_("blob expected for%s'%s'"),oid_to_hex(oid), path); 958goto free_buf; 959} 960if(S_ISREG(mode)) { 961struct strbuf strbuf = STRBUF_INIT; 962if(convert_to_working_tree(path, buf, size, &strbuf)) { 963free(buf); 964 size = strbuf.len; 965 buf =strbuf_detach(&strbuf, NULL); 966} 967} 968 969if(make_room_for_path(o, path) <0) { 970 update_wd =0; 971goto free_buf; 972} 973if(S_ISREG(mode) || (!has_symlinks &&S_ISLNK(mode))) { 974int fd; 975if(mode &0100) 976 mode =0777; 977else 978 mode =0666; 979 fd =open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); 980if(fd <0) { 981 ret =err(o,_("failed to open '%s':%s"), 982 path,strerror(errno)); 983goto free_buf; 984} 985write_in_full(fd, buf, size); 986close(fd); 987}else if(S_ISLNK(mode)) { 988char*lnk =xmemdupz(buf, size); 989safe_create_leading_directories_const(path); 990unlink(path); 991if(symlink(lnk, path)) 992 ret =err(o,_("failed to symlink '%s':%s"), 993 path,strerror(errno)); 994free(lnk); 995}else 996 ret =err(o, 997_("do not know what to do with%06o%s'%s'"), 998 mode,oid_to_hex(oid), path); 999 free_buf:1000free(buf);1001}1002 update_index:1003if(!ret && update_cache)1004if(add_cacheinfo(o, mode, oid, path,0, update_wd,1005 ADD_CACHE_OK_TO_ADD))1006return-1;1007return ret;1008}10091010static intupdate_file(struct merge_options *o,1011int clean,1012const struct object_id *oid,1013unsigned mode,1014const char*path)1015{1016returnupdate_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);1017}10181019/* Low level file merging, update and removal */10201021struct merge_file_info {1022struct object_id oid;1023unsigned mode;1024unsigned clean:1,1025 merge:1;1026};10271028static intmerge_3way(struct merge_options *o,1029 mmbuffer_t *result_buf,1030const struct diff_filespec *one,1031const struct diff_filespec *a,1032const struct diff_filespec *b,1033const char*branch1,1034const char*branch2)1035{1036 mmfile_t orig, src1, src2;1037struct ll_merge_options ll_opts = {0};1038char*base_name, *name1, *name2;1039int merge_status;10401041 ll_opts.renormalize = o->renormalize;1042 ll_opts.xdl_opts = o->xdl_opts;10431044if(o->call_depth) {1045 ll_opts.virtual_ancestor =1;1046 ll_opts.variant =0;1047}else{1048switch(o->recursive_variant) {1049case MERGE_RECURSIVE_OURS:1050 ll_opts.variant = XDL_MERGE_FAVOR_OURS;1051break;1052case MERGE_RECURSIVE_THEIRS:1053 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;1054break;1055default:1056 ll_opts.variant =0;1057break;1058}1059}10601061if(strcmp(a->path, b->path) ||1062(o->ancestor != NULL &&strcmp(a->path, one->path) !=0)) {1063 base_name = o->ancestor == NULL ? NULL :1064mkpathdup("%s:%s", o->ancestor, one->path);1065 name1 =mkpathdup("%s:%s", branch1, a->path);1066 name2 =mkpathdup("%s:%s", branch2, b->path);1067}else{1068 base_name = o->ancestor == NULL ? NULL :1069mkpathdup("%s", o->ancestor);1070 name1 =mkpathdup("%s", branch1);1071 name2 =mkpathdup("%s", branch2);1072}10731074read_mmblob(&orig, &one->oid);1075read_mmblob(&src1, &a->oid);1076read_mmblob(&src2, &b->oid);10771078 merge_status =ll_merge(result_buf, a->path, &orig, base_name,1079&src1, name1, &src2, name2, &ll_opts);10801081free(base_name);1082free(name1);1083free(name2);1084free(orig.ptr);1085free(src1.ptr);1086free(src2.ptr);1087return merge_status;1088}10891090static intmerge_file_1(struct merge_options *o,1091const struct diff_filespec *one,1092const struct diff_filespec *a,1093const struct diff_filespec *b,1094const char*filename,1095const char*branch1,1096const char*branch2,1097struct merge_file_info *result)1098{1099 result->merge =0;1100 result->clean =1;11011102if((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1103 result->clean =0;1104if(S_ISREG(a->mode)) {1105 result->mode = a->mode;1106oidcpy(&result->oid, &a->oid);1107}else{1108 result->mode = b->mode;1109oidcpy(&result->oid, &b->oid);1110}1111}else{1112if(!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))1113 result->merge =1;11141115/*1116 * Merge modes1117 */1118if(a->mode == b->mode || a->mode == one->mode)1119 result->mode = b->mode;1120else{1121 result->mode = a->mode;1122if(b->mode != one->mode) {1123 result->clean =0;1124 result->merge =1;1125}1126}11271128if(oid_eq(&a->oid, &b->oid) ||oid_eq(&a->oid, &one->oid))1129oidcpy(&result->oid, &b->oid);1130else if(oid_eq(&b->oid, &one->oid))1131oidcpy(&result->oid, &a->oid);1132else if(S_ISREG(a->mode)) {1133 mmbuffer_t result_buf;1134int ret =0, merge_status;11351136 merge_status =merge_3way(o, &result_buf, one, a, b,1137 branch1, branch2);11381139if((merge_status <0) || !result_buf.ptr)1140 ret =err(o,_("Failed to execute internal merge"));11411142if(!ret &&1143write_object_file(result_buf.ptr, result_buf.size,1144 blob_type, &result->oid))1145 ret =err(o,_("Unable to add%sto database"),1146 a->path);11471148free(result_buf.ptr);1149if(ret)1150return ret;1151 result->clean = (merge_status ==0);1152}else if(S_ISGITLINK(a->mode)) {1153 result->clean =merge_submodule(&result->oid,1154 one->path,1155&one->oid,1156&a->oid,1157&b->oid,1158!o->call_depth);1159}else if(S_ISLNK(a->mode)) {1160switch(o->recursive_variant) {1161case MERGE_RECURSIVE_NORMAL:1162oidcpy(&result->oid, &a->oid);1163if(!oid_eq(&a->oid, &b->oid))1164 result->clean =0;1165break;1166case MERGE_RECURSIVE_OURS:1167oidcpy(&result->oid, &a->oid);1168break;1169case MERGE_RECURSIVE_THEIRS:1170oidcpy(&result->oid, &b->oid);1171break;1172}1173}else1174die("BUG: unsupported object type in the tree");1175}11761177if(result->merge)1178output(o,2,_("Auto-merging%s"), filename);11791180return0;1181}11821183static intmerge_file_special_markers(struct merge_options *o,1184const struct diff_filespec *one,1185const struct diff_filespec *a,1186const struct diff_filespec *b,1187const char*target_filename,1188const char*branch1,1189const char*filename1,1190const char*branch2,1191const char*filename2,1192struct merge_file_info *mfi)1193{1194char*side1 = NULL;1195char*side2 = NULL;1196int ret;11971198if(filename1)1199 side1 =xstrfmt("%s:%s", branch1, filename1);1200if(filename2)1201 side2 =xstrfmt("%s:%s", branch2, filename2);12021203 ret =merge_file_1(o, one, a, b, target_filename,1204 side1 ? side1 : branch1,1205 side2 ? side2 : branch2, mfi);12061207free(side1);1208free(side2);1209return ret;1210}12111212static intmerge_file_one(struct merge_options *o,1213const char*path,1214const struct object_id *o_oid,int o_mode,1215const struct object_id *a_oid,int a_mode,1216const struct object_id *b_oid,int b_mode,1217const char*branch1,1218const char*branch2,1219struct merge_file_info *mfi)1220{1221struct diff_filespec one, a, b;12221223 one.path = a.path = b.path = (char*)path;1224oidcpy(&one.oid, o_oid);1225 one.mode = o_mode;1226oidcpy(&a.oid, a_oid);1227 a.mode = a_mode;1228oidcpy(&b.oid, b_oid);1229 b.mode = b_mode;1230returnmerge_file_1(o, &one, &a, &b, path, branch1, branch2, mfi);1231}12321233static intconflict_rename_dir(struct merge_options *o,1234struct diff_filepair *pair,1235const char*rename_branch,1236const char*other_branch)1237{1238const struct diff_filespec *dest = pair->two;12391240if(!o->call_depth &&would_lose_untracked(dest->path)) {1241char*alt_path =unique_path(o, dest->path, rename_branch);12421243output(o,1,_("Error: Refusing to lose untracked file at%s; "1244"writing to%sinstead."),1245 dest->path, alt_path);1246/*1247 * Write the file in worktree at alt_path, but not in the1248 * index. Instead, write to dest->path for the index but1249 * only at the higher appropriate stage.1250 */1251if(update_file(o,0, &dest->oid, dest->mode, alt_path))1252return-1;1253free(alt_path);1254returnupdate_stages(o, dest->path, NULL,1255 rename_branch == o->branch1 ? dest : NULL,1256 rename_branch == o->branch1 ? NULL : dest);1257}12581259/* Update dest->path both in index and in worktree */1260if(update_file(o,1, &dest->oid, dest->mode, dest->path))1261return-1;1262return0;1263}12641265static inthandle_change_delete(struct merge_options *o,1266const char*path,const char*old_path,1267const struct object_id *o_oid,int o_mode,1268const struct object_id *changed_oid,1269int changed_mode,1270const char*change_branch,1271const char*delete_branch,1272const char*change,const char*change_past)1273{1274char*alt_path = NULL;1275const char*update_path = path;1276int ret =0;12771278if(dir_in_way(path, !o->call_depth,0) ||1279(!o->call_depth &&would_lose_untracked(path))) {1280 update_path = alt_path =unique_path(o, path, change_branch);1281}12821283if(o->call_depth) {1284/*1285 * We cannot arbitrarily accept either a_sha or b_sha as1286 * correct; since there is no true "middle point" between1287 * them, simply reuse the base version for virtual merge base.1288 */1289 ret =remove_file_from_cache(path);1290if(!ret)1291 ret =update_file(o,0, o_oid, o_mode, update_path);1292}else{1293if(!alt_path) {1294if(!old_path) {1295output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1296"and%sin%s. Version%sof%sleft in tree."),1297 change, path, delete_branch, change_past,1298 change_branch, change_branch, path);1299}else{1300output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1301"and%sto%sin%s. Version%sof%sleft in tree."),1302 change, old_path, delete_branch, change_past, path,1303 change_branch, change_branch, path);1304}1305}else{1306if(!old_path) {1307output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1308"and%sin%s. Version%sof%sleft in tree at%s."),1309 change, path, delete_branch, change_past,1310 change_branch, change_branch, path, alt_path);1311}else{1312output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1313"and%sto%sin%s. Version%sof%sleft in tree at%s."),1314 change, old_path, delete_branch, change_past, path,1315 change_branch, change_branch, path, alt_path);1316}1317}1318/*1319 * No need to call update_file() on path when change_branch ==1320 * o->branch1 && !alt_path, since that would needlessly touch1321 * path. We could call update_file_flags() with update_cache=01322 * and update_wd=0, but that's a no-op.1323 */1324if(change_branch != o->branch1 || alt_path)1325 ret =update_file(o,0, changed_oid, changed_mode, update_path);1326}1327free(alt_path);13281329return ret;1330}13311332static intconflict_rename_delete(struct merge_options *o,1333struct diff_filepair *pair,1334const char*rename_branch,1335const char*delete_branch)1336{1337const struct diff_filespec *orig = pair->one;1338const struct diff_filespec *dest = pair->two;13391340if(handle_change_delete(o,1341 o->call_depth ? orig->path : dest->path,1342 o->call_depth ? NULL : orig->path,1343&orig->oid, orig->mode,1344&dest->oid, dest->mode,1345 rename_branch, delete_branch,1346_("rename"),_("renamed")))1347return-1;13481349if(o->call_depth)1350returnremove_file_from_cache(dest->path);1351else1352returnupdate_stages(o, dest->path, NULL,1353 rename_branch == o->branch1 ? dest : NULL,1354 rename_branch == o->branch1 ? NULL : dest);1355}13561357static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,1358struct stage_data *entry,1359int stage)1360{1361struct object_id *oid = &entry->stages[stage].oid;1362unsigned mode = entry->stages[stage].mode;1363if(mode ==0||is_null_oid(oid))1364return NULL;1365oidcpy(&target->oid, oid);1366 target->mode = mode;1367return target;1368}13691370static inthandle_file(struct merge_options *o,1371struct diff_filespec *rename,1372int stage,1373struct rename_conflict_info *ci)1374{1375char*dst_name = rename->path;1376struct stage_data *dst_entry;1377const char*cur_branch, *other_branch;1378struct diff_filespec other;1379struct diff_filespec *add;1380int ret;13811382if(stage ==2) {1383 dst_entry = ci->dst_entry1;1384 cur_branch = ci->branch1;1385 other_branch = ci->branch2;1386}else{1387 dst_entry = ci->dst_entry2;1388 cur_branch = ci->branch2;1389 other_branch = ci->branch1;1390}13911392 add =filespec_from_entry(&other, dst_entry, stage ^1);1393if(add) {1394int ren_src_was_dirty =was_dirty(o, rename->path);1395char*add_name =unique_path(o, rename->path, other_branch);1396if(update_file(o,0, &add->oid, add->mode, add_name))1397return-1;13981399if(ren_src_was_dirty) {1400output(o,1,_("Refusing to lose dirty file at%s"),1401 rename->path);1402}1403/*1404 * Because the double negatives somehow keep confusing me...1405 * 1) update_wd iff !ren_src_was_dirty.1406 * 2) no_wd iff !update_wd1407 * 3) so, no_wd == !!ren_src_was_dirty == ren_src_was_dirty1408 */1409remove_file(o,0, rename->path, ren_src_was_dirty);1410 dst_name =unique_path(o, rename->path, cur_branch);1411}else{1412if(dir_in_way(rename->path, !o->call_depth,0)) {1413 dst_name =unique_path(o, rename->path, cur_branch);1414output(o,1,_("%sis a directory in%sadding as%sinstead"),1415 rename->path, other_branch, dst_name);1416}else if(!o->call_depth &&1417would_lose_untracked(rename->path)) {1418 dst_name =unique_path(o, rename->path, cur_branch);1419output(o,1,_("Refusing to lose untracked file at%s; "1420"adding as%sinstead"),1421 rename->path, dst_name);1422}1423}1424if((ret =update_file(o,0, &rename->oid, rename->mode, dst_name)))1425;/* fall through, do allow dst_name to be released */1426else if(stage ==2)1427 ret =update_stages(o, rename->path, NULL, rename, add);1428else1429 ret =update_stages(o, rename->path, NULL, add, rename);14301431if(dst_name != rename->path)1432free(dst_name);14331434return ret;1435}14361437static intconflict_rename_rename_1to2(struct merge_options *o,1438struct rename_conflict_info *ci)1439{1440/* One file was renamed in both branches, but to different names. */1441struct diff_filespec *one = ci->pair1->one;1442struct diff_filespec *a = ci->pair1->two;1443struct diff_filespec *b = ci->pair2->two;14441445output(o,1,_("CONFLICT (rename/rename): "1446"Rename\"%s\"->\"%s\"in branch\"%s\""1447"rename\"%s\"->\"%s\"in\"%s\"%s"),1448 one->path, a->path, ci->branch1,1449 one->path, b->path, ci->branch2,1450 o->call_depth ?_(" (left unresolved)") :"");1451if(o->call_depth) {1452struct merge_file_info mfi;1453struct diff_filespec other;1454struct diff_filespec *add;1455if(merge_file_one(o, one->path,1456&one->oid, one->mode,1457&a->oid, a->mode,1458&b->oid, b->mode,1459 ci->branch1, ci->branch2, &mfi))1460return-1;14611462/*1463 * FIXME: For rename/add-source conflicts (if we could detect1464 * such), this is wrong. We should instead find a unique1465 * pathname and then either rename the add-source file to that1466 * unique path, or use that unique path instead of src here.1467 */1468if(update_file(o,0, &mfi.oid, mfi.mode, one->path))1469return-1;14701471/*1472 * Above, we put the merged content at the merge-base's1473 * path. Now we usually need to delete both a->path and1474 * b->path. However, the rename on each side of the merge1475 * could also be involved in a rename/add conflict. In1476 * such cases, we should keep the added file around,1477 * resolving the conflict at that path in its favor.1478 */1479 add =filespec_from_entry(&other, ci->dst_entry1,2^1);1480if(add) {1481if(update_file(o,0, &add->oid, add->mode, a->path))1482return-1;1483}1484else1485remove_file_from_cache(a->path);1486 add =filespec_from_entry(&other, ci->dst_entry2,3^1);1487if(add) {1488if(update_file(o,0, &add->oid, add->mode, b->path))1489return-1;1490}1491else1492remove_file_from_cache(b->path);1493}else if(handle_file(o, a,2, ci) ||handle_file(o, b,3, ci))1494return-1;14951496return0;1497}14981499static intconflict_rename_rename_2to1(struct merge_options *o,1500struct rename_conflict_info *ci)1501{1502/* Two files, a & b, were renamed to the same thing, c. */1503struct diff_filespec *a = ci->pair1->one;1504struct diff_filespec *b = ci->pair2->one;1505struct diff_filespec *c1 = ci->pair1->two;1506struct diff_filespec *c2 = ci->pair2->two;1507char*path = c1->path;/* == c2->path */1508char*path_side_1_desc;1509char*path_side_2_desc;1510struct merge_file_info mfi_c1;1511struct merge_file_info mfi_c2;1512int ret;15131514output(o,1,_("CONFLICT (rename/rename): "1515"Rename%s->%sin%s. "1516"Rename%s->%sin%s"),1517 a->path, c1->path, ci->branch1,1518 b->path, c2->path, ci->branch2);15191520remove_file(o,1, a->path, o->call_depth ||would_lose_untracked(a->path));1521remove_file(o,1, b->path, o->call_depth ||would_lose_untracked(b->path));15221523 path_side_1_desc =xstrfmt("%s(was%s)", path, a->path);1524 path_side_2_desc =xstrfmt("%s(was%s)", path, b->path);1525if(merge_file_special_markers(o, a, c1, &ci->ren1_other,1526 path_side_1_desc,1527 o->branch1, c1->path,1528 o->branch2, ci->ren1_other.path, &mfi_c1) ||1529merge_file_special_markers(o, b, &ci->ren2_other, c2,1530 path_side_2_desc,1531 o->branch1, ci->ren2_other.path,1532 o->branch2, c2->path, &mfi_c2))1533return-1;1534free(path_side_1_desc);1535free(path_side_2_desc);15361537if(o->call_depth) {1538/*1539 * If mfi_c1.clean && mfi_c2.clean, then it might make1540 * sense to do a two-way merge of those results. But, I1541 * think in all cases, it makes sense to have the virtual1542 * merge base just undo the renames; they can be detected1543 * again later for the non-recursive merge.1544 */1545remove_file(o,0, path,0);1546 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, a->path);1547if(!ret)1548 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1549 b->path);1550}else{1551char*new_path1 =unique_path(o, path, ci->branch1);1552char*new_path2 =unique_path(o, path, ci->branch2);1553output(o,1,_("Renaming%sto%sand%sto%sinstead"),1554 a->path, new_path1, b->path, new_path2);1555if(was_dirty(o, path))1556output(o,1,_("Refusing to lose dirty file at%s"),1557 path);1558else if(would_lose_untracked(path))1559/*1560 * Only way we get here is if both renames were from1561 * a directory rename AND user had an untracked file1562 * at the location where both files end up after the1563 * two directory renames. See testcase 10d of t6043.1564 */1565output(o,1,_("Refusing to lose untracked file at "1566"%s, even though it's in the way."),1567 path);1568else1569remove_file(o,0, path,0);1570 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, new_path1);1571if(!ret)1572 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1573 new_path2);1574/*1575 * unpack_trees() actually populates the index for us for1576 * "normal" rename/rename(2to1) situtations so that the1577 * correct entries are at the higher stages, which would1578 * make the call below to update_stages_for_stage_data1579 * unnecessary. However, if either of the renames came1580 * from a directory rename, then unpack_trees() will not1581 * have gotten the right data loaded into the index, so we1582 * need to do so now. (While it'd be tempting to move this1583 * call to update_stages_for_stage_data() to1584 * apply_directory_rename_modifications(), that would break1585 * our intermediate calls to would_lose_untracked() since1586 * those rely on the current in-memory index. See also the1587 * big "NOTE" in update_stages()).1588 */1589if(update_stages_for_stage_data(o, path, ci->dst_entry1))1590 ret = -1;15911592free(new_path2);1593free(new_path1);1594}15951596return ret;1597}15981599/*1600 * Get the diff_filepairs changed between o_tree and tree.1601 */1602static struct diff_queue_struct *get_diffpairs(struct merge_options *o,1603struct tree *o_tree,1604struct tree *tree)1605{1606struct diff_queue_struct *ret;1607struct diff_options opts;16081609diff_setup(&opts);1610 opts.flags.recursive =1;1611 opts.flags.rename_empty =0;1612 opts.detect_rename =merge_detect_rename(o);1613/*1614 * We do not have logic to handle the detection of copies. In1615 * fact, it may not even make sense to add such logic: would we1616 * really want a change to a base file to be propagated through1617 * multiple other files by a merge?1618 */1619if(opts.detect_rename > DIFF_DETECT_RENAME)1620 opts.detect_rename = DIFF_DETECT_RENAME;1621 opts.rename_limit = o->merge_rename_limit >=0? o->merge_rename_limit :1622 o->diff_rename_limit >=0? o->diff_rename_limit :16231000;1624 opts.rename_score = o->rename_score;1625 opts.show_rename_progress = o->show_rename_progress;1626 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1627diff_setup_done(&opts);1628diff_tree_oid(&o_tree->object.oid, &tree->object.oid,"", &opts);1629diffcore_std(&opts);1630if(opts.needed_rename_limit > o->needed_rename_limit)1631 o->needed_rename_limit = opts.needed_rename_limit;16321633 ret =xmalloc(sizeof(*ret));1634*ret = diff_queued_diff;16351636 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1637 diff_queued_diff.nr =0;1638 diff_queued_diff.queue = NULL;1639diff_flush(&opts);1640return ret;1641}16421643static inttree_has_path(struct tree *tree,const char*path)1644{1645struct object_id hashy;1646unsigned int mode_o;16471648return!get_tree_entry(&tree->object.oid, path,1649&hashy, &mode_o);1650}16511652/*1653 * Return a new string that replaces the beginning portion (which matches1654 * entry->dir), with entry->new_dir. In perl-speak:1655 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);1656 * NOTE:1657 * Caller must ensure that old_path starts with entry->dir + '/'.1658 */1659static char*apply_dir_rename(struct dir_rename_entry *entry,1660const char*old_path)1661{1662struct strbuf new_path = STRBUF_INIT;1663int oldlen, newlen;16641665if(entry->non_unique_new_dir)1666return NULL;16671668 oldlen =strlen(entry->dir);1669 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) +1;1670strbuf_grow(&new_path, newlen);1671strbuf_addbuf(&new_path, &entry->new_dir);1672strbuf_addstr(&new_path, &old_path[oldlen]);16731674returnstrbuf_detach(&new_path, NULL);1675}16761677static voidget_renamed_dir_portion(const char*old_path,const char*new_path,1678char**old_dir,char**new_dir)1679{1680char*end_of_old, *end_of_new;1681int old_len, new_len;16821683*old_dir = NULL;1684*new_dir = NULL;16851686/*1687 * For1688 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"1689 * the "e/foo.c" part is the same, we just want to know that1690 * "a/b/c/d" was renamed to "a/b/some/thing/else"1691 * so, for this example, this function returns "a/b/c/d" in1692 * *old_dir and "a/b/some/thing/else" in *new_dir.1693 *1694 * Also, if the basename of the file changed, we don't care. We1695 * want to know which portion of the directory, if any, changed.1696 */1697 end_of_old =strrchr(old_path,'/');1698 end_of_new =strrchr(new_path,'/');16991700if(end_of_old == NULL || end_of_new == NULL)1701return;1702while(*--end_of_new == *--end_of_old &&1703 end_of_old != old_path &&1704 end_of_new != new_path)1705;/* Do nothing; all in the while loop */1706/*1707 * We've found the first non-matching character in the directory1708 * paths. That means the current directory we were comparing1709 * represents the rename. Move end_of_old and end_of_new back1710 * to the full directory name.1711 */1712if(*end_of_old =='/')1713 end_of_old++;1714if(*end_of_old !='/')1715 end_of_new++;1716 end_of_old =strchr(end_of_old,'/');1717 end_of_new =strchr(end_of_new,'/');17181719/*1720 * It may have been the case that old_path and new_path were the same1721 * directory all along. Don't claim a rename if they're the same.1722 */1723 old_len = end_of_old - old_path;1724 new_len = end_of_new - new_path;17251726if(old_len != new_len ||strncmp(old_path, new_path, old_len)) {1727*old_dir =xstrndup(old_path, old_len);1728*new_dir =xstrndup(new_path, new_len);1729}1730}17311732static voidremove_hashmap_entries(struct hashmap *dir_renames,1733struct string_list *items_to_remove)1734{1735int i;1736struct dir_rename_entry *entry;17371738for(i =0; i < items_to_remove->nr; i++) {1739 entry = items_to_remove->items[i].util;1740hashmap_remove(dir_renames, entry, NULL);1741}1742string_list_clear(items_to_remove,0);1743}17441745/*1746 * See if there is a directory rename for path, and if there are any file1747 * level conflicts for the renamed location. If there is a rename and1748 * there are no conflicts, return the new name. Otherwise, return NULL.1749 */1750static char*handle_path_level_conflicts(struct merge_options *o,1751const char*path,1752struct dir_rename_entry *entry,1753struct hashmap *collisions,1754struct tree *tree)1755{1756char*new_path = NULL;1757struct collision_entry *collision_ent;1758int clean =1;1759struct strbuf collision_paths = STRBUF_INIT;17601761/*1762 * entry has the mapping of old directory name to new directory name1763 * that we want to apply to path.1764 */1765 new_path =apply_dir_rename(entry, path);17661767if(!new_path) {1768/* This should only happen when entry->non_unique_new_dir set */1769if(!entry->non_unique_new_dir)1770BUG("entry->non_unqiue_dir not set and !new_path");1771output(o,1,_("CONFLICT (directory rename split): "1772"Unclear where to place%sbecause directory "1773"%swas renamed to multiple other directories, "1774"with no destination getting a majority of the "1775"files."),1776 path, entry->dir);1777 clean =0;1778return NULL;1779}17801781/*1782 * The caller needs to have ensured that it has pre-populated1783 * collisions with all paths that map to new_path. Do a quick check1784 * to ensure that's the case.1785 */1786 collision_ent =collision_find_entry(collisions, new_path);1787if(collision_ent == NULL)1788BUG("collision_ent is NULL");17891790/*1791 * Check for one-sided add/add/.../add conflicts, i.e.1792 * where implicit renames from the other side doing1793 * directory rename(s) can affect this side of history1794 * to put multiple paths into the same location. Warn1795 * and bail on directory renames for such paths.1796 */1797if(collision_ent->reported_already) {1798 clean =0;1799}else if(tree_has_path(tree, new_path)) {1800 collision_ent->reported_already =1;1801strbuf_add_separated_string_list(&collision_paths,", ",1802&collision_ent->source_files);1803output(o,1,_("CONFLICT (implicit dir rename): Existing "1804"file/dir at%sin the way of implicit "1805"directory rename(s) putting the following "1806"path(s) there:%s."),1807 new_path, collision_paths.buf);1808 clean =0;1809}else if(collision_ent->source_files.nr >1) {1810 collision_ent->reported_already =1;1811strbuf_add_separated_string_list(&collision_paths,", ",1812&collision_ent->source_files);1813output(o,1,_("CONFLICT (implicit dir rename): Cannot map "1814"more than one path to%s; implicit directory "1815"renames tried to put these paths there:%s"),1816 new_path, collision_paths.buf);1817 clean =0;1818}18191820/* Free memory we no longer need */1821strbuf_release(&collision_paths);1822if(!clean && new_path) {1823free(new_path);1824return NULL;1825}18261827return new_path;1828}18291830/*1831 * There are a couple things we want to do at the directory level:1832 * 1. Check for both sides renaming to the same thing, in order to avoid1833 * implicit renaming of files that should be left in place. (See1834 * testcase 6b in t6043 for details.)1835 * 2. Prune directory renames if there are still files left in the1836 * the original directory. These represent a partial directory rename,1837 * i.e. a rename where only some of the files within the directory1838 * were renamed elsewhere. (Technically, this could be done earlier1839 * in get_directory_renames(), except that would prevent us from1840 * doing the previous check and thus failing testcase 6b.)1841 * 3. Check for rename/rename(1to2) conflicts (at the directory level).1842 * In the future, we could potentially record this info as well and1843 * omit reporting rename/rename(1to2) conflicts for each path within1844 * the affected directories, thus cleaning up the merge output.1845 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the1846 * directory level, because merging directories is fine. If it1847 * causes conflicts for files within those merged directories, then1848 * that should be detected at the individual path level.1849 */1850static voidhandle_directory_level_conflicts(struct merge_options *o,1851struct hashmap *dir_re_head,1852struct tree *head,1853struct hashmap *dir_re_merge,1854struct tree *merge)1855{1856struct hashmap_iter iter;1857struct dir_rename_entry *head_ent;1858struct dir_rename_entry *merge_ent;18591860struct string_list remove_from_head = STRING_LIST_INIT_NODUP;1861struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;18621863hashmap_iter_init(dir_re_head, &iter);1864while((head_ent =hashmap_iter_next(&iter))) {1865 merge_ent =dir_rename_find_entry(dir_re_merge, head_ent->dir);1866if(merge_ent &&1867!head_ent->non_unique_new_dir &&1868!merge_ent->non_unique_new_dir &&1869!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {1870/* 1. Renamed identically; remove it from both sides */1871string_list_append(&remove_from_head,1872 head_ent->dir)->util = head_ent;1873strbuf_release(&head_ent->new_dir);1874string_list_append(&remove_from_merge,1875 merge_ent->dir)->util = merge_ent;1876strbuf_release(&merge_ent->new_dir);1877}else if(tree_has_path(head, head_ent->dir)) {1878/* 2. This wasn't a directory rename after all */1879string_list_append(&remove_from_head,1880 head_ent->dir)->util = head_ent;1881strbuf_release(&head_ent->new_dir);1882}1883}18841885remove_hashmap_entries(dir_re_head, &remove_from_head);1886remove_hashmap_entries(dir_re_merge, &remove_from_merge);18871888hashmap_iter_init(dir_re_merge, &iter);1889while((merge_ent =hashmap_iter_next(&iter))) {1890 head_ent =dir_rename_find_entry(dir_re_head, merge_ent->dir);1891if(tree_has_path(merge, merge_ent->dir)) {1892/* 2. This wasn't a directory rename after all */1893string_list_append(&remove_from_merge,1894 merge_ent->dir)->util = merge_ent;1895}else if(head_ent &&1896!head_ent->non_unique_new_dir &&1897!merge_ent->non_unique_new_dir) {1898/* 3. rename/rename(1to2) */1899/*1900 * We can assume it's not rename/rename(1to1) because1901 * that was case (1), already checked above. So we1902 * know that head_ent->new_dir and merge_ent->new_dir1903 * are different strings.1904 */1905output(o,1,_("CONFLICT (rename/rename): "1906"Rename directory%s->%sin%s. "1907"Rename directory%s->%sin%s"),1908 head_ent->dir, head_ent->new_dir.buf, o->branch1,1909 head_ent->dir, merge_ent->new_dir.buf, o->branch2);1910string_list_append(&remove_from_head,1911 head_ent->dir)->util = head_ent;1912strbuf_release(&head_ent->new_dir);1913string_list_append(&remove_from_merge,1914 merge_ent->dir)->util = merge_ent;1915strbuf_release(&merge_ent->new_dir);1916}1917}19181919remove_hashmap_entries(dir_re_head, &remove_from_head);1920remove_hashmap_entries(dir_re_merge, &remove_from_merge);1921}19221923static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs,1924struct tree *tree)1925{1926struct hashmap *dir_renames;1927struct hashmap_iter iter;1928struct dir_rename_entry *entry;1929int i;19301931/*1932 * Typically, we think of a directory rename as all files from a1933 * certain directory being moved to a target directory. However,1934 * what if someone first moved two files from the original1935 * directory in one commit, and then renamed the directory1936 * somewhere else in a later commit? At merge time, we just know1937 * that files from the original directory went to two different1938 * places, and that the bulk of them ended up in the same place.1939 * We want each directory rename to represent where the bulk of the1940 * files from that directory end up; this function exists to find1941 * where the bulk of the files went.1942 *1943 * The first loop below simply iterates through the list of file1944 * renames, finding out how often each directory rename pair1945 * possibility occurs.1946 */1947 dir_renames =xmalloc(sizeof(*dir_renames));1948dir_rename_init(dir_renames);1949for(i =0; i < pairs->nr; ++i) {1950struct string_list_item *item;1951int*count;1952struct diff_filepair *pair = pairs->queue[i];1953char*old_dir, *new_dir;19541955/* File not part of directory rename if it wasn't renamed */1956if(pair->status !='R')1957continue;19581959get_renamed_dir_portion(pair->one->path, pair->two->path,1960&old_dir, &new_dir);1961if(!old_dir)1962/* Directory didn't change at all; ignore this one. */1963continue;19641965 entry =dir_rename_find_entry(dir_renames, old_dir);1966if(!entry) {1967 entry =xmalloc(sizeof(*entry));1968dir_rename_entry_init(entry, old_dir);1969hashmap_put(dir_renames, entry);1970}else{1971free(old_dir);1972}1973 item =string_list_lookup(&entry->possible_new_dirs, new_dir);1974if(!item) {1975 item =string_list_insert(&entry->possible_new_dirs,1976 new_dir);1977 item->util =xcalloc(1,sizeof(int));1978}else{1979free(new_dir);1980}1981 count = item->util;1982*count +=1;1983}19841985/*1986 * For each directory with files moved out of it, we find out which1987 * target directory received the most files so we can declare it to1988 * be the "winning" target location for the directory rename. This1989 * winner gets recorded in new_dir. If there is no winner1990 * (multiple target directories received the same number of files),1991 * we set non_unique_new_dir. Once we've determined the winner (or1992 * that there is no winner), we no longer need possible_new_dirs.1993 */1994hashmap_iter_init(dir_renames, &iter);1995while((entry =hashmap_iter_next(&iter))) {1996int max =0;1997int bad_max =0;1998char*best = NULL;19992000for(i =0; i < entry->possible_new_dirs.nr; i++) {2001int*count = entry->possible_new_dirs.items[i].util;20022003if(*count == max)2004 bad_max = max;2005else if(*count > max) {2006 max = *count;2007 best = entry->possible_new_dirs.items[i].string;2008}2009}2010if(bad_max == max)2011 entry->non_unique_new_dir =1;2012else{2013assert(entry->new_dir.len ==0);2014strbuf_addstr(&entry->new_dir, best);2015}2016/*2017 * The relevant directory sub-portion of the original full2018 * filepaths were xstrndup'ed before inserting into2019 * possible_new_dirs, and instead of manually iterating the2020 * list and free'ing each, just lie and tell2021 * possible_new_dirs that it did the strdup'ing so that it2022 * will free them for us.2023 */2024 entry->possible_new_dirs.strdup_strings =1;2025string_list_clear(&entry->possible_new_dirs,1);2026}20272028return dir_renames;2029}20302031static struct dir_rename_entry *check_dir_renamed(const char*path,2032struct hashmap *dir_renames)2033{2034char temp[PATH_MAX];2035char*end;2036struct dir_rename_entry *entry;20372038strcpy(temp, path);2039while((end =strrchr(temp,'/'))) {2040*end ='\0';2041 entry =dir_rename_find_entry(dir_renames, temp);2042if(entry)2043return entry;2044}2045return NULL;2046}20472048static voidcompute_collisions(struct hashmap *collisions,2049struct hashmap *dir_renames,2050struct diff_queue_struct *pairs)2051{2052int i;20532054/*2055 * Multiple files can be mapped to the same path due to directory2056 * renames done by the other side of history. Since that other2057 * side of history could have merged multiple directories into one,2058 * if our side of history added the same file basename to each of2059 * those directories, then all N of them would get implicitly2060 * renamed by the directory rename detection into the same path,2061 * and we'd get an add/add/.../add conflict, and all those adds2062 * from *this* side of history. This is not representable in the2063 * index, and users aren't going to easily be able to make sense of2064 * it. So we need to provide a good warning about what's2065 * happening, and fall back to no-directory-rename detection2066 * behavior for those paths.2067 *2068 * See testcases 9e and all of section 5 from t6043 for examples.2069 */2070collision_init(collisions);20712072for(i =0; i < pairs->nr; ++i) {2073struct dir_rename_entry *dir_rename_ent;2074struct collision_entry *collision_ent;2075char*new_path;2076struct diff_filepair *pair = pairs->queue[i];20772078if(pair->status !='A'&& pair->status !='R')2079continue;2080 dir_rename_ent =check_dir_renamed(pair->two->path,2081 dir_renames);2082if(!dir_rename_ent)2083continue;20842085 new_path =apply_dir_rename(dir_rename_ent, pair->two->path);2086if(!new_path)2087/*2088 * dir_rename_ent->non_unique_new_path is true, which2089 * means there is no directory rename for us to use,2090 * which means it won't cause us any additional2091 * collisions.2092 */2093continue;2094 collision_ent =collision_find_entry(collisions, new_path);2095if(!collision_ent) {2096 collision_ent =xcalloc(1,2097sizeof(struct collision_entry));2098hashmap_entry_init(collision_ent,strhash(new_path));2099hashmap_put(collisions, collision_ent);2100 collision_ent->target_file = new_path;2101}else{2102free(new_path);2103}2104string_list_insert(&collision_ent->source_files,2105 pair->two->path);2106}2107}21082109static char*check_for_directory_rename(struct merge_options *o,2110const char*path,2111struct tree *tree,2112struct hashmap *dir_renames,2113struct hashmap *dir_rename_exclusions,2114struct hashmap *collisions,2115int*clean_merge)2116{2117char*new_path = NULL;2118struct dir_rename_entry *entry =check_dir_renamed(path, dir_renames);2119struct dir_rename_entry *oentry = NULL;21202121if(!entry)2122return new_path;21232124/*2125 * This next part is a little weird. We do not want to do an2126 * implicit rename into a directory we renamed on our side, because2127 * that will result in a spurious rename/rename(1to2) conflict. An2128 * example:2129 * Base commit: dumbdir/afile, otherdir/bfile2130 * Side 1: smrtdir/afile, otherdir/bfile2131 * Side 2: dumbdir/afile, dumbdir/bfile2132 * Here, while working on Side 1, we could notice that otherdir was2133 * renamed/merged to dumbdir, and change the diff_filepair for2134 * otherdir/bfile into a rename into dumbdir/bfile. However, Side2135 * 2 will notice the rename from dumbdir to smrtdir, and do the2136 * transitive rename to move it from dumbdir/bfile to2137 * smrtdir/bfile. That gives us bfile in dumbdir vs being in2138 * smrtdir, a rename/rename(1to2) conflict. We really just want2139 * the file to end up in smrtdir. And the way to achieve that is2140 * to not let Side1 do the rename to dumbdir, since we know that is2141 * the source of one of our directory renames.2142 *2143 * That's why oentry and dir_rename_exclusions is here.2144 *2145 * As it turns out, this also prevents N-way transient rename2146 * confusion; See testcases 9c and 9d of t6043.2147 */2148 oentry =dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);2149if(oentry) {2150output(o,1,_("WARNING: Avoiding applying%s->%srename "2151"to%s, because%sitself was renamed."),2152 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);2153}else{2154 new_path =handle_path_level_conflicts(o, path, entry,2155 collisions, tree);2156*clean_merge &= (new_path != NULL);2157}21582159return new_path;2160}21612162static voidapply_directory_rename_modifications(struct merge_options *o,2163struct diff_filepair *pair,2164char*new_path,2165struct rename *re,2166struct tree *tree,2167struct tree *o_tree,2168struct tree *a_tree,2169struct tree *b_tree,2170struct string_list *entries,2171int*clean)2172{2173struct string_list_item *item;2174int stage = (tree == a_tree ?2:3);2175int update_wd;21762177/*2178 * In all cases where we can do directory rename detection,2179 * unpack_trees() will have read pair->two->path into the2180 * index and the working copy. We need to remove it so that2181 * we can instead place it at new_path. It is guaranteed to2182 * not be untracked (unpack_trees() would have errored out2183 * saying the file would have been overwritten), but it might2184 * be dirty, though.2185 */2186 update_wd = !was_dirty(o, pair->two->path);2187if(!update_wd)2188output(o,1,_("Refusing to lose dirty file at%s"),2189 pair->two->path);2190remove_file(o,1, pair->two->path, !update_wd);21912192/* Find or create a new re->dst_entry */2193 item =string_list_lookup(entries, new_path);2194if(item) {2195/*2196 * Since we're renaming on this side of history, and it's2197 * due to a directory rename on the other side of history2198 * (which we only allow when the directory in question no2199 * longer exists on the other side of history), the2200 * original entry for re->dst_entry is no longer2201 * necessary...2202 */2203 re->dst_entry->processed =1;22042205/*2206 * ...because we'll be using this new one.2207 */2208 re->dst_entry = item->util;2209}else{2210/*2211 * re->dst_entry is for the before-dir-rename path, and we2212 * need it to hold information for the after-dir-rename2213 * path. Before creating a new entry, we need to mark the2214 * old one as unnecessary (...unless it is shared by2215 * src_entry, i.e. this didn't use to be a rename, in which2216 * case we can just allow the normal processing to happen2217 * for it).2218 */2219if(pair->status =='R')2220 re->dst_entry->processed =1;22212222 re->dst_entry =insert_stage_data(new_path,2223 o_tree, a_tree, b_tree,2224 entries);2225 item =string_list_insert(entries, new_path);2226 item->util = re->dst_entry;2227}22282229/*2230 * Update the stage_data with the information about the path we are2231 * moving into place. That slot will be empty and available for us2232 * to write to because of the collision checks in2233 * handle_path_level_conflicts(). In other words,2234 * re->dst_entry->stages[stage].oid will be the null_oid, so it's2235 * open for us to write to.2236 *2237 * It may be tempting to actually update the index at this point as2238 * well, using update_stages_for_stage_data(), but as per the big2239 * "NOTE" in update_stages(), doing so will modify the current2240 * in-memory index which will break calls to would_lose_untracked()2241 * that we need to make. Instead, we need to just make sure that2242 * the various conflict_rename_*() functions update the index2243 * explicitly rather than relying on unpack_trees() to have done it.2244 */2245get_tree_entry(&tree->object.oid,2246 pair->two->path,2247&re->dst_entry->stages[stage].oid,2248&re->dst_entry->stages[stage].mode);22492250/* Update pair status */2251if(pair->status =='A') {2252/*2253 * Recording rename information for this add makes it look2254 * like a rename/delete conflict. Make sure we can2255 * correctly handle this as an add that was moved to a new2256 * directory instead of reporting a rename/delete conflict.2257 */2258 re->add_turned_into_rename =1;2259}2260/*2261 * We don't actually look at pair->status again, but it seems2262 * pedagogically correct to adjust it.2263 */2264 pair->status ='R';22652266/*2267 * Finally, record the new location.2268 */2269 pair->two->path = new_path;2270}22712272/*2273 * Get information of all renames which occurred in 'pairs', making use of2274 * any implicit directory renames inferred from the other side of history.2275 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')2276 * to be able to associate the correct cache entries with the rename2277 * information; tree is always equal to either a_tree or b_tree.2278 */2279static struct string_list *get_renames(struct merge_options *o,2280struct diff_queue_struct *pairs,2281struct hashmap *dir_renames,2282struct hashmap *dir_rename_exclusions,2283struct tree *tree,2284struct tree *o_tree,2285struct tree *a_tree,2286struct tree *b_tree,2287struct string_list *entries,2288int*clean_merge)2289{2290int i;2291struct hashmap collisions;2292struct hashmap_iter iter;2293struct collision_entry *e;2294struct string_list *renames;22952296compute_collisions(&collisions, dir_renames, pairs);2297 renames =xcalloc(1,sizeof(struct string_list));22982299for(i =0; i < pairs->nr; ++i) {2300struct string_list_item *item;2301struct rename *re;2302struct diff_filepair *pair = pairs->queue[i];2303char*new_path;/* non-NULL only with directory renames */23042305if(pair->status !='A'&& pair->status !='R') {2306diff_free_filepair(pair);2307continue;2308}2309 new_path =check_for_directory_rename(o, pair->two->path, tree,2310 dir_renames,2311 dir_rename_exclusions,2312&collisions,2313 clean_merge);2314if(pair->status !='R'&& !new_path) {2315diff_free_filepair(pair);2316continue;2317}23182319 re =xmalloc(sizeof(*re));2320 re->processed =0;2321 re->add_turned_into_rename =0;2322 re->pair = pair;2323 item =string_list_lookup(entries, re->pair->one->path);2324if(!item)2325 re->src_entry =insert_stage_data(re->pair->one->path,2326 o_tree, a_tree, b_tree, entries);2327else2328 re->src_entry = item->util;23292330 item =string_list_lookup(entries, re->pair->two->path);2331if(!item)2332 re->dst_entry =insert_stage_data(re->pair->two->path,2333 o_tree, a_tree, b_tree, entries);2334else2335 re->dst_entry = item->util;2336 item =string_list_insert(renames, pair->one->path);2337 item->util = re;2338if(new_path)2339apply_directory_rename_modifications(o, pair, new_path,2340 re, tree, o_tree,2341 a_tree, b_tree,2342 entries,2343 clean_merge);2344}23452346hashmap_iter_init(&collisions, &iter);2347while((e =hashmap_iter_next(&iter))) {2348free(e->target_file);2349string_list_clear(&e->source_files,0);2350}2351hashmap_free(&collisions,1);2352return renames;2353}23542355static intprocess_renames(struct merge_options *o,2356struct string_list *a_renames,2357struct string_list *b_renames)2358{2359int clean_merge =1, i, j;2360struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2361struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2362const struct rename *sre;23632364for(i =0; i < a_renames->nr; i++) {2365 sre = a_renames->items[i].util;2366string_list_insert(&a_by_dst, sre->pair->two->path)->util2367= (void*)sre;2368}2369for(i =0; i < b_renames->nr; i++) {2370 sre = b_renames->items[i].util;2371string_list_insert(&b_by_dst, sre->pair->two->path)->util2372= (void*)sre;2373}23742375for(i =0, j =0; i < a_renames->nr || j < b_renames->nr;) {2376struct string_list *renames1, *renames2Dst;2377struct rename *ren1 = NULL, *ren2 = NULL;2378const char*branch1, *branch2;2379const char*ren1_src, *ren1_dst;2380struct string_list_item *lookup;23812382if(i >= a_renames->nr) {2383 ren2 = b_renames->items[j++].util;2384}else if(j >= b_renames->nr) {2385 ren1 = a_renames->items[i++].util;2386}else{2387int compare =strcmp(a_renames->items[i].string,2388 b_renames->items[j].string);2389if(compare <=0)2390 ren1 = a_renames->items[i++].util;2391if(compare >=0)2392 ren2 = b_renames->items[j++].util;2393}23942395/* TODO: refactor, so that 1/2 are not needed */2396if(ren1) {2397 renames1 = a_renames;2398 renames2Dst = &b_by_dst;2399 branch1 = o->branch1;2400 branch2 = o->branch2;2401}else{2402 renames1 = b_renames;2403 renames2Dst = &a_by_dst;2404 branch1 = o->branch2;2405 branch2 = o->branch1;2406SWAP(ren2, ren1);2407}24082409if(ren1->processed)2410continue;2411 ren1->processed =1;2412 ren1->dst_entry->processed =1;2413/* BUG: We should only mark src_entry as processed if we2414 * are not dealing with a rename + add-source case.2415 */2416 ren1->src_entry->processed =1;24172418 ren1_src = ren1->pair->one->path;2419 ren1_dst = ren1->pair->two->path;24202421if(ren2) {2422/* One file renamed on both sides */2423const char*ren2_src = ren2->pair->one->path;2424const char*ren2_dst = ren2->pair->two->path;2425enum rename_type rename_type;2426if(strcmp(ren1_src, ren2_src) !=0)2427die("BUG: ren1_src != ren2_src");2428 ren2->dst_entry->processed =1;2429 ren2->processed =1;2430if(strcmp(ren1_dst, ren2_dst) !=0) {2431 rename_type = RENAME_ONE_FILE_TO_TWO;2432 clean_merge =0;2433}else{2434 rename_type = RENAME_ONE_FILE_TO_ONE;2435/* BUG: We should only remove ren1_src in2436 * the base stage (think of rename +2437 * add-source cases).2438 */2439remove_file(o,1, ren1_src,1);2440update_entry(ren1->dst_entry,2441 ren1->pair->one,2442 ren1->pair->two,2443 ren2->pair->two);2444}2445setup_rename_conflict_info(rename_type,2446 ren1->pair,2447 ren2->pair,2448 branch1,2449 branch2,2450 ren1->dst_entry,2451 ren2->dst_entry,2452 o,2453 NULL,2454 NULL);2455}else if((lookup =string_list_lookup(renames2Dst, ren1_dst))) {2456/* Two different files renamed to the same thing */2457char*ren2_dst;2458 ren2 = lookup->util;2459 ren2_dst = ren2->pair->two->path;2460if(strcmp(ren1_dst, ren2_dst) !=0)2461die("BUG: ren1_dst != ren2_dst");24622463 clean_merge =0;2464 ren2->processed =1;2465/*2466 * BUG: We should only mark src_entry as processed2467 * if we are not dealing with a rename + add-source2468 * case.2469 */2470 ren2->src_entry->processed =1;24712472setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2473 ren1->pair,2474 ren2->pair,2475 branch1,2476 branch2,2477 ren1->dst_entry,2478 ren2->dst_entry,2479 o,2480 ren1->src_entry,2481 ren2->src_entry);24822483}else{2484/* Renamed in 1, maybe changed in 2 */2485/* we only use sha1 and mode of these */2486struct diff_filespec src_other, dst_other;2487int try_merge;24882489/*2490 * unpack_trees loads entries from common-commit2491 * into stage 1, from head-commit into stage 2, and2492 * from merge-commit into stage 3. We keep track2493 * of which side corresponds to the rename.2494 */2495int renamed_stage = a_renames == renames1 ?2:3;2496int other_stage = a_renames == renames1 ?3:2;24972498/* BUG: We should only remove ren1_src in the base2499 * stage and in other_stage (think of rename +2500 * add-source case).2501 */2502remove_file(o,1, ren1_src,2503 renamed_stage ==2|| !was_tracked(o, ren1_src));25042505oidcpy(&src_other.oid,2506&ren1->src_entry->stages[other_stage].oid);2507 src_other.mode = ren1->src_entry->stages[other_stage].mode;2508oidcpy(&dst_other.oid,2509&ren1->dst_entry->stages[other_stage].oid);2510 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2511 try_merge =0;25122513if(oid_eq(&src_other.oid, &null_oid) &&2514 ren1->add_turned_into_rename) {2515setup_rename_conflict_info(RENAME_DIR,2516 ren1->pair,2517 NULL,2518 branch1,2519 branch2,2520 ren1->dst_entry,2521 NULL,2522 o,2523 NULL,2524 NULL);2525}else if(oid_eq(&src_other.oid, &null_oid)) {2526setup_rename_conflict_info(RENAME_DELETE,2527 ren1->pair,2528 NULL,2529 branch1,2530 branch2,2531 ren1->dst_entry,2532 NULL,2533 o,2534 NULL,2535 NULL);2536}else if((dst_other.mode == ren1->pair->two->mode) &&2537oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {2538/*2539 * Added file on the other side identical to2540 * the file being renamed: clean merge.2541 * Also, there is no need to overwrite the2542 * file already in the working copy, so call2543 * update_file_flags() instead of2544 * update_file().2545 */2546if(update_file_flags(o,2547&ren1->pair->two->oid,2548 ren1->pair->two->mode,2549 ren1_dst,25501,/* update_cache */25510/* update_wd */))2552 clean_merge = -1;2553}else if(!oid_eq(&dst_other.oid, &null_oid)) {2554 clean_merge =0;2555 try_merge =1;2556output(o,1,_("CONFLICT (rename/add): Rename%s->%sin%s. "2557"%sadded in%s"),2558 ren1_src, ren1_dst, branch1,2559 ren1_dst, branch2);2560if(o->call_depth) {2561struct merge_file_info mfi;2562if(merge_file_one(o, ren1_dst, &null_oid,0,2563&ren1->pair->two->oid,2564 ren1->pair->two->mode,2565&dst_other.oid,2566 dst_other.mode,2567 branch1, branch2, &mfi)) {2568 clean_merge = -1;2569goto cleanup_and_return;2570}2571output(o,1,_("Adding merged%s"), ren1_dst);2572if(update_file(o,0, &mfi.oid,2573 mfi.mode, ren1_dst))2574 clean_merge = -1;2575 try_merge =0;2576}else{2577char*new_path =unique_path(o, ren1_dst, branch2);2578output(o,1,_("Adding as%sinstead"), new_path);2579if(update_file(o,0, &dst_other.oid,2580 dst_other.mode, new_path))2581 clean_merge = -1;2582free(new_path);2583}2584}else2585 try_merge =1;25862587if(clean_merge <0)2588goto cleanup_and_return;2589if(try_merge) {2590struct diff_filespec *one, *a, *b;2591 src_other.path = (char*)ren1_src;25922593 one = ren1->pair->one;2594if(a_renames == renames1) {2595 a = ren1->pair->two;2596 b = &src_other;2597}else{2598 b = ren1->pair->two;2599 a = &src_other;2600}2601update_entry(ren1->dst_entry, one, a, b);2602setup_rename_conflict_info(RENAME_NORMAL,2603 ren1->pair,2604 NULL,2605 branch1,2606 NULL,2607 ren1->dst_entry,2608 NULL,2609 o,2610 NULL,2611 NULL);2612}2613}2614}2615cleanup_and_return:2616string_list_clear(&a_by_dst,0);2617string_list_clear(&b_by_dst,0);26182619return clean_merge;2620}26212622struct rename_info {2623struct string_list *head_renames;2624struct string_list *merge_renames;2625};26262627static voidinitial_cleanup_rename(struct diff_queue_struct *pairs,2628struct hashmap *dir_renames)2629{2630struct hashmap_iter iter;2631struct dir_rename_entry *e;26322633hashmap_iter_init(dir_renames, &iter);2634while((e =hashmap_iter_next(&iter))) {2635free(e->dir);2636strbuf_release(&e->new_dir);2637/* possible_new_dirs already cleared in get_directory_renames */2638}2639hashmap_free(dir_renames,1);2640free(dir_renames);26412642free(pairs->queue);2643free(pairs);2644}26452646static inthandle_renames(struct merge_options *o,2647struct tree *common,2648struct tree *head,2649struct tree *merge,2650struct string_list *entries,2651struct rename_info *ri)2652{2653struct diff_queue_struct *head_pairs, *merge_pairs;2654struct hashmap *dir_re_head, *dir_re_merge;2655int clean =1;26562657 ri->head_renames = NULL;2658 ri->merge_renames = NULL;26592660if(!merge_detect_rename(o))2661return1;26622663 head_pairs =get_diffpairs(o, common, head);2664 merge_pairs =get_diffpairs(o, common, merge);26652666 dir_re_head =get_directory_renames(head_pairs, head);2667 dir_re_merge =get_directory_renames(merge_pairs, merge);26682669handle_directory_level_conflicts(o,2670 dir_re_head, head,2671 dir_re_merge, merge);26722673 ri->head_renames =get_renames(o, head_pairs,2674 dir_re_merge, dir_re_head, head,2675 common, head, merge, entries,2676&clean);2677if(clean <0)2678goto cleanup;2679 ri->merge_renames =get_renames(o, merge_pairs,2680 dir_re_head, dir_re_merge, merge,2681 common, head, merge, entries,2682&clean);2683if(clean <0)2684goto cleanup;2685 clean &=process_renames(o, ri->head_renames, ri->merge_renames);26862687cleanup:2688/*2689 * Some cleanup is deferred until cleanup_renames() because the2690 * data structures are still needed and referenced in2691 * process_entry(). But there are a few things we can free now.2692 */2693initial_cleanup_rename(head_pairs, dir_re_head);2694initial_cleanup_rename(merge_pairs, dir_re_merge);26952696return clean;2697}26982699static voidfinal_cleanup_rename(struct string_list *rename)2700{2701const struct rename *re;2702int i;27032704if(rename == NULL)2705return;27062707for(i =0; i < rename->nr; i++) {2708 re = rename->items[i].util;2709diff_free_filepair(re->pair);2710}2711string_list_clear(rename,1);2712free(rename);2713}27142715static voidfinal_cleanup_renames(struct rename_info *re_info)2716{2717final_cleanup_rename(re_info->head_renames);2718final_cleanup_rename(re_info->merge_renames);2719}27202721static struct object_id *stage_oid(const struct object_id *oid,unsigned mode)2722{2723return(is_null_oid(oid) || mode ==0) ? NULL: (struct object_id *)oid;2724}27252726static intread_oid_strbuf(struct merge_options *o,2727const struct object_id *oid,struct strbuf *dst)2728{2729void*buf;2730enum object_type type;2731unsigned long size;2732 buf =read_object_file(oid, &type, &size);2733if(!buf)2734returnerr(o,_("cannot read object%s"),oid_to_hex(oid));2735if(type != OBJ_BLOB) {2736free(buf);2737returnerr(o,_("object%sis not a blob"),oid_to_hex(oid));2738}2739strbuf_attach(dst, buf, size, size +1);2740return0;2741}27422743static intblob_unchanged(struct merge_options *opt,2744const struct object_id *o_oid,2745unsigned o_mode,2746const struct object_id *a_oid,2747unsigned a_mode,2748int renormalize,const char*path)2749{2750struct strbuf o = STRBUF_INIT;2751struct strbuf a = STRBUF_INIT;2752int ret =0;/* assume changed for safety */27532754if(a_mode != o_mode)2755return0;2756if(oid_eq(o_oid, a_oid))2757return1;2758if(!renormalize)2759return0;27602761assert(o_oid && a_oid);2762if(read_oid_strbuf(opt, o_oid, &o) ||read_oid_strbuf(opt, a_oid, &a))2763goto error_return;2764/*2765 * Note: binary | is used so that both renormalizations are2766 * performed. Comparison can be skipped if both files are2767 * unchanged since their sha1s have already been compared.2768 */2769if(renormalize_buffer(&the_index, path, o.buf, o.len, &o) |2770renormalize_buffer(&the_index, path, a.buf, a.len, &a))2771 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));27722773error_return:2774strbuf_release(&o);2775strbuf_release(&a);2776return ret;2777}27782779static inthandle_modify_delete(struct merge_options *o,2780const char*path,2781struct object_id *o_oid,int o_mode,2782struct object_id *a_oid,int a_mode,2783struct object_id *b_oid,int b_mode)2784{2785const char*modify_branch, *delete_branch;2786struct object_id *changed_oid;2787int changed_mode;27882789if(a_oid) {2790 modify_branch = o->branch1;2791 delete_branch = o->branch2;2792 changed_oid = a_oid;2793 changed_mode = a_mode;2794}else{2795 modify_branch = o->branch2;2796 delete_branch = o->branch1;2797 changed_oid = b_oid;2798 changed_mode = b_mode;2799}28002801returnhandle_change_delete(o,2802 path, NULL,2803 o_oid, o_mode,2804 changed_oid, changed_mode,2805 modify_branch, delete_branch,2806_("modify"),_("modified"));2807}28082809static intmerge_content(struct merge_options *o,2810const char*path,2811int is_dirty,2812struct object_id *o_oid,int o_mode,2813struct object_id *a_oid,int a_mode,2814struct object_id *b_oid,int b_mode,2815struct rename_conflict_info *rename_conflict_info)2816{2817const char*reason =_("content");2818const char*path1 = NULL, *path2 = NULL;2819struct merge_file_info mfi;2820struct diff_filespec one, a, b;2821unsigned df_conflict_remains =0;28222823if(!o_oid) {2824 reason =_("add/add");2825 o_oid = (struct object_id *)&null_oid;2826}2827 one.path = a.path = b.path = (char*)path;2828oidcpy(&one.oid, o_oid);2829 one.mode = o_mode;2830oidcpy(&a.oid, a_oid);2831 a.mode = a_mode;2832oidcpy(&b.oid, b_oid);2833 b.mode = b_mode;28342835if(rename_conflict_info) {2836struct diff_filepair *pair1 = rename_conflict_info->pair1;28372838 path1 = (o->branch1 == rename_conflict_info->branch1) ?2839 pair1->two->path : pair1->one->path;2840/* If rename_conflict_info->pair2 != NULL, we are in2841 * RENAME_ONE_FILE_TO_ONE case. Otherwise, we have a2842 * normal rename.2843 */2844 path2 = (rename_conflict_info->pair2 ||2845 o->branch2 == rename_conflict_info->branch1) ?2846 pair1->two->path : pair1->one->path;28472848if(dir_in_way(path, !o->call_depth,2849S_ISGITLINK(pair1->two->mode)))2850 df_conflict_remains =1;2851}2852if(merge_file_special_markers(o, &one, &a, &b, path,2853 o->branch1, path1,2854 o->branch2, path2, &mfi))2855return-1;28562857/*2858 * We can skip updating the working tree file iff:2859 * a) The merge is clean2860 * b) The merge matches what was in HEAD (content, mode, pathname)2861 * c) The target path is usable (i.e. not involved in D/F conflict)2862 */2863if(mfi.clean &&2864was_tracked_and_matches(o, path, &mfi.oid, mfi.mode) &&2865!df_conflict_remains) {2866output(o,3,_("Skipped%s(merged same as existing)"), path);2867if(add_cacheinfo(o, mfi.mode, &mfi.oid, path,28680, (!o->call_depth && !is_dirty),0))2869return-1;2870return mfi.clean;2871}28722873if(!mfi.clean) {2874if(S_ISGITLINK(mfi.mode))2875 reason =_("submodule");2876output(o,1,_("CONFLICT (%s): Merge conflict in%s"),2877 reason, path);2878if(rename_conflict_info && !df_conflict_remains)2879if(update_stages(o, path, &one, &a, &b))2880return-1;2881}28822883if(df_conflict_remains || is_dirty) {2884char*new_path;2885if(o->call_depth) {2886remove_file_from_cache(path);2887}else{2888if(!mfi.clean) {2889if(update_stages(o, path, &one, &a, &b))2890return-1;2891}else{2892int file_from_stage2 =was_tracked(o, path);2893struct diff_filespec merged;2894oidcpy(&merged.oid, &mfi.oid);2895 merged.mode = mfi.mode;28962897if(update_stages(o, path, NULL,2898 file_from_stage2 ? &merged : NULL,2899 file_from_stage2 ? NULL : &merged))2900return-1;2901}29022903}2904 new_path =unique_path(o, path, rename_conflict_info->branch1);2905if(is_dirty) {2906output(o,1,_("Refusing to lose dirty file at%s"),2907 path);2908}2909output(o,1,_("Adding as%sinstead"), new_path);2910if(update_file(o,0, &mfi.oid, mfi.mode, new_path)) {2911free(new_path);2912return-1;2913}2914free(new_path);2915 mfi.clean =0;2916}else if(update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))2917return-1;2918return!is_dirty && mfi.clean;2919}29202921static intconflict_rename_normal(struct merge_options *o,2922const char*path,2923struct object_id *o_oid,unsigned int o_mode,2924struct object_id *a_oid,unsigned int a_mode,2925struct object_id *b_oid,unsigned int b_mode,2926struct rename_conflict_info *ci)2927{2928/* Merge the content and write it out */2929returnmerge_content(o, path,was_dirty(o, path),2930 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,2931 ci);2932}29332934/* Per entry merge function */2935static intprocess_entry(struct merge_options *o,2936const char*path,struct stage_data *entry)2937{2938int clean_merge =1;2939int normalize = o->renormalize;2940unsigned o_mode = entry->stages[1].mode;2941unsigned a_mode = entry->stages[2].mode;2942unsigned b_mode = entry->stages[3].mode;2943struct object_id *o_oid =stage_oid(&entry->stages[1].oid, o_mode);2944struct object_id *a_oid =stage_oid(&entry->stages[2].oid, a_mode);2945struct object_id *b_oid =stage_oid(&entry->stages[3].oid, b_mode);29462947 entry->processed =1;2948if(entry->rename_conflict_info) {2949struct rename_conflict_info *conflict_info = entry->rename_conflict_info;2950switch(conflict_info->rename_type) {2951case RENAME_NORMAL:2952case RENAME_ONE_FILE_TO_ONE:2953 clean_merge =conflict_rename_normal(o,2954 path,2955 o_oid, o_mode,2956 a_oid, a_mode,2957 b_oid, b_mode,2958 conflict_info);2959break;2960case RENAME_DIR:2961 clean_merge =1;2962if(conflict_rename_dir(o,2963 conflict_info->pair1,2964 conflict_info->branch1,2965 conflict_info->branch2))2966 clean_merge = -1;2967break;2968case RENAME_DELETE:2969 clean_merge =0;2970if(conflict_rename_delete(o,2971 conflict_info->pair1,2972 conflict_info->branch1,2973 conflict_info->branch2))2974 clean_merge = -1;2975break;2976case RENAME_ONE_FILE_TO_TWO:2977 clean_merge =0;2978if(conflict_rename_rename_1to2(o, conflict_info))2979 clean_merge = -1;2980break;2981case RENAME_TWO_FILES_TO_ONE:2982 clean_merge =0;2983if(conflict_rename_rename_2to1(o, conflict_info))2984 clean_merge = -1;2985break;2986default:2987 entry->processed =0;2988break;2989}2990}else if(o_oid && (!a_oid || !b_oid)) {2991/* Case A: Deleted in one */2992if((!a_oid && !b_oid) ||2993(!b_oid &&blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||2994(!a_oid &&blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {2995/* Deleted in both or deleted in one and2996 * unchanged in the other */2997if(a_oid)2998output(o,2,_("Removing%s"), path);2999/* do not touch working file if it did not exist */3000remove_file(o,1, path, !a_oid);3001}else{3002/* Modify/delete; deleted side may have put a directory in the way */3003 clean_merge =0;3004if(handle_modify_delete(o, path, o_oid, o_mode,3005 a_oid, a_mode, b_oid, b_mode))3006 clean_merge = -1;3007}3008}else if((!o_oid && a_oid && !b_oid) ||3009(!o_oid && !a_oid && b_oid)) {3010/* Case B: Added in one. */3011/* [nothing|directory] -> ([nothing|directory], file) */30123013const char*add_branch;3014const char*other_branch;3015unsigned mode;3016const struct object_id *oid;3017const char*conf;30183019if(a_oid) {3020 add_branch = o->branch1;3021 other_branch = o->branch2;3022 mode = a_mode;3023 oid = a_oid;3024 conf =_("file/directory");3025}else{3026 add_branch = o->branch2;3027 other_branch = o->branch1;3028 mode = b_mode;3029 oid = b_oid;3030 conf =_("directory/file");3031}3032if(dir_in_way(path,3033!o->call_depth && !S_ISGITLINK(a_mode),30340)) {3035char*new_path =unique_path(o, path, add_branch);3036 clean_merge =0;3037output(o,1,_("CONFLICT (%s): There is a directory with name%sin%s. "3038"Adding%sas%s"),3039 conf, path, other_branch, path, new_path);3040if(update_file(o,0, oid, mode, new_path))3041 clean_merge = -1;3042else if(o->call_depth)3043remove_file_from_cache(path);3044free(new_path);3045}else{3046output(o,2,_("Adding%s"), path);3047/* do not overwrite file if already present */3048if(update_file_flags(o, oid, mode, path,1, !a_oid))3049 clean_merge = -1;3050}3051}else if(a_oid && b_oid) {3052/* Case C: Added in both (check for same permissions) and */3053/* case D: Modified in both, but differently. */3054int is_dirty =0;/* unpack_trees would have bailed if dirty */3055 clean_merge =merge_content(o, path, is_dirty,3056 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,3057 NULL);3058}else if(!o_oid && !a_oid && !b_oid) {3059/*3060 * this entry was deleted altogether. a_mode == 0 means3061 * we had that path and want to actively remove it.3062 */3063remove_file(o,1, path, !a_mode);3064}else3065die("BUG: fatal merge failure, shouldn't happen.");30663067return clean_merge;3068}30693070intmerge_trees(struct merge_options *o,3071struct tree *head,3072struct tree *merge,3073struct tree *common,3074struct tree **result)3075{3076int code, clean;30773078if(o->subtree_shift) {3079 merge =shift_tree_object(head, merge, o->subtree_shift);3080 common =shift_tree_object(head, common, o->subtree_shift);3081}30823083if(oid_eq(&common->object.oid, &merge->object.oid)) {3084struct strbuf sb = STRBUF_INIT;30853086if(!o->call_depth &&index_has_changes(&sb)) {3087err(o,_("Dirty index: cannot merge (dirty:%s)"),3088 sb.buf);3089return0;3090}3091output(o,0,_("Already up to date!"));3092*result = head;3093return1;3094}30953096 code =unpack_trees_start(o, common, head, merge);30973098if(code !=0) {3099if(show(o,4) || o->call_depth)3100err(o,_("merging of trees%sand%sfailed"),3101oid_to_hex(&head->object.oid),3102oid_to_hex(&merge->object.oid));3103unpack_trees_finish(o);3104return-1;3105}31063107if(unmerged_cache()) {3108struct string_list *entries;3109struct rename_info re_info;3110int i;3111/*3112 * Only need the hashmap while processing entries, so3113 * initialize it here and free it when we are done running3114 * through the entries. Keeping it in the merge_options as3115 * opposed to decaring a local hashmap is for convenience3116 * so that we don't have to pass it to around.3117 */3118hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL,512);3119get_files_dirs(o, head);3120get_files_dirs(o, merge);31213122 entries =get_unmerged();3123 clean =handle_renames(o, common, head, merge, entries,3124&re_info);3125record_df_conflict_files(o, entries);3126if(clean <0)3127goto cleanup;3128for(i = entries->nr-1;0<= i; i--) {3129const char*path = entries->items[i].string;3130struct stage_data *e = entries->items[i].util;3131if(!e->processed) {3132int ret =process_entry(o, path, e);3133if(!ret)3134 clean =0;3135else if(ret <0) {3136 clean = ret;3137goto cleanup;3138}3139}3140}3141for(i =0; i < entries->nr; i++) {3142struct stage_data *e = entries->items[i].util;3143if(!e->processed)3144die("BUG: unprocessed path???%s",3145 entries->items[i].string);3146}31473148cleanup:3149final_cleanup_renames(&re_info);31503151string_list_clear(entries,1);3152free(entries);31533154hashmap_free(&o->current_file_dir_set,1);31553156if(clean <0) {3157unpack_trees_finish(o);3158return clean;3159}3160}3161else3162 clean =1;31633164unpack_trees_finish(o);31653166if(o->call_depth && !(*result =write_tree_from_memory(o)))3167return-1;31683169return clean;3170}31713172static struct commit_list *reverse_commit_list(struct commit_list *list)3173{3174struct commit_list *next = NULL, *current, *backup;3175for(current = list; current; current = backup) {3176 backup = current->next;3177 current->next = next;3178 next = current;3179}3180return next;3181}31823183/*3184 * Merge the commits h1 and h2, return the resulting virtual3185 * commit object and a flag indicating the cleanness of the merge.3186 */3187intmerge_recursive(struct merge_options *o,3188struct commit *h1,3189struct commit *h2,3190struct commit_list *ca,3191struct commit **result)3192{3193struct commit_list *iter;3194struct commit *merged_common_ancestors;3195struct tree *mrtree;3196int clean;31973198if(show(o,4)) {3199output(o,4,_("Merging:"));3200output_commit_title(o, h1);3201output_commit_title(o, h2);3202}32033204if(!ca) {3205 ca =get_merge_bases(h1, h2);3206 ca =reverse_commit_list(ca);3207}32083209if(show(o,5)) {3210unsigned cnt =commit_list_count(ca);32113212output(o,5,Q_("found%ucommon ancestor:",3213"found%ucommon ancestors:", cnt), cnt);3214for(iter = ca; iter; iter = iter->next)3215output_commit_title(o, iter->item);3216}32173218 merged_common_ancestors =pop_commit(&ca);3219if(merged_common_ancestors == NULL) {3220/* if there is no common ancestor, use an empty tree */3221struct tree *tree;32223223 tree =lookup_tree(the_hash_algo->empty_tree);3224 merged_common_ancestors =make_virtual_commit(tree,"ancestor");3225}32263227for(iter = ca; iter; iter = iter->next) {3228const char*saved_b1, *saved_b2;3229 o->call_depth++;3230/*3231 * When the merge fails, the result contains files3232 * with conflict markers. The cleanness flag is3233 * ignored (unless indicating an error), it was never3234 * actually used, as result of merge_trees has always3235 * overwritten it: the committed "conflicts" were3236 * already resolved.3237 */3238discard_cache();3239 saved_b1 = o->branch1;3240 saved_b2 = o->branch2;3241 o->branch1 ="Temporary merge branch 1";3242 o->branch2 ="Temporary merge branch 2";3243if(merge_recursive(o, merged_common_ancestors, iter->item,3244 NULL, &merged_common_ancestors) <0)3245return-1;3246 o->branch1 = saved_b1;3247 o->branch2 = saved_b2;3248 o->call_depth--;32493250if(!merged_common_ancestors)3251returnerr(o,_("merge returned no commit"));3252}32533254discard_cache();3255if(!o->call_depth)3256read_cache();32573258 o->ancestor ="merged common ancestors";3259 clean =merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,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}