ec8438b463a5b096ceeca916126e440198ff4740
   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 "cache-tree.h"
   8#include "commit.h"
   9#include "blob.h"
  10#include "tree-walk.h"
  11#include "diff.h"
  12#include "diffcore.h"
  13#include "run-command.h"
  14#include "tag.h"
  15#include "unpack-trees.h"
  16#include "path-list.h"
  17#include "xdiff-interface.h"
  18#include "interpolate.h"
  19#include "attr.h"
  20
  21static int subtree_merge;
  22
  23static struct tree *shift_tree_object(struct tree *one, struct tree *two)
  24{
  25        unsigned char shifted[20];
  26
  27        /*
  28         * NEEDSWORK: this limits the recursion depth to hardcoded
  29         * value '2' to avoid excessive overhead.
  30         */
  31        shift_tree(one->object.sha1, two->object.sha1, shifted, 2);
  32        if (!hashcmp(two->object.sha1, shifted))
  33                return two;
  34        return lookup_tree(shifted);
  35}
  36
  37/*
  38 * A virtual commit has
  39 * - (const char *)commit->util set to the name, and
  40 * - *(int *)commit->object.sha1 set to the virtual id.
  41 */
  42
  43static unsigned commit_list_count(const struct commit_list *l)
  44{
  45        unsigned c = 0;
  46        for (; l; l = l->next )
  47                c++;
  48        return c;
  49}
  50
  51static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
  52{
  53        struct commit *commit = xcalloc(1, sizeof(struct commit));
  54        static unsigned virtual_id = 1;
  55        commit->tree = tree;
  56        commit->util = (void*)comment;
  57        *(int*)commit->object.sha1 = virtual_id++;
  58        /* avoid warnings */
  59        commit->object.parsed = 1;
  60        return commit;
  61}
  62
  63/*
  64 * Since we use get_tree_entry(), which does not put the read object into
  65 * the object pool, we cannot rely on a == b.
  66 */
  67static int sha_eq(const unsigned char *a, const unsigned char *b)
  68{
  69        if (!a && !b)
  70                return 2;
  71        return a && b && hashcmp(a, b) == 0;
  72}
  73
  74/*
  75 * Since we want to write the index eventually, we cannot reuse the index
  76 * for these (temporary) data.
  77 */
  78struct stage_data
  79{
  80        struct
  81        {
  82                unsigned mode;
  83                unsigned char sha[20];
  84        } stages[4];
  85        unsigned processed:1;
  86};
  87
  88struct output_buffer
  89{
  90        struct output_buffer *next;
  91        char *str;
  92};
  93
  94static struct path_list current_file_set = {NULL, 0, 0, 1};
  95static struct path_list current_directory_set = {NULL, 0, 0, 1};
  96
  97static int call_depth = 0;
  98static int verbosity = 2;
  99static int buffer_output = 1;
 100static int do_progress = 1;
 101static unsigned last_percent;
 102static unsigned merged_cnt;
 103static unsigned total_cnt;
 104static volatile sig_atomic_t progress_update;
 105static struct output_buffer *output_list, *output_end;
 106
 107static int show (int v)
 108{
 109        return (!call_depth && verbosity >= v) || verbosity >= 5;
 110}
 111
 112static void output(int v, const char *fmt, ...)
 113{
 114        va_list args;
 115        va_start(args, fmt);
 116        if (buffer_output && show(v)) {
 117                struct output_buffer *b = xmalloc(sizeof(*b));
 118                nfvasprintf(&b->str, fmt, args);
 119                b->next = NULL;
 120                if (output_end)
 121                        output_end->next = b;
 122                else
 123                        output_list = b;
 124                output_end = b;
 125        } else if (show(v)) {
 126                int i;
 127                for (i = call_depth; i--;)
 128                        fputs("  ", stdout);
 129                vfprintf(stdout, fmt, args);
 130                fputc('\n', stdout);
 131        }
 132        va_end(args);
 133}
 134
 135static void flush_output()
 136{
 137        struct output_buffer *b, *n;
 138        for (b = output_list; b; b = n) {
 139                int i;
 140                for (i = call_depth; i--;)
 141                        fputs("  ", stdout);
 142                fputs(b->str, stdout);
 143                fputc('\n', stdout);
 144                n = b->next;
 145                free(b->str);
 146                free(b);
 147        }
 148        output_list = NULL;
 149        output_end = NULL;
 150}
 151
 152static void output_commit_title(struct commit *commit)
 153{
 154        int i;
 155        flush_output();
 156        for (i = call_depth; i--;)
 157                fputs("  ", stdout);
 158        if (commit->util)
 159                printf("virtual %s\n", (char *)commit->util);
 160        else {
 161                printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
 162                if (parse_commit(commit) != 0)
 163                        printf("(bad commit)\n");
 164                else {
 165                        const char *s;
 166                        int len;
 167                        for (s = commit->buffer; *s; s++)
 168                                if (*s == '\n' && s[1] == '\n') {
 169                                        s += 2;
 170                                        break;
 171                                }
 172                        for (len = 0; s[len] && '\n' != s[len]; len++)
 173                                ; /* do nothing */
 174                        printf("%.*s\n", len, s);
 175                }
 176        }
 177}
 178
 179static void progress_interval(int signum)
 180{
 181        progress_update = 1;
 182}
 183
 184static void setup_progress_signal(void)
 185{
 186        struct sigaction sa;
 187        struct itimerval v;
 188
 189        memset(&sa, 0, sizeof(sa));
 190        sa.sa_handler = progress_interval;
 191        sigemptyset(&sa.sa_mask);
 192        sa.sa_flags = SA_RESTART;
 193        sigaction(SIGALRM, &sa, NULL);
 194
 195        v.it_interval.tv_sec = 1;
 196        v.it_interval.tv_usec = 0;
 197        v.it_value = v.it_interval;
 198        setitimer(ITIMER_REAL, &v, NULL);
 199}
 200
 201static void display_progress()
 202{
 203        unsigned percent = total_cnt ? merged_cnt * 100 / total_cnt : 0;
 204        if (progress_update || percent != last_percent) {
 205                fprintf(stderr, "%4u%% (%u/%u) done\r",
 206                        percent, merged_cnt, total_cnt);
 207                progress_update = 0;
 208                last_percent = percent;
 209        }
 210}
 211
 212static struct cache_entry *make_cache_entry(unsigned int mode,
 213                const unsigned char *sha1, const char *path, int stage, int refresh)
 214{
 215        int size, len;
 216        struct cache_entry *ce;
 217
 218        if (!verify_path(path))
 219                return NULL;
 220
 221        len = strlen(path);
 222        size = cache_entry_size(len);
 223        ce = xcalloc(1, size);
 224
 225        hashcpy(ce->sha1, sha1);
 226        memcpy(ce->name, path, len);
 227        ce->ce_flags = create_ce_flags(len, stage);
 228        ce->ce_mode = create_ce_mode(mode);
 229
 230        if (refresh)
 231                return refresh_cache_entry(ce, 0);
 232
 233        return ce;
 234}
 235
 236static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
 237                const char *path, int stage, int refresh, int options)
 238{
 239        struct cache_entry *ce;
 240        ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
 241        if (!ce)
 242                return error("addinfo_cache failed for path '%s'", path);
 243        return add_cache_entry(ce, options);
 244}
 245
 246/*
 247 * This is a global variable which is used in a number of places but
 248 * only written to in the 'merge' function.
 249 *
 250 * index_only == 1    => Don't leave any non-stage 0 entries in the cache and
 251 *                       don't update the working directory.
 252 *               0    => Leave unmerged entries in the cache and update
 253 *                       the working directory.
 254 */
 255static int index_only = 0;
 256
 257static int git_merge_trees(int index_only,
 258                           struct tree *common,
 259                           struct tree *head,
 260                           struct tree *merge)
 261{
 262        int rc;
 263        struct object_list *trees = NULL;
 264        struct unpack_trees_options opts;
 265
 266        memset(&opts, 0, sizeof(opts));
 267        if (index_only)
 268                opts.index_only = 1;
 269        else
 270                opts.update = 1;
 271        opts.merge = 1;
 272        opts.head_idx = 2;
 273        opts.fn = threeway_merge;
 274
 275        object_list_append(&common->object, &trees);
 276        object_list_append(&head->object, &trees);
 277        object_list_append(&merge->object, &trees);
 278
 279        rc = unpack_trees(trees, &opts);
 280        cache_tree_free(&active_cache_tree);
 281        return rc;
 282}
 283
 284static int unmerged_index(void)
 285{
 286        int i;
 287        for (i = 0; i < active_nr; i++) {
 288                struct cache_entry *ce = active_cache[i];
 289                if (ce_stage(ce))
 290                        return 1;
 291        }
 292        return 0;
 293}
 294
 295static struct tree *git_write_tree(void)
 296{
 297        struct tree *result = NULL;
 298
 299        if (unmerged_index()) {
 300                int i;
 301                output(0, "There are unmerged index entries:");
 302                for (i = 0; i < active_nr; i++) {
 303                        struct cache_entry *ce = active_cache[i];
 304                        if (ce_stage(ce))
 305                                output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
 306                }
 307                return NULL;
 308        }
 309
 310        if (!active_cache_tree)
 311                active_cache_tree = cache_tree();
 312
 313        if (!cache_tree_fully_valid(active_cache_tree) &&
 314            cache_tree_update(active_cache_tree,
 315                              active_cache, active_nr, 0, 0) < 0)
 316                die("error building trees");
 317
 318        result = lookup_tree(active_cache_tree->sha1);
 319
 320        return result;
 321}
 322
 323static int save_files_dirs(const unsigned char *sha1,
 324                const char *base, int baselen, const char *path,
 325                unsigned int mode, int stage)
 326{
 327        int len = strlen(path);
 328        char *newpath = xmalloc(baselen + len + 1);
 329        memcpy(newpath, base, baselen);
 330        memcpy(newpath + baselen, path, len);
 331        newpath[baselen + len] = '\0';
 332
 333        if (S_ISDIR(mode))
 334                path_list_insert(newpath, &current_directory_set);
 335        else
 336                path_list_insert(newpath, &current_file_set);
 337        free(newpath);
 338
 339        return READ_TREE_RECURSIVE;
 340}
 341
 342static int get_files_dirs(struct tree *tree)
 343{
 344        int n;
 345        if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
 346                return 0;
 347        n = current_file_set.nr + current_directory_set.nr;
 348        return n;
 349}
 350
 351/*
 352 * Returns a index_entry instance which doesn't have to correspond to
 353 * a real cache entry in Git's index.
 354 */
 355static struct stage_data *insert_stage_data(const char *path,
 356                struct tree *o, struct tree *a, struct tree *b,
 357                struct path_list *entries)
 358{
 359        struct path_list_item *item;
 360        struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
 361        get_tree_entry(o->object.sha1, path,
 362                        e->stages[1].sha, &e->stages[1].mode);
 363        get_tree_entry(a->object.sha1, path,
 364                        e->stages[2].sha, &e->stages[2].mode);
 365        get_tree_entry(b->object.sha1, path,
 366                        e->stages[3].sha, &e->stages[3].mode);
 367        item = path_list_insert(path, entries);
 368        item->util = e;
 369        return e;
 370}
 371
 372/*
 373 * Create a dictionary mapping file names to stage_data objects. The
 374 * dictionary contains one entry for every path with a non-zero stage entry.
 375 */
 376static struct path_list *get_unmerged(void)
 377{
 378        struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
 379        int i;
 380
 381        unmerged->strdup_paths = 1;
 382        total_cnt += active_nr;
 383
 384        for (i = 0; i < active_nr; i++, merged_cnt++) {
 385                struct path_list_item *item;
 386                struct stage_data *e;
 387                struct cache_entry *ce = active_cache[i];
 388                if (do_progress)
 389                        display_progress();
 390                if (!ce_stage(ce))
 391                        continue;
 392
 393                item = path_list_lookup(ce->name, unmerged);
 394                if (!item) {
 395                        item = path_list_insert(ce->name, unmerged);
 396                        item->util = xcalloc(1, sizeof(struct stage_data));
 397                }
 398                e = item->util;
 399                e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
 400                hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
 401        }
 402
 403        return unmerged;
 404}
 405
 406struct rename
 407{
 408        struct diff_filepair *pair;
 409        struct stage_data *src_entry;
 410        struct stage_data *dst_entry;
 411        unsigned processed:1;
 412};
 413
 414/*
 415 * Get information of all renames which occurred between 'o_tree' and
 416 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
 417 * 'b_tree') to be able to associate the correct cache entries with
 418 * the rename information. 'tree' is always equal to either a_tree or b_tree.
 419 */
 420static struct path_list *get_renames(struct tree *tree,
 421                                        struct tree *o_tree,
 422                                        struct tree *a_tree,
 423                                        struct tree *b_tree,
 424                                        struct path_list *entries)
 425{
 426        int i;
 427        struct path_list *renames;
 428        struct diff_options opts;
 429
 430        renames = xcalloc(1, sizeof(struct path_list));
 431        diff_setup(&opts);
 432        opts.recursive = 1;
 433        opts.detect_rename = DIFF_DETECT_RENAME;
 434        opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 435        if (diff_setup_done(&opts) < 0)
 436                die("diff setup failed");
 437        diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
 438        diffcore_std(&opts);
 439        for (i = 0; i < diff_queued_diff.nr; ++i) {
 440                struct path_list_item *item;
 441                struct rename *re;
 442                struct diff_filepair *pair = diff_queued_diff.queue[i];
 443                if (pair->status != 'R') {
 444                        diff_free_filepair(pair);
 445                        continue;
 446                }
 447                re = xmalloc(sizeof(*re));
 448                re->processed = 0;
 449                re->pair = pair;
 450                item = path_list_lookup(re->pair->one->path, entries);
 451                if (!item)
 452                        re->src_entry = insert_stage_data(re->pair->one->path,
 453                                        o_tree, a_tree, b_tree, entries);
 454                else
 455                        re->src_entry = item->util;
 456
 457                item = path_list_lookup(re->pair->two->path, entries);
 458                if (!item)
 459                        re->dst_entry = insert_stage_data(re->pair->two->path,
 460                                        o_tree, a_tree, b_tree, entries);
 461                else
 462                        re->dst_entry = item->util;
 463                item = path_list_insert(pair->one->path, renames);
 464                item->util = re;
 465        }
 466        opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 467        diff_queued_diff.nr = 0;
 468        diff_flush(&opts);
 469        return renames;
 470}
 471
 472static int update_stages(const char *path, struct diff_filespec *o,
 473                         struct diff_filespec *a, struct diff_filespec *b,
 474                         int clear)
 475{
 476        int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
 477        if (clear)
 478                if (remove_file_from_cache(path))
 479                        return -1;
 480        if (o)
 481                if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
 482                        return -1;
 483        if (a)
 484                if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
 485                        return -1;
 486        if (b)
 487                if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
 488                        return -1;
 489        return 0;
 490}
 491
 492static int remove_path(const char *name)
 493{
 494        int ret, len;
 495        char *slash, *dirs;
 496
 497        ret = unlink(name);
 498        if (ret)
 499                return ret;
 500        len = strlen(name);
 501        dirs = xmalloc(len+1);
 502        memcpy(dirs, name, len);
 503        dirs[len] = '\0';
 504        while ((slash = strrchr(name, '/'))) {
 505                *slash = '\0';
 506                len = slash - name;
 507                if (rmdir(name) != 0)
 508                        break;
 509        }
 510        free(dirs);
 511        return ret;
 512}
 513
 514static int remove_file(int clean, const char *path, int no_wd)
 515{
 516        int update_cache = index_only || clean;
 517        int update_working_directory = !index_only && !no_wd;
 518
 519        if (update_cache) {
 520                if (remove_file_from_cache(path))
 521                        return -1;
 522        }
 523        if (update_working_directory) {
 524                unlink(path);
 525                if (errno != ENOENT || errno != EISDIR)
 526                        return -1;
 527                remove_path(path);
 528        }
 529        return 0;
 530}
 531
 532static char *unique_path(const char *path, const char *branch)
 533{
 534        char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
 535        int suffix = 0;
 536        struct stat st;
 537        char *p = newpath + strlen(path);
 538        strcpy(newpath, path);
 539        *(p++) = '~';
 540        strcpy(p, branch);
 541        for (; *p; ++p)
 542                if ('/' == *p)
 543                        *p = '_';
 544        while (path_list_has_path(&current_file_set, newpath) ||
 545               path_list_has_path(&current_directory_set, newpath) ||
 546               lstat(newpath, &st) == 0)
 547                sprintf(p, "_%d", suffix++);
 548
 549        path_list_insert(newpath, &current_file_set);
 550        return newpath;
 551}
 552
 553static int mkdir_p(const char *path, unsigned long mode)
 554{
 555        /* path points to cache entries, so xstrdup before messing with it */
 556        char *buf = xstrdup(path);
 557        int result = safe_create_leading_directories(buf);
 558        free(buf);
 559        return result;
 560}
 561
 562static void flush_buffer(int fd, const char *buf, unsigned long size)
 563{
 564        while (size > 0) {
 565                long ret = write_in_full(fd, buf, size);
 566                if (ret < 0) {
 567                        /* Ignore epipe */
 568                        if (errno == EPIPE)
 569                                break;
 570                        die("merge-recursive: %s", strerror(errno));
 571                } else if (!ret) {
 572                        die("merge-recursive: disk full?");
 573                }
 574                size -= ret;
 575                buf += ret;
 576        }
 577}
 578
 579static void update_file_flags(const unsigned char *sha,
 580                              unsigned mode,
 581                              const char *path,
 582                              int update_cache,
 583                              int update_wd)
 584{
 585        if (index_only)
 586                update_wd = 0;
 587
 588        if (update_wd) {
 589                enum object_type type;
 590                void *buf;
 591                unsigned long size;
 592
 593                buf = read_sha1_file(sha, &type, &size);
 594                if (!buf)
 595                        die("cannot read object %s '%s'", sha1_to_hex(sha), path);
 596                if (type != OBJ_BLOB)
 597                        die("blob expected for %s '%s'", sha1_to_hex(sha), path);
 598
 599                if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
 600                        int fd;
 601                        if (mkdir_p(path, 0777))
 602                                die("failed to create path %s: %s", path, strerror(errno));
 603                        unlink(path);
 604                        if (mode & 0100)
 605                                mode = 0777;
 606                        else
 607                                mode = 0666;
 608                        fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
 609                        if (fd < 0)
 610                                die("failed to open %s: %s", path, strerror(errno));
 611                        flush_buffer(fd, buf, size);
 612                        close(fd);
 613                } else if (S_ISLNK(mode)) {
 614                        char *lnk = xmalloc(size + 1);
 615                        memcpy(lnk, buf, size);
 616                        lnk[size] = '\0';
 617                        mkdir_p(path, 0777);
 618                        unlink(path);
 619                        symlink(lnk, path);
 620                        free(lnk);
 621                } else
 622                        die("do not know what to do with %06o %s '%s'",
 623                            mode, sha1_to_hex(sha), path);
 624        }
 625        if (update_cache)
 626                add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
 627}
 628
 629static void update_file(int clean,
 630                        const unsigned char *sha,
 631                        unsigned mode,
 632                        const char *path)
 633{
 634        update_file_flags(sha, mode, path, index_only || clean, !index_only);
 635}
 636
 637/* Low level file merging, update and removal */
 638
 639struct merge_file_info
 640{
 641        unsigned char sha[20];
 642        unsigned mode;
 643        unsigned clean:1,
 644                 merge:1;
 645};
 646
 647static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
 648{
 649        unsigned long size;
 650        enum object_type type;
 651
 652        if (!hashcmp(sha1, null_sha1)) {
 653                mm->ptr = xstrdup("");
 654                mm->size = 0;
 655                return;
 656        }
 657
 658        mm->ptr = read_sha1_file(sha1, &type, &size);
 659        if (!mm->ptr || type != OBJ_BLOB)
 660                die("unable to read blob object %s", sha1_to_hex(sha1));
 661        mm->size = size;
 662}
 663
 664/*
 665 * Customizable low-level merge drivers support.
 666 */
 667
 668struct ll_merge_driver;
 669typedef int (*ll_merge_fn)(const struct ll_merge_driver *,
 670                           const char *path,
 671                           mmfile_t *orig,
 672                           mmfile_t *src1, const char *name1,
 673                           mmfile_t *src2, const char *name2,
 674                           mmbuffer_t *result);
 675
 676struct ll_merge_driver {
 677        const char *name;
 678        const char *description;
 679        ll_merge_fn fn;
 680        const char *recursive;
 681        struct ll_merge_driver *next;
 682        char *cmdline;
 683};
 684
 685/*
 686 * Built-in low-levels
 687 */
 688static int ll_xdl_merge(const struct ll_merge_driver *drv_unused,
 689                        const char *path_unused,
 690                        mmfile_t *orig,
 691                        mmfile_t *src1, const char *name1,
 692                        mmfile_t *src2, const char *name2,
 693                        mmbuffer_t *result)
 694{
 695        xpparam_t xpp;
 696
 697        memset(&xpp, 0, sizeof(xpp));
 698        return xdl_merge(orig,
 699                         src1, name1,
 700                         src2, name2,
 701                         &xpp, XDL_MERGE_ZEALOUS,
 702                         result);
 703}
 704
 705static int ll_union_merge(const struct ll_merge_driver *drv_unused,
 706                          const char *path_unused,
 707                          mmfile_t *orig,
 708                          mmfile_t *src1, const char *name1,
 709                          mmfile_t *src2, const char *name2,
 710                          mmbuffer_t *result)
 711{
 712        char *src, *dst;
 713        long size;
 714        const int marker_size = 7;
 715
 716        int status = ll_xdl_merge(drv_unused, path_unused,
 717                                  orig, src1, NULL, src2, NULL, result);
 718        if (status <= 0)
 719                return status;
 720        size = result->size;
 721        src = dst = result->ptr;
 722        while (size) {
 723                char ch;
 724                if ((marker_size < size) &&
 725                    (*src == '<' || *src == '=' || *src == '>')) {
 726                        int i;
 727                        ch = *src;
 728                        for (i = 0; i < marker_size; i++)
 729                                if (src[i] != ch)
 730                                        goto not_a_marker;
 731                        if (src[marker_size] != '\n')
 732                                goto not_a_marker;
 733                        src += marker_size + 1;
 734                        size -= marker_size + 1;
 735                        continue;
 736                }
 737        not_a_marker:
 738                do {
 739                        ch = *src++;
 740                        *dst++ = ch;
 741                        size--;
 742                } while (ch != '\n' && size);
 743        }
 744        result->size = dst - result->ptr;
 745        return 0;
 746}
 747
 748static int ll_binary_merge(const struct ll_merge_driver *drv_unused,
 749                           const char *path_unused,
 750                           mmfile_t *orig,
 751                           mmfile_t *src1, const char *name1,
 752                           mmfile_t *src2, const char *name2,
 753                           mmbuffer_t *result)
 754{
 755        /*
 756         * The tentative merge result is "ours" for the final round,
 757         * or common ancestor for an internal merge.  Still return
 758         * "conflicted merge" status.
 759         */
 760        mmfile_t *stolen = index_only ? orig : src1;
 761
 762        result->ptr = stolen->ptr;
 763        result->size = stolen->size;
 764        stolen->ptr = NULL;
 765        return 1;
 766}
 767
 768#define LL_BINARY_MERGE 0
 769#define LL_TEXT_MERGE 1
 770#define LL_UNION_MERGE 2
 771static struct ll_merge_driver ll_merge_drv[] = {
 772        { "binary", "built-in binary merge", ll_binary_merge },
 773        { "text", "built-in 3-way text merge", ll_xdl_merge },
 774        { "union", "built-in union merge", ll_union_merge },
 775};
 776
 777static void create_temp(mmfile_t *src, char *path)
 778{
 779        int fd;
 780
 781        strcpy(path, ".merge_file_XXXXXX");
 782        fd = mkstemp(path);
 783        if (fd < 0)
 784                die("unable to create temp-file");
 785        if (write_in_full(fd, src->ptr, src->size) != src->size)
 786                die("unable to write temp-file");
 787        close(fd);
 788}
 789
 790/*
 791 * User defined low-level merge driver support.
 792 */
 793static int ll_ext_merge(const struct ll_merge_driver *fn,
 794                        const char *path,
 795                        mmfile_t *orig,
 796                        mmfile_t *src1, const char *name1,
 797                        mmfile_t *src2, const char *name2,
 798                        mmbuffer_t *result)
 799{
 800        char temp[3][50];
 801        char cmdbuf[2048];
 802        struct interp table[] = {
 803                { "%O" },
 804                { "%A" },
 805                { "%B" },
 806        };
 807        struct child_process child;
 808        const char *args[20];
 809        int status, fd, i;
 810        struct stat st;
 811
 812        result->ptr = NULL;
 813        result->size = 0;
 814        create_temp(orig, temp[0]);
 815        create_temp(src1, temp[1]);
 816        create_temp(src2, temp[2]);
 817
 818        interp_set_entry(table, 0, temp[0]);
 819        interp_set_entry(table, 1, temp[1]);
 820        interp_set_entry(table, 2, temp[2]);
 821
 822        output(1, "merging %s using %s", path,
 823               fn->description ? fn->description : fn->name);
 824
 825        interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3);
 826
 827        memset(&child, 0, sizeof(child));
 828        child.argv = args;
 829        args[0] = "sh";
 830        args[1] = "-c";
 831        args[2] = cmdbuf;
 832        args[3] = NULL;
 833
 834        status = run_command(&child);
 835        if (status < -ERR_RUN_COMMAND_FORK)
 836                ; /* failure in run-command */
 837        else
 838                status = -status;
 839        fd = open(temp[1], O_RDONLY);
 840        if (fd < 0)
 841                goto bad;
 842        if (fstat(fd, &st))
 843                goto close_bad;
 844        result->size = st.st_size;
 845        result->ptr = xmalloc(result->size + 1);
 846        if (read_in_full(fd, result->ptr, result->size) != result->size) {
 847                free(result->ptr);
 848                result->ptr = NULL;
 849                result->size = 0;
 850        }
 851 close_bad:
 852        close(fd);
 853 bad:
 854        for (i = 0; i < 3; i++)
 855                unlink(temp[i]);
 856        return status;
 857}
 858
 859/*
 860 * merge.default and merge.driver configuration items
 861 */
 862static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail;
 863static const char *default_ll_merge;
 864
 865static int read_merge_config(const char *var, const char *value)
 866{
 867        struct ll_merge_driver *fn;
 868        const char *ep, *name;
 869        int namelen;
 870
 871        if (!strcmp(var, "merge.default")) {
 872                if (value)
 873                        default_ll_merge = strdup(value);
 874                return 0;
 875        }
 876
 877        /*
 878         * We are not interested in anything but "merge.<name>.variable";
 879         * especially, we do not want to look at variables such as
 880         * "merge.summary", "merge.tool", and "merge.verbosity".
 881         */
 882        if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 6)
 883                return 0;
 884
 885        /*
 886         * Find existing one as we might be processing merge.<name>.var2
 887         * after seeing merge.<name>.var1.
 888         */
 889        name = var + 6;
 890        namelen = ep - name;
 891        for (fn = ll_user_merge; fn; fn = fn->next)
 892                if (!strncmp(fn->name, name, namelen) && !fn->name[namelen])
 893                        break;
 894        if (!fn) {
 895                char *namebuf;
 896                fn = xcalloc(1, sizeof(struct ll_merge_driver));
 897                namebuf = xmalloc(namelen + 1);
 898                memcpy(namebuf, name, namelen);
 899                namebuf[namelen] = 0;
 900                fn->name = namebuf;
 901                fn->fn = ll_ext_merge;
 902                fn->next = *ll_user_merge_tail;
 903                *ll_user_merge_tail = fn;
 904        }
 905
 906        ep++;
 907
 908        if (!strcmp("name", ep)) {
 909                if (!value)
 910                        return error("%s: lacks value", var);
 911                fn->description = strdup(value);
 912                return 0;
 913        }
 914
 915        if (!strcmp("driver", ep)) {
 916                if (!value)
 917                        return error("%s: lacks value", var);
 918                /*
 919                 * merge.<name>.driver specifies the command line:
 920                 *
 921                 *      command-line
 922                 *
 923                 * The command-line will be interpolated with the following
 924                 * tokens and is given to the shell:
 925                 *
 926                 *    %O - temporary file name for the merge base.
 927                 *    %A - temporary file name for our version.
 928                 *    %B - temporary file name for the other branches' version.
 929                 *
 930                 * The external merge driver should write the results in the
 931                 * file named by %A, and signal that it has done with zero exit
 932                 * status.
 933                 */
 934                fn->cmdline = strdup(value);
 935                return 0;
 936        }
 937
 938        if (!strcmp("recursive", ep)) {
 939                if (!value)
 940                        return error("%s: lacks value", var);
 941                fn->recursive = strdup(value);
 942                return 0;
 943        }
 944
 945        return 0;
 946}
 947
 948static void initialize_ll_merge(void)
 949{
 950        if (ll_user_merge_tail)
 951                return;
 952        ll_user_merge_tail = &ll_user_merge;
 953        git_config(read_merge_config);
 954}
 955
 956static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr)
 957{
 958        struct ll_merge_driver *fn;
 959        const char *name;
 960        int i;
 961
 962        initialize_ll_merge();
 963
 964        if (ATTR_TRUE(merge_attr))
 965                return &ll_merge_drv[LL_TEXT_MERGE];
 966        else if (ATTR_FALSE(merge_attr))
 967                return &ll_merge_drv[LL_BINARY_MERGE];
 968        else if (ATTR_UNSET(merge_attr)) {
 969                if (!default_ll_merge)
 970                        return &ll_merge_drv[LL_TEXT_MERGE];
 971                else
 972                        name = default_ll_merge;
 973        }
 974        else
 975                name = merge_attr;
 976
 977        for (fn = ll_user_merge; fn; fn = fn->next)
 978                if (!strcmp(fn->name, name))
 979                        return fn;
 980
 981        for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++)
 982                if (!strcmp(ll_merge_drv[i].name, name))
 983                        return &ll_merge_drv[i];
 984
 985        /* default to the 3-way */
 986        return &ll_merge_drv[LL_TEXT_MERGE];
 987}
 988
 989static const char *git_path_check_merge(const char *path)
 990{
 991        static struct git_attr_check attr_merge_check;
 992
 993        if (!attr_merge_check.attr)
 994                attr_merge_check.attr = git_attr("merge", 5);
 995
 996        if (git_checkattr(path, 1, &attr_merge_check))
 997                return NULL;
 998        return attr_merge_check.value;
 999}
1000
1001static int ll_merge(mmbuffer_t *result_buf,
1002                    struct diff_filespec *o,
1003                    struct diff_filespec *a,
1004                    struct diff_filespec *b,
1005                    const char *branch1,
1006                    const char *branch2)
1007{
1008        mmfile_t orig, src1, src2;
1009        char *name1, *name2;
1010        int merge_status;
1011        const char *ll_driver_name;
1012        const struct ll_merge_driver *driver;
1013
1014        name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
1015        name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
1016
1017        fill_mm(o->sha1, &orig);
1018        fill_mm(a->sha1, &src1);
1019        fill_mm(b->sha1, &src2);
1020
1021        ll_driver_name = git_path_check_merge(a->path);
1022        driver = find_ll_merge_driver(ll_driver_name);
1023
1024        if (index_only && driver->recursive) {
1025                void *merge_attr;
1026
1027                ll_driver_name = driver->recursive;
1028                merge_attr = git_attr(ll_driver_name, strlen(ll_driver_name));
1029                driver = find_ll_merge_driver(merge_attr);
1030        }
1031        merge_status = driver->fn(driver, a->path,
1032                                  &orig, &src1, name1, &src2, name2,
1033                                  result_buf);
1034
1035        free(name1);
1036        free(name2);
1037        free(orig.ptr);
1038        free(src1.ptr);
1039        free(src2.ptr);
1040        return merge_status;
1041}
1042
1043static struct merge_file_info merge_file(struct diff_filespec *o,
1044                struct diff_filespec *a, struct diff_filespec *b,
1045                const char *branch1, const char *branch2)
1046{
1047        struct merge_file_info result;
1048        result.merge = 0;
1049        result.clean = 1;
1050
1051        if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1052                result.clean = 0;
1053                if (S_ISREG(a->mode)) {
1054                        result.mode = a->mode;
1055                        hashcpy(result.sha, a->sha1);
1056                } else {
1057                        result.mode = b->mode;
1058                        hashcpy(result.sha, b->sha1);
1059                }
1060        } else {
1061                if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
1062                        result.merge = 1;
1063
1064                result.mode = a->mode == o->mode ? b->mode: a->mode;
1065
1066                if (sha_eq(a->sha1, o->sha1))
1067                        hashcpy(result.sha, b->sha1);
1068                else if (sha_eq(b->sha1, o->sha1))
1069                        hashcpy(result.sha, a->sha1);
1070                else if (S_ISREG(a->mode)) {
1071                        mmbuffer_t result_buf;
1072                        int merge_status;
1073
1074                        merge_status = ll_merge(&result_buf, o, a, b,
1075                                                branch1, branch2);
1076
1077                        if ((merge_status < 0) || !result_buf.ptr)
1078                                die("Failed to execute internal merge");
1079
1080                        if (write_sha1_file(result_buf.ptr, result_buf.size,
1081                                            blob_type, result.sha))
1082                                die("Unable to add %s to database",
1083                                    a->path);
1084
1085                        free(result_buf.ptr);
1086                        result.clean = (merge_status == 0);
1087                } else {
1088                        if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
1089                                die("cannot merge modes?");
1090
1091                        hashcpy(result.sha, a->sha1);
1092
1093                        if (!sha_eq(a->sha1, b->sha1))
1094                                result.clean = 0;
1095                }
1096        }
1097
1098        return result;
1099}
1100
1101static void conflict_rename_rename(struct rename *ren1,
1102                                   const char *branch1,
1103                                   struct rename *ren2,
1104                                   const char *branch2)
1105{
1106        char *del[2];
1107        int delp = 0;
1108        const char *ren1_dst = ren1->pair->two->path;
1109        const char *ren2_dst = ren2->pair->two->path;
1110        const char *dst_name1 = ren1_dst;
1111        const char *dst_name2 = ren2_dst;
1112        if (path_list_has_path(&current_directory_set, ren1_dst)) {
1113                dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
1114                output(1, "%s is a directory in %s added as %s instead",
1115                       ren1_dst, branch2, dst_name1);
1116                remove_file(0, ren1_dst, 0);
1117        }
1118        if (path_list_has_path(&current_directory_set, ren2_dst)) {
1119                dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
1120                output(1, "%s is a directory in %s added as %s instead",
1121                       ren2_dst, branch1, dst_name2);
1122                remove_file(0, ren2_dst, 0);
1123        }
1124        if (index_only) {
1125                remove_file_from_cache(dst_name1);
1126                remove_file_from_cache(dst_name2);
1127                /*
1128                 * Uncomment to leave the conflicting names in the resulting tree
1129                 *
1130                 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
1131                 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
1132                 */
1133        } else {
1134                update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
1135                update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
1136        }
1137        while (delp--)
1138                free(del[delp]);
1139}
1140
1141static void conflict_rename_dir(struct rename *ren1,
1142                                const char *branch1)
1143{
1144        char *new_path = unique_path(ren1->pair->two->path, branch1);
1145        output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
1146        remove_file(0, ren1->pair->two->path, 0);
1147        update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
1148        free(new_path);
1149}
1150
1151static void conflict_rename_rename_2(struct rename *ren1,
1152                                     const char *branch1,
1153                                     struct rename *ren2,
1154                                     const char *branch2)
1155{
1156        char *new_path1 = unique_path(ren1->pair->two->path, branch1);
1157        char *new_path2 = unique_path(ren2->pair->two->path, branch2);
1158        output(1, "Renamed %s to %s and %s to %s instead",
1159               ren1->pair->one->path, new_path1,
1160               ren2->pair->one->path, new_path2);
1161        remove_file(0, ren1->pair->two->path, 0);
1162        update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
1163        update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
1164        free(new_path2);
1165        free(new_path1);
1166}
1167
1168static int process_renames(struct path_list *a_renames,
1169                           struct path_list *b_renames,
1170                           const char *a_branch,
1171                           const char *b_branch)
1172{
1173        int clean_merge = 1, i, j;
1174        struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
1175        const struct rename *sre;
1176
1177        for (i = 0; i < a_renames->nr; i++) {
1178                sre = a_renames->items[i].util;
1179                path_list_insert(sre->pair->two->path, &a_by_dst)->util
1180                        = sre->dst_entry;
1181        }
1182        for (i = 0; i < b_renames->nr; i++) {
1183                sre = b_renames->items[i].util;
1184                path_list_insert(sre->pair->two->path, &b_by_dst)->util
1185                        = sre->dst_entry;
1186        }
1187
1188        for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1189                int compare;
1190                char *src;
1191                struct path_list *renames1, *renames2, *renames2Dst;
1192                struct rename *ren1 = NULL, *ren2 = NULL;
1193                const char *branch1, *branch2;
1194                const char *ren1_src, *ren1_dst;
1195
1196                if (i >= a_renames->nr) {
1197                        compare = 1;
1198                        ren2 = b_renames->items[j++].util;
1199                } else if (j >= b_renames->nr) {
1200                        compare = -1;
1201                        ren1 = a_renames->items[i++].util;
1202                } else {
1203                        compare = strcmp(a_renames->items[i].path,
1204                                        b_renames->items[j].path);
1205                        if (compare <= 0)
1206                                ren1 = a_renames->items[i++].util;
1207                        if (compare >= 0)
1208                                ren2 = b_renames->items[j++].util;
1209                }
1210
1211                /* TODO: refactor, so that 1/2 are not needed */
1212                if (ren1) {
1213                        renames1 = a_renames;
1214                        renames2 = b_renames;
1215                        renames2Dst = &b_by_dst;
1216                        branch1 = a_branch;
1217                        branch2 = b_branch;
1218                } else {
1219                        struct rename *tmp;
1220                        renames1 = b_renames;
1221                        renames2 = a_renames;
1222                        renames2Dst = &a_by_dst;
1223                        branch1 = b_branch;
1224                        branch2 = a_branch;
1225                        tmp = ren2;
1226                        ren2 = ren1;
1227                        ren1 = tmp;
1228                }
1229                src = ren1->pair->one->path;
1230
1231                ren1->dst_entry->processed = 1;
1232                ren1->src_entry->processed = 1;
1233
1234                if (ren1->processed)
1235                        continue;
1236                ren1->processed = 1;
1237
1238                ren1_src = ren1->pair->one->path;
1239                ren1_dst = ren1->pair->two->path;
1240
1241                if (ren2) {
1242                        const char *ren2_src = ren2->pair->one->path;
1243                        const char *ren2_dst = ren2->pair->two->path;
1244                        /* Renamed in 1 and renamed in 2 */
1245                        if (strcmp(ren1_src, ren2_src) != 0)
1246                                die("ren1.src != ren2.src");
1247                        ren2->dst_entry->processed = 1;
1248                        ren2->processed = 1;
1249                        if (strcmp(ren1_dst, ren2_dst) != 0) {
1250                                clean_merge = 0;
1251                                output(1, "CONFLICT (rename/rename): "
1252                                       "Rename \"%s\"->\"%s\" in branch \"%s\" "
1253                                       "rename \"%s\"->\"%s\" in \"%s\"%s",
1254                                       src, ren1_dst, branch1,
1255                                       src, ren2_dst, branch2,
1256                                       index_only ? " (left unresolved)": "");
1257                                if (index_only) {
1258                                        remove_file_from_cache(src);
1259                                        update_file(0, ren1->pair->one->sha1,
1260                                                    ren1->pair->one->mode, src);
1261                                }
1262                                conflict_rename_rename(ren1, branch1, ren2, branch2);
1263                        } else {
1264                                struct merge_file_info mfi;
1265                                remove_file(1, ren1_src, 1);
1266                                mfi = merge_file(ren1->pair->one,
1267                                                 ren1->pair->two,
1268                                                 ren2->pair->two,
1269                                                 branch1,
1270                                                 branch2);
1271                                if (mfi.merge || !mfi.clean)
1272                                        output(1, "Renamed %s->%s", src, ren1_dst);
1273
1274                                if (mfi.merge)
1275                                        output(2, "Auto-merged %s", ren1_dst);
1276
1277                                if (!mfi.clean) {
1278                                        output(1, "CONFLICT (content): merge conflict in %s",
1279                                               ren1_dst);
1280                                        clean_merge = 0;
1281
1282                                        if (!index_only)
1283                                                update_stages(ren1_dst,
1284                                                              ren1->pair->one,
1285                                                              ren1->pair->two,
1286                                                              ren2->pair->two,
1287                                                              1 /* clear */);
1288                                }
1289                                update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1290                        }
1291                } else {
1292                        /* Renamed in 1, maybe changed in 2 */
1293                        struct path_list_item *item;
1294                        /* we only use sha1 and mode of these */
1295                        struct diff_filespec src_other, dst_other;
1296                        int try_merge, stage = a_renames == renames1 ? 3: 2;
1297
1298                        remove_file(1, ren1_src, index_only || stage == 3);
1299
1300                        hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
1301                        src_other.mode = ren1->src_entry->stages[stage].mode;
1302                        hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
1303                        dst_other.mode = ren1->dst_entry->stages[stage].mode;
1304
1305                        try_merge = 0;
1306
1307                        if (path_list_has_path(&current_directory_set, ren1_dst)) {
1308                                clean_merge = 0;
1309                                output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
1310                                       " directory %s added in %s",
1311                                       ren1_src, ren1_dst, branch1,
1312                                       ren1_dst, branch2);
1313                                conflict_rename_dir(ren1, branch1);
1314                        } else if (sha_eq(src_other.sha1, null_sha1)) {
1315                                clean_merge = 0;
1316                                output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
1317                                       "and deleted in %s",
1318                                       ren1_src, ren1_dst, branch1,
1319                                       branch2);
1320                                update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
1321                        } else if (!sha_eq(dst_other.sha1, null_sha1)) {
1322                                const char *new_path;
1323                                clean_merge = 0;
1324                                try_merge = 1;
1325                                output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
1326                                       "%s added in %s",
1327                                       ren1_src, ren1_dst, branch1,
1328                                       ren1_dst, branch2);
1329                                new_path = unique_path(ren1_dst, branch2);
1330                                output(1, "Added as %s instead", new_path);
1331                                update_file(0, dst_other.sha1, dst_other.mode, new_path);
1332                        } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
1333                                ren2 = item->util;
1334                                clean_merge = 0;
1335                                ren2->processed = 1;
1336                                output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1337                                       "Renamed %s->%s in %s",
1338                                       ren1_src, ren1_dst, branch1,
1339                                       ren2->pair->one->path, ren2->pair->two->path, branch2);
1340                                conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1341                        } else
1342                                try_merge = 1;
1343
1344                        if (try_merge) {
1345                                struct diff_filespec *o, *a, *b;
1346                                struct merge_file_info mfi;
1347                                src_other.path = (char *)ren1_src;
1348
1349                                o = ren1->pair->one;
1350                                if (a_renames == renames1) {
1351                                        a = ren1->pair->two;
1352                                        b = &src_other;
1353                                } else {
1354                                        b = ren1->pair->two;
1355                                        a = &src_other;
1356                                }
1357                                mfi = merge_file(o, a, b,
1358                                                a_branch, b_branch);
1359
1360                                if (mfi.merge || !mfi.clean)
1361                                        output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1362                                if (mfi.merge)
1363                                        output(2, "Auto-merged %s", ren1_dst);
1364                                if (!mfi.clean) {
1365                                        output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1366                                               ren1_dst);
1367                                        clean_merge = 0;
1368
1369                                        if (!index_only)
1370                                                update_stages(ren1_dst,
1371                                                                o, a, b, 1);
1372                                }
1373                                update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1374                        }
1375                }
1376        }
1377        path_list_clear(&a_by_dst, 0);
1378        path_list_clear(&b_by_dst, 0);
1379
1380        return clean_merge;
1381}
1382
1383static unsigned char *has_sha(const unsigned char *sha)
1384{
1385        return is_null_sha1(sha) ? NULL: (unsigned char *)sha;
1386}
1387
1388/* Per entry merge function */
1389static int process_entry(const char *path, struct stage_data *entry,
1390                         const char *branch1,
1391                         const char *branch2)
1392{
1393        /*
1394        printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1395        print_index_entry("\tpath: ", entry);
1396        */
1397        int clean_merge = 1;
1398        unsigned char *o_sha = has_sha(entry->stages[1].sha);
1399        unsigned char *a_sha = has_sha(entry->stages[2].sha);
1400        unsigned char *b_sha = has_sha(entry->stages[3].sha);
1401        unsigned o_mode = entry->stages[1].mode;
1402        unsigned a_mode = entry->stages[2].mode;
1403        unsigned b_mode = entry->stages[3].mode;
1404
1405        if (o_sha && (!a_sha || !b_sha)) {
1406                /* Case A: Deleted in one */
1407                if ((!a_sha && !b_sha) ||
1408                    (sha_eq(a_sha, o_sha) && !b_sha) ||
1409                    (!a_sha && sha_eq(b_sha, o_sha))) {
1410                        /* Deleted in both or deleted in one and
1411                         * unchanged in the other */
1412                        if (a_sha)
1413                                output(2, "Removed %s", path);
1414                        /* do not touch working file if it did not exist */
1415                        remove_file(1, path, !a_sha);
1416                } else {
1417                        /* Deleted in one and changed in the other */
1418                        clean_merge = 0;
1419                        if (!a_sha) {
1420                                output(1, "CONFLICT (delete/modify): %s deleted in %s "
1421                                       "and modified in %s. Version %s of %s left in tree.",
1422                                       path, branch1,
1423                                       branch2, branch2, path);
1424                                update_file(0, b_sha, b_mode, path);
1425                        } else {
1426                                output(1, "CONFLICT (delete/modify): %s deleted in %s "
1427                                       "and modified in %s. Version %s of %s left in tree.",
1428                                       path, branch2,
1429                                       branch1, branch1, path);
1430                                update_file(0, a_sha, a_mode, path);
1431                        }
1432                }
1433
1434        } else if ((!o_sha && a_sha && !b_sha) ||
1435                   (!o_sha && !a_sha && b_sha)) {
1436                /* Case B: Added in one. */
1437                const char *add_branch;
1438                const char *other_branch;
1439                unsigned mode;
1440                const unsigned char *sha;
1441                const char *conf;
1442
1443                if (a_sha) {
1444                        add_branch = branch1;
1445                        other_branch = branch2;
1446                        mode = a_mode;
1447                        sha = a_sha;
1448                        conf = "file/directory";
1449                } else {
1450                        add_branch = branch2;
1451                        other_branch = branch1;
1452                        mode = b_mode;
1453                        sha = b_sha;
1454                        conf = "directory/file";
1455                }
1456                if (path_list_has_path(&current_directory_set, path)) {
1457                        const char *new_path = unique_path(path, add_branch);
1458                        clean_merge = 0;
1459                        output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1460                               "Added %s as %s",
1461                               conf, path, other_branch, path, new_path);
1462                        remove_file(0, path, 0);
1463                        update_file(0, sha, mode, new_path);
1464                } else {
1465                        output(2, "Added %s", path);
1466                        update_file(1, sha, mode, path);
1467                }
1468        } else if (a_sha && b_sha) {
1469                /* Case C: Added in both (check for same permissions) and */
1470                /* case D: Modified in both, but differently. */
1471                const char *reason = "content";
1472                struct merge_file_info mfi;
1473                struct diff_filespec o, a, b;
1474
1475                if (!o_sha) {
1476                        reason = "add/add";
1477                        o_sha = (unsigned char *)null_sha1;
1478                }
1479                output(2, "Auto-merged %s", path);
1480                o.path = a.path = b.path = (char *)path;
1481                hashcpy(o.sha1, o_sha);
1482                o.mode = o_mode;
1483                hashcpy(a.sha1, a_sha);
1484                a.mode = a_mode;
1485                hashcpy(b.sha1, b_sha);
1486                b.mode = b_mode;
1487
1488                mfi = merge_file(&o, &a, &b,
1489                                 branch1, branch2);
1490
1491                if (mfi.clean)
1492                        update_file(1, mfi.sha, mfi.mode, path);
1493                else {
1494                        clean_merge = 0;
1495                        output(1, "CONFLICT (%s): Merge conflict in %s",
1496                                        reason, path);
1497
1498                        if (index_only)
1499                                update_file(0, mfi.sha, mfi.mode, path);
1500                        else
1501                                update_file_flags(mfi.sha, mfi.mode, path,
1502                                              0 /* update_cache */, 1 /* update_working_directory */);
1503                }
1504        } else
1505                die("Fatal merge failure, shouldn't happen.");
1506
1507        return clean_merge;
1508}
1509
1510static int merge_trees(struct tree *head,
1511                       struct tree *merge,
1512                       struct tree *common,
1513                       const char *branch1,
1514                       const char *branch2,
1515                       struct tree **result)
1516{
1517        int code, clean;
1518
1519        if (subtree_merge) {
1520                merge = shift_tree_object(head, merge);
1521                common = shift_tree_object(head, common);
1522        }
1523
1524        if (sha_eq(common->object.sha1, merge->object.sha1)) {
1525                output(0, "Already uptodate!");
1526                *result = head;
1527                return 1;
1528        }
1529
1530        code = git_merge_trees(index_only, common, head, merge);
1531
1532        if (code != 0)
1533                die("merging of trees %s and %s failed",
1534                    sha1_to_hex(head->object.sha1),
1535                    sha1_to_hex(merge->object.sha1));
1536
1537        if (unmerged_index()) {
1538                struct path_list *entries, *re_head, *re_merge;
1539                int i;
1540                path_list_clear(&current_file_set, 1);
1541                path_list_clear(&current_directory_set, 1);
1542                get_files_dirs(head);
1543                get_files_dirs(merge);
1544
1545                entries = get_unmerged();
1546                re_head  = get_renames(head, common, head, merge, entries);
1547                re_merge = get_renames(merge, common, head, merge, entries);
1548                clean = process_renames(re_head, re_merge,
1549                                branch1, branch2);
1550                total_cnt += entries->nr;
1551                for (i = 0; i < entries->nr; i++, merged_cnt++) {
1552                        const char *path = entries->items[i].path;
1553                        struct stage_data *e = entries->items[i].util;
1554                        if (!e->processed
1555                                && !process_entry(path, e, branch1, branch2))
1556                                clean = 0;
1557                        if (do_progress)
1558                                display_progress();
1559                }
1560
1561                path_list_clear(re_merge, 0);
1562                path_list_clear(re_head, 0);
1563                path_list_clear(entries, 1);
1564
1565        }
1566        else
1567                clean = 1;
1568
1569        if (index_only)
1570                *result = git_write_tree();
1571
1572        return clean;
1573}
1574
1575static struct commit_list *reverse_commit_list(struct commit_list *list)
1576{
1577        struct commit_list *next = NULL, *current, *backup;
1578        for (current = list; current; current = backup) {
1579                backup = current->next;
1580                current->next = next;
1581                next = current;
1582        }
1583        return next;
1584}
1585
1586/*
1587 * Merge the commits h1 and h2, return the resulting virtual
1588 * commit object and a flag indicating the cleanness of the merge.
1589 */
1590static int merge(struct commit *h1,
1591                 struct commit *h2,
1592                 const char *branch1,
1593                 const char *branch2,
1594                 struct commit_list *ca,
1595                 struct commit **result)
1596{
1597        struct commit_list *iter;
1598        struct commit *merged_common_ancestors;
1599        struct tree *mrtree;
1600        int clean;
1601
1602        if (show(4)) {
1603                output(4, "Merging:");
1604                output_commit_title(h1);
1605                output_commit_title(h2);
1606        }
1607
1608        if (!ca) {
1609                ca = get_merge_bases(h1, h2, 1);
1610                ca = reverse_commit_list(ca);
1611        }
1612
1613        if (show(5)) {
1614                output(5, "found %u common ancestor(s):", commit_list_count(ca));
1615                for (iter = ca; iter; iter = iter->next)
1616                        output_commit_title(iter->item);
1617        }
1618
1619        merged_common_ancestors = pop_commit(&ca);
1620        if (merged_common_ancestors == NULL) {
1621                /* if there is no common ancestor, make an empty tree */
1622                struct tree *tree = xcalloc(1, sizeof(struct tree));
1623
1624                tree->object.parsed = 1;
1625                tree->object.type = OBJ_TREE;
1626                pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1627                merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1628        }
1629
1630        for (iter = ca; iter; iter = iter->next) {
1631                call_depth++;
1632                /*
1633                 * When the merge fails, the result contains files
1634                 * with conflict markers. The cleanness flag is
1635                 * ignored, it was never actually used, as result of
1636                 * merge_trees has always overwritten it: the committed
1637                 * "conflicts" were already resolved.
1638                 */
1639                discard_cache();
1640                merge(merged_common_ancestors, iter->item,
1641                      "Temporary merge branch 1",
1642                      "Temporary merge branch 2",
1643                      NULL,
1644                      &merged_common_ancestors);
1645                call_depth--;
1646
1647                if (!merged_common_ancestors)
1648                        die("merge returned no commit");
1649        }
1650
1651        discard_cache();
1652        if (!call_depth) {
1653                read_cache();
1654                index_only = 0;
1655        } else
1656                index_only = 1;
1657
1658        clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1659                            branch1, branch2, &mrtree);
1660
1661        if (index_only) {
1662                *result = make_virtual_commit(mrtree, "merged tree");
1663                commit_list_insert(h1, &(*result)->parents);
1664                commit_list_insert(h2, &(*result)->parents->next);
1665        }
1666        if (!call_depth && do_progress) {
1667                /* Make sure we end at 100% */
1668                if (!total_cnt)
1669                        total_cnt = 1;
1670                merged_cnt = total_cnt;
1671                progress_update = 1;
1672                display_progress();
1673                fputc('\n', stderr);
1674        }
1675        flush_output();
1676        return clean;
1677}
1678
1679static const char *better_branch_name(const char *branch)
1680{
1681        static char githead_env[8 + 40 + 1];
1682        char *name;
1683
1684        if (strlen(branch) != 40)
1685                return branch;
1686        sprintf(githead_env, "GITHEAD_%s", branch);
1687        name = getenv(githead_env);
1688        return name ? name : branch;
1689}
1690
1691static struct commit *get_ref(const char *ref)
1692{
1693        unsigned char sha1[20];
1694        struct object *object;
1695
1696        if (get_sha1(ref, sha1))
1697                die("Could not resolve ref '%s'", ref);
1698        object = deref_tag(parse_object(sha1), ref, strlen(ref));
1699        if (object->type == OBJ_TREE)
1700                return make_virtual_commit((struct tree*)object,
1701                        better_branch_name(ref));
1702        if (object->type != OBJ_COMMIT)
1703                return NULL;
1704        if (parse_commit((struct commit *)object))
1705                die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1706        return (struct commit *)object;
1707}
1708
1709static int merge_config(const char *var, const char *value)
1710{
1711        if (!strcasecmp(var, "merge.verbosity")) {
1712                verbosity = git_config_int(var, value);
1713                return 0;
1714        }
1715        return git_default_config(var, value);
1716}
1717
1718int main(int argc, char *argv[])
1719{
1720        static const char *bases[20];
1721        static unsigned bases_count = 0;
1722        int i, clean;
1723        const char *branch1, *branch2;
1724        struct commit *result, *h1, *h2;
1725        struct commit_list *ca = NULL;
1726        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1727        int index_fd;
1728
1729        if (argv[0]) {
1730                int namelen = strlen(argv[0]);
1731                if (8 < namelen &&
1732                    !strcmp(argv[0] + namelen - 8, "-subtree"))
1733                        subtree_merge = 1;
1734        }
1735
1736        git_config(merge_config);
1737        if (getenv("GIT_MERGE_VERBOSITY"))
1738                verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1739
1740        if (argc < 4)
1741                die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1742
1743        for (i = 1; i < argc; ++i) {
1744                if (!strcmp(argv[i], "--"))
1745                        break;
1746                if (bases_count < sizeof(bases)/sizeof(*bases))
1747                        bases[bases_count++] = argv[i];
1748        }
1749        if (argc - i != 3) /* "--" "<head>" "<remote>" */
1750                die("Not handling anything other than two heads merge.");
1751        if (verbosity >= 5) {
1752                buffer_output = 0;
1753                do_progress = 0;
1754        }
1755        else
1756                do_progress = isatty(1);
1757
1758        branch1 = argv[++i];
1759        branch2 = argv[++i];
1760
1761        h1 = get_ref(branch1);
1762        h2 = get_ref(branch2);
1763
1764        branch1 = better_branch_name(branch1);
1765        branch2 = better_branch_name(branch2);
1766
1767        if (do_progress)
1768                setup_progress_signal();
1769        if (show(3))
1770                printf("Merging %s with %s\n", branch1, branch2);
1771
1772        index_fd = hold_locked_index(lock, 1);
1773
1774        for (i = 0; i < bases_count; i++) {
1775                struct commit *ancestor = get_ref(bases[i]);
1776                ca = commit_list_insert(ancestor, &ca);
1777        }
1778        clean = merge(h1, h2, branch1, branch2, ca, &result);
1779
1780        if (active_cache_changed &&
1781            (write_cache(index_fd, active_cache, active_nr) ||
1782             close(index_fd) || commit_locked_index(lock)))
1783                        die ("unable to write %s", get_index_file());
1784
1785        return clean ? 0: 1;
1786}