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