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,_("addinfo_cache failed for path '%s'"), 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,_("addinfo_cache failed for path '%s'"), path); 328if(nce != ce) 329 ret =add_cache_entry(nce, options); 330} 331return ret; 332} 333 334static voidinit_tree_desc_from_tree(struct tree_desc *desc,struct tree *tree) 335{ 336parse_tree(tree); 337init_tree_desc(desc, tree->buffer, tree->size); 338} 339 340static intgit_merge_trees(int index_only, 341struct tree *common, 342struct tree *head, 343struct tree *merge) 344{ 345int rc; 346struct tree_desc t[3]; 347struct unpack_trees_options opts; 348 349memset(&opts,0,sizeof(opts)); 350if(index_only) 351 opts.index_only =1; 352else 353 opts.update =1; 354 opts.merge =1; 355 opts.head_idx =2; 356 opts.fn = threeway_merge; 357 opts.src_index = &the_index; 358 opts.dst_index = &the_index; 359setup_unpack_trees_porcelain(&opts,"merge"); 360 361init_tree_desc_from_tree(t+0, common); 362init_tree_desc_from_tree(t+1, head); 363init_tree_desc_from_tree(t+2, merge); 364 365 rc =unpack_trees(3, t, &opts); 366cache_tree_free(&active_cache_tree); 367return rc; 368} 369 370struct tree *write_tree_from_memory(struct merge_options *o) 371{ 372struct tree *result = NULL; 373 374if(unmerged_cache()) { 375int i; 376fprintf(stderr,"BUG: There are unmerged index entries:\n"); 377for(i =0; i < active_nr; i++) { 378const struct cache_entry *ce = active_cache[i]; 379if(ce_stage(ce)) 380fprintf(stderr,"BUG:%d%.*s\n",ce_stage(ce), 381(int)ce_namelen(ce), ce->name); 382} 383die("BUG: unmerged index entries in merge-recursive.c"); 384} 385 386if(!active_cache_tree) 387 active_cache_tree =cache_tree(); 388 389if(!cache_tree_fully_valid(active_cache_tree) && 390cache_tree_update(&the_index,0) <0) { 391err(o,_("error building trees")); 392return NULL; 393} 394 395 result =lookup_tree(&active_cache_tree->oid); 396 397return result; 398} 399 400static intsave_files_dirs(const struct object_id *oid, 401struct strbuf *base,const char*path, 402unsigned int mode,int stage,void*context) 403{ 404struct path_hashmap_entry *entry; 405int baselen = base->len; 406struct merge_options *o = context; 407 408strbuf_addstr(base, path); 409 410FLEX_ALLOC_MEM(entry, path, base->buf, base->len); 411hashmap_entry_init(entry,path_hash(entry->path)); 412hashmap_add(&o->current_file_dir_set, entry); 413 414strbuf_setlen(base, baselen); 415return(S_ISDIR(mode) ? READ_TREE_RECURSIVE :0); 416} 417 418static voidget_files_dirs(struct merge_options *o,struct tree *tree) 419{ 420struct pathspec match_all; 421memset(&match_all,0,sizeof(match_all)); 422read_tree_recursive(tree,"",0,0, &match_all, save_files_dirs, o); 423} 424 425static intget_tree_entry_if_blob(const struct object_id *tree, 426const char*path, 427struct object_id *hashy, 428unsigned int*mode_o) 429{ 430int ret; 431 432 ret =get_tree_entry(tree, path, hashy, mode_o); 433if(S_ISDIR(*mode_o)) { 434oidcpy(hashy, &null_oid); 435*mode_o =0; 436} 437return ret; 438} 439 440/* 441 * Returns an index_entry instance which doesn't have to correspond to 442 * a real cache entry in Git's index. 443 */ 444static struct stage_data *insert_stage_data(const char*path, 445struct tree *o,struct tree *a,struct tree *b, 446struct string_list *entries) 447{ 448struct string_list_item *item; 449struct stage_data *e =xcalloc(1,sizeof(struct stage_data)); 450get_tree_entry_if_blob(&o->object.oid, path, 451&e->stages[1].oid, &e->stages[1].mode); 452get_tree_entry_if_blob(&a->object.oid, path, 453&e->stages[2].oid, &e->stages[2].mode); 454get_tree_entry_if_blob(&b->object.oid, path, 455&e->stages[3].oid, &e->stages[3].mode); 456 item =string_list_insert(entries, path); 457 item->util = e; 458return e; 459} 460 461/* 462 * Create a dictionary mapping file names to stage_data objects. The 463 * dictionary contains one entry for every path with a non-zero stage entry. 464 */ 465static struct string_list *get_unmerged(void) 466{ 467struct string_list *unmerged =xcalloc(1,sizeof(struct string_list)); 468int i; 469 470 unmerged->strdup_strings =1; 471 472for(i =0; i < active_nr; i++) { 473struct string_list_item *item; 474struct stage_data *e; 475const struct cache_entry *ce = active_cache[i]; 476if(!ce_stage(ce)) 477continue; 478 479 item =string_list_lookup(unmerged, ce->name); 480if(!item) { 481 item =string_list_insert(unmerged, ce->name); 482 item->util =xcalloc(1,sizeof(struct stage_data)); 483} 484 e = item->util; 485 e->stages[ce_stage(ce)].mode = ce->ce_mode; 486oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid); 487} 488 489return unmerged; 490} 491 492static intstring_list_df_name_compare(const char*one,const char*two) 493{ 494int onelen =strlen(one); 495int twolen =strlen(two); 496/* 497 * Here we only care that entries for D/F conflicts are 498 * adjacent, in particular with the file of the D/F conflict 499 * appearing before files below the corresponding directory. 500 * The order of the rest of the list is irrelevant for us. 501 * 502 * To achieve this, we sort with df_name_compare and provide 503 * the mode S_IFDIR so that D/F conflicts will sort correctly. 504 * We use the mode S_IFDIR for everything else for simplicity, 505 * since in other cases any changes in their order due to 506 * sorting cause no problems for us. 507 */ 508int cmp =df_name_compare(one, onelen, S_IFDIR, 509 two, twolen, S_IFDIR); 510/* 511 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure 512 * that 'foo' comes before 'foo/bar'. 513 */ 514if(cmp) 515return cmp; 516return onelen - twolen; 517} 518 519static voidrecord_df_conflict_files(struct merge_options *o, 520struct string_list *entries) 521{ 522/* If there is a D/F conflict and the file for such a conflict 523 * currently exist in the working tree, we want to allow it to be 524 * removed to make room for the corresponding directory if needed. 525 * The files underneath the directories of such D/F conflicts will 526 * be processed before the corresponding file involved in the D/F 527 * conflict. If the D/F directory ends up being removed by the 528 * merge, then we won't have to touch the D/F file. If the D/F 529 * directory needs to be written to the working copy, then the D/F 530 * file will simply be removed (in make_room_for_path()) to make 531 * room for the necessary paths. Note that if both the directory 532 * and the file need to be present, then the D/F file will be 533 * reinstated with a new unique name at the time it is processed. 534 */ 535struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP; 536const char*last_file = NULL; 537int last_len =0; 538int i; 539 540/* 541 * If we're merging merge-bases, we don't want to bother with 542 * any working directory changes. 543 */ 544if(o->call_depth) 545return; 546 547/* Ensure D/F conflicts are adjacent in the entries list. */ 548for(i =0; i < entries->nr; i++) { 549struct string_list_item *next = &entries->items[i]; 550string_list_append(&df_sorted_entries, next->string)->util = 551 next->util; 552} 553 df_sorted_entries.cmp = string_list_df_name_compare; 554string_list_sort(&df_sorted_entries); 555 556string_list_clear(&o->df_conflict_file_set,1); 557for(i =0; i < df_sorted_entries.nr; i++) { 558const char*path = df_sorted_entries.items[i].string; 559int len =strlen(path); 560struct stage_data *e = df_sorted_entries.items[i].util; 561 562/* 563 * Check if last_file & path correspond to a D/F conflict; 564 * i.e. whether path is last_file+'/'+<something>. 565 * If so, record that it's okay to remove last_file to make 566 * room for path and friends if needed. 567 */ 568if(last_file && 569 len > last_len && 570memcmp(path, last_file, last_len) ==0&& 571 path[last_len] =='/') { 572string_list_insert(&o->df_conflict_file_set, last_file); 573} 574 575/* 576 * Determine whether path could exist as a file in the 577 * working directory as a possible D/F conflict. This 578 * will only occur when it exists in stage 2 as a 579 * file. 580 */ 581if(S_ISREG(e->stages[2].mode) ||S_ISLNK(e->stages[2].mode)) { 582 last_file = path; 583 last_len = len; 584}else{ 585 last_file = NULL; 586} 587} 588string_list_clear(&df_sorted_entries,0); 589} 590 591struct rename { 592struct diff_filepair *pair; 593/* 594 * Purpose of src_entry and dst_entry: 595 * 596 * If 'before' is renamed to 'after' then src_entry will contain 597 * the versions of 'before' from the merge_base, HEAD, and MERGE in 598 * stages 1, 2, and 3; dst_entry will contain the respective 599 * versions of 'after' in corresponding locations. Thus, we have a 600 * total of six modes and oids, though some will be null. (Stage 0 601 * is ignored; we're interested in handling conflicts.) 602 * 603 * Since we don't turn on break-rewrites by default, neither 604 * src_entry nor dst_entry can have all three of their stages have 605 * non-null oids, meaning at most four of the six will be non-null. 606 * Also, since this is a rename, both src_entry and dst_entry will 607 * have at least one non-null oid, meaning at least two will be 608 * non-null. Of the six oids, a typical rename will have three be 609 * non-null. Only two implies a rename/delete, and four implies a 610 * rename/add. 611 */ 612struct stage_data *src_entry; 613struct stage_data *dst_entry; 614unsigned add_turned_into_rename:1; 615unsigned processed:1; 616}; 617 618static intupdate_stages(struct merge_options *opt,const char*path, 619const struct diff_filespec *o, 620const struct diff_filespec *a, 621const struct diff_filespec *b) 622{ 623 624/* 625 * NOTE: It is usually a bad idea to call update_stages on a path 626 * before calling update_file on that same path, since it can 627 * sometimes lead to spurious "refusing to lose untracked file..." 628 * messages from update_file (via make_room_for path via 629 * would_lose_untracked). Instead, reverse the order of the calls 630 * (executing update_file first and then update_stages). 631 */ 632int clear =1; 633int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK; 634if(clear) 635if(remove_file_from_cache(path)) 636return-1; 637if(o) 638if(add_cacheinfo(opt, o->mode, &o->oid, path,1,0, options)) 639return-1; 640if(a) 641if(add_cacheinfo(opt, a->mode, &a->oid, path,2,0, options)) 642return-1; 643if(b) 644if(add_cacheinfo(opt, b->mode, &b->oid, path,3,0, options)) 645return-1; 646return0; 647} 648 649static intupdate_stages_for_stage_data(struct merge_options *opt, 650const char*path, 651const struct stage_data *stage_data) 652{ 653struct diff_filespec o, a, b; 654 655 o.mode = stage_data->stages[1].mode; 656oidcpy(&o.oid, &stage_data->stages[1].oid); 657 658 a.mode = stage_data->stages[2].mode; 659oidcpy(&a.oid, &stage_data->stages[2].oid); 660 661 b.mode = stage_data->stages[3].mode; 662oidcpy(&b.oid, &stage_data->stages[3].oid); 663 664returnupdate_stages(opt, path, 665is_null_oid(&o.oid) ? NULL : &o, 666is_null_oid(&a.oid) ? NULL : &a, 667is_null_oid(&b.oid) ? NULL : &b); 668} 669 670static voidupdate_entry(struct stage_data *entry, 671struct diff_filespec *o, 672struct diff_filespec *a, 673struct diff_filespec *b) 674{ 675 entry->processed =0; 676 entry->stages[1].mode = o->mode; 677 entry->stages[2].mode = a->mode; 678 entry->stages[3].mode = b->mode; 679oidcpy(&entry->stages[1].oid, &o->oid); 680oidcpy(&entry->stages[2].oid, &a->oid); 681oidcpy(&entry->stages[3].oid, &b->oid); 682} 683 684static intremove_file(struct merge_options *o,int clean, 685const char*path,int no_wd) 686{ 687int update_cache = o->call_depth || clean; 688int update_working_directory = !o->call_depth && !no_wd; 689 690if(update_cache) { 691if(remove_file_from_cache(path)) 692return-1; 693} 694if(update_working_directory) { 695if(ignore_case) { 696struct cache_entry *ce; 697 ce =cache_file_exists(path,strlen(path), ignore_case); 698if(ce &&ce_stage(ce) ==0&&strcmp(path, ce->name)) 699return0; 700} 701if(remove_path(path)) 702return-1; 703} 704return0; 705} 706 707/* add a string to a strbuf, but converting "/" to "_" */ 708static voidadd_flattened_path(struct strbuf *out,const char*s) 709{ 710size_t i = out->len; 711strbuf_addstr(out, s); 712for(; i < out->len; i++) 713if(out->buf[i] =='/') 714 out->buf[i] ='_'; 715} 716 717static char*unique_path(struct merge_options *o,const char*path,const char*branch) 718{ 719struct path_hashmap_entry *entry; 720struct strbuf newpath = STRBUF_INIT; 721int suffix =0; 722size_t base_len; 723 724strbuf_addf(&newpath,"%s~", path); 725add_flattened_path(&newpath, branch); 726 727 base_len = newpath.len; 728while(hashmap_get_from_hash(&o->current_file_dir_set, 729path_hash(newpath.buf), newpath.buf) || 730(!o->call_depth &&file_exists(newpath.buf))) { 731strbuf_setlen(&newpath, base_len); 732strbuf_addf(&newpath,"_%d", suffix++); 733} 734 735FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len); 736hashmap_entry_init(entry,path_hash(entry->path)); 737hashmap_add(&o->current_file_dir_set, entry); 738returnstrbuf_detach(&newpath, NULL); 739} 740 741/** 742 * Check whether a directory in the index is in the way of an incoming 743 * file. Return 1 if so. If check_working_copy is non-zero, also 744 * check the working directory. If empty_ok is non-zero, also return 745 * 0 in the case where the working-tree dir exists but is empty. 746 */ 747static intdir_in_way(const char*path,int check_working_copy,int empty_ok) 748{ 749int pos; 750struct strbuf dirpath = STRBUF_INIT; 751struct stat st; 752 753strbuf_addstr(&dirpath, path); 754strbuf_addch(&dirpath,'/'); 755 756 pos =cache_name_pos(dirpath.buf, dirpath.len); 757 758if(pos <0) 759 pos = -1- pos; 760if(pos < active_nr && 761!strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) { 762strbuf_release(&dirpath); 763return1; 764} 765 766strbuf_release(&dirpath); 767return check_working_copy && !lstat(path, &st) &&S_ISDIR(st.st_mode) && 768!(empty_ok &&is_empty_dir(path)); 769} 770 771static intwas_tracked(const char*path) 772{ 773int pos =cache_name_pos(path,strlen(path)); 774 775if(0<= pos) 776/* we have been tracking this path */ 777return1; 778 779/* 780 * Look for an unmerged entry for the path, 781 * specifically stage #2, which would indicate 782 * that "our" side before the merge started 783 * had the path tracked (and resulted in a conflict). 784 */ 785for(pos = -1- pos; 786 pos < active_nr && !strcmp(path, active_cache[pos]->name); 787 pos++) 788if(ce_stage(active_cache[pos]) ==2) 789return1; 790return0; 791} 792 793static intwould_lose_untracked(const char*path) 794{ 795return!was_tracked(path) &&file_exists(path); 796} 797 798static intmake_room_for_path(struct merge_options *o,const char*path) 799{ 800int status, i; 801const char*msg =_("failed to create path '%s'%s"); 802 803/* Unlink any D/F conflict files that are in the way */ 804for(i =0; i < o->df_conflict_file_set.nr; i++) { 805const char*df_path = o->df_conflict_file_set.items[i].string; 806size_t pathlen =strlen(path); 807size_t df_pathlen =strlen(df_path); 808if(df_pathlen < pathlen && 809 path[df_pathlen] =='/'&& 810strncmp(path, df_path, df_pathlen) ==0) { 811output(o,3, 812_("Removing%sto make room for subdirectory\n"), 813 df_path); 814unlink(df_path); 815unsorted_string_list_delete_item(&o->df_conflict_file_set, 816 i,0); 817break; 818} 819} 820 821/* Make sure leading directories are created */ 822 status =safe_create_leading_directories_const(path); 823if(status) { 824if(status == SCLD_EXISTS) 825/* something else exists */ 826returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 827returnerr(o, msg, path,""); 828} 829 830/* 831 * Do not unlink a file in the work tree if we are not 832 * tracking it. 833 */ 834if(would_lose_untracked(path)) 835returnerr(o,_("refusing to lose untracked file at '%s'"), 836 path); 837 838/* Successful unlink is good.. */ 839if(!unlink(path)) 840return0; 841/* .. and so is no existing file */ 842if(errno == ENOENT) 843return0; 844/* .. but not some other error (who really cares what?) */ 845returnerr(o, msg, path,_(": perhaps a D/F conflict?")); 846} 847 848static intupdate_file_flags(struct merge_options *o, 849const struct object_id *oid, 850unsigned mode, 851const char*path, 852int update_cache, 853int update_wd) 854{ 855int ret =0; 856 857if(o->call_depth) 858 update_wd =0; 859 860if(update_wd) { 861enum object_type type; 862void*buf; 863unsigned long size; 864 865if(S_ISGITLINK(mode)) { 866/* 867 * We may later decide to recursively descend into 868 * the submodule directory and update its index 869 * and/or work tree, but we do not do that now. 870 */ 871 update_wd =0; 872goto update_index; 873} 874 875 buf =read_object_file(oid, &type, &size); 876if(!buf) 877returnerr(o,_("cannot read object%s'%s'"),oid_to_hex(oid), path); 878if(type != OBJ_BLOB) { 879 ret =err(o,_("blob expected for%s'%s'"),oid_to_hex(oid), path); 880goto free_buf; 881} 882if(S_ISREG(mode)) { 883struct strbuf strbuf = STRBUF_INIT; 884if(convert_to_working_tree(path, buf, size, &strbuf)) { 885free(buf); 886 size = strbuf.len; 887 buf =strbuf_detach(&strbuf, NULL); 888} 889} 890 891if(make_room_for_path(o, path) <0) { 892 update_wd =0; 893goto free_buf; 894} 895if(S_ISREG(mode) || (!has_symlinks &&S_ISLNK(mode))) { 896int fd; 897if(mode &0100) 898 mode =0777; 899else 900 mode =0666; 901 fd =open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); 902if(fd <0) { 903 ret =err(o,_("failed to open '%s':%s"), 904 path,strerror(errno)); 905goto free_buf; 906} 907write_in_full(fd, buf, size); 908close(fd); 909}else if(S_ISLNK(mode)) { 910char*lnk =xmemdupz(buf, size); 911safe_create_leading_directories_const(path); 912unlink(path); 913if(symlink(lnk, path)) 914 ret =err(o,_("failed to symlink '%s':%s"), 915 path,strerror(errno)); 916free(lnk); 917}else 918 ret =err(o, 919_("do not know what to do with%06o%s'%s'"), 920 mode,oid_to_hex(oid), path); 921 free_buf: 922free(buf); 923} 924 update_index: 925if(!ret && update_cache) 926add_cacheinfo(o, mode, oid, path,0, update_wd, ADD_CACHE_OK_TO_ADD); 927return ret; 928} 929 930static intupdate_file(struct merge_options *o, 931int clean, 932const struct object_id *oid, 933unsigned mode, 934const char*path) 935{ 936returnupdate_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth); 937} 938 939/* Low level file merging, update and removal */ 940 941struct merge_file_info { 942struct object_id oid; 943unsigned mode; 944unsigned clean:1, 945 merge:1; 946}; 947 948static intmerge_3way(struct merge_options *o, 949 mmbuffer_t *result_buf, 950const struct diff_filespec *one, 951const struct diff_filespec *a, 952const struct diff_filespec *b, 953const char*branch1, 954const char*branch2) 955{ 956 mmfile_t orig, src1, src2; 957struct ll_merge_options ll_opts = {0}; 958char*base_name, *name1, *name2; 959int merge_status; 960 961 ll_opts.renormalize = o->renormalize; 962 ll_opts.xdl_opts = o->xdl_opts; 963 964if(o->call_depth) { 965 ll_opts.virtual_ancestor =1; 966 ll_opts.variant =0; 967}else{ 968switch(o->recursive_variant) { 969case MERGE_RECURSIVE_OURS: 970 ll_opts.variant = XDL_MERGE_FAVOR_OURS; 971break; 972case MERGE_RECURSIVE_THEIRS: 973 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS; 974break; 975default: 976 ll_opts.variant =0; 977break; 978} 979} 980 981if(strcmp(a->path, b->path) || 982(o->ancestor != NULL &&strcmp(a->path, one->path) !=0)) { 983 base_name = o->ancestor == NULL ? NULL : 984mkpathdup("%s:%s", o->ancestor, one->path); 985 name1 =mkpathdup("%s:%s", branch1, a->path); 986 name2 =mkpathdup("%s:%s", branch2, b->path); 987}else{ 988 base_name = o->ancestor == NULL ? NULL : 989mkpathdup("%s", o->ancestor); 990 name1 =mkpathdup("%s", branch1); 991 name2 =mkpathdup("%s", branch2); 992} 993 994read_mmblob(&orig, &one->oid); 995read_mmblob(&src1, &a->oid); 996read_mmblob(&src2, &b->oid); 997 998 merge_status =ll_merge(result_buf, a->path, &orig, base_name, 999&src1, name1, &src2, name2, &ll_opts);10001001free(base_name);1002free(name1);1003free(name2);1004free(orig.ptr);1005free(src1.ptr);1006free(src2.ptr);1007return merge_status;1008}10091010static intmerge_file_1(struct merge_options *o,1011const struct diff_filespec *one,1012const struct diff_filespec *a,1013const struct diff_filespec *b,1014const char*branch1,1015const char*branch2,1016struct merge_file_info *result)1017{1018 result->merge =0;1019 result->clean =1;10201021if((S_IFMT & a->mode) != (S_IFMT & b->mode)) {1022 result->clean =0;1023if(S_ISREG(a->mode)) {1024 result->mode = a->mode;1025oidcpy(&result->oid, &a->oid);1026}else{1027 result->mode = b->mode;1028oidcpy(&result->oid, &b->oid);1029}1030}else{1031if(!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))1032 result->merge =1;10331034/*1035 * Merge modes1036 */1037if(a->mode == b->mode || a->mode == one->mode)1038 result->mode = b->mode;1039else{1040 result->mode = a->mode;1041if(b->mode != one->mode) {1042 result->clean =0;1043 result->merge =1;1044}1045}10461047if(oid_eq(&a->oid, &b->oid) ||oid_eq(&a->oid, &one->oid))1048oidcpy(&result->oid, &b->oid);1049else if(oid_eq(&b->oid, &one->oid))1050oidcpy(&result->oid, &a->oid);1051else if(S_ISREG(a->mode)) {1052 mmbuffer_t result_buf;1053int ret =0, merge_status;10541055 merge_status =merge_3way(o, &result_buf, one, a, b,1056 branch1, branch2);10571058if((merge_status <0) || !result_buf.ptr)1059 ret =err(o,_("Failed to execute internal merge"));10601061if(!ret &&1062write_object_file(result_buf.ptr, result_buf.size,1063 blob_type, &result->oid))1064 ret =err(o,_("Unable to add%sto database"),1065 a->path);10661067free(result_buf.ptr);1068if(ret)1069return ret;1070 result->clean = (merge_status ==0);1071}else if(S_ISGITLINK(a->mode)) {1072 result->clean =merge_submodule(&result->oid,1073 one->path,1074&one->oid,1075&a->oid,1076&b->oid,1077!o->call_depth);1078}else if(S_ISLNK(a->mode)) {1079switch(o->recursive_variant) {1080case MERGE_RECURSIVE_NORMAL:1081oidcpy(&result->oid, &a->oid);1082if(!oid_eq(&a->oid, &b->oid))1083 result->clean =0;1084break;1085case MERGE_RECURSIVE_OURS:1086oidcpy(&result->oid, &a->oid);1087break;1088case MERGE_RECURSIVE_THEIRS:1089oidcpy(&result->oid, &b->oid);1090break;1091}1092}else1093die("BUG: unsupported object type in the tree");1094}10951096return0;1097}10981099static intmerge_file_special_markers(struct merge_options *o,1100const struct diff_filespec *one,1101const struct diff_filespec *a,1102const struct diff_filespec *b,1103const char*branch1,1104const char*filename1,1105const char*branch2,1106const char*filename2,1107struct merge_file_info *mfi)1108{1109char*side1 = NULL;1110char*side2 = NULL;1111int ret;11121113if(filename1)1114 side1 =xstrfmt("%s:%s", branch1, filename1);1115if(filename2)1116 side2 =xstrfmt("%s:%s", branch2, filename2);11171118 ret =merge_file_1(o, one, a, b,1119 side1 ? side1 : branch1,1120 side2 ? side2 : branch2, mfi);1121free(side1);1122free(side2);1123return ret;1124}11251126static intmerge_file_one(struct merge_options *o,1127const char*path,1128const struct object_id *o_oid,int o_mode,1129const struct object_id *a_oid,int a_mode,1130const struct object_id *b_oid,int b_mode,1131const char*branch1,1132const char*branch2,1133struct merge_file_info *mfi)1134{1135struct diff_filespec one, a, b;11361137 one.path = a.path = b.path = (char*)path;1138oidcpy(&one.oid, o_oid);1139 one.mode = o_mode;1140oidcpy(&a.oid, a_oid);1141 a.mode = a_mode;1142oidcpy(&b.oid, b_oid);1143 b.mode = b_mode;1144returnmerge_file_1(o, &one, &a, &b, branch1, branch2, mfi);1145}11461147static intconflict_rename_dir(struct merge_options *o,1148struct diff_filepair *pair,1149const char*rename_branch,1150const char*other_branch)1151{1152const struct diff_filespec *dest = pair->two;11531154if(update_file(o,1, &dest->oid, dest->mode, dest->path))1155return-1;1156return0;1157}11581159static inthandle_change_delete(struct merge_options *o,1160const char*path,const char*old_path,1161const struct object_id *o_oid,int o_mode,1162const struct object_id *changed_oid,1163int changed_mode,1164const char*change_branch,1165const char*delete_branch,1166const char*change,const char*change_past)1167{1168char*alt_path = NULL;1169const char*update_path = path;1170int ret =0;11711172if(dir_in_way(path, !o->call_depth,0)) {1173 update_path = alt_path =unique_path(o, path, change_branch);1174}11751176if(o->call_depth) {1177/*1178 * We cannot arbitrarily accept either a_sha or b_sha as1179 * correct; since there is no true "middle point" between1180 * them, simply reuse the base version for virtual merge base.1181 */1182 ret =remove_file_from_cache(path);1183if(!ret)1184 ret =update_file(o,0, o_oid, o_mode, update_path);1185}else{1186if(!alt_path) {1187if(!old_path) {1188output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1189"and%sin%s. Version%sof%sleft in tree."),1190 change, path, delete_branch, change_past,1191 change_branch, change_branch, path);1192}else{1193output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1194"and%sto%sin%s. Version%sof%sleft in tree."),1195 change, old_path, delete_branch, change_past, path,1196 change_branch, change_branch, path);1197}1198}else{1199if(!old_path) {1200output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1201"and%sin%s. Version%sof%sleft in tree at%s."),1202 change, path, delete_branch, change_past,1203 change_branch, change_branch, path, alt_path);1204}else{1205output(o,1,_("CONFLICT (%s/delete):%sdeleted in%s"1206"and%sto%sin%s. Version%sof%sleft in tree at%s."),1207 change, old_path, delete_branch, change_past, path,1208 change_branch, change_branch, path, alt_path);1209}1210}1211/*1212 * No need to call update_file() on path when change_branch ==1213 * o->branch1 && !alt_path, since that would needlessly touch1214 * path. We could call update_file_flags() with update_cache=01215 * and update_wd=0, but that's a no-op.1216 */1217if(change_branch != o->branch1 || alt_path)1218 ret =update_file(o,0, changed_oid, changed_mode, update_path);1219}1220free(alt_path);12211222return ret;1223}12241225static intconflict_rename_delete(struct merge_options *o,1226struct diff_filepair *pair,1227const char*rename_branch,1228const char*delete_branch)1229{1230const struct diff_filespec *orig = pair->one;1231const struct diff_filespec *dest = pair->two;12321233if(handle_change_delete(o,1234 o->call_depth ? orig->path : dest->path,1235 o->call_depth ? NULL : orig->path,1236&orig->oid, orig->mode,1237&dest->oid, dest->mode,1238 rename_branch, delete_branch,1239_("rename"),_("renamed")))1240return-1;12411242if(o->call_depth)1243returnremove_file_from_cache(dest->path);1244else1245returnupdate_stages(o, dest->path, NULL,1246 rename_branch == o->branch1 ? dest : NULL,1247 rename_branch == o->branch1 ? NULL : dest);1248}12491250static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,1251struct stage_data *entry,1252int stage)1253{1254struct object_id *oid = &entry->stages[stage].oid;1255unsigned mode = entry->stages[stage].mode;1256if(mode ==0||is_null_oid(oid))1257return NULL;1258oidcpy(&target->oid, oid);1259 target->mode = mode;1260return target;1261}12621263static inthandle_file(struct merge_options *o,1264struct diff_filespec *rename,1265int stage,1266struct rename_conflict_info *ci)1267{1268char*dst_name = rename->path;1269struct stage_data *dst_entry;1270const char*cur_branch, *other_branch;1271struct diff_filespec other;1272struct diff_filespec *add;1273int ret;12741275if(stage ==2) {1276 dst_entry = ci->dst_entry1;1277 cur_branch = ci->branch1;1278 other_branch = ci->branch2;1279}else{1280 dst_entry = ci->dst_entry2;1281 cur_branch = ci->branch2;1282 other_branch = ci->branch1;1283}12841285 add =filespec_from_entry(&other, dst_entry, stage ^1);1286if(add) {1287char*add_name =unique_path(o, rename->path, other_branch);1288if(update_file(o,0, &add->oid, add->mode, add_name))1289return-1;12901291remove_file(o,0, rename->path,0);1292 dst_name =unique_path(o, rename->path, cur_branch);1293}else{1294if(dir_in_way(rename->path, !o->call_depth,0)) {1295 dst_name =unique_path(o, rename->path, cur_branch);1296output(o,1,_("%sis a directory in%sadding as%sinstead"),1297 rename->path, other_branch, dst_name);1298}1299}1300if((ret =update_file(o,0, &rename->oid, rename->mode, dst_name)))1301;/* fall through, do allow dst_name to be released */1302else if(stage ==2)1303 ret =update_stages(o, rename->path, NULL, rename, add);1304else1305 ret =update_stages(o, rename->path, NULL, add, rename);13061307if(dst_name != rename->path)1308free(dst_name);13091310return ret;1311}13121313static intconflict_rename_rename_1to2(struct merge_options *o,1314struct rename_conflict_info *ci)1315{1316/* One file was renamed in both branches, but to different names. */1317struct diff_filespec *one = ci->pair1->one;1318struct diff_filespec *a = ci->pair1->two;1319struct diff_filespec *b = ci->pair2->two;13201321output(o,1,_("CONFLICT (rename/rename): "1322"Rename\"%s\"->\"%s\"in branch\"%s\""1323"rename\"%s\"->\"%s\"in\"%s\"%s"),1324 one->path, a->path, ci->branch1,1325 one->path, b->path, ci->branch2,1326 o->call_depth ?_(" (left unresolved)") :"");1327if(o->call_depth) {1328struct merge_file_info mfi;1329struct diff_filespec other;1330struct diff_filespec *add;1331if(merge_file_one(o, one->path,1332&one->oid, one->mode,1333&a->oid, a->mode,1334&b->oid, b->mode,1335 ci->branch1, ci->branch2, &mfi))1336return-1;13371338/*1339 * FIXME: For rename/add-source conflicts (if we could detect1340 * such), this is wrong. We should instead find a unique1341 * pathname and then either rename the add-source file to that1342 * unique path, or use that unique path instead of src here.1343 */1344if(update_file(o,0, &mfi.oid, mfi.mode, one->path))1345return-1;13461347/*1348 * Above, we put the merged content at the merge-base's1349 * path. Now we usually need to delete both a->path and1350 * b->path. However, the rename on each side of the merge1351 * could also be involved in a rename/add conflict. In1352 * such cases, we should keep the added file around,1353 * resolving the conflict at that path in its favor.1354 */1355 add =filespec_from_entry(&other, ci->dst_entry1,2^1);1356if(add) {1357if(update_file(o,0, &add->oid, add->mode, a->path))1358return-1;1359}1360else1361remove_file_from_cache(a->path);1362 add =filespec_from_entry(&other, ci->dst_entry2,3^1);1363if(add) {1364if(update_file(o,0, &add->oid, add->mode, b->path))1365return-1;1366}1367else1368remove_file_from_cache(b->path);1369}else if(handle_file(o, a,2, ci) ||handle_file(o, b,3, ci))1370return-1;13711372return0;1373}13741375static intconflict_rename_rename_2to1(struct merge_options *o,1376struct rename_conflict_info *ci)1377{1378/* Two files, a & b, were renamed to the same thing, c. */1379struct diff_filespec *a = ci->pair1->one;1380struct diff_filespec *b = ci->pair2->one;1381struct diff_filespec *c1 = ci->pair1->two;1382struct diff_filespec *c2 = ci->pair2->two;1383char*path = c1->path;/* == c2->path */1384struct merge_file_info mfi_c1;1385struct merge_file_info mfi_c2;1386int ret;13871388output(o,1,_("CONFLICT (rename/rename): "1389"Rename%s->%sin%s. "1390"Rename%s->%sin%s"),1391 a->path, c1->path, ci->branch1,1392 b->path, c2->path, ci->branch2);13931394remove_file(o,1, a->path, o->call_depth ||would_lose_untracked(a->path));1395remove_file(o,1, b->path, o->call_depth ||would_lose_untracked(b->path));13961397if(merge_file_special_markers(o, a, c1, &ci->ren1_other,1398 o->branch1, c1->path,1399 o->branch2, ci->ren1_other.path, &mfi_c1) ||1400merge_file_special_markers(o, b, &ci->ren2_other, c2,1401 o->branch1, ci->ren2_other.path,1402 o->branch2, c2->path, &mfi_c2))1403return-1;14041405if(o->call_depth) {1406/*1407 * If mfi_c1.clean && mfi_c2.clean, then it might make1408 * sense to do a two-way merge of those results. But, I1409 * think in all cases, it makes sense to have the virtual1410 * merge base just undo the renames; they can be detected1411 * again later for the non-recursive merge.1412 */1413remove_file(o,0, path,0);1414 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, a->path);1415if(!ret)1416 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1417 b->path);1418}else{1419char*new_path1 =unique_path(o, path, ci->branch1);1420char*new_path2 =unique_path(o, path, ci->branch2);1421output(o,1,_("Renaming%sto%sand%sto%sinstead"),1422 a->path, new_path1, b->path, new_path2);1423remove_file(o,0, path,0);1424 ret =update_file(o,0, &mfi_c1.oid, mfi_c1.mode, new_path1);1425if(!ret)1426 ret =update_file(o,0, &mfi_c2.oid, mfi_c2.mode,1427 new_path2);1428/*1429 * unpack_trees() actually populates the index for us for1430 * "normal" rename/rename(2to1) situtations so that the1431 * correct entries are at the higher stages, which would1432 * make the call below to update_stages_for_stage_data1433 * unnecessary. However, if either of the renames came1434 * from a directory rename, then unpack_trees() will not1435 * have gotten the right data loaded into the index, so we1436 * need to do so now. (While it'd be tempting to move this1437 * call to update_stages_for_stage_data() to1438 * apply_directory_rename_modifications(), that would break1439 * our intermediate calls to would_lose_untracked() since1440 * those rely on the current in-memory index. See also the1441 * big "NOTE" in update_stages()).1442 */1443if(update_stages_for_stage_data(o, path, ci->dst_entry1))1444 ret = -1;14451446free(new_path2);1447free(new_path1);1448}14491450return ret;1451}14521453/*1454 * Get the diff_filepairs changed between o_tree and tree.1455 */1456static struct diff_queue_struct *get_diffpairs(struct merge_options *o,1457struct tree *o_tree,1458struct tree *tree)1459{1460struct diff_queue_struct *ret;1461struct diff_options opts;14621463diff_setup(&opts);1464 opts.flags.recursive =1;1465 opts.flags.rename_empty =0;1466 opts.detect_rename = DIFF_DETECT_RENAME;1467 opts.rename_limit = o->merge_rename_limit >=0? o->merge_rename_limit :1468 o->diff_rename_limit >=0? o->diff_rename_limit :14691000;1470 opts.rename_score = o->rename_score;1471 opts.show_rename_progress = o->show_rename_progress;1472 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1473diff_setup_done(&opts);1474diff_tree_oid(&o_tree->object.oid, &tree->object.oid,"", &opts);1475diffcore_std(&opts);1476if(opts.needed_rename_limit > o->needed_rename_limit)1477 o->needed_rename_limit = opts.needed_rename_limit;14781479 ret =xmalloc(sizeof(*ret));1480*ret = diff_queued_diff;14811482 opts.output_format = DIFF_FORMAT_NO_OUTPUT;1483 diff_queued_diff.nr =0;1484 diff_queued_diff.queue = NULL;1485diff_flush(&opts);1486return ret;1487}14881489static inttree_has_path(struct tree *tree,const char*path)1490{1491struct object_id hashy;1492unsigned int mode_o;14931494return!get_tree_entry(&tree->object.oid, path,1495&hashy, &mode_o);1496}14971498/*1499 * Return a new string that replaces the beginning portion (which matches1500 * entry->dir), with entry->new_dir. In perl-speak:1501 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);1502 * NOTE:1503 * Caller must ensure that old_path starts with entry->dir + '/'.1504 */1505static char*apply_dir_rename(struct dir_rename_entry *entry,1506const char*old_path)1507{1508struct strbuf new_path = STRBUF_INIT;1509int oldlen, newlen;15101511if(entry->non_unique_new_dir)1512return NULL;15131514 oldlen =strlen(entry->dir);1515 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) +1;1516strbuf_grow(&new_path, newlen);1517strbuf_addbuf(&new_path, &entry->new_dir);1518strbuf_addstr(&new_path, &old_path[oldlen]);15191520returnstrbuf_detach(&new_path, NULL);1521}15221523static voidget_renamed_dir_portion(const char*old_path,const char*new_path,1524char**old_dir,char**new_dir)1525{1526char*end_of_old, *end_of_new;1527int old_len, new_len;15281529*old_dir = NULL;1530*new_dir = NULL;15311532/*1533 * For1534 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"1535 * the "e/foo.c" part is the same, we just want to know that1536 * "a/b/c/d" was renamed to "a/b/some/thing/else"1537 * so, for this example, this function returns "a/b/c/d" in1538 * *old_dir and "a/b/some/thing/else" in *new_dir.1539 *1540 * Also, if the basename of the file changed, we don't care. We1541 * want to know which portion of the directory, if any, changed.1542 */1543 end_of_old =strrchr(old_path,'/');1544 end_of_new =strrchr(new_path,'/');15451546if(end_of_old == NULL || end_of_new == NULL)1547return;1548while(*--end_of_new == *--end_of_old &&1549 end_of_old != old_path &&1550 end_of_new != new_path)1551;/* Do nothing; all in the while loop */1552/*1553 * We've found the first non-matching character in the directory1554 * paths. That means the current directory we were comparing1555 * represents the rename. Move end_of_old and end_of_new back1556 * to the full directory name.1557 */1558if(*end_of_old =='/')1559 end_of_old++;1560if(*end_of_old !='/')1561 end_of_new++;1562 end_of_old =strchr(end_of_old,'/');1563 end_of_new =strchr(end_of_new,'/');15641565/*1566 * It may have been the case that old_path and new_path were the same1567 * directory all along. Don't claim a rename if they're the same.1568 */1569 old_len = end_of_old - old_path;1570 new_len = end_of_new - new_path;15711572if(old_len != new_len ||strncmp(old_path, new_path, old_len)) {1573*old_dir =xstrndup(old_path, old_len);1574*new_dir =xstrndup(new_path, new_len);1575}1576}15771578static voidremove_hashmap_entries(struct hashmap *dir_renames,1579struct string_list *items_to_remove)1580{1581int i;1582struct dir_rename_entry *entry;15831584for(i =0; i < items_to_remove->nr; i++) {1585 entry = items_to_remove->items[i].util;1586hashmap_remove(dir_renames, entry, NULL);1587}1588string_list_clear(items_to_remove,0);1589}15901591/*1592 * See if there is a directory rename for path, and if there are any file1593 * level conflicts for the renamed location. If there is a rename and1594 * there are no conflicts, return the new name. Otherwise, return NULL.1595 */1596static char*handle_path_level_conflicts(struct merge_options *o,1597const char*path,1598struct dir_rename_entry *entry,1599struct hashmap *collisions,1600struct tree *tree)1601{1602char*new_path = NULL;1603struct collision_entry *collision_ent;1604int clean =1;1605struct strbuf collision_paths = STRBUF_INIT;16061607/*1608 * entry has the mapping of old directory name to new directory name1609 * that we want to apply to path.1610 */1611 new_path =apply_dir_rename(entry, path);16121613if(!new_path) {1614/* This should only happen when entry->non_unique_new_dir set */1615if(!entry->non_unique_new_dir)1616BUG("entry->non_unqiue_dir not set and !new_path");1617output(o,1,_("CONFLICT (directory rename split): "1618"Unclear where to place%sbecause directory "1619"%swas renamed to multiple other directories, "1620"with no destination getting a majority of the "1621"files."),1622 path, entry->dir);1623 clean =0;1624return NULL;1625}16261627/*1628 * The caller needs to have ensured that it has pre-populated1629 * collisions with all paths that map to new_path. Do a quick check1630 * to ensure that's the case.1631 */1632 collision_ent =collision_find_entry(collisions, new_path);1633if(collision_ent == NULL)1634BUG("collision_ent is NULL");16351636/*1637 * Check for one-sided add/add/.../add conflicts, i.e.1638 * where implicit renames from the other side doing1639 * directory rename(s) can affect this side of history1640 * to put multiple paths into the same location. Warn1641 * and bail on directory renames for such paths.1642 */1643if(collision_ent->reported_already) {1644 clean =0;1645}else if(tree_has_path(tree, new_path)) {1646 collision_ent->reported_already =1;1647strbuf_add_separated_string_list(&collision_paths,", ",1648&collision_ent->source_files);1649output(o,1,_("CONFLICT (implicit dir rename): Existing "1650"file/dir at%sin the way of implicit "1651"directory rename(s) putting the following "1652"path(s) there:%s."),1653 new_path, collision_paths.buf);1654 clean =0;1655}else if(collision_ent->source_files.nr >1) {1656 collision_ent->reported_already =1;1657strbuf_add_separated_string_list(&collision_paths,", ",1658&collision_ent->source_files);1659output(o,1,_("CONFLICT (implicit dir rename): Cannot map "1660"more than one path to%s; implicit directory "1661"renames tried to put these paths there:%s"),1662 new_path, collision_paths.buf);1663 clean =0;1664}16651666/* Free memory we no longer need */1667strbuf_release(&collision_paths);1668if(!clean && new_path) {1669free(new_path);1670return NULL;1671}16721673return new_path;1674}16751676/*1677 * There are a couple things we want to do at the directory level:1678 * 1. Check for both sides renaming to the same thing, in order to avoid1679 * implicit renaming of files that should be left in place. (See1680 * testcase 6b in t6043 for details.)1681 * 2. Prune directory renames if there are still files left in the1682 * the original directory. These represent a partial directory rename,1683 * i.e. a rename where only some of the files within the directory1684 * were renamed elsewhere. (Technically, this could be done earlier1685 * in get_directory_renames(), except that would prevent us from1686 * doing the previous check and thus failing testcase 6b.)1687 * 3. Check for rename/rename(1to2) conflicts (at the directory level).1688 * In the future, we could potentially record this info as well and1689 * omit reporting rename/rename(1to2) conflicts for each path within1690 * the affected directories, thus cleaning up the merge output.1691 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the1692 * directory level, because merging directories is fine. If it1693 * causes conflicts for files within those merged directories, then1694 * that should be detected at the individual path level.1695 */1696static voidhandle_directory_level_conflicts(struct merge_options *o,1697struct hashmap *dir_re_head,1698struct tree *head,1699struct hashmap *dir_re_merge,1700struct tree *merge)1701{1702struct hashmap_iter iter;1703struct dir_rename_entry *head_ent;1704struct dir_rename_entry *merge_ent;17051706struct string_list remove_from_head = STRING_LIST_INIT_NODUP;1707struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;17081709hashmap_iter_init(dir_re_head, &iter);1710while((head_ent =hashmap_iter_next(&iter))) {1711 merge_ent =dir_rename_find_entry(dir_re_merge, head_ent->dir);1712if(merge_ent &&1713!head_ent->non_unique_new_dir &&1714!merge_ent->non_unique_new_dir &&1715!strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {1716/* 1. Renamed identically; remove it from both sides */1717string_list_append(&remove_from_head,1718 head_ent->dir)->util = head_ent;1719strbuf_release(&head_ent->new_dir);1720string_list_append(&remove_from_merge,1721 merge_ent->dir)->util = merge_ent;1722strbuf_release(&merge_ent->new_dir);1723}else if(tree_has_path(head, head_ent->dir)) {1724/* 2. This wasn't a directory rename after all */1725string_list_append(&remove_from_head,1726 head_ent->dir)->util = head_ent;1727strbuf_release(&head_ent->new_dir);1728}1729}17301731remove_hashmap_entries(dir_re_head, &remove_from_head);1732remove_hashmap_entries(dir_re_merge, &remove_from_merge);17331734hashmap_iter_init(dir_re_merge, &iter);1735while((merge_ent =hashmap_iter_next(&iter))) {1736 head_ent =dir_rename_find_entry(dir_re_head, merge_ent->dir);1737if(tree_has_path(merge, merge_ent->dir)) {1738/* 2. This wasn't a directory rename after all */1739string_list_append(&remove_from_merge,1740 merge_ent->dir)->util = merge_ent;1741}else if(head_ent &&1742!head_ent->non_unique_new_dir &&1743!merge_ent->non_unique_new_dir) {1744/* 3. rename/rename(1to2) */1745/*1746 * We can assume it's not rename/rename(1to1) because1747 * that was case (1), already checked above. So we1748 * know that head_ent->new_dir and merge_ent->new_dir1749 * are different strings.1750 */1751output(o,1,_("CONFLICT (rename/rename): "1752"Rename directory%s->%sin%s. "1753"Rename directory%s->%sin%s"),1754 head_ent->dir, head_ent->new_dir.buf, o->branch1,1755 head_ent->dir, merge_ent->new_dir.buf, o->branch2);1756string_list_append(&remove_from_head,1757 head_ent->dir)->util = head_ent;1758strbuf_release(&head_ent->new_dir);1759string_list_append(&remove_from_merge,1760 merge_ent->dir)->util = merge_ent;1761strbuf_release(&merge_ent->new_dir);1762}1763}17641765remove_hashmap_entries(dir_re_head, &remove_from_head);1766remove_hashmap_entries(dir_re_merge, &remove_from_merge);1767}17681769static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs,1770struct tree *tree)1771{1772struct hashmap *dir_renames;1773struct hashmap_iter iter;1774struct dir_rename_entry *entry;1775int i;17761777/*1778 * Typically, we think of a directory rename as all files from a1779 * certain directory being moved to a target directory. However,1780 * what if someone first moved two files from the original1781 * directory in one commit, and then renamed the directory1782 * somewhere else in a later commit? At merge time, we just know1783 * that files from the original directory went to two different1784 * places, and that the bulk of them ended up in the same place.1785 * We want each directory rename to represent where the bulk of the1786 * files from that directory end up; this function exists to find1787 * where the bulk of the files went.1788 *1789 * The first loop below simply iterates through the list of file1790 * renames, finding out how often each directory rename pair1791 * possibility occurs.1792 */1793 dir_renames =xmalloc(sizeof(*dir_renames));1794dir_rename_init(dir_renames);1795for(i =0; i < pairs->nr; ++i) {1796struct string_list_item *item;1797int*count;1798struct diff_filepair *pair = pairs->queue[i];1799char*old_dir, *new_dir;18001801/* File not part of directory rename if it wasn't renamed */1802if(pair->status !='R')1803continue;18041805get_renamed_dir_portion(pair->one->path, pair->two->path,1806&old_dir, &new_dir);1807if(!old_dir)1808/* Directory didn't change at all; ignore this one. */1809continue;18101811 entry =dir_rename_find_entry(dir_renames, old_dir);1812if(!entry) {1813 entry =xmalloc(sizeof(*entry));1814dir_rename_entry_init(entry, old_dir);1815hashmap_put(dir_renames, entry);1816}else{1817free(old_dir);1818}1819 item =string_list_lookup(&entry->possible_new_dirs, new_dir);1820if(!item) {1821 item =string_list_insert(&entry->possible_new_dirs,1822 new_dir);1823 item->util =xcalloc(1,sizeof(int));1824}else{1825free(new_dir);1826}1827 count = item->util;1828*count +=1;1829}18301831/*1832 * For each directory with files moved out of it, we find out which1833 * target directory received the most files so we can declare it to1834 * be the "winning" target location for the directory rename. This1835 * winner gets recorded in new_dir. If there is no winner1836 * (multiple target directories received the same number of files),1837 * we set non_unique_new_dir. Once we've determined the winner (or1838 * that there is no winner), we no longer need possible_new_dirs.1839 */1840hashmap_iter_init(dir_renames, &iter);1841while((entry =hashmap_iter_next(&iter))) {1842int max =0;1843int bad_max =0;1844char*best = NULL;18451846for(i =0; i < entry->possible_new_dirs.nr; i++) {1847int*count = entry->possible_new_dirs.items[i].util;18481849if(*count == max)1850 bad_max = max;1851else if(*count > max) {1852 max = *count;1853 best = entry->possible_new_dirs.items[i].string;1854}1855}1856if(bad_max == max)1857 entry->non_unique_new_dir =1;1858else{1859assert(entry->new_dir.len ==0);1860strbuf_addstr(&entry->new_dir, best);1861}1862/*1863 * The relevant directory sub-portion of the original full1864 * filepaths were xstrndup'ed before inserting into1865 * possible_new_dirs, and instead of manually iterating the1866 * list and free'ing each, just lie and tell1867 * possible_new_dirs that it did the strdup'ing so that it1868 * will free them for us.1869 */1870 entry->possible_new_dirs.strdup_strings =1;1871string_list_clear(&entry->possible_new_dirs,1);1872}18731874return dir_renames;1875}18761877static struct dir_rename_entry *check_dir_renamed(const char*path,1878struct hashmap *dir_renames)1879{1880char temp[PATH_MAX];1881char*end;1882struct dir_rename_entry *entry;18831884strcpy(temp, path);1885while((end =strrchr(temp,'/'))) {1886*end ='\0';1887 entry =dir_rename_find_entry(dir_renames, temp);1888if(entry)1889return entry;1890}1891return NULL;1892}18931894static voidcompute_collisions(struct hashmap *collisions,1895struct hashmap *dir_renames,1896struct diff_queue_struct *pairs)1897{1898int i;18991900/*1901 * Multiple files can be mapped to the same path due to directory1902 * renames done by the other side of history. Since that other1903 * side of history could have merged multiple directories into one,1904 * if our side of history added the same file basename to each of1905 * those directories, then all N of them would get implicitly1906 * renamed by the directory rename detection into the same path,1907 * and we'd get an add/add/.../add conflict, and all those adds1908 * from *this* side of history. This is not representable in the1909 * index, and users aren't going to easily be able to make sense of1910 * it. So we need to provide a good warning about what's1911 * happening, and fall back to no-directory-rename detection1912 * behavior for those paths.1913 *1914 * See testcases 9e and all of section 5 from t6043 for examples.1915 */1916collision_init(collisions);19171918for(i =0; i < pairs->nr; ++i) {1919struct dir_rename_entry *dir_rename_ent;1920struct collision_entry *collision_ent;1921char*new_path;1922struct diff_filepair *pair = pairs->queue[i];19231924if(pair->status =='D')1925continue;1926 dir_rename_ent =check_dir_renamed(pair->two->path,1927 dir_renames);1928if(!dir_rename_ent)1929continue;19301931 new_path =apply_dir_rename(dir_rename_ent, pair->two->path);1932if(!new_path)1933/*1934 * dir_rename_ent->non_unique_new_path is true, which1935 * means there is no directory rename for us to use,1936 * which means it won't cause us any additional1937 * collisions.1938 */1939continue;1940 collision_ent =collision_find_entry(collisions, new_path);1941if(!collision_ent) {1942 collision_ent =xcalloc(1,1943sizeof(struct collision_entry));1944hashmap_entry_init(collision_ent,strhash(new_path));1945hashmap_put(collisions, collision_ent);1946 collision_ent->target_file = new_path;1947}else{1948free(new_path);1949}1950string_list_insert(&collision_ent->source_files,1951 pair->two->path);1952}1953}19541955static char*check_for_directory_rename(struct merge_options *o,1956const char*path,1957struct tree *tree,1958struct hashmap *dir_renames,1959struct hashmap *dir_rename_exclusions,1960struct hashmap *collisions,1961int*clean_merge)1962{1963char*new_path = NULL;1964struct dir_rename_entry *entry =check_dir_renamed(path, dir_renames);1965struct dir_rename_entry *oentry = NULL;19661967if(!entry)1968return new_path;19691970/*1971 * This next part is a little weird. We do not want to do an1972 * implicit rename into a directory we renamed on our side, because1973 * that will result in a spurious rename/rename(1to2) conflict. An1974 * example:1975 * Base commit: dumbdir/afile, otherdir/bfile1976 * Side 1: smrtdir/afile, otherdir/bfile1977 * Side 2: dumbdir/afile, dumbdir/bfile1978 * Here, while working on Side 1, we could notice that otherdir was1979 * renamed/merged to dumbdir, and change the diff_filepair for1980 * otherdir/bfile into a rename into dumbdir/bfile. However, Side1981 * 2 will notice the rename from dumbdir to smrtdir, and do the1982 * transitive rename to move it from dumbdir/bfile to1983 * smrtdir/bfile. That gives us bfile in dumbdir vs being in1984 * smrtdir, a rename/rename(1to2) conflict. We really just want1985 * the file to end up in smrtdir. And the way to achieve that is1986 * to not let Side1 do the rename to dumbdir, since we know that is1987 * the source of one of our directory renames.1988 *1989 * That's why oentry and dir_rename_exclusions is here.1990 *1991 * As it turns out, this also prevents N-way transient rename1992 * confusion; See testcases 9c and 9d of t6043.1993 */1994 oentry =dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);1995if(oentry) {1996output(o,1,_("WARNING: Avoiding applying%s->%srename "1997"to%s, because%sitself was renamed."),1998 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);1999}else{2000 new_path =handle_path_level_conflicts(o, path, entry,2001 collisions, tree);2002*clean_merge &= (new_path != NULL);2003}20042005return new_path;2006}20072008static voidapply_directory_rename_modifications(struct merge_options *o,2009struct diff_filepair *pair,2010char*new_path,2011struct rename *re,2012struct tree *tree,2013struct tree *o_tree,2014struct tree *a_tree,2015struct tree *b_tree,2016struct string_list *entries,2017int*clean)2018{2019struct string_list_item *item;2020int stage = (tree == a_tree ?2:3);20212022/*2023 * In all cases where we can do directory rename detection,2024 * unpack_trees() will have read pair->two->path into the2025 * index and the working copy. We need to remove it so that2026 * we can instead place it at new_path. It is guaranteed to2027 * not be untracked (unpack_trees() would have errored out2028 * saying the file would have been overwritten), but it might2029 * be dirty, though.2030 */2031remove_file(o,1, pair->two->path,0/* no_wd */);20322033/* Find or create a new re->dst_entry */2034 item =string_list_lookup(entries, new_path);2035if(item) {2036/*2037 * Since we're renaming on this side of history, and it's2038 * due to a directory rename on the other side of history2039 * (which we only allow when the directory in question no2040 * longer exists on the other side of history), the2041 * original entry for re->dst_entry is no longer2042 * necessary...2043 */2044 re->dst_entry->processed =1;20452046/*2047 * ...because we'll be using this new one.2048 */2049 re->dst_entry = item->util;2050}else{2051/*2052 * re->dst_entry is for the before-dir-rename path, and we2053 * need it to hold information for the after-dir-rename2054 * path. Before creating a new entry, we need to mark the2055 * old one as unnecessary (...unless it is shared by2056 * src_entry, i.e. this didn't use to be a rename, in which2057 * case we can just allow the normal processing to happen2058 * for it).2059 */2060if(pair->status =='R')2061 re->dst_entry->processed =1;20622063 re->dst_entry =insert_stage_data(new_path,2064 o_tree, a_tree, b_tree,2065 entries);2066 item =string_list_insert(entries, new_path);2067 item->util = re->dst_entry;2068}20692070/*2071 * Update the stage_data with the information about the path we are2072 * moving into place. That slot will be empty and available for us2073 * to write to because of the collision checks in2074 * handle_path_level_conflicts(). In other words,2075 * re->dst_entry->stages[stage].oid will be the null_oid, so it's2076 * open for us to write to.2077 *2078 * It may be tempting to actually update the index at this point as2079 * well, using update_stages_for_stage_data(), but as per the big2080 * "NOTE" in update_stages(), doing so will modify the current2081 * in-memory index which will break calls to would_lose_untracked()2082 * that we need to make. Instead, we need to just make sure that2083 * the various conflict_rename_*() functions update the index2084 * explicitly rather than relying on unpack_trees() to have done it.2085 */2086get_tree_entry(&tree->object.oid,2087 pair->two->path,2088&re->dst_entry->stages[stage].oid,2089&re->dst_entry->stages[stage].mode);20902091/* Update pair status */2092if(pair->status =='A') {2093/*2094 * Recording rename information for this add makes it look2095 * like a rename/delete conflict. Make sure we can2096 * correctly handle this as an add that was moved to a new2097 * directory instead of reporting a rename/delete conflict.2098 */2099 re->add_turned_into_rename =1;2100}2101/*2102 * We don't actually look at pair->status again, but it seems2103 * pedagogically correct to adjust it.2104 */2105 pair->status ='R';21062107/*2108 * Finally, record the new location.2109 */2110 pair->two->path = new_path;2111}21122113/*2114 * Get information of all renames which occurred in 'pairs', making use of2115 * any implicit directory renames inferred from the other side of history.2116 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')2117 * to be able to associate the correct cache entries with the rename2118 * information; tree is always equal to either a_tree or b_tree.2119 */2120static struct string_list *get_renames(struct merge_options *o,2121struct diff_queue_struct *pairs,2122struct hashmap *dir_renames,2123struct hashmap *dir_rename_exclusions,2124struct tree *tree,2125struct tree *o_tree,2126struct tree *a_tree,2127struct tree *b_tree,2128struct string_list *entries,2129int*clean_merge)2130{2131int i;2132struct hashmap collisions;2133struct hashmap_iter iter;2134struct collision_entry *e;2135struct string_list *renames;21362137compute_collisions(&collisions, dir_renames, pairs);2138 renames =xcalloc(1,sizeof(struct string_list));21392140for(i =0; i < pairs->nr; ++i) {2141struct string_list_item *item;2142struct rename *re;2143struct diff_filepair *pair = pairs->queue[i];2144char*new_path;/* non-NULL only with directory renames */21452146if(pair->status =='D') {2147diff_free_filepair(pair);2148continue;2149}2150 new_path =check_for_directory_rename(o, pair->two->path, tree,2151 dir_renames,2152 dir_rename_exclusions,2153&collisions,2154 clean_merge);2155if(pair->status !='R'&& !new_path) {2156diff_free_filepair(pair);2157continue;2158}21592160 re =xmalloc(sizeof(*re));2161 re->processed =0;2162 re->add_turned_into_rename =0;2163 re->pair = pair;2164 item =string_list_lookup(entries, re->pair->one->path);2165if(!item)2166 re->src_entry =insert_stage_data(re->pair->one->path,2167 o_tree, a_tree, b_tree, entries);2168else2169 re->src_entry = item->util;21702171 item =string_list_lookup(entries, re->pair->two->path);2172if(!item)2173 re->dst_entry =insert_stage_data(re->pair->two->path,2174 o_tree, a_tree, b_tree, entries);2175else2176 re->dst_entry = item->util;2177 item =string_list_insert(renames, pair->one->path);2178 item->util = re;2179if(new_path)2180apply_directory_rename_modifications(o, pair, new_path,2181 re, tree, o_tree,2182 a_tree, b_tree,2183 entries,2184 clean_merge);2185}21862187hashmap_iter_init(&collisions, &iter);2188while((e =hashmap_iter_next(&iter))) {2189free(e->target_file);2190string_list_clear(&e->source_files,0);2191}2192hashmap_free(&collisions,1);2193return renames;2194}21952196static intprocess_renames(struct merge_options *o,2197struct string_list *a_renames,2198struct string_list *b_renames)2199{2200int clean_merge =1, i, j;2201struct string_list a_by_dst = STRING_LIST_INIT_NODUP;2202struct string_list b_by_dst = STRING_LIST_INIT_NODUP;2203const struct rename *sre;22042205for(i =0; i < a_renames->nr; i++) {2206 sre = a_renames->items[i].util;2207string_list_insert(&a_by_dst, sre->pair->two->path)->util2208= (void*)sre;2209}2210for(i =0; i < b_renames->nr; i++) {2211 sre = b_renames->items[i].util;2212string_list_insert(&b_by_dst, sre->pair->two->path)->util2213= (void*)sre;2214}22152216for(i =0, j =0; i < a_renames->nr || j < b_renames->nr;) {2217struct string_list *renames1, *renames2Dst;2218struct rename *ren1 = NULL, *ren2 = NULL;2219const char*branch1, *branch2;2220const char*ren1_src, *ren1_dst;2221struct string_list_item *lookup;22222223if(i >= a_renames->nr) {2224 ren2 = b_renames->items[j++].util;2225}else if(j >= b_renames->nr) {2226 ren1 = a_renames->items[i++].util;2227}else{2228int compare =strcmp(a_renames->items[i].string,2229 b_renames->items[j].string);2230if(compare <=0)2231 ren1 = a_renames->items[i++].util;2232if(compare >=0)2233 ren2 = b_renames->items[j++].util;2234}22352236/* TODO: refactor, so that 1/2 are not needed */2237if(ren1) {2238 renames1 = a_renames;2239 renames2Dst = &b_by_dst;2240 branch1 = o->branch1;2241 branch2 = o->branch2;2242}else{2243 renames1 = b_renames;2244 renames2Dst = &a_by_dst;2245 branch1 = o->branch2;2246 branch2 = o->branch1;2247SWAP(ren2, ren1);2248}22492250if(ren1->processed)2251continue;2252 ren1->processed =1;2253 ren1->dst_entry->processed =1;2254/* BUG: We should only mark src_entry as processed if we2255 * are not dealing with a rename + add-source case.2256 */2257 ren1->src_entry->processed =1;22582259 ren1_src = ren1->pair->one->path;2260 ren1_dst = ren1->pair->two->path;22612262if(ren2) {2263/* One file renamed on both sides */2264const char*ren2_src = ren2->pair->one->path;2265const char*ren2_dst = ren2->pair->two->path;2266enum rename_type rename_type;2267if(strcmp(ren1_src, ren2_src) !=0)2268die("BUG: ren1_src != ren2_src");2269 ren2->dst_entry->processed =1;2270 ren2->processed =1;2271if(strcmp(ren1_dst, ren2_dst) !=0) {2272 rename_type = RENAME_ONE_FILE_TO_TWO;2273 clean_merge =0;2274}else{2275 rename_type = RENAME_ONE_FILE_TO_ONE;2276/* BUG: We should only remove ren1_src in2277 * the base stage (think of rename +2278 * add-source cases).2279 */2280remove_file(o,1, ren1_src,1);2281update_entry(ren1->dst_entry,2282 ren1->pair->one,2283 ren1->pair->two,2284 ren2->pair->two);2285}2286setup_rename_conflict_info(rename_type,2287 ren1->pair,2288 ren2->pair,2289 branch1,2290 branch2,2291 ren1->dst_entry,2292 ren2->dst_entry,2293 o,2294 NULL,2295 NULL);2296}else if((lookup =string_list_lookup(renames2Dst, ren1_dst))) {2297/* Two different files renamed to the same thing */2298char*ren2_dst;2299 ren2 = lookup->util;2300 ren2_dst = ren2->pair->two->path;2301if(strcmp(ren1_dst, ren2_dst) !=0)2302die("BUG: ren1_dst != ren2_dst");23032304 clean_merge =0;2305 ren2->processed =1;2306/*2307 * BUG: We should only mark src_entry as processed2308 * if we are not dealing with a rename + add-source2309 * case.2310 */2311 ren2->src_entry->processed =1;23122313setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,2314 ren1->pair,2315 ren2->pair,2316 branch1,2317 branch2,2318 ren1->dst_entry,2319 ren2->dst_entry,2320 o,2321 ren1->src_entry,2322 ren2->src_entry);23232324}else{2325/* Renamed in 1, maybe changed in 2 */2326/* we only use sha1 and mode of these */2327struct diff_filespec src_other, dst_other;2328int try_merge;23292330/*2331 * unpack_trees loads entries from common-commit2332 * into stage 1, from head-commit into stage 2, and2333 * from merge-commit into stage 3. We keep track2334 * of which side corresponds to the rename.2335 */2336int renamed_stage = a_renames == renames1 ?2:3;2337int other_stage = a_renames == renames1 ?3:2;23382339/* BUG: We should only remove ren1_src in the base2340 * stage and in other_stage (think of rename +2341 * add-source case).2342 */2343remove_file(o,1, ren1_src,2344 renamed_stage ==2|| !was_tracked(ren1_src));23452346oidcpy(&src_other.oid,2347&ren1->src_entry->stages[other_stage].oid);2348 src_other.mode = ren1->src_entry->stages[other_stage].mode;2349oidcpy(&dst_other.oid,2350&ren1->dst_entry->stages[other_stage].oid);2351 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;2352 try_merge =0;23532354if(oid_eq(&src_other.oid, &null_oid) &&2355 ren1->add_turned_into_rename) {2356setup_rename_conflict_info(RENAME_DIR,2357 ren1->pair,2358 NULL,2359 branch1,2360 branch2,2361 ren1->dst_entry,2362 NULL,2363 o,2364 NULL,2365 NULL);2366}else if(oid_eq(&src_other.oid, &null_oid)) {2367setup_rename_conflict_info(RENAME_DELETE,2368 ren1->pair,2369 NULL,2370 branch1,2371 branch2,2372 ren1->dst_entry,2373 NULL,2374 o,2375 NULL,2376 NULL);2377}else if((dst_other.mode == ren1->pair->two->mode) &&2378oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {2379/*2380 * Added file on the other side identical to2381 * the file being renamed: clean merge.2382 * Also, there is no need to overwrite the2383 * file already in the working copy, so call2384 * update_file_flags() instead of2385 * update_file().2386 */2387if(update_file_flags(o,2388&ren1->pair->two->oid,2389 ren1->pair->two->mode,2390 ren1_dst,23911,/* update_cache */23920/* update_wd */))2393 clean_merge = -1;2394}else if(!oid_eq(&dst_other.oid, &null_oid)) {2395 clean_merge =0;2396 try_merge =1;2397output(o,1,_("CONFLICT (rename/add): Rename%s->%sin%s. "2398"%sadded in%s"),2399 ren1_src, ren1_dst, branch1,2400 ren1_dst, branch2);2401if(o->call_depth) {2402struct merge_file_info mfi;2403if(merge_file_one(o, ren1_dst, &null_oid,0,2404&ren1->pair->two->oid,2405 ren1->pair->two->mode,2406&dst_other.oid,2407 dst_other.mode,2408 branch1, branch2, &mfi)) {2409 clean_merge = -1;2410goto cleanup_and_return;2411}2412output(o,1,_("Adding merged%s"), ren1_dst);2413if(update_file(o,0, &mfi.oid,2414 mfi.mode, ren1_dst))2415 clean_merge = -1;2416 try_merge =0;2417}else{2418char*new_path =unique_path(o, ren1_dst, branch2);2419output(o,1,_("Adding as%sinstead"), new_path);2420if(update_file(o,0, &dst_other.oid,2421 dst_other.mode, new_path))2422 clean_merge = -1;2423free(new_path);2424}2425}else2426 try_merge =1;24272428if(clean_merge <0)2429goto cleanup_and_return;2430if(try_merge) {2431struct diff_filespec *one, *a, *b;2432 src_other.path = (char*)ren1_src;24332434 one = ren1->pair->one;2435if(a_renames == renames1) {2436 a = ren1->pair->two;2437 b = &src_other;2438}else{2439 b = ren1->pair->two;2440 a = &src_other;2441}2442update_entry(ren1->dst_entry, one, a, b);2443setup_rename_conflict_info(RENAME_NORMAL,2444 ren1->pair,2445 NULL,2446 branch1,2447 NULL,2448 ren1->dst_entry,2449 NULL,2450 o,2451 NULL,2452 NULL);2453}2454}2455}2456cleanup_and_return:2457string_list_clear(&a_by_dst,0);2458string_list_clear(&b_by_dst,0);24592460return clean_merge;2461}24622463struct rename_info {2464struct string_list *head_renames;2465struct string_list *merge_renames;2466};24672468static voidinitial_cleanup_rename(struct diff_queue_struct *pairs,2469struct hashmap *dir_renames)2470{2471struct hashmap_iter iter;2472struct dir_rename_entry *e;24732474hashmap_iter_init(dir_renames, &iter);2475while((e =hashmap_iter_next(&iter))) {2476free(e->dir);2477strbuf_release(&e->new_dir);2478/* possible_new_dirs already cleared in get_directory_renames */2479}2480hashmap_free(dir_renames,1);2481free(dir_renames);24822483free(pairs->queue);2484free(pairs);2485}24862487static inthandle_renames(struct merge_options *o,2488struct tree *common,2489struct tree *head,2490struct tree *merge,2491struct string_list *entries,2492struct rename_info *ri)2493{2494struct diff_queue_struct *head_pairs, *merge_pairs;2495struct hashmap *dir_re_head, *dir_re_merge;2496int clean =1;24972498 ri->head_renames = NULL;2499 ri->merge_renames = NULL;25002501if(!o->detect_rename)2502return1;25032504 head_pairs =get_diffpairs(o, common, head);2505 merge_pairs =get_diffpairs(o, common, merge);25062507 dir_re_head =get_directory_renames(head_pairs, head);2508 dir_re_merge =get_directory_renames(merge_pairs, merge);25092510handle_directory_level_conflicts(o,2511 dir_re_head, head,2512 dir_re_merge, merge);25132514 ri->head_renames =get_renames(o, head_pairs,2515 dir_re_merge, dir_re_head, head,2516 common, head, merge, entries,2517&clean);2518if(clean <0)2519goto cleanup;2520 ri->merge_renames =get_renames(o, merge_pairs,2521 dir_re_head, dir_re_merge, merge,2522 common, head, merge, entries,2523&clean);2524if(clean <0)2525goto cleanup;2526 clean &=process_renames(o, ri->head_renames, ri->merge_renames);25272528cleanup:2529/*2530 * Some cleanup is deferred until cleanup_renames() because the2531 * data structures are still needed and referenced in2532 * process_entry(). But there are a few things we can free now.2533 */2534initial_cleanup_rename(head_pairs, dir_re_head);2535initial_cleanup_rename(merge_pairs, dir_re_merge);25362537return clean;2538}25392540static voidfinal_cleanup_rename(struct string_list *rename)2541{2542const struct rename *re;2543int i;25442545if(rename == NULL)2546return;25472548for(i =0; i < rename->nr; i++) {2549 re = rename->items[i].util;2550diff_free_filepair(re->pair);2551}2552string_list_clear(rename,1);2553free(rename);2554}25552556static voidfinal_cleanup_renames(struct rename_info *re_info)2557{2558final_cleanup_rename(re_info->head_renames);2559final_cleanup_rename(re_info->merge_renames);2560}25612562static struct object_id *stage_oid(const struct object_id *oid,unsigned mode)2563{2564return(is_null_oid(oid) || mode ==0) ? NULL: (struct object_id *)oid;2565}25662567static intread_oid_strbuf(struct merge_options *o,2568const struct object_id *oid,struct strbuf *dst)2569{2570void*buf;2571enum object_type type;2572unsigned long size;2573 buf =read_object_file(oid, &type, &size);2574if(!buf)2575returnerr(o,_("cannot read object%s"),oid_to_hex(oid));2576if(type != OBJ_BLOB) {2577free(buf);2578returnerr(o,_("object%sis not a blob"),oid_to_hex(oid));2579}2580strbuf_attach(dst, buf, size, size +1);2581return0;2582}25832584static intblob_unchanged(struct merge_options *opt,2585const struct object_id *o_oid,2586unsigned o_mode,2587const struct object_id *a_oid,2588unsigned a_mode,2589int renormalize,const char*path)2590{2591struct strbuf o = STRBUF_INIT;2592struct strbuf a = STRBUF_INIT;2593int ret =0;/* assume changed for safety */25942595if(a_mode != o_mode)2596return0;2597if(oid_eq(o_oid, a_oid))2598return1;2599if(!renormalize)2600return0;26012602assert(o_oid && a_oid);2603if(read_oid_strbuf(opt, o_oid, &o) ||read_oid_strbuf(opt, a_oid, &a))2604goto error_return;2605/*2606 * Note: binary | is used so that both renormalizations are2607 * performed. Comparison can be skipped if both files are2608 * unchanged since their sha1s have already been compared.2609 */2610if(renormalize_buffer(&the_index, path, o.buf, o.len, &o) |2611renormalize_buffer(&the_index, path, a.buf, a.len, &a))2612 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));26132614error_return:2615strbuf_release(&o);2616strbuf_release(&a);2617return ret;2618}26192620static inthandle_modify_delete(struct merge_options *o,2621const char*path,2622struct object_id *o_oid,int o_mode,2623struct object_id *a_oid,int a_mode,2624struct object_id *b_oid,int b_mode)2625{2626const char*modify_branch, *delete_branch;2627struct object_id *changed_oid;2628int changed_mode;26292630if(a_oid) {2631 modify_branch = o->branch1;2632 delete_branch = o->branch2;2633 changed_oid = a_oid;2634 changed_mode = a_mode;2635}else{2636 modify_branch = o->branch2;2637 delete_branch = o->branch1;2638 changed_oid = b_oid;2639 changed_mode = b_mode;2640}26412642returnhandle_change_delete(o,2643 path, NULL,2644 o_oid, o_mode,2645 changed_oid, changed_mode,2646 modify_branch, delete_branch,2647_("modify"),_("modified"));2648}26492650static intmerge_content(struct merge_options *o,2651const char*path,2652struct object_id *o_oid,int o_mode,2653struct object_id *a_oid,int a_mode,2654struct object_id *b_oid,int b_mode,2655struct rename_conflict_info *rename_conflict_info)2656{2657const char*reason =_("content");2658const char*path1 = NULL, *path2 = NULL;2659struct merge_file_info mfi;2660struct diff_filespec one, a, b;2661unsigned df_conflict_remains =0;26622663if(!o_oid) {2664 reason =_("add/add");2665 o_oid = (struct object_id *)&null_oid;2666}2667 one.path = a.path = b.path = (char*)path;2668oidcpy(&one.oid, o_oid);2669 one.mode = o_mode;2670oidcpy(&a.oid, a_oid);2671 a.mode = a_mode;2672oidcpy(&b.oid, b_oid);2673 b.mode = b_mode;26742675if(rename_conflict_info) {2676struct diff_filepair *pair1 = rename_conflict_info->pair1;26772678 path1 = (o->branch1 == rename_conflict_info->branch1) ?2679 pair1->two->path : pair1->one->path;2680/* If rename_conflict_info->pair2 != NULL, we are in2681 * RENAME_ONE_FILE_TO_ONE case. Otherwise, we have a2682 * normal rename.2683 */2684 path2 = (rename_conflict_info->pair2 ||2685 o->branch2 == rename_conflict_info->branch1) ?2686 pair1->two->path : pair1->one->path;26872688if(dir_in_way(path, !o->call_depth,2689S_ISGITLINK(pair1->two->mode)))2690 df_conflict_remains =1;2691}2692if(merge_file_special_markers(o, &one, &a, &b,2693 o->branch1, path1,2694 o->branch2, path2, &mfi))2695return-1;26962697if(mfi.clean && !df_conflict_remains &&2698oid_eq(&mfi.oid, a_oid) && mfi.mode == a_mode) {2699int path_renamed_outside_HEAD;2700output(o,3,_("Skipped%s(merged same as existing)"), path);2701/*2702 * The content merge resulted in the same file contents we2703 * already had. We can return early if those file contents2704 * are recorded at the correct path (which may not be true2705 * if the merge involves a rename).2706 */2707 path_renamed_outside_HEAD = !path2 || !strcmp(path, path2);2708if(!path_renamed_outside_HEAD) {2709add_cacheinfo(o, mfi.mode, &mfi.oid, path,27100, (!o->call_depth),0);2711return mfi.clean;2712}2713}else2714output(o,2,_("Auto-merging%s"), path);27152716if(!mfi.clean) {2717if(S_ISGITLINK(mfi.mode))2718 reason =_("submodule");2719output(o,1,_("CONFLICT (%s): Merge conflict in%s"),2720 reason, path);2721if(rename_conflict_info && !df_conflict_remains)2722if(update_stages(o, path, &one, &a, &b))2723return-1;2724}27252726if(df_conflict_remains) {2727char*new_path;2728if(o->call_depth) {2729remove_file_from_cache(path);2730}else{2731if(!mfi.clean) {2732if(update_stages(o, path, &one, &a, &b))2733return-1;2734}else{2735int file_from_stage2 =was_tracked(path);2736struct diff_filespec merged;2737oidcpy(&merged.oid, &mfi.oid);2738 merged.mode = mfi.mode;27392740if(update_stages(o, path, NULL,2741 file_from_stage2 ? &merged : NULL,2742 file_from_stage2 ? NULL : &merged))2743return-1;2744}27452746}2747 new_path =unique_path(o, path, rename_conflict_info->branch1);2748output(o,1,_("Adding as%sinstead"), new_path);2749if(update_file(o,0, &mfi.oid, mfi.mode, new_path)) {2750free(new_path);2751return-1;2752}2753free(new_path);2754 mfi.clean =0;2755}else if(update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))2756return-1;2757return mfi.clean;2758}27592760/* Per entry merge function */2761static intprocess_entry(struct merge_options *o,2762const char*path,struct stage_data *entry)2763{2764int clean_merge =1;2765int normalize = o->renormalize;2766unsigned o_mode = entry->stages[1].mode;2767unsigned a_mode = entry->stages[2].mode;2768unsigned b_mode = entry->stages[3].mode;2769struct object_id *o_oid =stage_oid(&entry->stages[1].oid, o_mode);2770struct object_id *a_oid =stage_oid(&entry->stages[2].oid, a_mode);2771struct object_id *b_oid =stage_oid(&entry->stages[3].oid, b_mode);27722773 entry->processed =1;2774if(entry->rename_conflict_info) {2775struct rename_conflict_info *conflict_info = entry->rename_conflict_info;2776switch(conflict_info->rename_type) {2777case RENAME_NORMAL:2778case RENAME_ONE_FILE_TO_ONE:2779 clean_merge =merge_content(o, path,2780 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,2781 conflict_info);2782break;2783case RENAME_DIR:2784 clean_merge =1;2785if(conflict_rename_dir(o,2786 conflict_info->pair1,2787 conflict_info->branch1,2788 conflict_info->branch2))2789 clean_merge = -1;2790break;2791case RENAME_DELETE:2792 clean_merge =0;2793if(conflict_rename_delete(o,2794 conflict_info->pair1,2795 conflict_info->branch1,2796 conflict_info->branch2))2797 clean_merge = -1;2798break;2799case RENAME_ONE_FILE_TO_TWO:2800 clean_merge =0;2801if(conflict_rename_rename_1to2(o, conflict_info))2802 clean_merge = -1;2803break;2804case RENAME_TWO_FILES_TO_ONE:2805 clean_merge =0;2806if(conflict_rename_rename_2to1(o, conflict_info))2807 clean_merge = -1;2808break;2809default:2810 entry->processed =0;2811break;2812}2813}else if(o_oid && (!a_oid || !b_oid)) {2814/* Case A: Deleted in one */2815if((!a_oid && !b_oid) ||2816(!b_oid &&blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||2817(!a_oid &&blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {2818/* Deleted in both or deleted in one and2819 * unchanged in the other */2820if(a_oid)2821output(o,2,_("Removing%s"), path);2822/* do not touch working file if it did not exist */2823remove_file(o,1, path, !a_oid);2824}else{2825/* Modify/delete; deleted side may have put a directory in the way */2826 clean_merge =0;2827if(handle_modify_delete(o, path, o_oid, o_mode,2828 a_oid, a_mode, b_oid, b_mode))2829 clean_merge = -1;2830}2831}else if((!o_oid && a_oid && !b_oid) ||2832(!o_oid && !a_oid && b_oid)) {2833/* Case B: Added in one. */2834/* [nothing|directory] -> ([nothing|directory], file) */28352836const char*add_branch;2837const char*other_branch;2838unsigned mode;2839const struct object_id *oid;2840const char*conf;28412842if(a_oid) {2843 add_branch = o->branch1;2844 other_branch = o->branch2;2845 mode = a_mode;2846 oid = a_oid;2847 conf =_("file/directory");2848}else{2849 add_branch = o->branch2;2850 other_branch = o->branch1;2851 mode = b_mode;2852 oid = b_oid;2853 conf =_("directory/file");2854}2855if(dir_in_way(path,2856!o->call_depth && !S_ISGITLINK(a_mode),28570)) {2858char*new_path =unique_path(o, path, add_branch);2859 clean_merge =0;2860output(o,1,_("CONFLICT (%s): There is a directory with name%sin%s. "2861"Adding%sas%s"),2862 conf, path, other_branch, path, new_path);2863if(update_file(o,0, oid, mode, new_path))2864 clean_merge = -1;2865else if(o->call_depth)2866remove_file_from_cache(path);2867free(new_path);2868}else{2869output(o,2,_("Adding%s"), path);2870/* do not overwrite file if already present */2871if(update_file_flags(o, oid, mode, path,1, !a_oid))2872 clean_merge = -1;2873}2874}else if(a_oid && b_oid) {2875/* Case C: Added in both (check for same permissions) and */2876/* case D: Modified in both, but differently. */2877 clean_merge =merge_content(o, path,2878 o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,2879 NULL);2880}else if(!o_oid && !a_oid && !b_oid) {2881/*2882 * this entry was deleted altogether. a_mode == 0 means2883 * we had that path and want to actively remove it.2884 */2885remove_file(o,1, path, !a_mode);2886}else2887die("BUG: fatal merge failure, shouldn't happen.");28882889return clean_merge;2890}28912892intmerge_trees(struct merge_options *o,2893struct tree *head,2894struct tree *merge,2895struct tree *common,2896struct tree **result)2897{2898int code, clean;28992900if(o->subtree_shift) {2901 merge =shift_tree_object(head, merge, o->subtree_shift);2902 common =shift_tree_object(head, common, o->subtree_shift);2903}29042905if(oid_eq(&common->object.oid, &merge->object.oid)) {2906struct strbuf sb = STRBUF_INIT;29072908if(!o->call_depth &&index_has_changes(&sb)) {2909err(o,_("Dirty index: cannot merge (dirty:%s)"),2910 sb.buf);2911return0;2912}2913output(o,0,_("Already up to date!"));2914*result = head;2915return1;2916}29172918 code =git_merge_trees(o->call_depth, common, head, merge);29192920if(code !=0) {2921if(show(o,4) || o->call_depth)2922err(o,_("merging of trees%sand%sfailed"),2923oid_to_hex(&head->object.oid),2924oid_to_hex(&merge->object.oid));2925return-1;2926}29272928if(unmerged_cache()) {2929struct string_list *entries;2930struct rename_info re_info;2931int i;2932/*2933 * Only need the hashmap while processing entries, so2934 * initialize it here and free it when we are done running2935 * through the entries. Keeping it in the merge_options as2936 * opposed to decaring a local hashmap is for convenience2937 * so that we don't have to pass it to around.2938 */2939hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL,512);2940get_files_dirs(o, head);2941get_files_dirs(o, merge);29422943 entries =get_unmerged();2944 clean =handle_renames(o, common, head, merge, entries,2945&re_info);2946record_df_conflict_files(o, entries);2947if(clean <0)2948goto cleanup;2949for(i = entries->nr-1;0<= i; i--) {2950const char*path = entries->items[i].string;2951struct stage_data *e = entries->items[i].util;2952if(!e->processed) {2953int ret =process_entry(o, path, e);2954if(!ret)2955 clean =0;2956else if(ret <0) {2957 clean = ret;2958goto cleanup;2959}2960}2961}2962for(i =0; i < entries->nr; i++) {2963struct stage_data *e = entries->items[i].util;2964if(!e->processed)2965die("BUG: unprocessed path???%s",2966 entries->items[i].string);2967}29682969cleanup:2970final_cleanup_renames(&re_info);29712972string_list_clear(entries,1);2973free(entries);29742975hashmap_free(&o->current_file_dir_set,1);29762977if(clean <0)2978return clean;2979}2980else2981 clean =1;29822983if(o->call_depth && !(*result =write_tree_from_memory(o)))2984return-1;29852986return clean;2987}29882989static struct commit_list *reverse_commit_list(struct commit_list *list)2990{2991struct commit_list *next = NULL, *current, *backup;2992for(current = list; current; current = backup) {2993 backup = current->next;2994 current->next = next;2995 next = current;2996}2997return next;2998}29993000/*3001 * Merge the commits h1 and h2, return the resulting virtual3002 * commit object and a flag indicating the cleanness of the merge.3003 */3004intmerge_recursive(struct merge_options *o,3005struct commit *h1,3006struct commit *h2,3007struct commit_list *ca,3008struct commit **result)3009{3010struct commit_list *iter;3011struct commit *merged_common_ancestors;3012struct tree *mrtree;3013int clean;30143015if(show(o,4)) {3016output(o,4,_("Merging:"));3017output_commit_title(o, h1);3018output_commit_title(o, h2);3019}30203021if(!ca) {3022 ca =get_merge_bases(h1, h2);3023 ca =reverse_commit_list(ca);3024}30253026if(show(o,5)) {3027unsigned cnt =commit_list_count(ca);30283029output(o,5,Q_("found%ucommon ancestor:",3030"found%ucommon ancestors:", cnt), cnt);3031for(iter = ca; iter; iter = iter->next)3032output_commit_title(o, iter->item);3033}30343035 merged_common_ancestors =pop_commit(&ca);3036if(merged_common_ancestors == NULL) {3037/* if there is no common ancestor, use an empty tree */3038struct tree *tree;30393040 tree =lookup_tree(the_hash_algo->empty_tree);3041 merged_common_ancestors =make_virtual_commit(tree,"ancestor");3042}30433044for(iter = ca; iter; iter = iter->next) {3045const char*saved_b1, *saved_b2;3046 o->call_depth++;3047/*3048 * When the merge fails, the result contains files3049 * with conflict markers. The cleanness flag is3050 * ignored (unless indicating an error), it was never3051 * actually used, as result of merge_trees has always3052 * overwritten it: the committed "conflicts" were3053 * already resolved.3054 */3055discard_cache();3056 saved_b1 = o->branch1;3057 saved_b2 = o->branch2;3058 o->branch1 ="Temporary merge branch 1";3059 o->branch2 ="Temporary merge branch 2";3060if(merge_recursive(o, merged_common_ancestors, iter->item,3061 NULL, &merged_common_ancestors) <0)3062return-1;3063 o->branch1 = saved_b1;3064 o->branch2 = saved_b2;3065 o->call_depth--;30663067if(!merged_common_ancestors)3068returnerr(o,_("merge returned no commit"));3069}30703071discard_cache();3072if(!o->call_depth)3073read_cache();30743075 o->ancestor ="merged common ancestors";3076 clean =merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,3077&mrtree);3078if(clean <0) {3079flush_output(o);3080return clean;3081}30823083if(o->call_depth) {3084*result =make_virtual_commit(mrtree,"merged tree");3085commit_list_insert(h1, &(*result)->parents);3086commit_list_insert(h2, &(*result)->parents->next);3087}3088flush_output(o);3089if(!o->call_depth && o->buffer_output <2)3090strbuf_release(&o->obuf);3091if(show(o,2))3092diff_warn_rename_limit("merge.renamelimit",3093 o->needed_rename_limit,0);3094return clean;3095}30963097static struct commit *get_ref(const struct object_id *oid,const char*name)3098{3099struct object *object;31003101 object =deref_tag(parse_object(oid), name,strlen(name));3102if(!object)3103return NULL;3104if(object->type == OBJ_TREE)3105returnmake_virtual_commit((struct tree*)object, name);3106if(object->type != OBJ_COMMIT)3107return NULL;3108if(parse_commit((struct commit *)object))3109return NULL;3110return(struct commit *)object;3111}31123113intmerge_recursive_generic(struct merge_options *o,3114const struct object_id *head,3115const struct object_id *merge,3116int num_base_list,3117const struct object_id **base_list,3118struct commit **result)3119{3120int clean;3121struct lock_file lock = LOCK_INIT;3122struct commit *head_commit =get_ref(head, o->branch1);3123struct commit *next_commit =get_ref(merge, o->branch2);3124struct commit_list *ca = NULL;31253126if(base_list) {3127int i;3128for(i =0; i < num_base_list; ++i) {3129struct commit *base;3130if(!(base =get_ref(base_list[i],oid_to_hex(base_list[i]))))3131returnerr(o,_("Could not parse object '%s'"),3132oid_to_hex(base_list[i]));3133commit_list_insert(base, &ca);3134}3135}31363137hold_locked_index(&lock, LOCK_DIE_ON_ERROR);3138 clean =merge_recursive(o, head_commit, next_commit, ca,3139 result);3140if(clean <0) {3141rollback_lock_file(&lock);3142return clean;3143}31443145if(write_locked_index(&the_index, &lock,3146 COMMIT_LOCK | SKIP_IF_UNCHANGED))3147returnerr(o,_("Unable to write index."));31483149return clean ?0:1;3150}31513152static voidmerge_recursive_config(struct merge_options *o)3153{3154git_config_get_int("merge.verbosity", &o->verbosity);3155git_config_get_int("diff.renamelimit", &o->diff_rename_limit);3156git_config_get_int("merge.renamelimit", &o->merge_rename_limit);3157git_config(git_xmerge_config, NULL);3158}31593160voidinit_merge_options(struct merge_options *o)3161{3162const char*merge_verbosity;3163memset(o,0,sizeof(struct merge_options));3164 o->verbosity =2;3165 o->buffer_output =1;3166 o->diff_rename_limit = -1;3167 o->merge_rename_limit = -1;3168 o->renormalize =0;3169 o->detect_rename =1;3170merge_recursive_config(o);3171 merge_verbosity =getenv("GIT_MERGE_VERBOSITY");3172if(merge_verbosity)3173 o->verbosity =strtol(merge_verbosity, NULL,10);3174if(o->verbosity >=5)3175 o->buffer_output =0;3176strbuf_init(&o->obuf,0);3177string_list_init(&o->df_conflict_file_set,1);3178}31793180intparse_merge_opt(struct merge_options *o,const char*s)3181{3182const char*arg;31833184if(!s || !*s)3185return-1;3186if(!strcmp(s,"ours"))3187 o->recursive_variant = MERGE_RECURSIVE_OURS;3188else if(!strcmp(s,"theirs"))3189 o->recursive_variant = MERGE_RECURSIVE_THEIRS;3190else if(!strcmp(s,"subtree"))3191 o->subtree_shift ="";3192else if(skip_prefix(s,"subtree=", &arg))3193 o->subtree_shift = arg;3194else if(!strcmp(s,"patience"))3195 o->xdl_opts =DIFF_WITH_ALG(o, PATIENCE_DIFF);3196else if(!strcmp(s,"histogram"))3197 o->xdl_opts =DIFF_WITH_ALG(o, HISTOGRAM_DIFF);3198else if(skip_prefix(s,"diff-algorithm=", &arg)) {3199long value =parse_algorithm_value(arg);3200if(value <0)3201return-1;3202/* clear out previous settings */3203DIFF_XDL_CLR(o, NEED_MINIMAL);3204 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;3205 o->xdl_opts |= value;3206}3207else if(!strcmp(s,"ignore-space-change"))3208DIFF_XDL_SET(o, IGNORE_WHITESPACE_CHANGE);3209else if(!strcmp(s,"ignore-all-space"))3210DIFF_XDL_SET(o, IGNORE_WHITESPACE);3211else if(!strcmp(s,"ignore-space-at-eol"))3212DIFF_XDL_SET(o, IGNORE_WHITESPACE_AT_EOL);3213else if(!strcmp(s,"ignore-cr-at-eol"))3214DIFF_XDL_SET(o, IGNORE_CR_AT_EOL);3215else if(!strcmp(s,"renormalize"))3216 o->renormalize =1;3217else if(!strcmp(s,"no-renormalize"))3218 o->renormalize =0;3219else if(!strcmp(s,"no-renames"))3220 o->detect_rename =0;3221else if(!strcmp(s,"find-renames")) {3222 o->detect_rename =1;3223 o->rename_score =0;3224}3225else if(skip_prefix(s,"find-renames=", &arg) ||3226skip_prefix(s,"rename-threshold=", &arg)) {3227if((o->rename_score =parse_rename_score(&arg)) == -1|| *arg !=0)3228return-1;3229 o->detect_rename =1;3230}3231else3232return-1;3233return0;3234}