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