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