notes-merge.con commit git notes merge: List conflicting notes in notes merge commit message (443259c)
   1#include "cache.h"
   2#include "commit.h"
   3#include "refs.h"
   4#include "diff.h"
   5#include "diffcore.h"
   6#include "xdiff-interface.h"
   7#include "ll-merge.h"
   8#include "dir.h"
   9#include "notes.h"
  10#include "notes-merge.h"
  11#include "strbuf.h"
  12
  13struct notes_merge_pair {
  14        unsigned char obj[20], base[20], local[20], remote[20];
  15};
  16
  17void init_notes_merge_options(struct notes_merge_options *o)
  18{
  19        memset(o, 0, sizeof(struct notes_merge_options));
  20        strbuf_init(&(o->commit_msg), 0);
  21        o->verbosity = NOTES_MERGE_VERBOSITY_DEFAULT;
  22}
  23
  24#define OUTPUT(o, v, ...) \
  25        do { \
  26                if ((o)->verbosity >= (v)) { \
  27                        printf(__VA_ARGS__); \
  28                        puts(""); \
  29                } \
  30        } while (0)
  31
  32static int path_to_sha1(const char *path, unsigned char *sha1)
  33{
  34        char hex_sha1[40];
  35        int i = 0;
  36        while (*path && i < 40) {
  37                if (*path != '/')
  38                        hex_sha1[i++] = *path;
  39                path++;
  40        }
  41        if (*path || i != 40)
  42                return -1;
  43        return get_sha1_hex(hex_sha1, sha1);
  44}
  45
  46static int verify_notes_filepair(struct diff_filepair *p, unsigned char *sha1)
  47{
  48        switch (p->status) {
  49        case DIFF_STATUS_MODIFIED:
  50                assert(p->one->mode == p->two->mode);
  51                assert(!is_null_sha1(p->one->sha1));
  52                assert(!is_null_sha1(p->two->sha1));
  53                break;
  54        case DIFF_STATUS_ADDED:
  55                assert(is_null_sha1(p->one->sha1));
  56                break;
  57        case DIFF_STATUS_DELETED:
  58                assert(is_null_sha1(p->two->sha1));
  59                break;
  60        default:
  61                return -1;
  62        }
  63        assert(!strcmp(p->one->path, p->two->path));
  64        return path_to_sha1(p->one->path, sha1);
  65}
  66
  67static struct notes_merge_pair *find_notes_merge_pair_pos(
  68                struct notes_merge_pair *list, int len, unsigned char *obj,
  69                int insert_new, int *occupied)
  70{
  71        /*
  72         * Both diff_tree_remote() and diff_tree_local() tend to process
  73         * merge_pairs in ascending order. Therefore, cache last returned
  74         * index, and search sequentially from there until the appropriate
  75         * position is found.
  76         *
  77         * Since inserts only happen from diff_tree_remote() (which mainly
  78         * _appends_), we don't care that inserting into the middle of the
  79         * list is expensive (using memmove()).
  80         */
  81        static int last_index;
  82        int i = last_index < len ? last_index : len - 1;
  83        int prev_cmp = 0, cmp = -1;
  84        while (i >= 0 && i < len) {
  85                cmp = hashcmp(obj, list[i].obj);
  86                if (!cmp) /* obj belongs @ i */
  87                        break;
  88                else if (cmp < 0 && prev_cmp <= 0) /* obj belongs < i */
  89                        i--;
  90                else if (cmp < 0) /* obj belongs between i-1 and i */
  91                        break;
  92                else if (cmp > 0 && prev_cmp >= 0) /* obj belongs > i */
  93                        i++;
  94                else /* if (cmp > 0) */ { /* obj belongs between i and i+1 */
  95                        i++;
  96                        break;
  97                }
  98                prev_cmp = cmp;
  99        }
 100        if (i < 0)
 101                i = 0;
 102        /* obj belongs at, or immediately preceding, index i (0 <= i <= len) */
 103
 104        if (!cmp)
 105                *occupied = 1;
 106        else {
 107                *occupied = 0;
 108                if (insert_new && i < len) {
 109                        memmove(list + i + 1, list + i,
 110                                (len - i) * sizeof(struct notes_merge_pair));
 111                        memset(list + i, 0, sizeof(struct notes_merge_pair));
 112                }
 113        }
 114        last_index = i;
 115        return list + i;
 116}
 117
 118static unsigned char uninitialized[20] =
 119        "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" \
 120        "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";
 121
 122static struct notes_merge_pair *diff_tree_remote(struct notes_merge_options *o,
 123                                                 const unsigned char *base,
 124                                                 const unsigned char *remote,
 125                                                 int *num_changes)
 126{
 127        struct diff_options opt;
 128        struct notes_merge_pair *changes;
 129        int i, len = 0;
 130
 131        trace_printf("\tdiff_tree_remote(base = %.7s, remote = %.7s)\n",
 132               sha1_to_hex(base), sha1_to_hex(remote));
 133
 134        diff_setup(&opt);
 135        DIFF_OPT_SET(&opt, RECURSIVE);
 136        opt.output_format = DIFF_FORMAT_NO_OUTPUT;
 137        if (diff_setup_done(&opt) < 0)
 138                die("diff_setup_done failed");
 139        diff_tree_sha1(base, remote, "", &opt);
 140        diffcore_std(&opt);
 141
 142        changes = xcalloc(diff_queued_diff.nr, sizeof(struct notes_merge_pair));
 143
 144        for (i = 0; i < diff_queued_diff.nr; i++) {
 145                struct diff_filepair *p = diff_queued_diff.queue[i];
 146                struct notes_merge_pair *mp;
 147                int occupied;
 148                unsigned char obj[20];
 149
 150                if (verify_notes_filepair(p, obj)) {
 151                        trace_printf("\t\tCannot merge entry '%s' (%c): "
 152                               "%.7s -> %.7s. Skipping!\n", p->one->path,
 153                               p->status, sha1_to_hex(p->one->sha1),
 154                               sha1_to_hex(p->two->sha1));
 155                        continue;
 156                }
 157                mp = find_notes_merge_pair_pos(changes, len, obj, 1, &occupied);
 158                if (occupied) {
 159                        /* We've found an addition/deletion pair */
 160                        assert(!hashcmp(mp->obj, obj));
 161                        if (is_null_sha1(p->one->sha1)) { /* addition */
 162                                assert(is_null_sha1(mp->remote));
 163                                hashcpy(mp->remote, p->two->sha1);
 164                        } else if (is_null_sha1(p->two->sha1)) { /* deletion */
 165                                assert(is_null_sha1(mp->base));
 166                                hashcpy(mp->base, p->one->sha1);
 167                        } else
 168                                assert(!"Invalid existing change recorded");
 169                } else {
 170                        hashcpy(mp->obj, obj);
 171                        hashcpy(mp->base, p->one->sha1);
 172                        hashcpy(mp->local, uninitialized);
 173                        hashcpy(mp->remote, p->two->sha1);
 174                        len++;
 175                }
 176                trace_printf("\t\tStored remote change for %s: %.7s -> %.7s\n",
 177                       sha1_to_hex(mp->obj), sha1_to_hex(mp->base),
 178                       sha1_to_hex(mp->remote));
 179        }
 180        diff_flush(&opt);
 181        diff_tree_release_paths(&opt);
 182
 183        *num_changes = len;
 184        return changes;
 185}
 186
 187static void diff_tree_local(struct notes_merge_options *o,
 188                            struct notes_merge_pair *changes, int len,
 189                            const unsigned char *base,
 190                            const unsigned char *local)
 191{
 192        struct diff_options opt;
 193        int i;
 194
 195        trace_printf("\tdiff_tree_local(len = %i, base = %.7s, local = %.7s)\n",
 196               len, sha1_to_hex(base), sha1_to_hex(local));
 197
 198        diff_setup(&opt);
 199        DIFF_OPT_SET(&opt, RECURSIVE);
 200        opt.output_format = DIFF_FORMAT_NO_OUTPUT;
 201        if (diff_setup_done(&opt) < 0)
 202                die("diff_setup_done failed");
 203        diff_tree_sha1(base, local, "", &opt);
 204        diffcore_std(&opt);
 205
 206        for (i = 0; i < diff_queued_diff.nr; i++) {
 207                struct diff_filepair *p = diff_queued_diff.queue[i];
 208                struct notes_merge_pair *mp;
 209                int match;
 210                unsigned char obj[20];
 211
 212                if (verify_notes_filepair(p, obj)) {
 213                        trace_printf("\t\tCannot merge entry '%s' (%c): "
 214                               "%.7s -> %.7s. Skipping!\n", p->one->path,
 215                               p->status, sha1_to_hex(p->one->sha1),
 216                               sha1_to_hex(p->two->sha1));
 217                        continue;
 218                }
 219                mp = find_notes_merge_pair_pos(changes, len, obj, 0, &match);
 220                if (!match) {
 221                        trace_printf("\t\tIgnoring local-only change for %s: "
 222                               "%.7s -> %.7s\n", sha1_to_hex(obj),
 223                               sha1_to_hex(p->one->sha1),
 224                               sha1_to_hex(p->two->sha1));
 225                        continue;
 226                }
 227
 228                assert(!hashcmp(mp->obj, obj));
 229                if (is_null_sha1(p->two->sha1)) { /* deletion */
 230                        /*
 231                         * Either this is a true deletion (1), or it is part
 232                         * of an A/D pair (2), or D/A pair (3):
 233                         *
 234                         * (1) mp->local is uninitialized; set it to null_sha1
 235                         * (2) mp->local is not uninitialized; don't touch it
 236                         * (3) mp->local is uninitialized; set it to null_sha1
 237                         *     (will be overwritten by following addition)
 238                         */
 239                        if (!hashcmp(mp->local, uninitialized))
 240                                hashclr(mp->local);
 241                } else if (is_null_sha1(p->one->sha1)) { /* addition */
 242                        /*
 243                         * Either this is a true addition (1), or it is part
 244                         * of an A/D pair (2), or D/A pair (3):
 245                         *
 246                         * (1) mp->local is uninitialized; set to p->two->sha1
 247                         * (2) mp->local is uninitialized; set to p->two->sha1
 248                         * (3) mp->local is null_sha1;     set to p->two->sha1
 249                         */
 250                        assert(is_null_sha1(mp->local) ||
 251                               !hashcmp(mp->local, uninitialized));
 252                        hashcpy(mp->local, p->two->sha1);
 253                } else { /* modification */
 254                        /*
 255                         * This is a true modification. p->one->sha1 shall
 256                         * match mp->base, and mp->local shall be uninitialized.
 257                         * Set mp->local to p->two->sha1.
 258                         */
 259                        assert(!hashcmp(p->one->sha1, mp->base));
 260                        assert(!hashcmp(mp->local, uninitialized));
 261                        hashcpy(mp->local, p->two->sha1);
 262                }
 263                trace_printf("\t\tStored local change for %s: %.7s -> %.7s\n",
 264                       sha1_to_hex(mp->obj), sha1_to_hex(mp->base),
 265                       sha1_to_hex(mp->local));
 266        }
 267        diff_flush(&opt);
 268        diff_tree_release_paths(&opt);
 269}
 270
 271static void check_notes_merge_worktree(struct notes_merge_options *o)
 272{
 273        if (!o->has_worktree) {
 274                /*
 275                 * Must establish NOTES_MERGE_WORKTREE.
 276                 * Abort if NOTES_MERGE_WORKTREE already exists
 277                 */
 278                if (file_exists(git_path(NOTES_MERGE_WORKTREE))) {
 279                        if (advice_resolve_conflict)
 280                                die("You have not concluded your previous "
 281                                    "notes merge (%s exists).\nPlease, use "
 282                                    "'git notes merge --commit' or 'git notes "
 283                                    "merge --abort' to commit/abort the "
 284                                    "previous merge before you start a new "
 285                                    "notes merge.", git_path("NOTES_MERGE_*"));
 286                        else
 287                                die("You have not concluded your notes merge "
 288                                    "(%s exists).", git_path("NOTES_MERGE_*"));
 289                }
 290
 291                if (safe_create_leading_directories(git_path(
 292                                NOTES_MERGE_WORKTREE "/.test")))
 293                        die_errno("unable to create directory %s",
 294                                  git_path(NOTES_MERGE_WORKTREE));
 295                o->has_worktree = 1;
 296        } else if (!file_exists(git_path(NOTES_MERGE_WORKTREE)))
 297                /* NOTES_MERGE_WORKTREE should already be established */
 298                die("missing '%s'. This should not happen",
 299                    git_path(NOTES_MERGE_WORKTREE));
 300}
 301
 302static void write_buf_to_worktree(const unsigned char *obj,
 303                                  const char *buf, unsigned long size)
 304{
 305        int fd;
 306        char *path = git_path(NOTES_MERGE_WORKTREE "/%s", sha1_to_hex(obj));
 307        if (safe_create_leading_directories(path))
 308                die_errno("unable to create directory for '%s'", path);
 309        if (file_exists(path))
 310                die("found existing file at '%s'", path);
 311
 312        fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0666);
 313        if (fd < 0)
 314                die_errno("failed to open '%s'", path);
 315
 316        while (size > 0) {
 317                long ret = write_in_full(fd, buf, size);
 318                if (ret < 0) {
 319                        /* Ignore epipe */
 320                        if (errno == EPIPE)
 321                                break;
 322                        die_errno("notes-merge");
 323                } else if (!ret) {
 324                        die("notes-merge: disk full?");
 325                }
 326                size -= ret;
 327                buf += ret;
 328        }
 329
 330        close(fd);
 331}
 332
 333static void write_note_to_worktree(const unsigned char *obj,
 334                                   const unsigned char *note)
 335{
 336        enum object_type type;
 337        unsigned long size;
 338        void *buf = read_sha1_file(note, &type, &size);
 339
 340        if (!buf)
 341                die("cannot read note %s for object %s",
 342                    sha1_to_hex(note), sha1_to_hex(obj));
 343        if (type != OBJ_BLOB)
 344                die("blob expected in note %s for object %s",
 345                    sha1_to_hex(note), sha1_to_hex(obj));
 346        write_buf_to_worktree(obj, buf, size);
 347        free(buf);
 348}
 349
 350static int ll_merge_in_worktree(struct notes_merge_options *o,
 351                                struct notes_merge_pair *p)
 352{
 353        mmbuffer_t result_buf;
 354        mmfile_t base, local, remote;
 355        int status;
 356
 357        read_mmblob(&base, p->base);
 358        read_mmblob(&local, p->local);
 359        read_mmblob(&remote, p->remote);
 360
 361        status = ll_merge(&result_buf, sha1_to_hex(p->obj), &base, NULL,
 362                          &local, o->local_ref, &remote, o->remote_ref, 0);
 363
 364        free(base.ptr);
 365        free(local.ptr);
 366        free(remote.ptr);
 367
 368        if ((status < 0) || !result_buf.ptr)
 369                die("Failed to execute internal merge");
 370
 371        write_buf_to_worktree(p->obj, result_buf.ptr, result_buf.size);
 372        free(result_buf.ptr);
 373
 374        return status;
 375}
 376
 377static int merge_one_change_manual(struct notes_merge_options *o,
 378                                   struct notes_merge_pair *p,
 379                                   struct notes_tree *t)
 380{
 381        const char *lref = o->local_ref ? o->local_ref : "local version";
 382        const char *rref = o->remote_ref ? o->remote_ref : "remote version";
 383
 384        trace_printf("\t\t\tmerge_one_change_manual(obj = %.7s, base = %.7s, "
 385               "local = %.7s, remote = %.7s)\n",
 386               sha1_to_hex(p->obj), sha1_to_hex(p->base),
 387               sha1_to_hex(p->local), sha1_to_hex(p->remote));
 388
 389        /* add "Conflicts:" section to commit message first time through */
 390        if (!o->has_worktree)
 391                strbuf_addstr(&(o->commit_msg), "\n\nConflicts:\n");
 392
 393        strbuf_addf(&(o->commit_msg), "\t%s\n", sha1_to_hex(p->obj));
 394
 395        OUTPUT(o, 2, "Auto-merging notes for %s", sha1_to_hex(p->obj));
 396        check_notes_merge_worktree(o);
 397        if (is_null_sha1(p->local)) {
 398                /* D/F conflict, checkout p->remote */
 399                assert(!is_null_sha1(p->remote));
 400                OUTPUT(o, 1, "CONFLICT (delete/modify): Notes for object %s "
 401                       "deleted in %s and modified in %s. Version from %s "
 402                       "left in tree.", sha1_to_hex(p->obj), lref, rref, rref);
 403                write_note_to_worktree(p->obj, p->remote);
 404        } else if (is_null_sha1(p->remote)) {
 405                /* D/F conflict, checkout p->local */
 406                assert(!is_null_sha1(p->local));
 407                OUTPUT(o, 1, "CONFLICT (delete/modify): Notes for object %s "
 408                       "deleted in %s and modified in %s. Version from %s "
 409                       "left in tree.", sha1_to_hex(p->obj), rref, lref, lref);
 410                write_note_to_worktree(p->obj, p->local);
 411        } else {
 412                /* "regular" conflict, checkout result of ll_merge() */
 413                const char *reason = "content";
 414                if (is_null_sha1(p->base))
 415                        reason = "add/add";
 416                assert(!is_null_sha1(p->local));
 417                assert(!is_null_sha1(p->remote));
 418                OUTPUT(o, 1, "CONFLICT (%s): Merge conflict in notes for "
 419                       "object %s", reason, sha1_to_hex(p->obj));
 420                ll_merge_in_worktree(o, p);
 421        }
 422
 423        trace_printf("\t\t\tremoving from partial merge result\n");
 424        remove_note(t, p->obj);
 425
 426        return 1;
 427}
 428
 429static int merge_one_change(struct notes_merge_options *o,
 430                            struct notes_merge_pair *p, struct notes_tree *t)
 431{
 432        /*
 433         * Return 0 if change is successfully resolved (stored in notes_tree).
 434         * Return 1 is change results in a conflict (NOT stored in notes_tree,
 435         * but instead written to NOTES_MERGE_WORKTREE with conflict markers).
 436         */
 437        switch (o->strategy) {
 438        case NOTES_MERGE_RESOLVE_MANUAL:
 439                return merge_one_change_manual(o, p, t);
 440        case NOTES_MERGE_RESOLVE_OURS:
 441                OUTPUT(o, 2, "Using local notes for %s", sha1_to_hex(p->obj));
 442                /* nothing to do */
 443                return 0;
 444        case NOTES_MERGE_RESOLVE_THEIRS:
 445                OUTPUT(o, 2, "Using remote notes for %s", sha1_to_hex(p->obj));
 446                if (add_note(t, p->obj, p->remote, combine_notes_overwrite))
 447                        die("BUG: combine_notes_overwrite failed");
 448                return 0;
 449        case NOTES_MERGE_RESOLVE_UNION:
 450                OUTPUT(o, 2, "Concatenating local and remote notes for %s",
 451                       sha1_to_hex(p->obj));
 452                if (add_note(t, p->obj, p->remote, combine_notes_concatenate))
 453                        die("failed to concatenate notes "
 454                            "(combine_notes_concatenate)");
 455                return 0;
 456        }
 457        die("Unknown strategy (%i).", o->strategy);
 458}
 459
 460static int merge_changes(struct notes_merge_options *o,
 461                         struct notes_merge_pair *changes, int *num_changes,
 462                         struct notes_tree *t)
 463{
 464        int i, conflicts = 0;
 465
 466        trace_printf("\tmerge_changes(num_changes = %i)\n", *num_changes);
 467        for (i = 0; i < *num_changes; i++) {
 468                struct notes_merge_pair *p = changes + i;
 469                trace_printf("\t\t%.7s: %.7s -> %.7s/%.7s\n",
 470                       sha1_to_hex(p->obj), sha1_to_hex(p->base),
 471                       sha1_to_hex(p->local), sha1_to_hex(p->remote));
 472
 473                if (!hashcmp(p->base, p->remote)) {
 474                        /* no remote change; nothing to do */
 475                        trace_printf("\t\t\tskipping (no remote change)\n");
 476                } else if (!hashcmp(p->local, p->remote)) {
 477                        /* same change in local and remote; nothing to do */
 478                        trace_printf("\t\t\tskipping (local == remote)\n");
 479                } else if (!hashcmp(p->local, uninitialized) ||
 480                           !hashcmp(p->local, p->base)) {
 481                        /* no local change; adopt remote change */
 482                        trace_printf("\t\t\tno local change, adopted remote\n");
 483                        if (add_note(t, p->obj, p->remote,
 484                                     combine_notes_overwrite))
 485                                die("BUG: combine_notes_overwrite failed");
 486                } else {
 487                        /* need file-level merge between local and remote */
 488                        trace_printf("\t\t\tneed content-level merge\n");
 489                        conflicts += merge_one_change(o, p, t);
 490                }
 491        }
 492
 493        return conflicts;
 494}
 495
 496static int merge_from_diffs(struct notes_merge_options *o,
 497                            const unsigned char *base,
 498                            const unsigned char *local,
 499                            const unsigned char *remote, struct notes_tree *t)
 500{
 501        struct notes_merge_pair *changes;
 502        int num_changes, conflicts;
 503
 504        trace_printf("\tmerge_from_diffs(base = %.7s, local = %.7s, "
 505               "remote = %.7s)\n", sha1_to_hex(base), sha1_to_hex(local),
 506               sha1_to_hex(remote));
 507
 508        changes = diff_tree_remote(o, base, remote, &num_changes);
 509        diff_tree_local(o, changes, num_changes, base, local);
 510
 511        conflicts = merge_changes(o, changes, &num_changes, t);
 512        free(changes);
 513
 514        OUTPUT(o, 4, "Merge result: %i unmerged notes and a %s notes tree",
 515               conflicts, t->dirty ? "dirty" : "clean");
 516
 517        return conflicts ? -1 : 1;
 518}
 519
 520void create_notes_commit(struct notes_tree *t, struct commit_list *parents,
 521                         const char *msg, unsigned char *result_sha1)
 522{
 523        unsigned char tree_sha1[20];
 524
 525        assert(t->initialized);
 526
 527        if (write_notes_tree(t, tree_sha1))
 528                die("Failed to write notes tree to database");
 529
 530        if (!parents) {
 531                /* Deduce parent commit from t->ref */
 532                unsigned char parent_sha1[20];
 533                if (!read_ref(t->ref, parent_sha1)) {
 534                        struct commit *parent = lookup_commit(parent_sha1);
 535                        if (!parent || parse_commit(parent))
 536                                die("Failed to find/parse commit %s", t->ref);
 537                        commit_list_insert(parent, &parents);
 538                }
 539                /* else: t->ref points to nothing, assume root/orphan commit */
 540        }
 541
 542        if (commit_tree(msg, tree_sha1, parents, result_sha1, NULL))
 543                die("Failed to commit notes tree to database");
 544}
 545
 546int notes_merge(struct notes_merge_options *o,
 547                struct notes_tree *local_tree,
 548                unsigned char *result_sha1)
 549{
 550        unsigned char local_sha1[20], remote_sha1[20];
 551        struct commit *local, *remote;
 552        struct commit_list *bases = NULL;
 553        const unsigned char *base_sha1, *base_tree_sha1;
 554        int result = 0;
 555
 556        assert(o->local_ref && o->remote_ref);
 557        assert(!strcmp(o->local_ref, local_tree->ref));
 558        hashclr(result_sha1);
 559
 560        trace_printf("notes_merge(o->local_ref = %s, o->remote_ref = %s)\n",
 561               o->local_ref, o->remote_ref);
 562
 563        /* Dereference o->local_ref into local_sha1 */
 564        if (!resolve_ref(o->local_ref, local_sha1, 0, NULL))
 565                die("Failed to resolve local notes ref '%s'", o->local_ref);
 566        else if (!check_ref_format(o->local_ref) && is_null_sha1(local_sha1))
 567                local = NULL; /* local_sha1 == null_sha1 indicates unborn ref */
 568        else if (!(local = lookup_commit_reference(local_sha1)))
 569                die("Could not parse local commit %s (%s)",
 570                    sha1_to_hex(local_sha1), o->local_ref);
 571        trace_printf("\tlocal commit: %.7s\n", sha1_to_hex(local_sha1));
 572
 573        /* Dereference o->remote_ref into remote_sha1 */
 574        if (get_sha1(o->remote_ref, remote_sha1)) {
 575                /*
 576                 * Failed to get remote_sha1. If o->remote_ref looks like an
 577                 * unborn ref, perform the merge using an empty notes tree.
 578                 */
 579                if (!check_ref_format(o->remote_ref)) {
 580                        hashclr(remote_sha1);
 581                        remote = NULL;
 582                } else {
 583                        die("Failed to resolve remote notes ref '%s'",
 584                            o->remote_ref);
 585                }
 586        } else if (!(remote = lookup_commit_reference(remote_sha1))) {
 587                die("Could not parse remote commit %s (%s)",
 588                    sha1_to_hex(remote_sha1), o->remote_ref);
 589        }
 590        trace_printf("\tremote commit: %.7s\n", sha1_to_hex(remote_sha1));
 591
 592        if (!local && !remote)
 593                die("Cannot merge empty notes ref (%s) into empty notes ref "
 594                    "(%s)", o->remote_ref, o->local_ref);
 595        if (!local) {
 596                /* result == remote commit */
 597                hashcpy(result_sha1, remote_sha1);
 598                goto found_result;
 599        }
 600        if (!remote) {
 601                /* result == local commit */
 602                hashcpy(result_sha1, local_sha1);
 603                goto found_result;
 604        }
 605        assert(local && remote);
 606
 607        /* Find merge bases */
 608        bases = get_merge_bases(local, remote, 1);
 609        if (!bases) {
 610                base_sha1 = null_sha1;
 611                base_tree_sha1 = (unsigned char *)EMPTY_TREE_SHA1_BIN;
 612                OUTPUT(o, 4, "No merge base found; doing history-less merge");
 613        } else if (!bases->next) {
 614                base_sha1 = bases->item->object.sha1;
 615                base_tree_sha1 = bases->item->tree->object.sha1;
 616                OUTPUT(o, 4, "One merge base found (%.7s)",
 617                       sha1_to_hex(base_sha1));
 618        } else {
 619                /* TODO: How to handle multiple merge-bases? */
 620                base_sha1 = bases->item->object.sha1;
 621                base_tree_sha1 = bases->item->tree->object.sha1;
 622                OUTPUT(o, 3, "Multiple merge bases found. Using the first "
 623                       "(%.7s)", sha1_to_hex(base_sha1));
 624        }
 625
 626        OUTPUT(o, 4, "Merging remote commit %.7s into local commit %.7s with "
 627               "merge-base %.7s", sha1_to_hex(remote->object.sha1),
 628               sha1_to_hex(local->object.sha1), sha1_to_hex(base_sha1));
 629
 630        if (!hashcmp(remote->object.sha1, base_sha1)) {
 631                /* Already merged; result == local commit */
 632                OUTPUT(o, 2, "Already up-to-date!");
 633                hashcpy(result_sha1, local->object.sha1);
 634                goto found_result;
 635        }
 636        if (!hashcmp(local->object.sha1, base_sha1)) {
 637                /* Fast-forward; result == remote commit */
 638                OUTPUT(o, 2, "Fast-forward");
 639                hashcpy(result_sha1, remote->object.sha1);
 640                goto found_result;
 641        }
 642
 643        result = merge_from_diffs(o, base_tree_sha1, local->tree->object.sha1,
 644                                  remote->tree->object.sha1, local_tree);
 645
 646        if (result != 0) { /* non-trivial merge (with or without conflicts) */
 647                /* Commit (partial) result */
 648                struct commit_list *parents = NULL;
 649                commit_list_insert(remote, &parents); /* LIFO order */
 650                commit_list_insert(local, &parents);
 651                create_notes_commit(local_tree, parents, o->commit_msg.buf,
 652                                    result_sha1);
 653        }
 654
 655found_result:
 656        free_commit_list(bases);
 657        strbuf_release(&(o->commit_msg));
 658        trace_printf("notes_merge(): result = %i, result_sha1 = %.7s\n",
 659               result, sha1_to_hex(result_sha1));
 660        return result;
 661}
 662
 663int notes_merge_commit(struct notes_merge_options *o,
 664                       struct notes_tree *partial_tree,
 665                       struct commit *partial_commit,
 666                       unsigned char *result_sha1)
 667{
 668        /*
 669         * Iterate through files in .git/NOTES_MERGE_WORKTREE and add all
 670         * found notes to 'partial_tree'. Write the updates notes tree to
 671         * the DB, and commit the resulting tree object while reusing the
 672         * commit message and parents from 'partial_commit'.
 673         * Finally store the new commit object SHA1 into 'result_sha1'.
 674         */
 675        struct dir_struct dir;
 676        const char *path = git_path(NOTES_MERGE_WORKTREE "/");
 677        int path_len = strlen(path), i;
 678        const char *msg = strstr(partial_commit->buffer, "\n\n");
 679
 680        OUTPUT(o, 3, "Committing notes in notes merge worktree at %.*s",
 681               path_len - 1, path);
 682
 683        if (!msg || msg[2] == '\0')
 684                die("partial notes commit has empty message");
 685        msg += 2;
 686
 687        memset(&dir, 0, sizeof(dir));
 688        read_directory(&dir, path, path_len, NULL);
 689        for (i = 0; i < dir.nr; i++) {
 690                struct dir_entry *ent = dir.entries[i];
 691                struct stat st;
 692                const char *relpath = ent->name + path_len;
 693                unsigned char obj_sha1[20], blob_sha1[20];
 694
 695                if (ent->len - path_len != 40 || get_sha1_hex(relpath, obj_sha1)) {
 696                        OUTPUT(o, 3, "Skipping non-SHA1 entry '%s'", ent->name);
 697                        continue;
 698                }
 699
 700                /* write file as blob, and add to partial_tree */
 701                if (stat(ent->name, &st))
 702                        die_errno("Failed to stat '%s'", ent->name);
 703                if (index_path(blob_sha1, ent->name, &st, 1))
 704                        die("Failed to write blob object from '%s'", ent->name);
 705                if (add_note(partial_tree, obj_sha1, blob_sha1, NULL))
 706                        die("Failed to add resolved note '%s' to notes tree",
 707                            ent->name);
 708                OUTPUT(o, 4, "Added resolved note for object %s: %s",
 709                       sha1_to_hex(obj_sha1), sha1_to_hex(blob_sha1));
 710        }
 711
 712        create_notes_commit(partial_tree, partial_commit->parents, msg,
 713                            result_sha1);
 714        OUTPUT(o, 4, "Finalized notes merge commit: %s",
 715               sha1_to_hex(result_sha1));
 716        return 0;
 717}
 718
 719int notes_merge_abort(struct notes_merge_options *o)
 720{
 721        /* Remove .git/NOTES_MERGE_WORKTREE directory and all files within */
 722        struct strbuf buf = STRBUF_INIT;
 723        int ret;
 724
 725        strbuf_addstr(&buf, git_path(NOTES_MERGE_WORKTREE));
 726        OUTPUT(o, 3, "Removing notes merge worktree at %s", buf.buf);
 727        ret = remove_dir_recursively(&buf, 0);
 728        strbuf_release(&buf);
 729        return ret;
 730}