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