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