merge-recursive.con commit Allow the user to control the verbosity of merge-recursive. (8c3275a)
   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
  19/*
  20 * A virtual commit has
  21 * - (const char *)commit->util set to the name, and
  22 * - *(int *)commit->object.sha1 set to the virtual id.
  23 */
  24
  25static unsigned commit_list_count(const struct commit_list *l)
  26{
  27        unsigned c = 0;
  28        for (; l; l = l->next )
  29                c++;
  30        return c;
  31}
  32
  33static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
  34{
  35        struct commit *commit = xcalloc(1, sizeof(struct commit));
  36        static unsigned virtual_id = 1;
  37        commit->tree = tree;
  38        commit->util = (void*)comment;
  39        *(int*)commit->object.sha1 = virtual_id++;
  40        /* avoid warnings */
  41        commit->object.parsed = 1;
  42        return commit;
  43}
  44
  45/*
  46 * Since we use get_tree_entry(), which does not put the read object into
  47 * the object pool, we cannot rely on a == b.
  48 */
  49static int sha_eq(const unsigned char *a, const unsigned char *b)
  50{
  51        if (!a && !b)
  52                return 2;
  53        return a && b && hashcmp(a, b) == 0;
  54}
  55
  56/*
  57 * Since we want to write the index eventually, we cannot reuse the index
  58 * for these (temporary) data.
  59 */
  60struct stage_data
  61{
  62        struct
  63        {
  64                unsigned mode;
  65                unsigned char sha[20];
  66        } stages[4];
  67        unsigned processed:1;
  68};
  69
  70static struct path_list current_file_set = {NULL, 0, 0, 1};
  71static struct path_list current_directory_set = {NULL, 0, 0, 1};
  72
  73static int call_depth = 0;
  74static int verbosity = 2;
  75
  76static int show (int v)
  77{
  78        return (!call_depth && verbosity >= v) || verbosity >= 5;
  79}
  80
  81static void output(int v, const char *fmt, ...)
  82{
  83        va_list args;
  84        va_start(args, fmt);
  85        if (show(v)) {
  86                int i;
  87                for (i = call_depth; i--;)
  88                        fputs("  ", stdout);
  89                vfprintf(stdout, fmt, args);
  90                fputc('\n', stdout);
  91        }
  92        va_end(args);
  93}
  94
  95static void output_commit_title(struct commit *commit)
  96{
  97        int i;
  98        for (i = call_depth; i--;)
  99                fputs("  ", stdout);
 100        if (commit->util)
 101                printf("virtual %s\n", (char *)commit->util);
 102        else {
 103                printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
 104                if (parse_commit(commit) != 0)
 105                        printf("(bad commit)\n");
 106                else {
 107                        const char *s;
 108                        int len;
 109                        for (s = commit->buffer; *s; s++)
 110                                if (*s == '\n' && s[1] == '\n') {
 111                                        s += 2;
 112                                        break;
 113                                }
 114                        for (len = 0; s[len] && '\n' != s[len]; len++)
 115                                ; /* do nothing */
 116                        printf("%.*s\n", len, s);
 117                }
 118        }
 119}
 120
 121static struct cache_entry *make_cache_entry(unsigned int mode,
 122                const unsigned char *sha1, const char *path, int stage, int refresh)
 123{
 124        int size, len;
 125        struct cache_entry *ce;
 126
 127        if (!verify_path(path))
 128                return NULL;
 129
 130        len = strlen(path);
 131        size = cache_entry_size(len);
 132        ce = xcalloc(1, size);
 133
 134        hashcpy(ce->sha1, sha1);
 135        memcpy(ce->name, path, len);
 136        ce->ce_flags = create_ce_flags(len, stage);
 137        ce->ce_mode = create_ce_mode(mode);
 138
 139        if (refresh)
 140                return refresh_cache_entry(ce, 0);
 141
 142        return ce;
 143}
 144
 145static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
 146                const char *path, int stage, int refresh, int options)
 147{
 148        struct cache_entry *ce;
 149        ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
 150        if (!ce)
 151                return error("cache_addinfo failed: %s", strerror(cache_errno));
 152        return add_cache_entry(ce, options);
 153}
 154
 155/*
 156 * This is a global variable which is used in a number of places but
 157 * only written to in the 'merge' function.
 158 *
 159 * index_only == 1    => Don't leave any non-stage 0 entries in the cache and
 160 *                       don't update the working directory.
 161 *               0    => Leave unmerged entries in the cache and update
 162 *                       the working directory.
 163 */
 164static int index_only = 0;
 165
 166static int git_merge_trees(int index_only,
 167                           struct tree *common,
 168                           struct tree *head,
 169                           struct tree *merge)
 170{
 171        int rc;
 172        struct object_list *trees = NULL;
 173        struct unpack_trees_options opts;
 174
 175        memset(&opts, 0, sizeof(opts));
 176        if (index_only)
 177                opts.index_only = 1;
 178        else
 179                opts.update = 1;
 180        opts.merge = 1;
 181        opts.head_idx = 2;
 182        opts.fn = threeway_merge;
 183
 184        object_list_append(&common->object, &trees);
 185        object_list_append(&head->object, &trees);
 186        object_list_append(&merge->object, &trees);
 187
 188        rc = unpack_trees(trees, &opts);
 189        cache_tree_free(&active_cache_tree);
 190        return rc;
 191}
 192
 193static int unmerged_index(void)
 194{
 195        int i;
 196        for (i = 0; i < active_nr; i++) {
 197                struct cache_entry *ce = active_cache[i];
 198                if (ce_stage(ce))
 199                        return 1;
 200        }
 201        return 0;
 202}
 203
 204static struct tree *git_write_tree(void)
 205{
 206        struct tree *result = NULL;
 207
 208        if (unmerged_index())
 209                return NULL;
 210
 211        if (!active_cache_tree)
 212                active_cache_tree = cache_tree();
 213
 214        if (!cache_tree_fully_valid(active_cache_tree) &&
 215            cache_tree_update(active_cache_tree,
 216                              active_cache, active_nr, 0, 0) < 0)
 217                die("error building trees");
 218
 219        result = lookup_tree(active_cache_tree->sha1);
 220
 221        return result;
 222}
 223
 224static int save_files_dirs(const unsigned char *sha1,
 225                const char *base, int baselen, const char *path,
 226                unsigned int mode, int stage)
 227{
 228        int len = strlen(path);
 229        char *newpath = xmalloc(baselen + len + 1);
 230        memcpy(newpath, base, baselen);
 231        memcpy(newpath + baselen, path, len);
 232        newpath[baselen + len] = '\0';
 233
 234        if (S_ISDIR(mode))
 235                path_list_insert(newpath, &current_directory_set);
 236        else
 237                path_list_insert(newpath, &current_file_set);
 238        free(newpath);
 239
 240        return READ_TREE_RECURSIVE;
 241}
 242
 243static int get_files_dirs(struct tree *tree)
 244{
 245        int n;
 246        if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
 247                return 0;
 248        n = current_file_set.nr + current_directory_set.nr;
 249        return n;
 250}
 251
 252/*
 253 * Returns a index_entry instance which doesn't have to correspond to
 254 * a real cache entry in Git's index.
 255 */
 256static struct stage_data *insert_stage_data(const char *path,
 257                struct tree *o, struct tree *a, struct tree *b,
 258                struct path_list *entries)
 259{
 260        struct path_list_item *item;
 261        struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
 262        get_tree_entry(o->object.sha1, path,
 263                        e->stages[1].sha, &e->stages[1].mode);
 264        get_tree_entry(a->object.sha1, path,
 265                        e->stages[2].sha, &e->stages[2].mode);
 266        get_tree_entry(b->object.sha1, path,
 267                        e->stages[3].sha, &e->stages[3].mode);
 268        item = path_list_insert(path, entries);
 269        item->util = e;
 270        return e;
 271}
 272
 273/*
 274 * Create a dictionary mapping file names to stage_data objects. The
 275 * dictionary contains one entry for every path with a non-zero stage entry.
 276 */
 277static struct path_list *get_unmerged(void)
 278{
 279        struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
 280        int i;
 281
 282        unmerged->strdup_paths = 1;
 283
 284        for (i = 0; i < active_nr; i++) {
 285                struct path_list_item *item;
 286                struct stage_data *e;
 287                struct cache_entry *ce = active_cache[i];
 288                if (!ce_stage(ce))
 289                        continue;
 290
 291                item = path_list_lookup(ce->name, unmerged);
 292                if (!item) {
 293                        item = path_list_insert(ce->name, unmerged);
 294                        item->util = xcalloc(1, sizeof(struct stage_data));
 295                }
 296                e = item->util;
 297                e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
 298                hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
 299        }
 300
 301        return unmerged;
 302}
 303
 304struct rename
 305{
 306        struct diff_filepair *pair;
 307        struct stage_data *src_entry;
 308        struct stage_data *dst_entry;
 309        unsigned processed:1;
 310};
 311
 312/*
 313 * Get information of all renames which occured between 'o_tree' and
 314 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
 315 * 'b_tree') to be able to associate the correct cache entries with
 316 * the rename information. 'tree' is always equal to either a_tree or b_tree.
 317 */
 318static struct path_list *get_renames(struct tree *tree,
 319                                        struct tree *o_tree,
 320                                        struct tree *a_tree,
 321                                        struct tree *b_tree,
 322                                        struct path_list *entries)
 323{
 324        int i;
 325        struct path_list *renames;
 326        struct diff_options opts;
 327
 328        renames = xcalloc(1, sizeof(struct path_list));
 329        diff_setup(&opts);
 330        opts.recursive = 1;
 331        opts.detect_rename = DIFF_DETECT_RENAME;
 332        opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 333        if (diff_setup_done(&opts) < 0)
 334                die("diff setup failed");
 335        diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
 336        diffcore_std(&opts);
 337        for (i = 0; i < diff_queued_diff.nr; ++i) {
 338                struct path_list_item *item;
 339                struct rename *re;
 340                struct diff_filepair *pair = diff_queued_diff.queue[i];
 341                if (pair->status != 'R') {
 342                        diff_free_filepair(pair);
 343                        continue;
 344                }
 345                re = xmalloc(sizeof(*re));
 346                re->processed = 0;
 347                re->pair = pair;
 348                item = path_list_lookup(re->pair->one->path, entries);
 349                if (!item)
 350                        re->src_entry = insert_stage_data(re->pair->one->path,
 351                                        o_tree, a_tree, b_tree, entries);
 352                else
 353                        re->src_entry = item->util;
 354
 355                item = path_list_lookup(re->pair->two->path, entries);
 356                if (!item)
 357                        re->dst_entry = insert_stage_data(re->pair->two->path,
 358                                        o_tree, a_tree, b_tree, entries);
 359                else
 360                        re->dst_entry = item->util;
 361                item = path_list_insert(pair->one->path, renames);
 362                item->util = re;
 363        }
 364        opts.output_format = DIFF_FORMAT_NO_OUTPUT;
 365        diff_queued_diff.nr = 0;
 366        diff_flush(&opts);
 367        return renames;
 368}
 369
 370static int update_stages(const char *path, struct diff_filespec *o,
 371                         struct diff_filespec *a, struct diff_filespec *b,
 372                         int clear)
 373{
 374        int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
 375        if (clear)
 376                if (remove_file_from_cache(path))
 377                        return -1;
 378        if (o)
 379                if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
 380                        return -1;
 381        if (a)
 382                if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
 383                        return -1;
 384        if (b)
 385                if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
 386                        return -1;
 387        return 0;
 388}
 389
 390static int remove_path(const char *name)
 391{
 392        int ret, len;
 393        char *slash, *dirs;
 394
 395        ret = unlink(name);
 396        if (ret)
 397                return ret;
 398        len = strlen(name);
 399        dirs = xmalloc(len+1);
 400        memcpy(dirs, name, len);
 401        dirs[len] = '\0';
 402        while ((slash = strrchr(name, '/'))) {
 403                *slash = '\0';
 404                len = slash - name;
 405                if (rmdir(name) != 0)
 406                        break;
 407        }
 408        free(dirs);
 409        return ret;
 410}
 411
 412static int remove_file(int clean, const char *path, int no_wd)
 413{
 414        int update_cache = index_only || clean;
 415        int update_working_directory = !index_only && !no_wd;
 416
 417        if (update_cache) {
 418                if (remove_file_from_cache(path))
 419                        return -1;
 420        }
 421        if (update_working_directory) {
 422                unlink(path);
 423                if (errno != ENOENT || errno != EISDIR)
 424                        return -1;
 425                remove_path(path);
 426        }
 427        return 0;
 428}
 429
 430static char *unique_path(const char *path, const char *branch)
 431{
 432        char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
 433        int suffix = 0;
 434        struct stat st;
 435        char *p = newpath + strlen(path);
 436        strcpy(newpath, path);
 437        *(p++) = '~';
 438        strcpy(p, branch);
 439        for (; *p; ++p)
 440                if ('/' == *p)
 441                        *p = '_';
 442        while (path_list_has_path(&current_file_set, newpath) ||
 443               path_list_has_path(&current_directory_set, newpath) ||
 444               lstat(newpath, &st) == 0)
 445                sprintf(p, "_%d", suffix++);
 446
 447        path_list_insert(newpath, &current_file_set);
 448        return newpath;
 449}
 450
 451static int mkdir_p(const char *path, unsigned long mode)
 452{
 453        /* path points to cache entries, so xstrdup before messing with it */
 454        char *buf = xstrdup(path);
 455        int result = safe_create_leading_directories(buf);
 456        free(buf);
 457        return result;
 458}
 459
 460static void flush_buffer(int fd, const char *buf, unsigned long size)
 461{
 462        while (size > 0) {
 463                long ret = write_in_full(fd, buf, size);
 464                if (ret < 0) {
 465                        /* Ignore epipe */
 466                        if (errno == EPIPE)
 467                                break;
 468                        die("merge-recursive: %s", strerror(errno));
 469                } else if (!ret) {
 470                        die("merge-recursive: disk full?");
 471                }
 472                size -= ret;
 473                buf += ret;
 474        }
 475}
 476
 477static void update_file_flags(const unsigned char *sha,
 478                              unsigned mode,
 479                              const char *path,
 480                              int update_cache,
 481                              int update_wd)
 482{
 483        if (index_only)
 484                update_wd = 0;
 485
 486        if (update_wd) {
 487                char type[20];
 488                void *buf;
 489                unsigned long size;
 490
 491                buf = read_sha1_file(sha, type, &size);
 492                if (!buf)
 493                        die("cannot read object %s '%s'", sha1_to_hex(sha), path);
 494                if (strcmp(type, blob_type) != 0)
 495                        die("blob expected for %s '%s'", sha1_to_hex(sha), path);
 496
 497                if (S_ISREG(mode)) {
 498                        int fd;
 499                        if (mkdir_p(path, 0777))
 500                                die("failed to create path %s: %s", path, strerror(errno));
 501                        unlink(path);
 502                        if (mode & 0100)
 503                                mode = 0777;
 504                        else
 505                                mode = 0666;
 506                        fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
 507                        if (fd < 0)
 508                                die("failed to open %s: %s", path, strerror(errno));
 509                        flush_buffer(fd, buf, size);
 510                        close(fd);
 511                } else if (S_ISLNK(mode)) {
 512                        char *lnk = xmalloc(size + 1);
 513                        memcpy(lnk, buf, size);
 514                        lnk[size] = '\0';
 515                        mkdir_p(path, 0777);
 516                        unlink(lnk);
 517                        symlink(lnk, path);
 518                } else
 519                        die("do not know what to do with %06o %s '%s'",
 520                            mode, sha1_to_hex(sha), path);
 521        }
 522        if (update_cache)
 523                add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
 524}
 525
 526static void update_file(int clean,
 527                        const unsigned char *sha,
 528                        unsigned mode,
 529                        const char *path)
 530{
 531        update_file_flags(sha, mode, path, index_only || clean, !index_only);
 532}
 533
 534/* Low level file merging, update and removal */
 535
 536struct merge_file_info
 537{
 538        unsigned char sha[20];
 539        unsigned mode;
 540        unsigned clean:1,
 541                 merge:1;
 542};
 543
 544static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
 545{
 546        unsigned long size;
 547        char type[20];
 548
 549        if (!hashcmp(sha1, null_sha1)) {
 550                mm->ptr = xstrdup("");
 551                mm->size = 0;
 552                return;
 553        }
 554
 555        mm->ptr = read_sha1_file(sha1, type, &size);
 556        if (!mm->ptr || strcmp(type, blob_type))
 557                die("unable to read blob object %s", sha1_to_hex(sha1));
 558        mm->size = size;
 559}
 560
 561static struct merge_file_info merge_file(struct diff_filespec *o,
 562                struct diff_filespec *a, struct diff_filespec *b,
 563                const char *branch1, const char *branch2)
 564{
 565        struct merge_file_info result;
 566        result.merge = 0;
 567        result.clean = 1;
 568
 569        if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
 570                result.clean = 0;
 571                if (S_ISREG(a->mode)) {
 572                        result.mode = a->mode;
 573                        hashcpy(result.sha, a->sha1);
 574                } else {
 575                        result.mode = b->mode;
 576                        hashcpy(result.sha, b->sha1);
 577                }
 578        } else {
 579                if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
 580                        result.merge = 1;
 581
 582                result.mode = a->mode == o->mode ? b->mode: a->mode;
 583
 584                if (sha_eq(a->sha1, o->sha1))
 585                        hashcpy(result.sha, b->sha1);
 586                else if (sha_eq(b->sha1, o->sha1))
 587                        hashcpy(result.sha, a->sha1);
 588                else if (S_ISREG(a->mode)) {
 589                        mmfile_t orig, src1, src2;
 590                        mmbuffer_t result_buf;
 591                        xpparam_t xpp;
 592                        char *name1, *name2;
 593                        int merge_status;
 594
 595                        name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
 596                        name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
 597
 598                        fill_mm(o->sha1, &orig);
 599                        fill_mm(a->sha1, &src1);
 600                        fill_mm(b->sha1, &src2);
 601
 602                        memset(&xpp, 0, sizeof(xpp));
 603                        merge_status = xdl_merge(&orig,
 604                                                 &src1, name1,
 605                                                 &src2, name2,
 606                                                 &xpp, XDL_MERGE_ZEALOUS,
 607                                                 &result_buf);
 608                        free(name1);
 609                        free(name2);
 610                        free(orig.ptr);
 611                        free(src1.ptr);
 612                        free(src2.ptr);
 613
 614                        if ((merge_status < 0) || !result_buf.ptr)
 615                                die("Failed to execute internal merge");
 616
 617                        if (write_sha1_file(result_buf.ptr, result_buf.size,
 618                                            blob_type, result.sha))
 619                                die("Unable to add %s to database",
 620                                    a->path);
 621
 622                        free(result_buf.ptr);
 623                        result.clean = (merge_status == 0);
 624                } else {
 625                        if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
 626                                die("cannot merge modes?");
 627
 628                        hashcpy(result.sha, a->sha1);
 629
 630                        if (!sha_eq(a->sha1, b->sha1))
 631                                result.clean = 0;
 632                }
 633        }
 634
 635        return result;
 636}
 637
 638static void conflict_rename_rename(struct rename *ren1,
 639                                   const char *branch1,
 640                                   struct rename *ren2,
 641                                   const char *branch2)
 642{
 643        char *del[2];
 644        int delp = 0;
 645        const char *ren1_dst = ren1->pair->two->path;
 646        const char *ren2_dst = ren2->pair->two->path;
 647        const char *dst_name1 = ren1_dst;
 648        const char *dst_name2 = ren2_dst;
 649        if (path_list_has_path(&current_directory_set, ren1_dst)) {
 650                dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
 651                output(1, "%s is a directory in %s adding as %s instead",
 652                       ren1_dst, branch2, dst_name1);
 653                remove_file(0, ren1_dst, 0);
 654        }
 655        if (path_list_has_path(&current_directory_set, ren2_dst)) {
 656                dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
 657                output(1, "%s is a directory in %s adding as %s instead",
 658                       ren2_dst, branch1, dst_name2);
 659                remove_file(0, ren2_dst, 0);
 660        }
 661        update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
 662        update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
 663        while (delp--)
 664                free(del[delp]);
 665}
 666
 667static void conflict_rename_dir(struct rename *ren1,
 668                                const char *branch1)
 669{
 670        char *new_path = unique_path(ren1->pair->two->path, branch1);
 671        output(1, "Renaming %s to %s instead", ren1->pair->one->path, new_path);
 672        remove_file(0, ren1->pair->two->path, 0);
 673        update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
 674        free(new_path);
 675}
 676
 677static void conflict_rename_rename_2(struct rename *ren1,
 678                                     const char *branch1,
 679                                     struct rename *ren2,
 680                                     const char *branch2)
 681{
 682        char *new_path1 = unique_path(ren1->pair->two->path, branch1);
 683        char *new_path2 = unique_path(ren2->pair->two->path, branch2);
 684        output(1, "Renaming %s to %s and %s to %s instead",
 685               ren1->pair->one->path, new_path1,
 686               ren2->pair->one->path, new_path2);
 687        remove_file(0, ren1->pair->two->path, 0);
 688        update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
 689        update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
 690        free(new_path2);
 691        free(new_path1);
 692}
 693
 694static int process_renames(struct path_list *a_renames,
 695                           struct path_list *b_renames,
 696                           const char *a_branch,
 697                           const char *b_branch)
 698{
 699        int clean_merge = 1, i, j;
 700        struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
 701        const struct rename *sre;
 702
 703        for (i = 0; i < a_renames->nr; i++) {
 704                sre = a_renames->items[i].util;
 705                path_list_insert(sre->pair->two->path, &a_by_dst)->util
 706                        = sre->dst_entry;
 707        }
 708        for (i = 0; i < b_renames->nr; i++) {
 709                sre = b_renames->items[i].util;
 710                path_list_insert(sre->pair->two->path, &b_by_dst)->util
 711                        = sre->dst_entry;
 712        }
 713
 714        for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
 715                int compare;
 716                char *src;
 717                struct path_list *renames1, *renames2, *renames2Dst;
 718                struct rename *ren1 = NULL, *ren2 = NULL;
 719                const char *branch1, *branch2;
 720                const char *ren1_src, *ren1_dst;
 721
 722                if (i >= a_renames->nr) {
 723                        compare = 1;
 724                        ren2 = b_renames->items[j++].util;
 725                } else if (j >= b_renames->nr) {
 726                        compare = -1;
 727                        ren1 = a_renames->items[i++].util;
 728                } else {
 729                        compare = strcmp(a_renames->items[i].path,
 730                                        b_renames->items[j].path);
 731                        if (compare <= 0)
 732                                ren1 = a_renames->items[i++].util;
 733                        if (compare >= 0)
 734                                ren2 = b_renames->items[j++].util;
 735                }
 736
 737                /* TODO: refactor, so that 1/2 are not needed */
 738                if (ren1) {
 739                        renames1 = a_renames;
 740                        renames2 = b_renames;
 741                        renames2Dst = &b_by_dst;
 742                        branch1 = a_branch;
 743                        branch2 = b_branch;
 744                } else {
 745                        struct rename *tmp;
 746                        renames1 = b_renames;
 747                        renames2 = a_renames;
 748                        renames2Dst = &a_by_dst;
 749                        branch1 = b_branch;
 750                        branch2 = a_branch;
 751                        tmp = ren2;
 752                        ren2 = ren1;
 753                        ren1 = tmp;
 754                }
 755                src = ren1->pair->one->path;
 756
 757                ren1->dst_entry->processed = 1;
 758                ren1->src_entry->processed = 1;
 759
 760                if (ren1->processed)
 761                        continue;
 762                ren1->processed = 1;
 763
 764                ren1_src = ren1->pair->one->path;
 765                ren1_dst = ren1->pair->two->path;
 766
 767                if (ren2) {
 768                        const char *ren2_src = ren2->pair->one->path;
 769                        const char *ren2_dst = ren2->pair->two->path;
 770                        /* Renamed in 1 and renamed in 2 */
 771                        if (strcmp(ren1_src, ren2_src) != 0)
 772                                die("ren1.src != ren2.src");
 773                        ren2->dst_entry->processed = 1;
 774                        ren2->processed = 1;
 775                        if (strcmp(ren1_dst, ren2_dst) != 0) {
 776                                clean_merge = 0;
 777                                output(1, "CONFLICT (rename/rename): "
 778                                       "Rename %s->%s in branch %s "
 779                                       "rename %s->%s in %s",
 780                                       src, ren1_dst, branch1,
 781                                       src, ren2_dst, branch2);
 782                                conflict_rename_rename(ren1, branch1, ren2, branch2);
 783                        } else {
 784                                struct merge_file_info mfi;
 785                                remove_file(1, ren1_src, 1);
 786                                mfi = merge_file(ren1->pair->one,
 787                                                 ren1->pair->two,
 788                                                 ren2->pair->two,
 789                                                 branch1,
 790                                                 branch2);
 791                                if (mfi.merge || !mfi.clean)
 792                                        output(1, "Renaming %s->%s", src, ren1_dst);
 793
 794                                if (mfi.merge)
 795                                        output(2, "Auto-merging %s", ren1_dst);
 796
 797                                if (!mfi.clean) {
 798                                        output(1, "CONFLICT (content): merge conflict in %s",
 799                                               ren1_dst);
 800                                        clean_merge = 0;
 801
 802                                        if (!index_only)
 803                                                update_stages(ren1_dst,
 804                                                              ren1->pair->one,
 805                                                              ren1->pair->two,
 806                                                              ren2->pair->two,
 807                                                              1 /* clear */);
 808                                }
 809                                update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
 810                        }
 811                } else {
 812                        /* Renamed in 1, maybe changed in 2 */
 813                        struct path_list_item *item;
 814                        /* we only use sha1 and mode of these */
 815                        struct diff_filespec src_other, dst_other;
 816                        int try_merge, stage = a_renames == renames1 ? 3: 2;
 817
 818                        remove_file(1, ren1_src, index_only);
 819
 820                        hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
 821                        src_other.mode = ren1->src_entry->stages[stage].mode;
 822                        hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
 823                        dst_other.mode = ren1->dst_entry->stages[stage].mode;
 824
 825                        try_merge = 0;
 826
 827                        if (path_list_has_path(&current_directory_set, ren1_dst)) {
 828                                clean_merge = 0;
 829                                output(1, "CONFLICT (rename/directory): Rename %s->%s in %s "
 830                                       " directory %s added in %s",
 831                                       ren1_src, ren1_dst, branch1,
 832                                       ren1_dst, branch2);
 833                                conflict_rename_dir(ren1, branch1);
 834                        } else if (sha_eq(src_other.sha1, null_sha1)) {
 835                                clean_merge = 0;
 836                                output(1, "CONFLICT (rename/delete): Rename %s->%s in %s "
 837                                       "and deleted in %s",
 838                                       ren1_src, ren1_dst, branch1,
 839                                       branch2);
 840                                update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
 841                        } else if (!sha_eq(dst_other.sha1, null_sha1)) {
 842                                const char *new_path;
 843                                clean_merge = 0;
 844                                try_merge = 1;
 845                                output(1, "CONFLICT (rename/add): Rename %s->%s in %s. "
 846                                       "%s added in %s",
 847                                       ren1_src, ren1_dst, branch1,
 848                                       ren1_dst, branch2);
 849                                new_path = unique_path(ren1_dst, branch2);
 850                                output(1, "Adding as %s instead", new_path);
 851                                update_file(0, dst_other.sha1, dst_other.mode, new_path);
 852                        } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
 853                                ren2 = item->util;
 854                                clean_merge = 0;
 855                                ren2->processed = 1;
 856                                output(1, "CONFLICT (rename/rename): Rename %s->%s in %s. "
 857                                       "Rename %s->%s in %s",
 858                                       ren1_src, ren1_dst, branch1,
 859                                       ren2->pair->one->path, ren2->pair->two->path, branch2);
 860                                conflict_rename_rename_2(ren1, branch1, ren2, branch2);
 861                        } else
 862                                try_merge = 1;
 863
 864                        if (try_merge) {
 865                                struct diff_filespec *o, *a, *b;
 866                                struct merge_file_info mfi;
 867                                src_other.path = (char *)ren1_src;
 868
 869                                o = ren1->pair->one;
 870                                if (a_renames == renames1) {
 871                                        a = ren1->pair->two;
 872                                        b = &src_other;
 873                                } else {
 874                                        b = ren1->pair->two;
 875                                        a = &src_other;
 876                                }
 877                                mfi = merge_file(o, a, b,
 878                                                a_branch, b_branch);
 879
 880                                if (mfi.merge || !mfi.clean)
 881                                        output(1, "Renaming %s => %s", ren1_src, ren1_dst);
 882                                if (mfi.merge)
 883                                        output(2, "Auto-merging %s", ren1_dst);
 884                                if (!mfi.clean) {
 885                                        output(1, "CONFLICT (rename/modify): Merge conflict in %s",
 886                                               ren1_dst);
 887                                        clean_merge = 0;
 888
 889                                        if (!index_only)
 890                                                update_stages(ren1_dst,
 891                                                                o, a, b, 1);
 892                                }
 893                                update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
 894                        }
 895                }
 896        }
 897        path_list_clear(&a_by_dst, 0);
 898        path_list_clear(&b_by_dst, 0);
 899
 900        return clean_merge;
 901}
 902
 903static unsigned char *has_sha(const unsigned char *sha)
 904{
 905        return is_null_sha1(sha) ? NULL: (unsigned char *)sha;
 906}
 907
 908/* Per entry merge function */
 909static int process_entry(const char *path, struct stage_data *entry,
 910                         const char *branch1,
 911                         const char *branch2)
 912{
 913        /*
 914        printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
 915        print_index_entry("\tpath: ", entry);
 916        */
 917        int clean_merge = 1;
 918        unsigned char *o_sha = has_sha(entry->stages[1].sha);
 919        unsigned char *a_sha = has_sha(entry->stages[2].sha);
 920        unsigned char *b_sha = has_sha(entry->stages[3].sha);
 921        unsigned o_mode = entry->stages[1].mode;
 922        unsigned a_mode = entry->stages[2].mode;
 923        unsigned b_mode = entry->stages[3].mode;
 924
 925        if (o_sha && (!a_sha || !b_sha)) {
 926                /* Case A: Deleted in one */
 927                if ((!a_sha && !b_sha) ||
 928                    (sha_eq(a_sha, o_sha) && !b_sha) ||
 929                    (!a_sha && sha_eq(b_sha, o_sha))) {
 930                        /* Deleted in both or deleted in one and
 931                         * unchanged in the other */
 932                        if (a_sha)
 933                                output(2, "Removing %s", path);
 934                        /* do not touch working file if it did not exist */
 935                        remove_file(1, path, !a_sha);
 936                } else {
 937                        /* Deleted in one and changed in the other */
 938                        clean_merge = 0;
 939                        if (!a_sha) {
 940                                output(1, "CONFLICT (delete/modify): %s deleted in %s "
 941                                       "and modified in %s. Version %s of %s left in tree.",
 942                                       path, branch1,
 943                                       branch2, branch2, path);
 944                                update_file(0, b_sha, b_mode, path);
 945                        } else {
 946                                output(1, "CONFLICT (delete/modify): %s deleted in %s "
 947                                       "and modified in %s. Version %s of %s left in tree.",
 948                                       path, branch2,
 949                                       branch1, branch1, path);
 950                                update_file(0, a_sha, a_mode, path);
 951                        }
 952                }
 953
 954        } else if ((!o_sha && a_sha && !b_sha) ||
 955                   (!o_sha && !a_sha && b_sha)) {
 956                /* Case B: Added in one. */
 957                const char *add_branch;
 958                const char *other_branch;
 959                unsigned mode;
 960                const unsigned char *sha;
 961                const char *conf;
 962
 963                if (a_sha) {
 964                        add_branch = branch1;
 965                        other_branch = branch2;
 966                        mode = a_mode;
 967                        sha = a_sha;
 968                        conf = "file/directory";
 969                } else {
 970                        add_branch = branch2;
 971                        other_branch = branch1;
 972                        mode = b_mode;
 973                        sha = b_sha;
 974                        conf = "directory/file";
 975                }
 976                if (path_list_has_path(&current_directory_set, path)) {
 977                        const char *new_path = unique_path(path, add_branch);
 978                        clean_merge = 0;
 979                        output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
 980                               "Adding %s as %s",
 981                               conf, path, other_branch, path, new_path);
 982                        remove_file(0, path, 0);
 983                        update_file(0, sha, mode, new_path);
 984                } else {
 985                        output(2, "Adding %s", path);
 986                        update_file(1, sha, mode, path);
 987                }
 988        } else if (a_sha && b_sha) {
 989                /* Case C: Added in both (check for same permissions) and */
 990                /* case D: Modified in both, but differently. */
 991                const char *reason = "content";
 992                struct merge_file_info mfi;
 993                struct diff_filespec o, a, b;
 994
 995                if (!o_sha) {
 996                        reason = "add/add";
 997                        o_sha = (unsigned char *)null_sha1;
 998                }
 999                output(2, "Auto-merging %s", path);
1000                o.path = a.path = b.path = (char *)path;
1001                hashcpy(o.sha1, o_sha);
1002                o.mode = o_mode;
1003                hashcpy(a.sha1, a_sha);
1004                a.mode = a_mode;
1005                hashcpy(b.sha1, b_sha);
1006                b.mode = b_mode;
1007
1008                mfi = merge_file(&o, &a, &b,
1009                                 branch1, branch2);
1010
1011                if (mfi.clean)
1012                        update_file(1, mfi.sha, mfi.mode, path);
1013                else {
1014                        clean_merge = 0;
1015                        output(1, "CONFLICT (%s): Merge conflict in %s",
1016                                        reason, path);
1017
1018                        if (index_only)
1019                                update_file(0, mfi.sha, mfi.mode, path);
1020                        else
1021                                update_file_flags(mfi.sha, mfi.mode, path,
1022                                              0 /* update_cache */, 1 /* update_working_directory */);
1023                }
1024        } else
1025                die("Fatal merge failure, shouldn't happen.");
1026
1027        return clean_merge;
1028}
1029
1030static int merge_trees(struct tree *head,
1031                       struct tree *merge,
1032                       struct tree *common,
1033                       const char *branch1,
1034                       const char *branch2,
1035                       struct tree **result)
1036{
1037        int code, clean;
1038        if (sha_eq(common->object.sha1, merge->object.sha1)) {
1039                output(0, "Already uptodate!");
1040                *result = head;
1041                return 1;
1042        }
1043
1044        code = git_merge_trees(index_only, common, head, merge);
1045
1046        if (code != 0)
1047                die("merging of trees %s and %s failed",
1048                    sha1_to_hex(head->object.sha1),
1049                    sha1_to_hex(merge->object.sha1));
1050
1051        if (unmerged_index()) {
1052                struct path_list *entries, *re_head, *re_merge;
1053                int i;
1054                path_list_clear(&current_file_set, 1);
1055                path_list_clear(&current_directory_set, 1);
1056                get_files_dirs(head);
1057                get_files_dirs(merge);
1058
1059                entries = get_unmerged();
1060                re_head  = get_renames(head, common, head, merge, entries);
1061                re_merge = get_renames(merge, common, head, merge, entries);
1062                clean = process_renames(re_head, re_merge,
1063                                branch1, branch2);
1064                for (i = 0; i < entries->nr; i++) {
1065                        const char *path = entries->items[i].path;
1066                        struct stage_data *e = entries->items[i].util;
1067                        if (e->processed)
1068                                continue;
1069                        if (!process_entry(path, e, branch1, branch2))
1070                                clean = 0;
1071                }
1072
1073                path_list_clear(re_merge, 0);
1074                path_list_clear(re_head, 0);
1075                path_list_clear(entries, 1);
1076
1077        }
1078        else
1079                clean = 1;
1080
1081        if (index_only)
1082                *result = git_write_tree();
1083
1084        return clean;
1085}
1086
1087static struct commit_list *reverse_commit_list(struct commit_list *list)
1088{
1089        struct commit_list *next = NULL, *current, *backup;
1090        for (current = list; current; current = backup) {
1091                backup = current->next;
1092                current->next = next;
1093                next = current;
1094        }
1095        return next;
1096}
1097
1098/*
1099 * Merge the commits h1 and h2, return the resulting virtual
1100 * commit object and a flag indicating the cleaness of the merge.
1101 */
1102static int merge(struct commit *h1,
1103                 struct commit *h2,
1104                 const char *branch1,
1105                 const char *branch2,
1106                 struct commit_list *ca,
1107                 struct commit **result)
1108{
1109        struct commit_list *iter;
1110        struct commit *merged_common_ancestors;
1111        struct tree *mrtree;
1112        int clean;
1113
1114        if (show(4)) {
1115                output(4, "Merging:");
1116                output_commit_title(h1);
1117                output_commit_title(h2);
1118        }
1119
1120        if (!ca) {
1121                ca = get_merge_bases(h1, h2, 1);
1122                ca = reverse_commit_list(ca);
1123        }
1124
1125        if (show(5)) {
1126                output(5, "found %u common ancestor(s):", commit_list_count(ca));
1127                for (iter = ca; iter; iter = iter->next)
1128                        output_commit_title(iter->item);
1129        }
1130
1131        merged_common_ancestors = pop_commit(&ca);
1132        if (merged_common_ancestors == NULL) {
1133                /* if there is no common ancestor, make an empty tree */
1134                struct tree *tree = xcalloc(1, sizeof(struct tree));
1135
1136                tree->object.parsed = 1;
1137                tree->object.type = OBJ_TREE;
1138                write_sha1_file(NULL, 0, tree_type, tree->object.sha1);
1139                merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1140        }
1141
1142        for (iter = ca; iter; iter = iter->next) {
1143                call_depth++;
1144                /*
1145                 * When the merge fails, the result contains files
1146                 * with conflict markers. The cleanness flag is
1147                 * ignored, it was never acutally used, as result of
1148                 * merge_trees has always overwritten it: the commited
1149                 * "conflicts" were already resolved.
1150                 */
1151                discard_cache();
1152                merge(merged_common_ancestors, iter->item,
1153                      "Temporary merge branch 1",
1154                      "Temporary merge branch 2",
1155                      NULL,
1156                      &merged_common_ancestors);
1157                call_depth--;
1158
1159                if (!merged_common_ancestors)
1160                        die("merge returned no commit");
1161        }
1162
1163        discard_cache();
1164        if (!call_depth) {
1165                read_cache();
1166                index_only = 0;
1167        } else
1168                index_only = 1;
1169
1170        clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1171                            branch1, branch2, &mrtree);
1172
1173        if (index_only) {
1174                *result = make_virtual_commit(mrtree, "merged tree");
1175                commit_list_insert(h1, &(*result)->parents);
1176                commit_list_insert(h2, &(*result)->parents->next);
1177        }
1178        return clean;
1179}
1180
1181static const char *better_branch_name(const char *branch)
1182{
1183        static char githead_env[8 + 40 + 1];
1184        char *name;
1185
1186        if (strlen(branch) != 40)
1187                return branch;
1188        sprintf(githead_env, "GITHEAD_%s", branch);
1189        name = getenv(githead_env);
1190        return name ? name : branch;
1191}
1192
1193static struct commit *get_ref(const char *ref)
1194{
1195        unsigned char sha1[20];
1196        struct object *object;
1197
1198        if (get_sha1(ref, sha1))
1199                die("Could not resolve ref '%s'", ref);
1200        object = deref_tag(parse_object(sha1), ref, strlen(ref));
1201        if (object->type == OBJ_TREE)
1202                return make_virtual_commit((struct tree*)object,
1203                        better_branch_name(ref));
1204        if (object->type != OBJ_COMMIT)
1205                return NULL;
1206        if (parse_commit((struct commit *)object))
1207                die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1208        return (struct commit *)object;
1209}
1210
1211static int merge_config(const char *var, const char *value)
1212{
1213        if (!strcasecmp(var, "merge.verbosity")) {
1214                verbosity = git_config_int(var, value);
1215                return 0;
1216        }
1217        return git_default_config(var, value);
1218}
1219
1220int main(int argc, char *argv[])
1221{
1222        static const char *bases[20];
1223        static unsigned bases_count = 0;
1224        int i, clean;
1225        const char *branch1, *branch2;
1226        struct commit *result, *h1, *h2;
1227        struct commit_list *ca = NULL;
1228        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1229        int index_fd;
1230
1231        git_config(merge_config);
1232        if (getenv("GIT_MERGE_VERBOSITY"))
1233                verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1234
1235        if (argc < 4)
1236                die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1237
1238        for (i = 1; i < argc; ++i) {
1239                if (!strcmp(argv[i], "--"))
1240                        break;
1241                if (bases_count < sizeof(bases)/sizeof(*bases))
1242                        bases[bases_count++] = argv[i];
1243        }
1244        if (argc - i != 3) /* "--" "<head>" "<remote>" */
1245                die("Not handling anything other than two heads merge.");
1246
1247        branch1 = argv[++i];
1248        branch2 = argv[++i];
1249
1250        h1 = get_ref(branch1);
1251        h2 = get_ref(branch2);
1252
1253        branch1 = better_branch_name(branch1);
1254        branch2 = better_branch_name(branch2);
1255        if (show(3))
1256                printf("Merging %s with %s\n", branch1, branch2);
1257
1258        index_fd = hold_lock_file_for_update(lock, get_index_file(), 1);
1259
1260        for (i = 0; i < bases_count; i++) {
1261                struct commit *ancestor = get_ref(bases[i]);
1262                ca = commit_list_insert(ancestor, &ca);
1263        }
1264        clean = merge(h1, h2, branch1, branch2, ca, &result);
1265
1266        if (active_cache_changed &&
1267            (write_cache(index_fd, active_cache, active_nr) ||
1268             close(index_fd) || commit_lock_file(lock)))
1269                        die ("unable to write %s", get_index_file());
1270
1271        return clean ? 0: 1;
1272}