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); 385clear_unpack_trees_porcelain(&o->unpack_opts); 386} 387 388struct tree *write_tree_from_memory(struct merge_options *o) 389{ 390struct tree *result = NULL; 391 392if(unmerged_cache()) { 393int i; 394fprintf(stderr,"BUG: There are unmerged index entries:\n"); 395for(i =0; i < active_nr; i++) { 396const struct cache_entry *ce = active_cache[i]; 397if(ce_stage(ce)) 398fprintf(stderr,"BUG:%d%.*s\n",ce_stage(ce), 399(int)ce_namelen(ce), ce->name); 400} 401die("BUG: unmerged index entries in merge-recursive.c"); 402} 403 404if(!active_cache_tree) 405 active_cache_tree =cache_tree(); 406 407if(!cache_tree_fully_valid(active_cache_tree) && 408cache_tree_update(&the_index,0) <0) { 409err(o,_("error building trees")); 410return NULL; 411} 412 413 result =lookup_tree(&active_cache_tree->oid); 414 415return result; 416} 417 418static intsave_files_dirs(const struct object_id *oid, 419struct strbuf *base,const char*path, 420unsigned int mode,int stage,void*context) 421{ 422struct path_hashmap_entry *entry; 423int baselen = base->len; 424struct merge_options *o = context; 425 426strbuf_addstr(base, path); 427 428FLEX_ALLOC_MEM(entry, path, base->buf, base->len); 429hashmap_entry_init(entry,path_hash(entry->path)); 430hashmap_add(&o->current_file_dir_set, entry); 431 432strbuf_setlen(base, baselen); 433return(S_ISDIR(mode) ? READ_TREE_RECURSIVE :0); 434} 435 436static voidget_files_dirs(struct merge_options *o,struct tree *tree) 437{ 438struct pathspec match_all; 439memset(&match_all,0,sizeof(match_all)); 440read_tree_recursive(tree,"",0,0, &match_all, save_files_dirs, o); 441} 442 443static intget_tree_entry_if_blob(const struct object_id *tree, 444const char*path, 445struct object_id *hashy, 446unsigned int*mode_o) 447{ 448int ret; 449 450 ret =get_tree_entry(tree, path, hashy, mode_o); 451if(S_ISDIR(*mode_o)) { 452oidcpy(hashy, &null_oid); 453*mode_o =0; 454} 455return ret; 456} 457 458/* 459 * Returns an index_entry instance which doesn't have to correspond to 460 * a real cache entry in Git's index. 461 */ 462static struct stage_data *insert_stage_data(const char*path, 463struct tree *o,struct tree *a,struct tree *b, 464struct string_list *entries) 465{ 466struct string_list_item *item; 467struct stage_data *e =xcalloc(1,sizeof(struct stage_data)); 468get_tree_entry_if_blob(&o->object.oid, path, 469&e->stages[1].oid, &e->stages[1].mode); 470get_tree_entry_if_blob(&a->object.oid, path, 471&e->stages[2].oid, &e->stages[2].mode); 472get_tree_entry_if_blob(&b->object.oid, path, 473&e->stages[3].oid, &e->stages[3].mode); 474 item =string_list_insert(entries, path); 475 item->util = e; 476return e; 477} 478 479/* 480 * Create a dictionary mapping file names to stage_data objects. The 481 * dictionary contains one entry for every path with a non-zero stage entry. 482 */ 483static struct string_list *get_unmerged(void) 484{ 485struct string_list *unmerged =xcalloc(1,sizeof(struct string_list)); 486int i; 487 488 unmerged->strdup_strings =1; 489 490for(i =0; i < active_nr; i++) { 491struct string_list_item *item; 492struct stage_data *e; 493const struct cache_entry *ce = active_cache[i]; 494if(!ce_stage(ce)) 495continue; 496 497 item =string_list_lookup(unmerged, ce->name); 498if(!item) { 499 item =string_list_insert(unmerged, ce->name); 500 item->util =xcalloc(1,sizeof(struct stage_data)); 501} 502 e = item->util; 503 e->stages[ce_stage(ce)].mode = ce->ce_mode; 504oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid); 505} 506 507return unmerged; 508} 509 510static intstring_list_df_name_compare(const char*one,const char*two) 511{ 512int onelen =strlen(one); 513int twolen =strlen(two); 514/* 515 * Here we only care that entries for D/F conflicts are 516 * adjacent, in particular with the file of the D/F conflict 517 * appearing before files below the corresponding directory. 518 * The order of the rest of the list is irrelevant for us. 519 * 520 * To achieve this, we sort with df_name_compare and provide 521 * the mode S_IFDIR so that D/F conflicts will sort correctly. 522 * We use the mode S_IFDIR for everything else for simplicity, 523 * since in other cases any changes in their order due to 524 * sorting cause no problems for us. 525 */ 526int cmp =df_name_compare(one, onelen, S_IFDIR, 527 two, twolen, S_IFDIR); 528/* 529 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure 530 * that 'foo' comes before 'foo/bar'. 531 */ 532if(cmp) 533return cmp; 534return onelen - twolen; 535} 536 537static voidrecord_df_conflict_files(struct merge_options *o, 538struct string_list *entries) 539{ 540/* If there is a D/F conflict and the file for such a conflict 541 * currently exist in the working tree, we want to allow it to be 542 * removed to make room for the corresponding directory if needed. 543 * The files underneath the directories of such D/F conflicts will 544 * be processed before the corresponding file involved in the D/F 545 * conflict. If the D/F directory ends up being removed by the 546 * merge, then we won't have to touch the D/F file. If the D/F 547 * directory needs to be written to the working copy, then the D/F 548 * file will simply be removed (in make_room_for_path()) to make 549 * room for the necessary paths. Note that if both the directory 550 * and the file need to be present, then the D/F file will be 551 * reinstated with a new unique name at the time it is processed. 552 */ 553struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP; 554const char*last_file = NULL; 555int last_len =0; 556int i; 557 558/* 559 * If we're merging merge-bases, we don't want to bother with 560 * any working directory changes. 561 */ 562if(o->call_depth) 563return; 564 565/* Ensure D/F conflicts are adjacent in the entries list. */ 566for(i =0; i < entries->nr; i++) { 567struct string_list_item *next = &entries->items[i]; 568string_list_append(&df_sorted_entries, next->string)->util = 569 next->util; 570} 571 df_sorted_entries.cmp = string_list_df_name_compare; 572string_list_sort(&df_sorted_entries); 573 574string_list_clear(&o->df_conflict_file_set,1); 575for(i =0; i < df_sorted_entries.nr; i++) { 576const char*path = df_sorted_entries.items[i].string; 577int len =strlen(path); 578struct stage_data *e = df_sorted_entries.items[i].util; 579 580/* 581 * Check if last_file & path correspond to a D/F conflict; 582 * i.e. whether path is last_file+'/'+<something>. 583 * If so, record that it's okay to remove last_file to make 584 * room for path and friends if needed. 585 */ 586if(last_file && 587 len > last_len && 588memcmp(path, last_file, last_len) ==0&& 589 path[last_len] =='/') { 590string_list_insert(&o->df_conflict_file_set, last_file); 591} 592 593/* 594 * Determine whether path could exist as a file in the 595 * working directory as a possible D/F conflict. This 596 * will only occur when it exists in stage 2 as a 597 * file. 598 */ 599if(S_ISREG(e->stages[2].mode) ||S_ISLNK(e->stages[2].mode)) { 600 last_file = path; 601 last_len = len; 602}else{ 603 last_file = NULL; 604} 605} 606string_list_clear(&df_sorted_entries,0); 607} 608 609struct rename { 610struct diff_filepair *pair; 611/* 612 * Purpose of src_entry and dst_entry: 613 * 614 * If 'before' is renamed to 'after' then src_entry will contain 615 * the versions of 'before' from the merge_base, HEAD, and MERGE in 616 * stages 1, 2, and 3; dst_entry will contain the respective 617 * versions of 'after' in corresponding locations. Thus, we have a 618 * total of six modes and oids, though some will be null. (Stage 0 619 * is ignored; we're interested in handling conflicts.) 620 * 621 * Since we don't turn on break-rewrites by default, neither 622 * src_entry nor dst_entry can have all three of their stages have 623 * non-null oids, meaning at most four of the six will be non-null. 624 * Also, since this is a rename, both src_entry and dst_entry will 625 * have at least one non-null oid, meaning at least two will be 626 * non-null. Of the six oids, a typical rename will have three be 627 * non-null. Only two implies a rename/delete, and four implies a 628 * rename/add. 629 */ 630struct stage_data *src_entry; 631struct stage_data *dst_entry; 632unsigned add_turned_into_rename:1; 633unsigned processed:1; 634}; 635 636static intupdate_stages(struct merge_options *opt,const char*path, 637const struct diff_filespec *o, 638const struct diff_filespec *a, 639const struct diff_filespec *b) 640{ 641 642/* 643 * NOTE: It is usually a bad idea to call update_stages on a path 644 * before calling update_file on that same path, since it can 645 * sometimes lead to spurious "refusing to lose untracked file..." 646 * messages from update_file (via make_room_for path via 647 * would_lose_untracked). Instead, reverse the order of the calls 648 * (executing update_file first and then update_stages). 649 */ 650int clear =1; 651int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK; 652if(clear) 653if(remove_file_from_cache(path)) 654return-1; 655if(o) 656if(add_cacheinfo(opt, o->mode, &o->oid, path,1,0, options)) 657return-1; 658if(a) 659if(add_cacheinfo(opt, a->mode, &a->oid, path,2,0, options)) 660return-1; 661if(b) 662if(add_cacheinfo(opt, b->mode, &b->oid, path,3,0, options)) 663return-1; 664return0; 665} 666 667static intupdate_stages_for_stage_data(struct merge_options *opt, 668const char*path, 669const struct stage_data *stage_data) 670{ 671struct diff_filespec o, a, b; 672 673 o.mode = stage_data->stages[1].mode; 674oidcpy(&o.oid, &stage_data->stages[1].oid); 675 676 a.mode = stage_data->stages[2].mode; 677oidcpy(&a.oid, &stage_data->stages[2].oid); 678 679 b.mode = stage_data->stages[3].mode; 680oidcpy(&b.oid, &stage_data->stages[3].oid); 681 682returnupdate_stages(opt, path, 683is_null_oid(&o.oid) ? NULL : &o, 684is_null_oid(&a.oid) ? NULL : &a, 685is_null_oid(&b.oid) ? NULL : &b); 686} 687 688static voidupdate_entry(struct stage_data *entry, 689struct diff_filespec *o, 690struct diff_filespec *a, 691struct diff_filespec *b) 692{ 693 entry->processed =0; 694 entry->stages[1].mode = o->mode; 695 entry->stages[2].mode = a->mode; 696 entry->stages[3].mode = b->mode; 697oidcpy(&entry->stages[1].oid, &o->oid); 698oidcpy(&entry->stages[2].oid, &a->oid); 699oidcpy(&entry->stages[3].oid, &b->oid); 700} 701 702static intremove_file(struct merge_options *o,int clean, 703const char*path,int no_wd) 704{ 705int update_cache = o->call_depth || clean; 706int update_working_directory = !o->call_depth && !no_wd; 707 708if(update_cache) { 709if(remove_file_from_cache(path)) 710return-1; 711} 712if(update_working_directory) { 713if(ignore_case) { 714struct cache_entry *ce; 715 ce =cache_file_exists(path,strlen(path), ignore_case); 716if(ce &&ce_stage(ce) ==0&&strcmp(path, ce->name)) 717return0; 718} 719if(remove_path(path)) 720return-1; 721} 722return0; 723} 724 725/* add a string to a strbuf, but converting "/" to "_" */ 726static voidadd_flattened_path(struct strbuf *out,const char*s) 727{ 728size_t i = out->len; 729strbuf_addstr(out, s); 730for(; i < out->len; i++) 731if(out->buf[i] =='/') 732 out->buf[i] ='_'; 733} 734 735static char*unique_path(struct merge_options *o,const char*path,const char*branch) 736{ 737struct path_hashmap_entry *entry; 738struct strbuf newpath = STRBUF_INIT; 739int suffix =0; 740size_t base_len; 741 742strbuf_addf(&newpath,"%s~", path); 743add_flattened_path(&newpath, branch); 744 745 base_len = newpath.len; 746while(hashmap_get_from_hash(&o->current_file_dir_set, 747path_hash(newpath.buf), newpath.buf) || 748(!o->call_depth &&file_exists(newpath.buf))) { 749strbuf_setlen(&newpath, base_len); 750strbuf_addf(&newpath,"_%d", suffix++); 751} 752 753FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len); 754hashmap_entry_init(entry,path_hash(entry->path)); 755hashmap_add(&o->current_file_dir_set, entry); 756returnstrbuf_detach(&newpath, NULL); 757} 758 759/** 760 * Check whether a directory in the index is in the way of an incoming 761 * file. Return 1 if so. If check_working_copy is non-zero, also 762 * check the working directory. If empty_ok is non-zero, also return 763 * 0 in the case where the working-tree dir exists but is empty. 764 */ 765static intdir_in_way(const char*path,int check_working_copy,int empty_ok) 766{ 767int pos; 768struct strbuf dirpath = STRBUF_INIT; 769struct stat st; 770 771strbuf_addstr(&dirpath, path); 772strbuf_addch(&dirpath,'/'); 773 774 pos =cache_name_pos(dirpath.buf, dirpath.len); 775 776if(pos <0) 777 pos = -1- pos; 778if(pos < active_nr && 779!strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) { 780strbuf_release(&dirpath); 781return1; 782} 783 784strbuf_release(&dirpath); 785return check_working_copy && !lstat(path, &st) &&S_ISDIR(st.st_mode) && 786!(empty_ok &&is_empty_dir(path)); 787} 788 789/* 790 * Returns whether path was tracked in the index before the merge started, 791 * and its oid and mode match the specified values 792 */ 793static intwas_tracked_and_matches(struct merge_options *o,const char*path, 794const struct object_id *oid,unsigned mode) 795{ 796int pos =index_name_pos(&o->orig_index, path,strlen(path)); 797struct cache_entry *ce; 798 799if(0> pos) 800/* we were not tracking this path before the merge */ 801return0; 802 803/* See if the file we were tracking before matches */ 804 ce = o->orig_index.cache[pos]; 805return(oid_eq(&ce->oid, oid) && ce->ce_mode == mode); 806} 807 808/* 809 * Returns whether path was tracked in the index before the merge started 810 */ 811static intwas_tracked(struct merge_options *o,const char*path) 812{ 813int pos =index_name_pos(&o->orig_index, path,strlen(path)); 814 815if(0<= pos) 816/* we were tracking this path before the merge */ 817return1; 818 819return0; 820} 821 822static intwould_lose_untracked(const char*path) 823{ 824/* 825 * This may look like it can be simplified to: 826 * return !was_tracked(o, path) && file_exists(path) 827 * but it can't. This function needs to know whether path was in 828 * the working tree due to EITHER having been tracked in the index 829 * before the merge OR having been put into the working copy and 830 * index by unpack_trees(). Due to that either-or requirement, we 831 * check the current index instead of the original one. 832 * 833 * Note that we do not need to worry about merge-recursive itself 834 * updating the index after unpack_trees() and before calling this 835 * function, because we strictly require all code paths in 836 * merge-recursive to update the working tree first and the index 837 * second. Doing otherwise would break 838 * update_file()/would_lose_untracked(); see every comment in this 839 * file which mentions "update_stages". 840 */ 841int pos =cache_name_pos(path,strlen(path)); 842 843if(pos <0) 844 pos = -1- pos; 845while(pos < active_nr && 846!strcmp(path, active_cache[pos]->name)) { 847/* 848 * If stage #0, it is definitely tracked. 849 * If it has stage #2 then it was tracked 850 * before this merge started. All other 851 * cases the path was not tracked. 852 */ 853switch(ce_stage(active_cache[pos])) { 854case0: 855case2: 856return0; 857} 858 pos++; 859} 860returnfile_exists(path); 861} 862 863static intwas_dirty(struct merge_options *o,const char*path) 864{ 865struct cache_entry *ce; 866int dirty =1; 867 868if(o->call_depth || !was_tracked(o, path)) 869return!dirty; 870 871 ce =index_file_exists(o->unpack_opts.src_index, 872 path,strlen(path), ignore_case); 873 dirty =verify_uptodate(ce, &o->unpack_opts) !=0; 874return dirty; 875} 876 877static intmake_room_for_path(struct merge_options *o,const char*path) 878{ 879int status, i; 880const char*msg =_("failed to create path '%s'%s"); 881 882/* Unlink any D/F conflict files that are in the way */ 883for(i =0; i < o->df_conflict_file_set.nr; i++) { 884const char*df_path = o->df_conflict_file_set.items[i].string; 885size_t pathlen =strlen(path); 886size_t df_pathlen =strlen(df_path); 887if(df_pathlen < pathlen && 888 path[df_pathlen] =='/'&& 889strncmp(path, df_path, df_pathlen) ==0) { 890output(o,3, 891_("Removing%sto make room for subdirectory\n"), 892 df_path); 893unlink(df_path); 894unsorted_string_list_delete_item(&o->df_conflict_file_set, 895 i,0); 896break; 897} 898} 899 900/* Make sure leading directories are created */ 901 status =safe_create_leading_directories_const(path); 902if(status) { 903if(status == SCLD_EXISTS) 904/* something else exists */ 905returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 906returnerr(o, msg, path,""); 907} 908 909/* 910 * Do not unlink a file in the work tree if we are not 911 * tracking it. 912 */ 913if(would_lose_untracked(path)) 914returnerr(o,_("refusing to lose untracked file at '%s'"), 915 path); 916 917/* Successful unlink is good.. */ 918if(!unlink(path)) 919return0; 920/* .. and so is no existing file */ 921if(errno == ENOENT) 922return0; 923/* .. but not some other error (who really cares what?) */ 924returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 925} 926 927static intupdate_file_flags(struct merge_options *o, 928const struct object_id *oid, 929unsigned mode, 930const char*path, 931int update_cache, 932int update_wd) 933{ 934int ret =0; 935 936if(o->call_depth) 937 update_wd =0; 938 939if(update_wd) { 940enum object_type type; 941void*buf; 942unsigned long size; 943 944if(S_ISGITLINK(mode)) { 945/* 946 * We may later decide to recursively descend into 947 * the submodule directory and update its index 948 * and/or work tree, but we do not do that now. 949 */ 950 update_wd =0; 951goto update_index; 952} 953 954 buf =read_object_file(oid, &type, &size); 955if(!buf) 956returnerr(o,_("cannot read object%s'%s'"),oid_to_hex(oid), path); 957if(type != OBJ_BLOB) { 958 ret =err(o,_("blob expected for%s'%s'"),oid_to_hex(oid), path); 959goto free_buf; 960} 961if(S_ISREG(mode)) { 962struct strbuf strbuf = STRBUF_INIT; 963if(convert_to_working_tree(path, buf, size, &strbuf)) { 964free(buf); 965 size = strbuf.len; 966 buf =strbuf_detach(&strbuf, NULL); 967} 968} 969 970if(make_room_for_path(o, path) <0) { 971 update_wd =0; 972goto free_buf; 973} 974if(S_ISREG(mode) || (!has_symlinks &&S_ISLNK(mode))) { 975int fd; 976if(mode &0100) 977 mode =0777; 978else 979 mode =0666; 980 fd =open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); 981if(fd <0) { 982 ret =err(o,_("failed to open '%s':%s"), 983 path,strerror(errno)); 984goto free_buf; 985} 986write_in_full(fd, buf, size); 987close(fd); 988}else if(S_ISLNK(mode)) { 989char*lnk =xmemdupz(buf, size); 990safe_create_leading_directories_const(path); 991unlink(path); 992if(symlink(lnk, path)) 993 ret =err(o,_("failed to symlink '%s':%s"), 994 path,strerror(errno)); 995free(lnk); 996}else 997 ret =err(o, 998_("do not know what to do with%06o%s'%s'"), 999 mode,oid_to_hex(oid), path);1000 free_buf:1001free(buf);1002}1003 update_index:1004if(!ret && update_cache)1005if(add_cacheinfo(o, mode, oid, path,0, update_wd,1006 ADD_CACHE_OK_TO_ADD))1007return-1;1008return ret;1009}10101011static intupdate_file(struct merge_options *o,1012int clean,1013const struct object_id *oid,1014unsigned mode,1015const char*path)1016{1017returnupdate_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);1018}10191020/* Low level file merging, update and removal */10211022struct merge_file_info {1023struct object_id oid;1024unsigned mode;1025unsigned clean:1,1026 merge:1;1027};10281029static intmerge_3way(struct merge_options *o,1030 mmbuffer_t *result_buf,1031const struct diff_filespec *one,1032const struct diff_filespec *a,1033const struct diff_filespec *b,1034const char*branch1,1035const char*branch2)1036{1037 mmfile_t orig, src1, src2;1038struct ll_merge_options ll_opts = {0};1039char*base_name, *name1, *name2;1040int merge_status;10411042 ll_opts.renormalize = o->renormalize;1043 ll_opts.xdl_opts = o->xdl_opts;10441045if(o->call_depth) {1046 ll_opts.virtual_ancestor =1;1047 ll_opts.variant =0;1048}else{1049switch(o->recursive_variant) {1050case MERGE_RECURSIVE_OURS:1051 ll_opts.variant = XDL_MERGE_FAVOR_OURS;1052break;1053case MERGE_RECURSIVE_THEIRS:1054 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;1055break;1056default:1057 ll_opts.variant =0;1058break;1059}1060}10611062if(strcmp(a->path, b->path) ||1063(o->ancestor != NULL &&strcmp(a->path, one->path) !=0)) {1064 base_name = o->ancestor == NULL ? NULL :1065mkpathdup("%s:%s", o->ancestor, one->path);1066 name1 =mkpathdup("%s:%s", branch1, a->path);1067 name2 =mkpathdup("%s:%s", branch2, b->path);1068}else{1069 base_name = o->ancestor == NULL ? NULL :1070mkpathdup("%s", o->ancestor);1071 name1 =mkpathdup("%s", branch1);1072 name2 =mkpathdup("%s", branch2);1073}10741075read_mmblob(&orig, &one->oid);1076read_mmblob(&src1, &a->oid);1077read_mmblob(&src2, &b->oid);10781079 merge_status =ll_merge(result_buf, a->path, &orig, base_name,1080&src1, name1, &src2, name2, &ll_opts);10811082free(base_name);1083free(name1);1084free(name2);1085free(orig.ptr);1086free(src1.ptr);1087free(src2.ptr);1088return merge_status;1089}10901091static intmerge_file_1(struct merge_options *o,1092const struct diff_filespec *one,1093const struct diff_filespec *a,1094const struct diff_filespec *b,1095const char*filename,1096const char*branch1,1097const char*branch2,1098struct merge_file_info *result)1099{1100 result->merge =0;1101 result->clean =1;11021103if((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1104 result->clean =0;1105if(S_ISREG(a->mode)) {1106 result->mode = a->mode;1107oidcpy(&result->oid, &a->oid);1108}else{1109 result->mode = b->mode;1110oidcpy(&result->oid, &b->oid);1111}1112}else{1113if(!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))1114 result->merge =1;11151116/*1117 * Merge modes1118 */1119if(a->mode == b->mode || a->mode == one->mode)1120 result->mode = b->mode;1121else{1122 result->mode = a->mode;1123if(b->mode != one->mode) {1124 result->clean =0;1125 result->merge =1;1126}1127}11281129if(oid_eq(&a->oid, &b->oid) ||oid_eq(&a->oid, &one->oid))1130oidcpy(&result->oid, &b->oid);1131else if(oid_eq(&b->oid, &one->oid))1132oidcpy(&result->oid, &a->oid);1133else if(S_ISREG(a->mode)) {1134 mmbuffer_t result_buf;1135int ret =0, merge_status;11361137 merge_status =merge_3way(o, &result_buf, one, a, b,1138 branch1, branch2);11391140if((merge_status <0) || !result_buf.ptr)1141 ret =err(o,_("Failed to execute internal merge"));11421143if(!ret &&1144write_object_file(result_buf.ptr, result_buf.size,1145 blob_type, &result->oid))1146 ret =err(o,_("Unable to add%sto database"),1147 a->path);11481149free(result_buf.ptr);1150if(ret)1151return ret;1152 result->clean = (merge_status ==0);1153}else if(S_ISGITLINK(a->mode)) {1154 result->clean =merge_submodule(&result->oid,1155 one->path,1156&one->oid,1157&a->oid,1158&b->oid,1159!o->call_depth);1160}else if(S_ISLNK(a->mode)) {1161switch(o->recursive_variant) {1162case MERGE_RECURSIVE_NORMAL:1163oidcpy(&result->oid, &a->oid);1164if(!oid_eq(&a->oid, &b->oid))1165 result->clean =0;1166break;1167case MERGE_RECURSIVE_OURS:1168oidcpy(&result->oid, &a->oid);1169break;1170case MERGE_RECURSIVE_THEIRS:1171oidcpy(&result->oid, &b->oid);1172break;1173}1174}else1175die("BUG: unsupported object type in the tree");1176}11771178if(result->merge)1179output(o,2,_("Auto-merging%s"), filename);11801181return0;1182}11831184static intmerge_file_special_markers(struct merge_options *o,1185const struct diff_filespec *one,1186const struct diff_filespec *a,1187const struct diff_filespec *b,1188const char*target_filename,1189const char*branch1,1190const char*filename1,1191const char*branch2,1192const char*filename2,1193struct merge_file_info *mfi)1194{1195char*side1 = NULL;1196char*side2 = NULL;1197int ret;11981199if(filename1)1200 side1 =xstrfmt("%s:%s", branch1, filename1);1201if(filename2)1202 side2 =xstrfmt("%s:%s", branch2, filename2);12031204 ret =merge_file_1(o, one, a, b, target_filename,1205 side1 ? side1 : branch1,1206 side2 ? side2 : branch2, mfi);12071208free(side1);1209free(side2);1210return ret;1211}12121213static intmerge_file_one(struct merge_options *o,1214const char*path,1215const struct object_id *o_oid,int o_mode,1216const struct object_id *a_oid,int a_mode,1217const struct object_id *b_oid,int b_mode,1218const char*branch1,1219const char*branch2,1220struct merge_file_info *mfi)1221{1222struct diff_filespec one, a, b;12231224 one.path = a.path = b.path = (char*)path;1225oidcpy(&one.oid, o_oid);1226 one.mode = o_mode;1227oidcpy(&a.oid, a_oid);1228 a.mode = a_mode;1229oidcpy(&b.oid, b_oid);1230 b.mode = b_mode;1231returnmerge_file_1(o, &one, &a, &b, path, branch1, branch2, mfi);1232}12331234static intconflict_rename_dir(struct merge_options *o,1235struct diff_filepair *pair,1236const char*rename_branch,1237const char*other_branch)1238{1239const struct diff_filespec *dest = pair->two;12401241if(!o->call_depth &&would_lose_untracked(dest->path)) {1242char*alt_path =unique_path(o, dest->path, rename_branch);12431244output(o,1,_("Error: Refusing to lose untracked file at%s; "1245"writing to%sinstead."),1246 dest->path, alt_path);1247/*1248 * Write the file in worktree at alt_path, but not in the1249 * index. Instead, write to dest->path for the index but1250 * only at the higher appropriate stage.1251 */1252if(update_file(o,0, &dest->oid, dest->mode, alt_path))1253return-1;1254free(alt_path);1255returnupdate_stages(o, dest->path, NULL,1256 rename_branch == o->branch1 ? dest : NULL,1257 rename_branch == o->branch1 ? NULL : dest);1258}12591260/* Update dest->path both in index and in worktree */1261if(update_file(o,1, &dest->oid, dest->mode, dest->path))1262return-1;1263return0;1264}12651266static inthandle_change_delete(struct merge_options *o,1267const char*path,const char*old_path,1268const struct object_id *o_oid,int o_mode,1269const struct object_id *changed_oid,1270int changed_mode,1271const char*change_branch,1272const char*delete_branch,1273const char*change,const char*change_past)1274{1275char*alt_path = NULL;1276const char*update_path = path;1277int ret =0;12781279if(dir_in_way(path, !o->call_depth,0) ||1280(!o->call_depth &&would_lose_untracked(path))) {1281 update_path = alt_path =unique_path(o, path, change_branch);1282}12831284if(o->call_depth) {1285/*1286 * We cannot arbitrarily accept either a_sha or b_sha as1287 * correct; since there is no true "middle point" between1288 * them, simply reuse the base version for virtual merge base.1289 */1290 ret =remove_file_from_cache(path);1291if(!ret)1292 ret =update_file(o,0, o_oid, o_mode, update_path);1293}else{1294if(!alt_path) {1295if(!old_path) {1296output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1297"and%sin%s. Version%sof%sleft in tree."),1298 change, path, delete_branch, change_past,1299 change_branch, change_branch, path);1300}else{1301output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1302"and%sto%sin%s. Version%sof%sleft in tree."),1303 change, old_path, delete_branch, change_past, path,1304 change_branch, change_branch, path);1305}1306}else{1307if(!old_path) {1308output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1309"and%sin%s. Version%sof%sleft in tree at%s."),1310 change, path, delete_branch, change_past,1311 change_branch, change_branch, path, alt_path);1312}else{1313output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1314"and%sto%sin%s. Version%sof%sleft in tree at%s."),1315 change, old_path, delete_branch, change_past, path,1316 change_branch, change_branch, path, alt_path);1317}1318}1319/*1320 * No need to call update_file() on path when change_branch ==1321 * o->branch1 && !alt_path, since that would needlessly touch1322 * path. We could call update_file_flags() with update_cache=01323 * and update_wd=0, but that's a no-op.1324 */1325if(change_branch != o->branch1 || alt_path)1326 ret =update_file(o,0, changed_oid, changed_mode, update_path);1327}1328free(alt_path);13291330return ret;1331}13321333static intconflict_rename_delete(struct merge_options *o,1334struct diff_filepair *pair,1335const char*rename_branch,1336const char*delete_branch)1337{1338const struct diff_filespec *orig = pair->one;1339const struct diff_filespec *dest = pair->two;13401341if(handle_change_delete(o,1342 o->call_depth ? orig->path : dest->path,1343 o->call_depth ? NULL : orig->path,1344&orig->oid, orig->mode,1345&dest->oid, dest->mode,1346 rename_branch, delete_branch,1347_("rename"),_("renamed")))1348return-1;13491350if(o->call_depth)1351returnremove_file_from_cache(dest->path);1352else1353returnupdate_stages(o, dest->path, NULL,1354 rename_branch == o->branch1 ? dest : NULL,1355 rename_branch == o->branch1 ? NULL : dest);1356}13571358static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,1359struct stage_data *entry,1360int stage)1361{1362struct object_id *oid = &entry->stages[stage].oid;1363unsigned mode = entry->stages[stage].mode;1364if(mode ==0||is_null_oid(oid))1365return NULL;1366oidcpy(&target->oid, oid);1367 target->mode = mode;1368return target;1369}13701371static inthandle_file(struct merge_options *o,1372struct diff_filespec *rename,1373int stage,1374struct rename_conflict_info *ci)1375{1376char*dst_name = rename->path;1377struct stage_data *dst_entry;1378const char*cur_branch, *other_branch;1379struct diff_filespec other;1380struct diff_filespec *add;1381int ret;13821383if(stage ==2) {1384 dst_entry = ci->dst_entry1;1385 cur_branch = ci->branch1;1386 other_branch = ci->branch2;1387}else{1388 dst_entry = ci->dst_entry2;1389 cur_branch = ci->branch2;1390 other_branch = ci->branch1;1391}13921393 add =filespec_from_entry(&other, dst_entry, stage ^1);1394if(add) {1395int ren_src_was_dirty =was_dirty(o, rename->path);1396char*add_name =unique_path(o, rename->path, other_branch);1397if(update_file(o,0, &add->oid, add->mode, add_name))1398return-1;13991400if(ren_src_was_dirty) {1401output(o,1,_("Refusing to lose dirty file at%s"),1402 rename->path);1403}1404/*1405 * Because the double negatives somehow keep confusing me...1406 * 1) update_wd iff !ren_src_was_dirty.1407 * 2) no_wd iff !update_wd1408 * 3) so, no_wd == !!ren_src_was_dirty == ren_src_was_dirty1409 */1410remove_file(o,0, rename->path, ren_src_was_dirty);1411 dst_name =unique_path(o, rename->path, cur_branch);1412}else{1413if(dir_in_way(rename->path, !o->call_depth,0)) {1414 dst_name =unique_path(o, rename->path, cur_branch);1415output(o,1,_("%sis a directory in%sadding as%sinstead"),1416 rename->path, other_branch, dst_name);1417}else if(!o->call_depth &&1418would_lose_untracked(rename->path)) {1419 dst_name =unique_path(o, rename->path, cur_branch);1420output(o,1,_("Refusing to lose untracked file at%s; "1421"adding as%sinstead"),1422 rename->path, dst_name);1423}1424}1425if((ret =update_file(o,0, &rename->oid, rename->mode, dst_name)))1426;/* fall through, do allow dst_name to be released */1427else if(stage ==2)1428 ret =update_stages(o, rename->path, NULL, rename, add);1429else1430 ret =update_stages(o, rename->path, NULL, add, rename);14311432if(dst_name != rename->path)1433free(dst_name);14341435return ret;1436}14371438static intconflict_rename_rename_1to2(struct merge_options *o,1439struct rename_conflict_info *ci)1440{1441/* One file was renamed in both branches, but to different names. */1442struct diff_filespec *one = ci->pair1->one;1443struct diff_filespec *a = ci->pair1->two;1444struct diff_filespec *b = ci->pair2->two;14451446output(o,1,_("CONFLICT (rename/rename): "1447"Rename\"%s\"->\"%s\"in branch\"%s\""1448"rename\"%s\"->\"%s\"in\"%s\"%s"),1449 one->path, a->path, ci->branch1,1450 one->path, b->path, ci->branch2,1451 o->call_depth ?_(" (left unresolved)") :"");1452if(o->call_depth) {1453struct merge_file_info mfi;1454struct diff_filespec other;1455struct diff_filespec *add;1456if(merge_file_one(o, one->path,1457&one->oid, one->mode,1458&a->oid, a->mode,1459&b->oid, b->mode,1460 ci->branch1, ci->branch2, &mfi))1461return-1;14621463/*1464 * FIXME: For rename/add-source conflicts (if we could detect1465 * such), this is wrong. We should instead find a unique1466 * pathname and then either rename the add-source file to that1467 * unique path, or use that unique path instead of src here.1468 */1469if(update_file(o,0, &mfi.oid, mfi.mode, one->path))1470return-1;14711472/*1473 * Above, we put the merged content at the merge-base's1474 * path. Now we usually need to delete both a->path and1475 * b->path. However, the rename on each side of the merge1476 * could also be involved in a rename/add conflict. In1477 * such cases, we should keep the added file around,1478 * resolving the conflict at that path in its favor.1479 */1480 add =filespec_from_entry(&other, ci->dst_entry1,2^1);1481if(add) {1482if(update_file(o,0, &add->oid, add->mode, a->path))1483return-1;1484}1485else1486remove_file_from_cache(a->path);1487 add =filespec_from_entry(&other, ci->dst_entry2,3^1);1488if(add) {1489if(update_file(o,0, &add->oid, add->mode, b->path))1490return-1;1491}1492else1493remove_file_from_cache(b->path);1494}else if(handle_file(o, a,2, ci) ||handle_file(o, b,3, ci))1495return-1;14961497return0;1498}14991500static intconflict_rename_rename_2to1(struct merge_options *o,1501struct rename_conflict_info *ci)1502{1503/* Two files, a & b, were renamed to the same thing, c. */1504struct diff_filespec *a = ci->pair1->one;1505struct diff_filespec *b = ci->pair2->one;1506struct diff_filespec *c1 = ci->pair1->two;1507struct diff_filespec *c2 = ci->pair2->two;1508char*path = c1->path;/* == c2->path */1509char*path_side_1_desc;1510char*path_side_2_desc;1511struct merge_file_info mfi_c1;1512struct merge_file_info mfi_c2;1513int ret;15141515output(o,1,_("CONFLICT (rename/rename): "1516"Rename%s->%sin%s. "1517"Rename%s->%sin%s"),1518 a->path, c1->path, ci->branch1,1519 b->path, c2->path, ci->branch2);15201521remove_file(o,1, a->path, o->call_depth ||would_lose_untracked(a->path));1522remove_file(o,1, b->path, o->call_depth ||would_lose_untracked(b->path));15231524 path_side_1_desc =xstrfmt("%s(was%s)", path, a->path);1525 path_side_2_desc =xstrfmt("%s(was%s)", path, b->path);1526if(merge_file_special_markers(o, a, c1, &ci->ren1_other,1527 path_side_1_desc,1528 o->branch1, c1->path,1529 o->branch2, ci->ren1_other.path, &mfi_c1) ||1530merge_file_special_markers(o, b, &ci->ren2_other, c2,1531 path_side_2_desc,1532 o->branch1, ci->ren2_other.path,1533 o->branch2, c2->path, &mfi_c2))1534return-1;1535free(path_side_1_desc);1536free(path_side_2_desc);15371538if(o->call_depth) {1539/*1540 * If mfi_c1.clean && mfi_c2.clean, then it might make1541 * sense to do a two-way merge of those results. But, I1542 * think in all cases, it makes sense to have the virtual1543 * merge base just undo the renames; they can be detected1544 * again later for the non-recursive merge.1545 */1546remove_file(o,0, path,0);1547 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, a->path);1548if(!ret)1549 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1550 b->path);1551}else{1552char*new_path1 =unique_path(o, path, ci->branch1);1553char*new_path2 =unique_path(o, path, ci->branch2);1554output(o,1,_("Renaming%sto%sand%sto%sinstead"),1555 a->path, new_path1, b->path, new_path2);1556if(was_dirty(o, path))1557output(o,1,_("Refusing to lose dirty file at%s"),1558 path);1559else if(would_lose_untracked(path))1560/*1561 * Only way we get here is if both renames were from1562 * a directory rename AND user had an untracked file1563 * at the location where both files end up after the1564 * two directory renames. See testcase 10d of t6043.1565 */1566output(o,1,_("Refusing to lose untracked file at "1567"%s, even though it's in the way."),1568 path);1569else1570remove_file(o,0, path,0);1571 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, new_path1);1572if(!ret)1573 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1574 new_path2);1575/*1576 * unpack_trees() actually populates the index for us for1577 * "normal" rename/rename(2to1) situtations so that the1578 * correct entries are at the higher stages, which would1579 * make the call below to update_stages_for_stage_data1580 * unnecessary. However, if either of the renames came1581 * from a directory rename, then unpack_trees() will not1582 * have gotten the right data loaded into the index, so we1583 * need to do so now. (While it'd be tempting to move this1584 * call to update_stages_for_stage_data() to1585 * apply_directory_rename_modifications(), that would break1586 * our intermediate calls to would_lose_untracked() since1587 * those rely on the current in-memory index. See also the1588 * big "NOTE" in update_stages()).1589 */1590if(update_stages_for_stage_data(o, path, ci->dst_entry1))1591 ret = -1;15921593free(new_path2);1594free(new_path1);1595}15961597return ret;1598}15991600/*1601 * Get the diff_filepairs changed between o_tree and tree.1602 */1603static struct diff_queue_struct *get_diffpairs(struct merge_options *o,1604struct tree *o_tree,1605struct tree *tree)1606{1607struct diff_queue_struct *ret;1608struct diff_options opts;16091610diff_setup(&opts);1611 opts.flags.recursive =1;1612 opts.flags.rename_empty =0;1613 opts.detect_rename =merge_detect_rename(o);1614/*1615 * We do not have logic to handle the detection of copies. In1616 * fact, it may not even make sense to add such logic: would we1617 * really want a change to a base file to be propagated through1618 * multiple other files by a merge?1619 */1620if(opts.detect_rename > DIFF_DETECT_RENAME)1621 opts.detect_rename = DIFF_DETECT_RENAME;1622 opts.rename_limit = o->merge_rename_limit >=0? o->merge_rename_limit :1623 o->diff_rename_limit >=0? o->diff_rename_limit :16241000;1625 opts.rename_score = o->rename_score;1626 opts.show_rename_progress = o->show_rename_progress;1627 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1628diff_setup_done(&opts);1629diff_tree_oid(&o_tree->object.oid, &tree->object.oid,"", &opts);1630diffcore_std(&opts);1631if(opts.needed_rename_limit > o->needed_rename_limit)1632 o->needed_rename_limit = opts.needed_rename_limit;16331634 ret =xmalloc(sizeof(*ret));1635*ret = diff_queued_diff;16361637 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1638 diff_queued_diff.nr =0;1639 diff_queued_diff.queue = NULL;1640diff_flush(&opts);1641return ret;1642}16431644static inttree_has_path(struct tree *tree,const char*path)1645{1646struct object_id hashy;1647unsigned int mode_o;16481649return!get_tree_entry(&tree->object.oid, path,1650&hashy, &mode_o);1651}16521653/*1654 * Return a new string that replaces the beginning portion (which matches1655 * entry->dir), with entry->new_dir. In perl-speak:1656 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);1657 * NOTE:1658 * Caller must ensure that old_path starts with entry->dir + '/'.1659 */1660static char*apply_dir_rename(struct dir_rename_entry *entry,1661const char*old_path)1662{1663struct strbuf new_path = STRBUF_INIT;1664int oldlen, newlen;16651666if(entry->non_unique_new_dir)1667return NULL;16681669 oldlen =strlen(entry->dir);1670 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) +1;1671strbuf_grow(&new_path, newlen);1672strbuf_addbuf(&new_path, &entry->new_dir);1673strbuf_addstr(&new_path, &old_path[oldlen]);16741675returnstrbuf_detach(&new_path, NULL);1676}16771678static voidget_renamed_dir_portion(const char*old_path,const char*new_path,1679char**old_dir,char**new_dir)1680{1681char*end_of_old, *end_of_new;1682int old_len, new_len;16831684*old_dir = NULL;1685*new_dir = NULL;16861687/*1688 * For1689 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"1690 * the "e/foo.c" part is the same, we just want to know that1691 * "a/b/c/d" was renamed to "a/b/some/thing/else"1692 * so, for this example, this function returns "a/b/c/d" in1693 * *old_dir and "a/b/some/thing/else" in *new_dir.1694 *1695 * Also, if the basename of the file changed, we don't care. We1696 * want to know which portion of the directory, if any, changed.1697 */1698 end_of_old =strrchr(old_path,'/');1699 end_of_new =strrchr(new_path,'/');17001701if(end_of_old == NULL || end_of_new == NULL)1702return;1703while(*--end_of_new == *--end_of_old &&1704 end_of_old != old_path &&1705 end_of_new != new_path)1706;/* Do nothing; all in the while loop */1707/*1708 * We've found the first non-matching character in the directory1709 * paths. That means the current directory we were comparing1710 * represents the rename. Move end_of_old and end_of_new back1711 * to the full directory name.1712 */1713if(*end_of_old =='/')1714 end_of_old++;1715if(*end_of_old !='/')1716 end_of_new++;1717 end_of_old =strchr(end_of_old,'/');1718 end_of_new =strchr(end_of_new,'/');17191720/*1721 * It may have been the case that old_path and new_path were the same1722 * directory all along. Don't claim a rename if they're the same.1723 */1724 old_len = end_of_old - old_path;1725 new_len = end_of_new - new_path;17261727if(old_len != new_len ||strncmp(old_path, new_path, old_len)) {1728*old_dir =xstrndup(old_path, old_len);1729*new_dir =xstrndup(new_path, new_len);1730}1731}17321733static voidremove_hashmap_entries(struct hashmap *dir_renames,1734struct string_list *items_to_remove)1735{1736int i;1737struct dir_rename_entry *entry;17381739for(i =0; i < items_to_remove->nr; i++) {1740 entry = items_to_remove->items[i].util;1741hashmap_remove(dir_renames, entry, NULL);1742}1743string_list_clear(items_to_remove,0);1744}17451746/*1747 * See if there is a directory rename for path, and if there are any file1748 * level conflicts for the renamed location. If there is a rename and1749 * there are no conflicts, return the new name. Otherwise, return NULL.1750 */1751static char*handle_path_level_conflicts(struct merge_options *o,1752const char*path,1753struct dir_rename_entry *entry,1754struct hashmap *collisions,1755struct tree *tree)1756{1757char*new_path = NULL;1758struct collision_entry *collision_ent;1759int clean =1;1760struct strbuf collision_paths = STRBUF_INIT;17611762/*1763 * entry has the mapping of old directory name to new directory name1764 * that we want to apply to path.1765 */1766 new_path =apply_dir_rename(entry, path);17671768if(!new_path) {1769/* This should only happen when entry->non_unique_new_dir set */1770if(!entry->non_unique_new_dir)1771BUG("entry->non_unqiue_dir not set and !new_path");1772output(o,1,_("CONFLICT (directory rename split): "1773"Unclear where to place%sbecause directory "1774"%swas renamed to multiple other directories, "1775"with no destination getting a majority of the "1776"files."),1777 path, entry->dir);1778 clean =0;1779return NULL;1780}17811782/*1783 * The caller needs to have ensured that it has pre-populated1784 * collisions with all paths that map to new_path. Do a quick check1785 * to ensure that's the case.1786 */1787 collision_ent =collision_find_entry(collisions, new_path);1788if(collision_ent == NULL)1789BUG("collision_ent is NULL");17901791/*1792 * Check for one-sided add/add/.../add conflicts, i.e.1793 * where implicit renames from the other side doing1794 * directory rename(s) can affect this side of history1795 * to put multiple paths into the same location. Warn1796 * and bail on directory renames for such paths.1797 */1798if(collision_ent->reported_already) {1799 clean =0;1800}else if(tree_has_path(tree, new_path)) {1801 collision_ent->reported_already =1;1802strbuf_add_separated_string_list(&collision_paths,", ",1803&collision_ent->source_files);1804output(o,1,_("CONFLICT (implicit dir rename): Existing "1805"file/dir at%sin the way of implicit "1806"directory rename(s) putting the following "1807"path(s) there:%s."),1808 new_path, collision_paths.buf);1809 clean =0;1810}else if(collision_ent->source_files.nr >1) {1811 collision_ent->reported_already =1;1812strbuf_add_separated_string_list(&collision_paths,", ",1813&collision_ent->source_files);1814output(o,1,_("CONFLICT (implicit dir rename): Cannot map "1815"more than one path to%s; implicit directory "1816"renames tried to put these paths there:%s"),1817 new_path, collision_paths.buf);1818 clean =0;1819}18201821/* Free memory we no longer need */1822strbuf_release(&collision_paths);1823if(!clean && new_path) {1824free(new_path);1825return NULL;1826}18271828return new_path;1829}18301831/*1832 * There are a couple things we want to do at the directory level:1833 * 1. Check for both sides renaming to the same thing, in order to avoid1834 * implicit renaming of files that should be left in place. (See1835 * testcase 6b in t6043 for details.)1836 * 2. Prune directory renames if there are still files left in the1837 * the original directory. These represent a partial directory rename,1838 * i.e. a rename where only some of the files within the directory1839 * were renamed elsewhere. (Technically, this could be done earlier1840 * in get_directory_renames(), except that would prevent us from1841 * doing the previous check and thus failing testcase 6b.)1842 * 3. Check for rename/rename(1to2) conflicts (at the directory level).1843 * In the future, we could potentially record this info as well and1844 * omit reporting rename/rename(1to2) conflicts for each path within1845 * the affected directories, thus cleaning up the merge output.1846 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the1847 * directory level, because merging directories is fine. If it1848 * causes conflicts for files within those merged directories, then1849 * that should be detected at the individual path level.1850 */1851static voidhandle_directory_level_conflicts(struct merge_options *o,1852struct hashmap *dir_re_head,1853struct tree *head,1854struct hashmap *dir_re_merge,1855struct tree *merge)1856{1857struct hashmap_iter iter;1858struct dir_rename_entry *head_ent;1859struct dir_rename_entry *merge_ent;18601861struct string_list remove_from_head = STRING_LIST_INIT_NODUP;1862struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;18631864hashmap_iter_init(dir_re_head, &iter);1865while((head_ent =hashmap_iter_next(&iter))) {1866 merge_ent =dir_rename_find_entry(dir_re_merge, head_ent->dir);1867if(merge_ent &&1868!head_ent->non_unique_new_dir &&1869!merge_ent->non_unique_new_dir &&1870!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {1871/* 1. Renamed identically; remove it from both sides */1872string_list_append(&remove_from_head,1873 head_ent->dir)->util = head_ent;1874strbuf_release(&head_ent->new_dir);1875string_list_append(&remove_from_merge,1876 merge_ent->dir)->util = merge_ent;1877strbuf_release(&merge_ent->new_dir);1878}else if(tree_has_path(head, head_ent->dir)) {1879/* 2. This wasn't a directory rename after all */1880string_list_append(&remove_from_head,1881 head_ent->dir)->util = head_ent;1882strbuf_release(&head_ent->new_dir);1883}1884}18851886remove_hashmap_entries(dir_re_head, &remove_from_head);1887remove_hashmap_entries(dir_re_merge, &remove_from_merge);18881889hashmap_iter_init(dir_re_merge, &iter);1890while((merge_ent =hashmap_iter_next(&iter))) {1891 head_ent =dir_rename_find_entry(dir_re_head, merge_ent->dir);1892if(tree_has_path(merge, merge_ent->dir)) {1893/* 2. This wasn't a directory rename after all */1894string_list_append(&remove_from_merge,1895 merge_ent->dir)->util = merge_ent;1896}else if(head_ent &&1897!head_ent->non_unique_new_dir &&1898!merge_ent->non_unique_new_dir) {1899/* 3. rename/rename(1to2) */1900/*1901 * We can assume it's not rename/rename(1to1) because1902 * that was case (1), already checked above. So we1903 * know that head_ent->new_dir and merge_ent->new_dir1904 * are different strings.1905 */1906output(o,1,_("CONFLICT (rename/rename): "1907"Rename directory%s->%sin%s. "1908"Rename directory%s->%sin%s"),1909 head_ent->dir, head_ent->new_dir.buf, o->branch1,1910 head_ent->dir, merge_ent->new_dir.buf, o->branch2);1911string_list_append(&remove_from_head,1912 head_ent->dir)->util = head_ent;1913strbuf_release(&head_ent->new_dir);1914string_list_append(&remove_from_merge,1915 merge_ent->dir)->util = merge_ent;1916strbuf_release(&merge_ent->new_dir);1917}1918}19191920remove_hashmap_entries(dir_re_head, &remove_from_head);1921remove_hashmap_entries(dir_re_merge, &remove_from_merge);1922}19231924static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs,1925struct tree *tree)1926{1927struct hashmap *dir_renames;1928struct hashmap_iter iter;1929struct dir_rename_entry *entry;1930int i;19311932/*1933 * Typically, we think of a directory rename as all files from a1934 * certain directory being moved to a target directory. However,1935 * what if someone first moved two files from the original1936 * directory in one commit, and then renamed the directory1937 * somewhere else in a later commit? At merge time, we just know1938 * that files from the original directory went to two different1939 * places, and that the bulk of them ended up in the same place.1940 * We want each directory rename to represent where the bulk of the1941 * files from that directory end up; this function exists to find1942 * where the bulk of the files went.1943 *1944 * The first loop below simply iterates through the list of file1945 * renames, finding out how often each directory rename pair1946 * possibility occurs.1947 */1948 dir_renames =xmalloc(sizeof(*dir_renames));1949dir_rename_init(dir_renames);1950for(i =0; i < pairs->nr; ++i) {1951struct string_list_item *item;1952int*count;1953struct diff_filepair *pair = pairs->queue[i];1954char*old_dir, *new_dir;19551956/* File not part of directory rename if it wasn't renamed */1957if(pair->status !='R')1958continue;19591960get_renamed_dir_portion(pair->one->path, pair->two->path,1961&old_dir, &new_dir);1962if(!old_dir)1963/* Directory didn't change at all; ignore this one. */1964continue;19651966 entry =dir_rename_find_entry(dir_renames, old_dir);1967if(!entry) {1968 entry =xmalloc(sizeof(*entry));1969dir_rename_entry_init(entry, old_dir);1970hashmap_put(dir_renames, entry);1971}else{1972free(old_dir);1973}1974 item =string_list_lookup(&entry->possible_new_dirs, new_dir);1975if(!item) {1976 item =string_list_insert(&entry->possible_new_dirs,1977 new_dir);1978 item->util =xcalloc(1,sizeof(int));1979}else{1980free(new_dir);1981}1982 count = item->util;1983*count +=1;1984}19851986/*1987 * For each directory with files moved out of it, we find out which1988 * target directory received the most files so we can declare it to1989 * be the "winning" target location for the directory rename. This1990 * winner gets recorded in new_dir. If there is no winner1991 * (multiple target directories received the same number of files),1992 * we set non_unique_new_dir. Once we've determined the winner (or1993 * that there is no winner), we no longer need possible_new_dirs.1994 */1995hashmap_iter_init(dir_renames, &iter);1996while((entry =hashmap_iter_next(&iter))) {1997int max =0;1998int bad_max =0;1999char*best = NULL;20002001for(i =0; i < entry->possible_new_dirs.nr; i++) {2002int*count = entry->possible_new_dirs.items[i].util;20032004if(*count == max)2005 bad_max = max;2006else if(*count > max) {2007 max = *count;2008 best = entry->possible_new_dirs.items[i].string;2009}2010}2011if(bad_max == max)2012 entry->non_unique_new_dir =1;2013else{2014assert(entry->new_dir.len ==0);2015strbuf_addstr(&entry->new_dir, best);2016}2017/*2018 * The relevant directory sub-portion of the original full2019 * filepaths were xstrndup'ed before inserting into2020 * possible_new_dirs, and instead of manually iterating the2021 * list and free'ing each, just lie and tell2022 * possible_new_dirs that it did the strdup'ing so that it2023 * will free them for us.2024 */2025 entry->possible_new_dirs.strdup_strings =1;2026string_list_clear(&entry->possible_new_dirs,1);2027}20282029return dir_renames;2030}20312032static struct dir_rename_entry *check_dir_renamed(const char*path,2033struct hashmap *dir_renames)2034{2035char temp[PATH_MAX];2036char*end;2037struct dir_rename_entry *entry;20382039strcpy(temp, path);2040while((end =strrchr(temp,'/'))) {2041*end ='\0';2042 entry =dir_rename_find_entry(dir_renames, temp);2043if(entry)2044return entry;2045}2046return NULL;2047}20482049static voidcompute_collisions(struct hashmap *collisions,2050struct hashmap *dir_renames,2051struct diff_queue_struct *pairs)2052{2053int i;20542055/*2056 * Multiple files can be mapped to the same path due to directory2057 * renames done by the other side of history. Since that other2058 * side of history could have merged multiple directories into one,2059 * if our side of history added the same file basename to each of2060 * those directories, then all N of them would get implicitly2061 * renamed by the directory rename detection into the same path,2062 * and we'd get an add/add/.../add conflict, and all those adds2063 * from *this* side of history. This is not representable in the2064 * index, and users aren't going to easily be able to make sense of2065 * it. So we need to provide a good warning about what's2066 * happening, and fall back to no-directory-rename detection2067 * behavior for those paths.2068 *2069 * See testcases 9e and all of section 5 from t6043 for examples.2070 */2071collision_init(collisions);20722073for(i =0; i < pairs->nr; ++i) {2074struct dir_rename_entry *dir_rename_ent;2075struct collision_entry *collision_ent;2076char*new_path;2077struct diff_filepair *pair = pairs->queue[i];20782079if(pair->status !='A'&& pair->status !='R')2080continue;2081 dir_rename_ent =check_dir_renamed(pair->two->path,2082 dir_renames);2083if(!dir_rename_ent)2084continue;20852086 new_path =apply_dir_rename(dir_rename_ent, pair->two->path);2087if(!new_path)2088/*2089 * dir_rename_ent->non_unique_new_path is true, which2090 * means there is no directory rename for us to use,2091 * which means it won't cause us any additional2092 * collisions.2093 */2094continue;2095 collision_ent =collision_find_entry(collisions, new_path);2096if(!collision_ent) {2097 collision_ent =xcalloc(1,2098sizeof(struct collision_entry));2099hashmap_entry_init(collision_ent,strhash(new_path));2100hashmap_put(collisions, collision_ent);2101 collision_ent->target_file = new_path;2102}else{2103free(new_path);2104}2105string_list_insert(&collision_ent->source_files,2106 pair->two->path);2107}2108}21092110static char*check_for_directory_rename(struct merge_options *o,2111const char*path,2112struct tree *tree,2113struct hashmap *dir_renames,2114struct hashmap *dir_rename_exclusions,2115struct hashmap *collisions,2116int*clean_merge)2117{2118char*new_path = NULL;2119struct dir_rename_entry *entry =check_dir_renamed(path, dir_renames);2120struct dir_rename_entry *oentry = NULL;21212122if(!entry)2123return new_path;21242125/*2126 * This next part is a little weird. We do not want to do an2127 * implicit rename into a directory we renamed on our side, because2128 * that will result in a spurious rename/rename(1to2) conflict. An2129 * example:2130 * Base commit: dumbdir/afile, otherdir/bfile2131 * Side 1: smrtdir/afile, otherdir/bfile2132 * Side 2: dumbdir/afile, dumbdir/bfile2133 * Here, while working on Side 1, we could notice that otherdir was2134 * renamed/merged to dumbdir, and change the diff_filepair for2135 * otherdir/bfile into a rename into dumbdir/bfile. However, Side2136 * 2 will notice the rename from dumbdir to smrtdir, and do the2137 * transitive rename to move it from dumbdir/bfile to2138 * smrtdir/bfile. That gives us bfile in dumbdir vs being in2139 * smrtdir, a rename/rename(1to2) conflict. We really just want2140 * the file to end up in smrtdir. And the way to achieve that is2141 * to not let Side1 do the rename to dumbdir, since we know that is2142 * the source of one of our directory renames.2143 *2144 * That's why oentry and dir_rename_exclusions is here.2145 *2146 * As it turns out, this also prevents N-way transient rename2147 * confusion; See testcases 9c and 9d of t6043.2148 */2149 oentry =dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);2150if(oentry) {2151output(o,1,_("WARNING: Avoiding applying%s->%srename "2152"to%s, because%sitself was renamed."),2153 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);2154}else{2155 new_path =handle_path_level_conflicts(o, path, entry,2156 collisions, tree);2157*clean_merge &= (new_path != NULL);2158}21592160return new_path;2161}21622163static voidapply_directory_rename_modifications(struct merge_options *o,2164struct diff_filepair *pair,2165char*new_path,2166struct rename *re,2167struct tree *tree,2168struct tree *o_tree,2169struct tree *a_tree,2170struct tree *b_tree,2171struct string_list *entries,2172int*clean)2173{2174struct string_list_item *item;2175int stage = (tree == a_tree ?2:3);2176int update_wd;21772178/*2179 * In all cases where we can do directory rename detection,2180 * unpack_trees() will have read pair->two->path into the2181 * index and the working copy. We need to remove it so that2182 * we can instead place it at new_path. It is guaranteed to2183 * not be untracked (unpack_trees() would have errored out2184 * saying the file would have been overwritten), but it might2185 * be dirty, though.2186 */2187 update_wd = !was_dirty(o, pair->two->path);2188if(!update_wd)2189output(o,1,_("Refusing to lose dirty file at%s"),2190 pair->two->path);2191remove_file(o,1, pair->two->path, !update_wd);21922193/* Find or create a new re->dst_entry */2194 item =string_list_lookup(entries, new_path);2195if(item) {2196/*2197 * Since we're renaming on this side of history, and it's2198 * due to a directory rename on the other side of history2199 * (which we only allow when the directory in question no2200 * longer exists on the other side of history), the2201 * original entry for re->dst_entry is no longer2202 * necessary...2203 */2204 re->dst_entry->processed =1;22052206/*2207 * ...because we'll be using this new one.2208 */2209 re->dst_entry = item->util;2210}else{2211/*2212 * re->dst_entry is for the before-dir-rename path, and we2213 * need it to hold information for the after-dir-rename2214 * path. Before creating a new entry, we need to mark the2215 * old one as unnecessary (...unless it is shared by2216 * src_entry, i.e. this didn't use to be a rename, in which2217 * case we can just allow the normal processing to happen2218 * for it).2219 */2220if(pair->status =='R')2221 re->dst_entry->processed =1;22222223 re->dst_entry =insert_stage_data(new_path,2224 o_tree, a_tree, b_tree,2225 entries);2226 item =string_list_insert(entries, new_path);2227 item->util = re->dst_entry;2228}22292230/*2231 * Update the stage_data with the information about the path we are2232 * moving into place. That slot will be empty and available for us2233 * to write to because of the collision checks in2234 * handle_path_level_conflicts(). In other words,2235 * re->dst_entry->stages[stage].oid will be the null_oid, so it's2236 * open for us to write to.2237 *2238 * It may be tempting to actually update the index at this point as2239 * well, using update_stages_for_stage_data(), but as per the big2240 * "NOTE" in update_stages(), doing so will modify the current2241 * in-memory index which will break calls to would_lose_untracked()2242 * that we need to make. Instead, we need to just make sure that2243 * the various conflict_rename_*() functions update the index2244 * explicitly rather than relying on unpack_trees() to have done it.2245 */2246get_tree_entry(&tree->object.oid,2247 pair->two->path,2248&re->dst_entry->stages[stage].oid,2249&re->dst_entry->stages[stage].mode);22502251/* Update pair status */2252if(pair->status =='A') {2253/*2254 * Recording rename information for this add makes it look2255 * like a rename/delete conflict. Make sure we can2256 * correctly handle this as an add that was moved to a new2257 * directory instead of reporting a rename/delete conflict.2258 */2259 re->add_turned_into_rename =1;2260}2261/*2262 * We don't actually look at pair->status again, but it seems2263 * pedagogically correct to adjust it.2264 */2265 pair->status ='R';22662267/*2268 * Finally, record the new location.2269 */2270 pair->two->path = new_path;2271}22722273/*2274 * Get information of all renames which occurred in 'pairs', making use of2275 * any implicit directory renames inferred from the other side of history.2276 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')2277 * to be able to associate the correct cache entries with the rename2278 * information; tree is always equal to either a_tree or b_tree.2279 */2280static struct string_list *get_renames(struct merge_options *o,2281struct diff_queue_struct *pairs,2282struct hashmap *dir_renames,2283struct hashmap *dir_rename_exclusions,2284struct tree *tree,2285struct tree *o_tree,2286struct tree *a_tree,2287struct tree *b_tree,2288struct string_list *entries,2289int*clean_merge)2290{2291int i;2292struct hashmap collisions;2293struct hashmap_iter iter;2294struct collision_entry *e;2295struct string_list *renames;22962297compute_collisions(&collisions, dir_renames, pairs);2298 renames =xcalloc(1,sizeof(struct string_list));22992300for(i =0; i < pairs->nr; ++i) {2301struct string_list_item *item;2302struct rename *re;2303struct diff_filepair *pair = pairs->queue[i];2304char*new_path;/* non-NULL only with directory renames */23052306if(pair->status !='A'&& pair->status !='R') {2307diff_free_filepair(pair);2308continue;2309}2310 new_path =check_for_directory_rename(o, pair->two->path, tree,2311 dir_renames,2312 dir_rename_exclusions,2313&collisions,2314 clean_merge);2315if(pair->status !='R'&& !new_path) {2316diff_free_filepair(pair);2317continue;2318}23192320 re =xmalloc(sizeof(*re));2321 re->processed =0;2322 re->add_turned_into_rename =0;2323 re->pair = pair;2324 item =string_list_lookup(entries, re->pair->one->path);2325if(!item)2326 re->src_entry =insert_stage_data(re->pair->one->path,2327 o_tree, a_tree, b_tree, entries);2328else2329 re->src_entry = item->util;23302331 item =string_list_lookup(entries, re->pair->two->path);2332if(!item)2333 re->dst_entry =insert_stage_data(re->pair->two->path,2334 o_tree, a_tree, b_tree, entries);2335else2336 re->dst_entry = item->util;2337 item =string_list_insert(renames, pair->one->path);2338 item->util = re;2339if(new_path)2340apply_directory_rename_modifications(o, pair, new_path,2341 re, tree, o_tree,2342 a_tree, b_tree,2343 entries,2344 clean_merge);2345}23462347hashmap_iter_init(&collisions, &iter);2348while((e =hashmap_iter_next(&iter))) {2349free(e->target_file);2350string_list_clear(&e->source_files,0);2351}2352hashmap_free(&collisions,1);2353return renames;2354}23552356static intprocess_renames(struct merge_options *o,2357struct string_list *a_renames,2358struct string_list *b_renames)2359{2360int clean_merge =1, i, j;2361struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2362struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2363const struct rename *sre;23642365for(i =0; i < a_renames->nr; i++) {2366 sre = a_renames->items[i].util;2367string_list_insert(&a_by_dst, sre->pair->two->path)->util2368= (void*)sre;2369}2370for(i =0; i < b_renames->nr; i++) {2371 sre = b_renames->items[i].util;2372string_list_insert(&b_by_dst, sre->pair->two->path)->util2373= (void*)sre;2374}23752376for(i =0, j =0; i < a_renames->nr || j < b_renames->nr;) {2377struct string_list *renames1, *renames2Dst;2378struct rename *ren1 = NULL, *ren2 = NULL;2379const char*branch1, *branch2;2380const char*ren1_src, *ren1_dst;2381struct string_list_item *lookup;23822383if(i >= a_renames->nr) {2384 ren2 = b_renames->items[j++].util;2385}else if(j >= b_renames->nr) {2386 ren1 = a_renames->items[i++].util;2387}else{2388int compare =strcmp(a_renames->items[i].string,2389 b_renames->items[j].string);2390if(compare <=0)2391 ren1 = a_renames->items[i++].util;2392if(compare >=0)2393 ren2 = b_renames->items[j++].util;2394}23952396/* TODO: refactor, so that 1/2 are not needed */2397if(ren1) {2398 renames1 = a_renames;2399 renames2Dst = &b_by_dst;2400 branch1 = o->branch1;2401 branch2 = o->branch2;2402}else{2403 renames1 = b_renames;2404 renames2Dst = &a_by_dst;2405 branch1 = o->branch2;2406 branch2 = o->branch1;2407SWAP(ren2, ren1);2408}24092410if(ren1->processed)2411continue;2412 ren1->processed =1;2413 ren1->dst_entry->processed =1;2414/* BUG: We should only mark src_entry as processed if we2415 * are not dealing with a rename + add-source case.2416 */2417 ren1->src_entry->processed =1;24182419 ren1_src = ren1->pair->one->path;2420 ren1_dst = ren1->pair->two->path;24212422if(ren2) {2423/* One file renamed on both sides */2424const char*ren2_src = ren2->pair->one->path;2425const char*ren2_dst = ren2->pair->two->path;2426enum rename_type rename_type;2427if(strcmp(ren1_src, ren2_src) !=0)2428die("BUG: ren1_src != ren2_src");2429 ren2->dst_entry->processed =1;2430 ren2->processed =1;2431if(strcmp(ren1_dst, ren2_dst) !=0) {2432 rename_type = RENAME_ONE_FILE_TO_TWO;2433 clean_merge =0;2434}else{2435 rename_type = RENAME_ONE_FILE_TO_ONE;2436/* BUG: We should only remove ren1_src in2437 * the base stage (think of rename +2438 * add-source cases).2439 */2440remove_file(o,1, ren1_src,1);2441update_entry(ren1->dst_entry,2442 ren1->pair->one,2443 ren1->pair->two,2444 ren2->pair->two);2445}2446setup_rename_conflict_info(rename_type,2447 ren1->pair,2448 ren2->pair,2449 branch1,2450 branch2,2451 ren1->dst_entry,2452 ren2->dst_entry,2453 o,2454 NULL,2455 NULL);2456}else if((lookup =string_list_lookup(renames2Dst, ren1_dst))) {2457/* Two different files renamed to the same thing */2458char*ren2_dst;2459 ren2 = lookup->util;2460 ren2_dst = ren2->pair->two->path;2461if(strcmp(ren1_dst, ren2_dst) !=0)2462die("BUG: ren1_dst != ren2_dst");24632464 clean_merge =0;2465 ren2->processed =1;2466/*2467 * BUG: We should only mark src_entry as processed2468 * if we are not dealing with a rename + add-source2469 * case.2470 */2471 ren2->src_entry->processed =1;24722473setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2474 ren1->pair,2475 ren2->pair,2476 branch1,2477 branch2,2478 ren1->dst_entry,2479 ren2->dst_entry,2480 o,2481 ren1->src_entry,2482 ren2->src_entry);24832484}else{2485/* Renamed in 1, maybe changed in 2 */2486/* we only use sha1 and mode of these */2487struct diff_filespec src_other, dst_other;2488int try_merge;24892490/*2491 * unpack_trees loads entries from common-commit2492 * into stage 1, from head-commit into stage 2, and2493 * from merge-commit into stage 3. We keep track2494 * of which side corresponds to the rename.2495 */2496int renamed_stage = a_renames == renames1 ?2:3;2497int other_stage = a_renames == renames1 ?3:2;24982499/* BUG: We should only remove ren1_src in the base2500 * stage and in other_stage (think of rename +2501 * add-source case).2502 */2503remove_file(o,1, ren1_src,2504 renamed_stage ==2|| !was_tracked(o, ren1_src));25052506oidcpy(&src_other.oid,2507&ren1->src_entry->stages[other_stage].oid);2508 src_other.mode = ren1->src_entry->stages[other_stage].mode;2509oidcpy(&dst_other.oid,2510&ren1->dst_entry->stages[other_stage].oid);2511 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2512 try_merge =0;25132514if(oid_eq(&src_other.oid, &null_oid) &&2515 ren1->add_turned_into_rename) {2516setup_rename_conflict_info(RENAME_DIR,2517 ren1->pair,2518 NULL,2519 branch1,2520 branch2,2521 ren1->dst_entry,2522 NULL,2523 o,2524 NULL,2525 NULL);2526}else if(oid_eq(&src_other.oid, &null_oid)) {2527setup_rename_conflict_info(RENAME_DELETE,2528 ren1->pair,2529 NULL,2530 branch1,2531 branch2,2532 ren1->dst_entry,2533 NULL,2534 o,2535 NULL,2536 NULL);2537}else if((dst_other.mode == ren1->pair->two->mode) &&2538oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {2539/*2540 * Added file on the other side identical to2541 * the file being renamed: clean merge.2542 * Also, there is no need to overwrite the2543 * file already in the working copy, so call2544 * update_file_flags() instead of2545 * update_file().2546 */2547if(update_file_flags(o,2548&ren1->pair->two->oid,2549 ren1->pair->two->mode,2550 ren1_dst,25511,/* update_cache */25520/* update_wd */))2553 clean_merge = -1;2554}else if(!oid_eq(&dst_other.oid, &null_oid)) {2555 clean_merge =0;2556 try_merge =1;2557output(o,1,_("CONFLICT (rename/add): Rename%s->%sin%s. "2558"%sadded in%s"),2559 ren1_src, ren1_dst, branch1,2560 ren1_dst, branch2);2561if(o->call_depth) {2562struct merge_file_info mfi;2563if(merge_file_one(o, ren1_dst, &null_oid,0,2564&ren1->pair->two->oid,2565 ren1->pair->two->mode,2566&dst_other.oid,2567 dst_other.mode,2568 branch1, branch2, &mfi)) {2569 clean_merge = -1;2570goto cleanup_and_return;2571}2572output(o,1,_("Adding merged%s"), ren1_dst);2573if(update_file(o,0, &mfi.oid,2574 mfi.mode, ren1_dst))2575 clean_merge = -1;2576 try_merge =0;2577}else{2578char*new_path =unique_path(o, ren1_dst, branch2);2579output(o,1,_("Adding as%sinstead"), new_path);2580if(update_file(o,0, &dst_other.oid,2581 dst_other.mode, new_path))2582 clean_merge = -1;2583free(new_path);2584}2585}else2586 try_merge =1;25872588if(clean_merge <0)2589goto cleanup_and_return;2590if(try_merge) {2591struct diff_filespec *one, *a, *b;2592 src_other.path = (char*)ren1_src;25932594 one = ren1->pair->one;2595if(a_renames == renames1) {2596 a = ren1->pair->two;2597 b = &src_other;2598}else{2599 b = ren1->pair->two;2600 a = &src_other;2601}2602update_entry(ren1->dst_entry, one, a, b);2603setup_rename_conflict_info(RENAME_NORMAL,2604 ren1->pair,2605 NULL,2606 branch1,2607 NULL,2608 ren1->dst_entry,2609 NULL,2610 o,2611 NULL,2612 NULL);2613}2614}2615}2616cleanup_and_return:2617string_list_clear(&a_by_dst,0);2618string_list_clear(&b_by_dst,0);26192620return clean_merge;2621}26222623struct rename_info {2624struct string_list *head_renames;2625struct string_list *merge_renames;2626};26272628static voidinitial_cleanup_rename(struct diff_queue_struct *pairs,2629struct hashmap *dir_renames)2630{2631struct hashmap_iter iter;2632struct dir_rename_entry *e;26332634hashmap_iter_init(dir_renames, &iter);2635while((e =hashmap_iter_next(&iter))) {2636free(e->dir);2637strbuf_release(&e->new_dir);2638/* possible_new_dirs already cleared in get_directory_renames */2639}2640hashmap_free(dir_renames,1);2641free(dir_renames);26422643free(pairs->queue);2644free(pairs);2645}26462647static inthandle_renames(struct merge_options *o,2648struct tree *common,2649struct tree *head,2650struct tree *merge,2651struct string_list *entries,2652struct rename_info *ri)2653{2654struct diff_queue_struct *head_pairs, *merge_pairs;2655struct hashmap *dir_re_head, *dir_re_merge;2656int clean =1;26572658 ri->head_renames = NULL;2659 ri->merge_renames = NULL;26602661if(!merge_detect_rename(o))2662return1;26632664 head_pairs =get_diffpairs(o, common, head);2665 merge_pairs =get_diffpairs(o, common, merge);26662667 dir_re_head =get_directory_renames(head_pairs, head);2668 dir_re_merge =get_directory_renames(merge_pairs, merge);26692670handle_directory_level_conflicts(o,2671 dir_re_head, head,2672 dir_re_merge, merge);26732674 ri->head_renames =get_renames(o, head_pairs,2675 dir_re_merge, dir_re_head, head,2676 common, head, merge, entries,2677&clean);2678if(clean <0)2679goto cleanup;2680 ri->merge_renames =get_renames(o, merge_pairs,2681 dir_re_head, dir_re_merge, merge,2682 common, head, merge, entries,2683&clean);2684if(clean <0)2685goto cleanup;2686 clean &=process_renames(o, ri->head_renames, ri->merge_renames);26872688cleanup:2689/*2690 * Some cleanup is deferred until cleanup_renames() because the2691 * data structures are still needed and referenced in2692 * process_entry(). But there are a few things we can free now.2693 */2694initial_cleanup_rename(head_pairs, dir_re_head);2695initial_cleanup_rename(merge_pairs, dir_re_merge);26962697return clean;2698}26992700static voidfinal_cleanup_rename(struct string_list *rename)2701{2702const struct rename *re;2703int i;27042705if(rename == NULL)2706return;27072708for(i =0; i < rename->nr; i++) {2709 re = rename->items[i].util;2710diff_free_filepair(re->pair);2711}2712string_list_clear(rename,1);2713free(rename);2714}27152716static voidfinal_cleanup_renames(struct rename_info *re_info)2717{2718final_cleanup_rename(re_info->head_renames);2719final_cleanup_rename(re_info->merge_renames);2720}27212722static struct object_id *stage_oid(const struct object_id *oid,unsigned mode)2723{2724return(is_null_oid(oid) || mode ==0) ? NULL: (struct object_id *)oid;2725}27262727static intread_oid_strbuf(struct merge_options *o,2728const struct object_id *oid,struct strbuf *dst)2729{2730void*buf;2731enum object_type type;2732unsigned long size;2733 buf =read_object_file(oid, &type, &size);2734if(!buf)2735returnerr(o,_("cannot read object%s"),oid_to_hex(oid));2736if(type != OBJ_BLOB) {2737free(buf);2738returnerr(o,_("object%sis not a blob"),oid_to_hex(oid));2739}2740strbuf_attach(dst, buf, size, size +1);2741return0;2742}27432744static intblob_unchanged(struct merge_options *opt,2745const struct object_id *o_oid,2746unsigned o_mode,2747const struct object_id *a_oid,2748unsigned a_mode,2749int renormalize,const char*path)2750{2751struct strbuf o = STRBUF_INIT;2752struct strbuf a = STRBUF_INIT;2753int ret =0;/* assume changed for safety */27542755if(a_mode != o_mode)2756return0;2757if(oid_eq(o_oid, a_oid))2758return1;2759if(!renormalize)2760return0;27612762assert(o_oid && a_oid);2763if(read_oid_strbuf(opt, o_oid, &o) ||read_oid_strbuf(opt, a_oid, &a))2764goto error_return;2765/*2766 * Note: binary | is used so that both renormalizations are2767 * performed. Comparison can be skipped if both files are2768 * unchanged since their sha1s have already been compared.2769 */2770if(renormalize_buffer(&the_index, path, o.buf, o.len, &o) |2771renormalize_buffer(&the_index, path, a.buf, a.len, &a))2772 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));27732774error_return:2775strbuf_release(&o);2776strbuf_release(&a);2777return ret;2778}27792780static inthandle_modify_delete(struct merge_options *o,2781const char*path,2782struct object_id *o_oid,int o_mode,2783struct object_id *a_oid,int a_mode,2784struct object_id *b_oid,int b_mode)2785{2786const char*modify_branch, *delete_branch;2787struct object_id *changed_oid;2788int changed_mode;27892790if(a_oid) {2791 modify_branch = o->branch1;2792 delete_branch = o->branch2;2793 changed_oid = a_oid;2794 changed_mode = a_mode;2795}else{2796 modify_branch = o->branch2;2797 delete_branch = o->branch1;2798 changed_oid = b_oid;2799 changed_mode = b_mode;2800}28012802returnhandle_change_delete(o,2803 path, NULL,2804 o_oid, o_mode,2805 changed_oid, changed_mode,2806 modify_branch, delete_branch,2807_("modify"),_("modified"));2808}28092810static intmerge_content(struct merge_options *o,2811const char*path,2812int is_dirty,2813struct object_id *o_oid,int o_mode,2814struct object_id *a_oid,int a_mode,2815struct object_id *b_oid,int b_mode,2816struct rename_conflict_info *rename_conflict_info)2817{2818const char*reason =_("content");2819const char*path1 = NULL, *path2 = NULL;2820struct merge_file_info mfi;2821struct diff_filespec one, a, b;2822unsigned df_conflict_remains =0;28232824if(!o_oid) {2825 reason =_("add/add");2826 o_oid = (struct object_id *)&null_oid;2827}2828 one.path = a.path = b.path = (char*)path;2829oidcpy(&one.oid, o_oid);2830 one.mode = o_mode;2831oidcpy(&a.oid, a_oid);2832 a.mode = a_mode;2833oidcpy(&b.oid, b_oid);2834 b.mode = b_mode;28352836if(rename_conflict_info) {2837struct diff_filepair *pair1 = rename_conflict_info->pair1;28382839 path1 = (o->branch1 == rename_conflict_info->branch1) ?2840 pair1->two->path : pair1->one->path;2841/* If rename_conflict_info->pair2 != NULL, we are in2842 * RENAME_ONE_FILE_TO_ONE case. Otherwise, we have a2843 * normal rename.2844 */2845 path2 = (rename_conflict_info->pair2 ||2846 o->branch2 == rename_conflict_info->branch1) ?2847 pair1->two->path : pair1->one->path;28482849if(dir_in_way(path, !o->call_depth,2850S_ISGITLINK(pair1->two->mode)))2851 df_conflict_remains =1;2852}2853if(merge_file_special_markers(o, &one, &a, &b, path,2854 o->branch1, path1,2855 o->branch2, path2, &mfi))2856return-1;28572858/*2859 * We can skip updating the working tree file iff:2860 * a) The merge is clean2861 * b) The merge matches what was in HEAD (content, mode, pathname)2862 * c) The target path is usable (i.e. not involved in D/F conflict)2863 */2864if(mfi.clean &&2865was_tracked_and_matches(o, path, &mfi.oid, mfi.mode) &&2866!df_conflict_remains) {2867output(o,3,_("Skipped%s(merged same as existing)"), path);2868if(add_cacheinfo(o, mfi.mode, &mfi.oid, path,28690, (!o->call_depth && !is_dirty),0))2870return-1;2871return mfi.clean;2872}28732874if(!mfi.clean) {2875if(S_ISGITLINK(mfi.mode))2876 reason =_("submodule");2877output(o,1,_("CONFLICT (%s): Merge conflict in%s"),2878 reason, path);2879if(rename_conflict_info && !df_conflict_remains)2880if(update_stages(o, path, &one, &a, &b))2881return-1;2882}28832884if(df_conflict_remains || is_dirty) {2885char*new_path;2886if(o->call_depth) {2887remove_file_from_cache(path);2888}else{2889if(!mfi.clean) {2890if(update_stages(o, path, &one, &a, &b))2891return-1;2892}else{2893int file_from_stage2 =was_tracked(o, path);2894struct diff_filespec merged;2895oidcpy(&merged.oid, &mfi.oid);2896 merged.mode = mfi.mode;28972898if(update_stages(o, path, NULL,2899 file_from_stage2 ? &merged : NULL,2900 file_from_stage2 ? NULL : &merged))2901return-1;2902}29032904}2905 new_path =unique_path(o, path, rename_conflict_info->branch1);2906if(is_dirty) {2907output(o,1,_("Refusing to lose dirty file at%s"),2908 path);2909}2910output(o,1,_("Adding as%sinstead"), new_path);2911if(update_file(o,0, &mfi.oid, mfi.mode, new_path)) {2912free(new_path);2913return-1;2914}2915free(new_path);2916 mfi.clean =0;2917}else if(update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))2918return-1;2919return!is_dirty && mfi.clean;2920}29212922static intconflict_rename_normal(struct merge_options *o,2923const char*path,2924struct object_id *o_oid,unsigned int o_mode,2925struct object_id *a_oid,unsigned int a_mode,2926struct object_id *b_oid,unsigned int b_mode,2927struct rename_conflict_info *ci)2928{2929/* Merge the content and write it out */2930returnmerge_content(o, path,was_dirty(o, path),2931 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,2932 ci);2933}29342935/* Per entry merge function */2936static intprocess_entry(struct merge_options *o,2937const char*path,struct stage_data *entry)2938{2939int clean_merge =1;2940int normalize = o->renormalize;2941unsigned o_mode = entry->stages[1].mode;2942unsigned a_mode = entry->stages[2].mode;2943unsigned b_mode = entry->stages[3].mode;2944struct object_id *o_oid =stage_oid(&entry->stages[1].oid, o_mode);2945struct object_id *a_oid =stage_oid(&entry->stages[2].oid, a_mode);2946struct object_id *b_oid =stage_oid(&entry->stages[3].oid, b_mode);29472948 entry->processed =1;2949if(entry->rename_conflict_info) {2950struct rename_conflict_info *conflict_info = entry->rename_conflict_info;2951switch(conflict_info->rename_type) {2952case RENAME_NORMAL:2953case RENAME_ONE_FILE_TO_ONE:2954 clean_merge =conflict_rename_normal(o,2955 path,2956 o_oid, o_mode,2957 a_oid, a_mode,2958 b_oid, b_mode,2959 conflict_info);2960break;2961case RENAME_DIR:2962 clean_merge =1;2963if(conflict_rename_dir(o,2964 conflict_info->pair1,2965 conflict_info->branch1,2966 conflict_info->branch2))2967 clean_merge = -1;2968break;2969case RENAME_DELETE:2970 clean_merge =0;2971if(conflict_rename_delete(o,2972 conflict_info->pair1,2973 conflict_info->branch1,2974 conflict_info->branch2))2975 clean_merge = -1;2976break;2977case RENAME_ONE_FILE_TO_TWO:2978 clean_merge =0;2979if(conflict_rename_rename_1to2(o, conflict_info))2980 clean_merge = -1;2981break;2982case RENAME_TWO_FILES_TO_ONE:2983 clean_merge =0;2984if(conflict_rename_rename_2to1(o, conflict_info))2985 clean_merge = -1;2986break;2987default:2988 entry->processed =0;2989break;2990}2991}else if(o_oid && (!a_oid || !b_oid)) {2992/* Case A: Deleted in one */2993if((!a_oid && !b_oid) ||2994(!b_oid &&blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||2995(!a_oid &&blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {2996/* Deleted in both or deleted in one and2997 * unchanged in the other */2998if(a_oid)2999output(o,2,_("Removing%s"), path);3000/* do not touch working file if it did not exist */3001remove_file(o,1, path, !a_oid);3002}else{3003/* Modify/delete; deleted side may have put a directory in the way */3004 clean_merge =0;3005if(handle_modify_delete(o, path, o_oid, o_mode,3006 a_oid, a_mode, b_oid, b_mode))3007 clean_merge = -1;3008}3009}else if((!o_oid && a_oid && !b_oid) ||3010(!o_oid && !a_oid && b_oid)) {3011/* Case B: Added in one. */3012/* [nothing|directory] -> ([nothing|directory], file) */30133014const char*add_branch;3015const char*other_branch;3016unsigned mode;3017const struct object_id *oid;3018const char*conf;30193020if(a_oid) {3021 add_branch = o->branch1;3022 other_branch = o->branch2;3023 mode = a_mode;3024 oid = a_oid;3025 conf =_("file/directory");3026}else{3027 add_branch = o->branch2;3028 other_branch = o->branch1;3029 mode = b_mode;3030 oid = b_oid;3031 conf =_("directory/file");3032}3033if(dir_in_way(path,3034!o->call_depth && !S_ISGITLINK(a_mode),30350)) {3036char*new_path =unique_path(o, path, add_branch);3037 clean_merge =0;3038output(o,1,_("CONFLICT (%s): There is a directory with name%sin%s. "3039"Adding%sas%s"),3040 conf, path, other_branch, path, new_path);3041if(update_file(o,0, oid, mode, new_path))3042 clean_merge = -1;3043else if(o->call_depth)3044remove_file_from_cache(path);3045free(new_path);3046}else{3047output(o,2,_("Adding%s"), path);3048/* do not overwrite file if already present */3049if(update_file_flags(o, oid, mode, path,1, !a_oid))3050 clean_merge = -1;3051}3052}else if(a_oid && b_oid) {3053/* Case C: Added in both (check for same permissions) and */3054/* case D: Modified in both, but differently. */3055int is_dirty =0;/* unpack_trees would have bailed if dirty */3056 clean_merge =merge_content(o, path, is_dirty,3057 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,3058 NULL);3059}else if(!o_oid && !a_oid && !b_oid) {3060/*3061 * this entry was deleted altogether. a_mode == 0 means3062 * we had that path and want to actively remove it.3063 */3064remove_file(o,1, path, !a_mode);3065}else3066die("BUG: fatal merge failure, shouldn't happen.");30673068return clean_merge;3069}30703071intmerge_trees(struct merge_options *o,3072struct tree *head,3073struct tree *merge,3074struct tree *common,3075struct tree **result)3076{3077int code, clean;30783079if(o->subtree_shift) {3080 merge =shift_tree_object(head, merge, o->subtree_shift);3081 common =shift_tree_object(head, common, o->subtree_shift);3082}30833084if(oid_eq(&common->object.oid, &merge->object.oid)) {3085struct strbuf sb = STRBUF_INIT;30863087if(!o->call_depth &&index_has_changes(&sb)) {3088err(o,_("Dirty index: cannot merge (dirty:%s)"),3089 sb.buf);3090return0;3091}3092output(o,0,_("Already up to date!"));3093*result = head;3094return1;3095}30963097 code =unpack_trees_start(o, common, head, merge);30983099if(code !=0) {3100if(show(o,4) || o->call_depth)3101err(o,_("merging of trees%sand%sfailed"),3102oid_to_hex(&head->object.oid),3103oid_to_hex(&merge->object.oid));3104unpack_trees_finish(o);3105return-1;3106}31073108if(unmerged_cache()) {3109struct string_list *entries;3110struct rename_info re_info;3111int i;3112/*3113 * Only need the hashmap while processing entries, so3114 * initialize it here and free it when we are done running3115 * through the entries. Keeping it in the merge_options as3116 * opposed to decaring a local hashmap is for convenience3117 * so that we don't have to pass it to around.3118 */3119hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL,512);3120get_files_dirs(o, head);3121get_files_dirs(o, merge);31223123 entries =get_unmerged();3124 clean =handle_renames(o, common, head, merge, entries,3125&re_info);3126record_df_conflict_files(o, entries);3127if(clean <0)3128goto cleanup;3129for(i = entries->nr-1;0<= i; i--) {3130const char*path = entries->items[i].string;3131struct stage_data *e = entries->items[i].util;3132if(!e->processed) {3133int ret =process_entry(o, path, e);3134if(!ret)3135 clean =0;3136else if(ret <0) {3137 clean = ret;3138goto cleanup;3139}3140}3141}3142for(i =0; i < entries->nr; i++) {3143struct stage_data *e = entries->items[i].util;3144if(!e->processed)3145die("BUG: unprocessed path???%s",3146 entries->items[i].string);3147}31483149cleanup:3150final_cleanup_renames(&re_info);31513152string_list_clear(entries,1);3153free(entries);31543155hashmap_free(&o->current_file_dir_set,1);31563157if(clean <0) {3158unpack_trees_finish(o);3159return clean;3160}3161}3162else3163 clean =1;31643165unpack_trees_finish(o);31663167if(o->call_depth && !(*result =write_tree_from_memory(o)))3168return-1;31693170return clean;3171}31723173static struct commit_list *reverse_commit_list(struct commit_list *list)3174{3175struct commit_list *next = NULL, *current, *backup;3176for(current = list; current; current = backup) {3177 backup = current->next;3178 current->next = next;3179 next = current;3180}3181return next;3182}31833184/*3185 * Merge the commits h1 and h2, return the resulting virtual3186 * commit object and a flag indicating the cleanness of the merge.3187 */3188intmerge_recursive(struct merge_options *o,3189struct commit *h1,3190struct commit *h2,3191struct commit_list *ca,3192struct commit **result)3193{3194struct commit_list *iter;3195struct commit *merged_common_ancestors;3196struct tree *mrtree;3197int clean;31983199if(show(o,4)) {3200output(o,4,_("Merging:"));3201output_commit_title(o, h1);3202output_commit_title(o, h2);3203}32043205if(!ca) {3206 ca =get_merge_bases(h1, h2);3207 ca =reverse_commit_list(ca);3208}32093210if(show(o,5)) {3211unsigned cnt =commit_list_count(ca);32123213output(o,5,Q_("found%ucommon ancestor:",3214"found%ucommon ancestors:", cnt), cnt);3215for(iter = ca; iter; iter = iter->next)3216output_commit_title(o, iter->item);3217}32183219 merged_common_ancestors =pop_commit(&ca);3220if(merged_common_ancestors == NULL) {3221/* if there is no common ancestor, use an empty tree */3222struct tree *tree;32233224 tree =lookup_tree(the_hash_algo->empty_tree);3225 merged_common_ancestors =make_virtual_commit(tree,"ancestor");3226}32273228for(iter = ca; iter; iter = iter->next) {3229const char*saved_b1, *saved_b2;3230 o->call_depth++;3231/*3232 * When the merge fails, the result contains files3233 * with conflict markers. The cleanness flag is3234 * ignored (unless indicating an error), it was never3235 * actually used, as result of merge_trees has always3236 * overwritten it: the committed "conflicts" were3237 * already resolved.3238 */3239discard_cache();3240 saved_b1 = o->branch1;3241 saved_b2 = o->branch2;3242 o->branch1 ="Temporary merge branch 1";3243 o->branch2 ="Temporary merge branch 2";3244if(merge_recursive(o, merged_common_ancestors, iter->item,3245 NULL, &merged_common_ancestors) <0)3246return-1;3247 o->branch1 = saved_b1;3248 o->branch2 = saved_b2;3249 o->call_depth--;32503251if(!merged_common_ancestors)3252returnerr(o,_("merge returned no commit"));3253}32543255discard_cache();3256if(!o->call_depth)3257read_cache();32583259 o->ancestor ="merged common ancestors";3260 clean =merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,3261&mrtree);3262if(clean <0) {3263flush_output(o);3264return clean;3265}32663267if(o->call_depth) {3268*result =make_virtual_commit(mrtree,"merged tree");3269commit_list_insert(h1, &(*result)->parents);3270commit_list_insert(h2, &(*result)->parents->next);3271}3272flush_output(o);3273if(!o->call_depth && o->buffer_output <2)3274strbuf_release(&o->obuf);3275if(show(o,2))3276diff_warn_rename_limit("merge.renamelimit",3277 o->needed_rename_limit,0);3278return clean;3279}32803281static struct commit *get_ref(const struct object_id *oid,const char*name)3282{3283struct object *object;32843285 object =deref_tag(parse_object(oid), name,strlen(name));3286if(!object)3287return NULL;3288if(object->type == OBJ_TREE)3289returnmake_virtual_commit((struct tree*)object, name);3290if(object->type != OBJ_COMMIT)3291return NULL;3292if(parse_commit((struct commit *)object))3293return NULL;3294return(struct commit *)object;3295}32963297intmerge_recursive_generic(struct merge_options *o,3298const struct object_id *head,3299const struct object_id *merge,3300int num_base_list,3301const struct object_id **base_list,3302struct commit **result)3303{3304int clean;3305struct lock_file lock = LOCK_INIT;3306struct commit *head_commit =get_ref(head, o->branch1);3307struct commit *next_commit =get_ref(merge, o->branch2);3308struct commit_list *ca = NULL;33093310if(base_list) {3311int i;3312for(i =0; i < num_base_list; ++i) {3313struct commit *base;3314if(!(base =get_ref(base_list[i],oid_to_hex(base_list[i]))))3315returnerr(o,_("Could not parse object '%s'"),3316oid_to_hex(base_list[i]));3317commit_list_insert(base, &ca);3318}3319}33203321hold_locked_index(&lock, LOCK_DIE_ON_ERROR);3322 clean =merge_recursive(o, head_commit, next_commit, ca,3323 result);3324if(clean <0) {3325rollback_lock_file(&lock);3326return clean;3327}33283329if(write_locked_index(&the_index, &lock,3330 COMMIT_LOCK | SKIP_IF_UNCHANGED))3331returnerr(o,_("Unable to write index."));33323333return clean ?0:1;3334}33353336static voidmerge_recursive_config(struct merge_options *o)3337{3338char*value = NULL;3339git_config_get_int("merge.verbosity", &o->verbosity);3340git_config_get_int("diff.renamelimit", &o->diff_rename_limit);3341git_config_get_int("merge.renamelimit", &o->merge_rename_limit);3342if(!git_config_get_string("diff.renames", &value)) {3343 o->diff_detect_rename =git_config_rename("diff.renames", value);3344free(value);3345}3346if(!git_config_get_string("merge.renames", &value)) {3347 o->merge_detect_rename =git_config_rename("merge.renames", value);3348free(value);3349}3350git_config(git_xmerge_config, NULL);3351}33523353voidinit_merge_options(struct merge_options *o)3354{3355const char*merge_verbosity;3356memset(o,0,sizeof(struct merge_options));3357 o->verbosity =2;3358 o->buffer_output =1;3359 o->diff_rename_limit = -1;3360 o->merge_rename_limit = -1;3361 o->renormalize =0;3362 o->diff_detect_rename = -1;3363 o->merge_detect_rename = -1;3364merge_recursive_config(o);3365 merge_verbosity =getenv("GIT_MERGE_VERBOSITY");3366if(merge_verbosity)3367 o->verbosity =strtol(merge_verbosity, NULL,10);3368if(o->verbosity >=5)3369 o->buffer_output =0;3370strbuf_init(&o->obuf,0);3371string_list_init(&o->df_conflict_file_set,1);3372}33733374intparse_merge_opt(struct merge_options *o,const char*s)3375{3376const char*arg;33773378if(!s || !*s)3379return-1;3380if(!strcmp(s,"ours"))3381 o->recursive_variant = MERGE_RECURSIVE_OURS;3382else if(!strcmp(s,"theirs"))3383 o->recursive_variant = MERGE_RECURSIVE_THEIRS;3384else if(!strcmp(s,"subtree"))3385 o->subtree_shift ="";3386else if(skip_prefix(s,"subtree=", &arg))3387 o->subtree_shift = arg;3388else if(!strcmp(s,"patience"))3389 o->xdl_opts =DIFF_WITH_ALG(o, PATIENCE_DIFF);3390else if(!strcmp(s,"histogram"))3391 o->xdl_opts =DIFF_WITH_ALG(o, HISTOGRAM_DIFF);3392else if(skip_prefix(s,"diff-algorithm=", &arg)) {3393long value =parse_algorithm_value(arg);3394if(value <0)3395return-1;3396/* clear out previous settings */3397DIFF_XDL_CLR(o, NEED_MINIMAL);3398 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;3399 o->xdl_opts |= value;3400}3401else if(!strcmp(s,"ignore-space-change"))3402DIFF_XDL_SET(o, IGNORE_WHITESPACE_CHANGE);3403else if(!strcmp(s,"ignore-all-space"))3404DIFF_XDL_SET(o, IGNORE_WHITESPACE);3405else if(!strcmp(s,"ignore-space-at-eol"))3406DIFF_XDL_SET(o, IGNORE_WHITESPACE_AT_EOL);3407else if(!strcmp(s,"ignore-cr-at-eol"))3408DIFF_XDL_SET(o, IGNORE_CR_AT_EOL);3409else if(!strcmp(s,"renormalize"))3410 o->renormalize =1;3411else if(!strcmp(s,"no-renormalize"))3412 o->renormalize =0;3413else if(!strcmp(s,"no-renames"))3414 o->merge_detect_rename =0;3415else if(!strcmp(s,"find-renames")) {3416 o->merge_detect_rename =1;3417 o->rename_score =0;3418}3419else if(skip_prefix(s,"find-renames=", &arg) ||3420skip_prefix(s,"rename-threshold=", &arg)) {3421if((o->rename_score =parse_rename_score(&arg)) == -1|| *arg !=0)3422return-1;3423 o->merge_detect_rename =1;3424}3425else3426return-1;3427return0;3428}