a5d8a06cebdf9cdb7f33f84225a4ebd34ce682c8
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "string-list.h"
   4#include "rerere.h"
   5#include "xdiff-interface.h"
   6#include "dir.h"
   7#include "resolve-undo.h"
   8#include "ll-merge.h"
   9#include "attr.h"
  10#include "pathspec.h"
  11#include "sha1-lookup.h"
  12
  13#define RESOLVED 0
  14#define PUNTED 1
  15#define THREE_STAGED 2
  16void *RERERE_RESOLVED = &RERERE_RESOLVED;
  17
  18/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
  19static int rerere_enabled = -1;
  20
  21/* automatically update cleanly resolved paths to the index */
  22static int rerere_autoupdate;
  23
  24static char *merge_rr_path;
  25
  26static int rerere_dir_nr;
  27static int rerere_dir_alloc;
  28
  29static struct rerere_dir {
  30        unsigned char sha1[20];
  31} **rerere_dir;
  32
  33static void free_rerere_dirs(void)
  34{
  35        int i;
  36        for (i = 0; i < rerere_dir_nr; i++)
  37                free(rerere_dir[i]);
  38        free(rerere_dir);
  39        rerere_dir_nr = rerere_dir_alloc = 0;
  40        rerere_dir = NULL;
  41}
  42
  43static void free_rerere_id(struct string_list_item *item)
  44{
  45        free(item->util);
  46}
  47
  48static const char *rerere_id_hex(const struct rerere_id *id)
  49{
  50        return sha1_to_hex(id->collection->sha1);
  51}
  52
  53const char *rerere_path(const struct rerere_id *id, const char *file)
  54{
  55        if (!file)
  56                return git_path("rr-cache/%s", rerere_id_hex(id));
  57
  58        return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
  59}
  60
  61static const unsigned char *rerere_dir_sha1(size_t i, void *table)
  62{
  63        struct rerere_dir **rr_dir = table;
  64        return rr_dir[i]->sha1;
  65}
  66
  67static struct rerere_dir *find_rerere_dir(const char *hex)
  68{
  69        unsigned char sha1[20];
  70        struct rerere_dir *rr_dir;
  71        int pos;
  72
  73        if (get_sha1_hex(hex, sha1))
  74                return NULL; /* BUG */
  75        pos = sha1_pos(sha1, rerere_dir, rerere_dir_nr, rerere_dir_sha1);
  76        if (pos < 0) {
  77                rr_dir = xmalloc(sizeof(*rr_dir));
  78                hashcpy(rr_dir->sha1, sha1);
  79                pos = -1 - pos;
  80
  81                /* Make sure the array is big enough ... */
  82                ALLOC_GROW(rerere_dir, rerere_dir_nr + 1, rerere_dir_alloc);
  83                /* ... and add it in. */
  84                rerere_dir_nr++;
  85                memmove(rerere_dir + pos + 1, rerere_dir + pos,
  86                        (rerere_dir_nr - pos - 1) * sizeof(*rerere_dir));
  87                rerere_dir[pos] = rr_dir;
  88        }
  89        return rerere_dir[pos];
  90}
  91
  92static int has_rerere_resolution(const struct rerere_id *id)
  93{
  94        struct stat st;
  95
  96        return !stat(rerere_path(id, "postimage"), &st);
  97}
  98
  99static struct rerere_id *new_rerere_id_hex(char *hex)
 100{
 101        struct rerere_id *id = xmalloc(sizeof(*id));
 102        id->collection = find_rerere_dir(hex);
 103        return id;
 104}
 105
 106static struct rerere_id *new_rerere_id(unsigned char *sha1)
 107{
 108        return new_rerere_id_hex(sha1_to_hex(sha1));
 109}
 110
 111/*
 112 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
 113 * "conflict ID", a HT and pathname, terminated with a NUL, and is
 114 * used to keep track of the set of paths that "rerere" may need to
 115 * work on (i.e. what is left by the previous invocation of "git
 116 * rerere" during the current conflict resolution session).
 117 */
 118static void read_rr(struct string_list *rr)
 119{
 120        struct strbuf buf = STRBUF_INIT;
 121        FILE *in = fopen(merge_rr_path, "r");
 122
 123        if (!in)
 124                return;
 125        while (!strbuf_getwholeline(&buf, in, '\0')) {
 126                char *path;
 127                unsigned char sha1[20];
 128                struct rerere_id *id;
 129
 130                /* There has to be the hash, tab, path and then NUL */
 131                if (buf.len < 42 || get_sha1_hex(buf.buf, sha1))
 132                        die("corrupt MERGE_RR");
 133
 134                if (buf.buf[40] != '\t')
 135                        die("corrupt MERGE_RR");
 136                buf.buf[40] = '\0';
 137                path = buf.buf + 41;
 138                id = new_rerere_id_hex(buf.buf);
 139                string_list_insert(rr, path)->util = id;
 140        }
 141        strbuf_release(&buf);
 142        fclose(in);
 143}
 144
 145static struct lock_file write_lock;
 146
 147static int write_rr(struct string_list *rr, int out_fd)
 148{
 149        int i;
 150        for (i = 0; i < rr->nr; i++) {
 151                struct strbuf buf = STRBUF_INIT;
 152                struct rerere_id *id;
 153
 154                assert(rr->items[i].util != RERERE_RESOLVED);
 155
 156                id = rr->items[i].util;
 157                if (!id)
 158                        continue;
 159                strbuf_addf(&buf, "%s\t%s%c",
 160                            rerere_id_hex(id),
 161                            rr->items[i].string, 0);
 162                if (write_in_full(out_fd, buf.buf, buf.len) != buf.len)
 163                        die("unable to write rerere record");
 164
 165                strbuf_release(&buf);
 166        }
 167        if (commit_lock_file(&write_lock) != 0)
 168                die("unable to write rerere record");
 169        return 0;
 170}
 171
 172/*
 173 * "rerere" interacts with conflicted file contents using this I/O
 174 * abstraction.  It reads a conflicted contents from one place via
 175 * "getline()" method, and optionally can write it out after
 176 * normalizing the conflicted hunks to the "output".  Subclasses of
 177 * rerere_io embed this structure at the beginning of their own
 178 * rerere_io object.
 179 */
 180struct rerere_io {
 181        int (*getline)(struct strbuf *, struct rerere_io *);
 182        FILE *output;
 183        int wrerror;
 184        /* some more stuff */
 185};
 186
 187static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
 188{
 189        if (!count || *err)
 190                return;
 191        if (fwrite(p, count, 1, fp) != 1)
 192                *err = errno;
 193}
 194
 195static inline void ferr_puts(const char *s, FILE *fp, int *err)
 196{
 197        ferr_write(s, strlen(s), fp, err);
 198}
 199
 200static void rerere_io_putstr(const char *str, struct rerere_io *io)
 201{
 202        if (io->output)
 203                ferr_puts(str, io->output, &io->wrerror);
 204}
 205
 206/*
 207 * Write a conflict marker to io->output (if defined).
 208 */
 209static void rerere_io_putconflict(int ch, int size, struct rerere_io *io)
 210{
 211        char buf[64];
 212
 213        while (size) {
 214                if (size <= sizeof(buf) - 2) {
 215                        memset(buf, ch, size);
 216                        buf[size] = '\n';
 217                        buf[size + 1] = '\0';
 218                        size = 0;
 219                } else {
 220                        int sz = sizeof(buf) - 1;
 221
 222                        /*
 223                         * Make sure we will not write everything out
 224                         * in this round by leaving at least 1 byte
 225                         * for the next round, giving the next round
 226                         * a chance to add the terminating LF.  Yuck.
 227                         */
 228                        if (size <= sz)
 229                                sz -= (sz - size) + 1;
 230                        memset(buf, ch, sz);
 231                        buf[sz] = '\0';
 232                        size -= sz;
 233                }
 234                rerere_io_putstr(buf, io);
 235        }
 236}
 237
 238static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
 239{
 240        if (io->output)
 241                ferr_write(mem, sz, io->output, &io->wrerror);
 242}
 243
 244/*
 245 * Subclass of rerere_io that reads from an on-disk file
 246 */
 247struct rerere_io_file {
 248        struct rerere_io io;
 249        FILE *input;
 250};
 251
 252/*
 253 * ... and its getline() method implementation
 254 */
 255static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
 256{
 257        struct rerere_io_file *io = (struct rerere_io_file *)io_;
 258        return strbuf_getwholeline(sb, io->input, '\n');
 259}
 260
 261/*
 262 * Require the exact number of conflict marker letters, no more, no
 263 * less, followed by SP or any whitespace
 264 * (including LF).
 265 */
 266static int is_cmarker(char *buf, int marker_char, int marker_size)
 267{
 268        int want_sp;
 269
 270        /*
 271         * The beginning of our version and the end of their version
 272         * always are labeled like "<<<<< ours" or ">>>>> theirs",
 273         * hence we set want_sp for them.  Note that the version from
 274         * the common ancestor in diff3-style output is not always
 275         * labelled (e.g. "||||| common" is often seen but "|||||"
 276         * alone is also valid), so we do not set want_sp.
 277         */
 278        want_sp = (marker_char == '<') || (marker_char == '>');
 279
 280        while (marker_size--)
 281                if (*buf++ != marker_char)
 282                        return 0;
 283        if (want_sp && *buf != ' ')
 284                return 0;
 285        return isspace(*buf);
 286}
 287
 288/*
 289 * Read contents a file with conflicts, normalize the conflicts
 290 * by (1) discarding the common ancestor version in diff3-style,
 291 * (2) reordering our side and their side so that whichever sorts
 292 * alphabetically earlier comes before the other one, while
 293 * computing the "conflict ID", which is just an SHA-1 hash of
 294 * one side of the conflict, NUL, the other side of the conflict,
 295 * and NUL concatenated together.
 296 *
 297 * Return the number of conflict hunks found.
 298 *
 299 * NEEDSWORK: the logic and theory of operation behind this conflict
 300 * normalization may deserve to be documented somewhere, perhaps in
 301 * Documentation/technical/rerere.txt.
 302 */
 303static int handle_path(unsigned char *sha1, struct rerere_io *io, int marker_size)
 304{
 305        git_SHA_CTX ctx;
 306        int hunk_no = 0;
 307        enum {
 308                RR_CONTEXT = 0, RR_SIDE_1, RR_SIDE_2, RR_ORIGINAL
 309        } hunk = RR_CONTEXT;
 310        struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
 311        struct strbuf buf = STRBUF_INIT;
 312
 313        if (sha1)
 314                git_SHA1_Init(&ctx);
 315
 316        while (!io->getline(&buf, io)) {
 317                if (is_cmarker(buf.buf, '<', marker_size)) {
 318                        if (hunk != RR_CONTEXT)
 319                                goto bad;
 320                        hunk = RR_SIDE_1;
 321                } else if (is_cmarker(buf.buf, '|', marker_size)) {
 322                        if (hunk != RR_SIDE_1)
 323                                goto bad;
 324                        hunk = RR_ORIGINAL;
 325                } else if (is_cmarker(buf.buf, '=', marker_size)) {
 326                        if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
 327                                goto bad;
 328                        hunk = RR_SIDE_2;
 329                } else if (is_cmarker(buf.buf, '>', marker_size)) {
 330                        if (hunk != RR_SIDE_2)
 331                                goto bad;
 332                        if (strbuf_cmp(&one, &two) > 0)
 333                                strbuf_swap(&one, &two);
 334                        hunk_no++;
 335                        hunk = RR_CONTEXT;
 336                        rerere_io_putconflict('<', marker_size, io);
 337                        rerere_io_putmem(one.buf, one.len, io);
 338                        rerere_io_putconflict('=', marker_size, io);
 339                        rerere_io_putmem(two.buf, two.len, io);
 340                        rerere_io_putconflict('>', marker_size, io);
 341                        if (sha1) {
 342                                git_SHA1_Update(&ctx, one.buf ? one.buf : "",
 343                                            one.len + 1);
 344                                git_SHA1_Update(&ctx, two.buf ? two.buf : "",
 345                                            two.len + 1);
 346                        }
 347                        strbuf_reset(&one);
 348                        strbuf_reset(&two);
 349                } else if (hunk == RR_SIDE_1)
 350                        strbuf_addbuf(&one, &buf);
 351                else if (hunk == RR_ORIGINAL)
 352                        ; /* discard */
 353                else if (hunk == RR_SIDE_2)
 354                        strbuf_addbuf(&two, &buf);
 355                else
 356                        rerere_io_putstr(buf.buf, io);
 357                continue;
 358        bad:
 359                hunk = 99; /* force error exit */
 360                break;
 361        }
 362        strbuf_release(&one);
 363        strbuf_release(&two);
 364        strbuf_release(&buf);
 365
 366        if (sha1)
 367                git_SHA1_Final(sha1, &ctx);
 368        if (hunk != RR_CONTEXT)
 369                return -1;
 370        return hunk_no;
 371}
 372
 373/*
 374 * Scan the path for conflicts, do the "handle_path()" thing above, and
 375 * return the number of conflict hunks found.
 376 */
 377static int handle_file(const char *path, unsigned char *sha1, const char *output)
 378{
 379        int hunk_no = 0;
 380        struct rerere_io_file io;
 381        int marker_size = ll_merge_marker_size(path);
 382
 383        memset(&io, 0, sizeof(io));
 384        io.io.getline = rerere_file_getline;
 385        io.input = fopen(path, "r");
 386        io.io.wrerror = 0;
 387        if (!io.input)
 388                return error("Could not open %s", path);
 389
 390        if (output) {
 391                io.io.output = fopen(output, "w");
 392                if (!io.io.output) {
 393                        fclose(io.input);
 394                        return error("Could not write %s", output);
 395                }
 396        }
 397
 398        hunk_no = handle_path(sha1, (struct rerere_io *)&io, marker_size);
 399
 400        fclose(io.input);
 401        if (io.io.wrerror)
 402                error("There were errors while writing %s (%s)",
 403                      path, strerror(io.io.wrerror));
 404        if (io.io.output && fclose(io.io.output))
 405                io.io.wrerror = error("Failed to flush %s: %s",
 406                                      path, strerror(errno));
 407
 408        if (hunk_no < 0) {
 409                if (output)
 410                        unlink_or_warn(output);
 411                return error("Could not parse conflict hunks in %s", path);
 412        }
 413        if (io.io.wrerror)
 414                return -1;
 415        return hunk_no;
 416}
 417
 418/*
 419 * Subclass of rerere_io that reads from an in-core buffer that is a
 420 * strbuf
 421 */
 422struct rerere_io_mem {
 423        struct rerere_io io;
 424        struct strbuf input;
 425};
 426
 427/*
 428 * ... and its getline() method implementation
 429 */
 430static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
 431{
 432        struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
 433        char *ep;
 434        size_t len;
 435
 436        strbuf_release(sb);
 437        if (!io->input.len)
 438                return -1;
 439        ep = memchr(io->input.buf, '\n', io->input.len);
 440        if (!ep)
 441                ep = io->input.buf + io->input.len;
 442        else if (*ep == '\n')
 443                ep++;
 444        len = ep - io->input.buf;
 445        strbuf_add(sb, io->input.buf, len);
 446        strbuf_remove(&io->input, 0, len);
 447        return 0;
 448}
 449
 450static int handle_cache(const char *path, unsigned char *sha1, const char *output)
 451{
 452        mmfile_t mmfile[3] = {{NULL}};
 453        mmbuffer_t result = {NULL, 0};
 454        const struct cache_entry *ce;
 455        int pos, len, i, hunk_no;
 456        struct rerere_io_mem io;
 457        int marker_size = ll_merge_marker_size(path);
 458
 459        /*
 460         * Reproduce the conflicted merge in-core
 461         */
 462        len = strlen(path);
 463        pos = cache_name_pos(path, len);
 464        if (0 <= pos)
 465                return -1;
 466        pos = -pos - 1;
 467
 468        while (pos < active_nr) {
 469                enum object_type type;
 470                unsigned long size;
 471
 472                ce = active_cache[pos++];
 473                if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
 474                        break;
 475                i = ce_stage(ce) - 1;
 476                if (!mmfile[i].ptr) {
 477                        mmfile[i].ptr = read_sha1_file(ce->sha1, &type, &size);
 478                        mmfile[i].size = size;
 479                }
 480        }
 481        for (i = 0; i < 3; i++)
 482                if (!mmfile[i].ptr && !mmfile[i].size)
 483                        mmfile[i].ptr = xstrdup("");
 484
 485        /*
 486         * NEEDSWORK: handle conflicts from merges with
 487         * merge.renormalize set, too
 488         */
 489        ll_merge(&result, path, &mmfile[0], NULL,
 490                 &mmfile[1], "ours",
 491                 &mmfile[2], "theirs", NULL);
 492        for (i = 0; i < 3; i++)
 493                free(mmfile[i].ptr);
 494
 495        memset(&io, 0, sizeof(io));
 496        io.io.getline = rerere_mem_getline;
 497        if (output)
 498                io.io.output = fopen(output, "w");
 499        else
 500                io.io.output = NULL;
 501        strbuf_init(&io.input, 0);
 502        strbuf_attach(&io.input, result.ptr, result.size, result.size);
 503
 504        /*
 505         * Grab the conflict ID and optionally write the original
 506         * contents with conflict markers out.
 507         */
 508        hunk_no = handle_path(sha1, (struct rerere_io *)&io, marker_size);
 509        strbuf_release(&io.input);
 510        if (io.io.output)
 511                fclose(io.io.output);
 512        return hunk_no;
 513}
 514
 515/*
 516 * Look at a cache entry at "i" and see if it is not conflicting,
 517 * conflicting and we are willing to handle, or conflicting and
 518 * we are unable to handle, and return the determination in *type.
 519 * Return the cache index to be looked at next, by skipping the
 520 * stages we have already looked at in this invocation of this
 521 * function.
 522 */
 523static int check_one_conflict(int i, int *type)
 524{
 525        const struct cache_entry *e = active_cache[i];
 526
 527        if (!ce_stage(e)) {
 528                *type = RESOLVED;
 529                return i + 1;
 530        }
 531
 532        *type = PUNTED;
 533        while (ce_stage(active_cache[i]) == 1)
 534                i++;
 535
 536        /* Only handle regular files with both stages #2 and #3 */
 537        if (i + 1 < active_nr) {
 538                const struct cache_entry *e2 = active_cache[i];
 539                const struct cache_entry *e3 = active_cache[i + 1];
 540                if (ce_stage(e2) == 2 &&
 541                    ce_stage(e3) == 3 &&
 542                    ce_same_name(e, e3) &&
 543                    S_ISREG(e2->ce_mode) &&
 544                    S_ISREG(e3->ce_mode))
 545                        *type = THREE_STAGED;
 546        }
 547
 548        /* Skip the entries with the same name */
 549        while (i < active_nr && ce_same_name(e, active_cache[i]))
 550                i++;
 551        return i;
 552}
 553
 554/*
 555 * Scan the index and find paths that have conflicts that rerere can
 556 * handle, i.e. the ones that has both stages #2 and #3.
 557 *
 558 * NEEDSWORK: we do not record or replay a previous "resolve by
 559 * deletion" for a delete-modify conflict, as that is inherently risky
 560 * without knowing what modification is being discarded.  The only
 561 * safe case, i.e. both side doing the deletion and modification that
 562 * are identical to the previous round, might want to be handled,
 563 * though.
 564 */
 565static int find_conflict(struct string_list *conflict)
 566{
 567        int i;
 568        if (read_cache() < 0)
 569                return error("Could not read index");
 570
 571        for (i = 0; i < active_nr;) {
 572                int conflict_type;
 573                const struct cache_entry *e = active_cache[i];
 574                i = check_one_conflict(i, &conflict_type);
 575                if (conflict_type == THREE_STAGED)
 576                        string_list_insert(conflict, (const char *)e->name);
 577        }
 578        return 0;
 579}
 580
 581/*
 582 * The merge_rr list is meant to hold outstanding conflicted paths
 583 * that rerere could handle.  Abuse the list by adding other types of
 584 * entries to allow the caller to show "rerere remaining".
 585 *
 586 * - Conflicted paths that rerere does not handle are added
 587 * - Conflicted paths that have been resolved are marked as such
 588 *   by storing RERERE_RESOLVED to .util field (where conflict ID
 589 *   is expected to be stored).
 590 *
 591 * Do *not* write MERGE_RR file out after calling this function.
 592 *
 593 * NEEDSWORK: we may want to fix the caller that implements "rerere
 594 * remaining" to do this without abusing merge_rr.
 595 */
 596int rerere_remaining(struct string_list *merge_rr)
 597{
 598        int i;
 599        if (read_cache() < 0)
 600                return error("Could not read index");
 601
 602        for (i = 0; i < active_nr;) {
 603                int conflict_type;
 604                const struct cache_entry *e = active_cache[i];
 605                i = check_one_conflict(i, &conflict_type);
 606                if (conflict_type == PUNTED)
 607                        string_list_insert(merge_rr, (const char *)e->name);
 608                else if (conflict_type == RESOLVED) {
 609                        struct string_list_item *it;
 610                        it = string_list_lookup(merge_rr, (const char *)e->name);
 611                        if (it != NULL) {
 612                                free_rerere_id(it);
 613                                it->util = RERERE_RESOLVED;
 614                        }
 615                }
 616        }
 617        return 0;
 618}
 619
 620/*
 621 * Find the conflict identified by "id"; the change between its
 622 * "preimage" (i.e. a previous contents with conflict markers) and its
 623 * "postimage" (i.e. the corresponding contents with conflicts
 624 * resolved) may apply cleanly to the contents stored in "path", i.e.
 625 * the conflict this time around.
 626 *
 627 * Returns 0 for successful replay of recorded resolution, or non-zero
 628 * for failure.
 629 */
 630static int merge(const struct rerere_id *id, const char *path)
 631{
 632        FILE *f;
 633        int ret;
 634        mmfile_t cur = {NULL, 0}, base = {NULL, 0}, other = {NULL, 0};
 635        mmbuffer_t result = {NULL, 0};
 636
 637        /*
 638         * Normalize the conflicts in path and write it out to
 639         * "thisimage" temporary file.
 640         */
 641        if (handle_file(path, NULL, rerere_path(id, "thisimage")) < 0) {
 642                ret = 1;
 643                goto out;
 644        }
 645
 646        if (read_mmfile(&cur, rerere_path(id, "thisimage")) ||
 647            read_mmfile(&base, rerere_path(id, "preimage")) ||
 648            read_mmfile(&other, rerere_path(id, "postimage"))) {
 649                ret = 1;
 650                goto out;
 651        }
 652
 653        /*
 654         * A three-way merge. Note that this honors user-customizable
 655         * low-level merge driver settings.
 656         */
 657        ret = ll_merge(&result, path, &base, NULL, &cur, "", &other, "", NULL);
 658        if (ret)
 659                goto out;
 660
 661        /*
 662         * A successful replay of recorded resolution.
 663         * Mark that "postimage" was used to help gc.
 664         */
 665        if (utime(rerere_path(id, "postimage"), NULL) < 0)
 666                warning("failed utime() on %s: %s",
 667                        rerere_path(id, "postimage"),
 668                        strerror(errno));
 669
 670        /* Update "path" with the resolution */
 671        f = fopen(path, "w");
 672        if (!f)
 673                return error("Could not open %s: %s", path,
 674                             strerror(errno));
 675        if (fwrite(result.ptr, result.size, 1, f) != 1)
 676                error("Could not write %s: %s", path, strerror(errno));
 677        if (fclose(f))
 678                return error("Writing %s failed: %s", path,
 679                             strerror(errno));
 680
 681out:
 682        free(cur.ptr);
 683        free(base.ptr);
 684        free(other.ptr);
 685        free(result.ptr);
 686
 687        return ret;
 688}
 689
 690static struct lock_file index_lock;
 691
 692static void update_paths(struct string_list *update)
 693{
 694        int i;
 695
 696        hold_locked_index(&index_lock, 1);
 697
 698        for (i = 0; i < update->nr; i++) {
 699                struct string_list_item *item = &update->items[i];
 700                if (add_file_to_cache(item->string, 0))
 701                        exit(128);
 702                fprintf(stderr, "Staged '%s' using previous resolution.\n",
 703                        item->string);
 704        }
 705
 706        if (active_cache_changed) {
 707                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 708                        die("Unable to write new index file");
 709        } else
 710                rollback_lock_file(&index_lock);
 711}
 712
 713/*
 714 * The path indicated by rr_item may still have conflict for which we
 715 * have a recorded resolution, in which case replay it and optionally
 716 * update it.  Or it may have been resolved by the user and we may
 717 * only have the preimage for that conflict, in which case the result
 718 * needs to be recorded as a resolution in a postimage file.
 719 */
 720static void do_rerere_one_path(struct string_list_item *rr_item,
 721                               struct string_list *update)
 722{
 723        const char *path = rr_item->string;
 724        const struct rerere_id *id = rr_item->util;
 725
 726        /* Is there a recorded resolution we could attempt to apply? */
 727        if (has_rerere_resolution(id)) {
 728                if (merge(id, path))
 729                        return; /* failed to replay */
 730
 731                if (rerere_autoupdate)
 732                        string_list_insert(update, path);
 733                else
 734                        fprintf(stderr,
 735                                "Resolved '%s' using previous resolution.\n",
 736                                path);
 737        } else if (!handle_file(path, NULL, NULL)) {
 738                /* The user has resolved it. */
 739                copy_file(rerere_path(id, "postimage"), path, 0666);
 740                fprintf(stderr, "Recorded resolution for '%s'.\n", path);
 741        } else {
 742                return;
 743        }
 744        free_rerere_id(rr_item);
 745        rr_item->util = NULL;
 746}
 747
 748static int do_plain_rerere(struct string_list *rr, int fd)
 749{
 750        struct string_list conflict = STRING_LIST_INIT_DUP;
 751        struct string_list update = STRING_LIST_INIT_DUP;
 752        int i;
 753
 754        find_conflict(&conflict);
 755
 756        /*
 757         * MERGE_RR records paths with conflicts immediately after
 758         * merge failed.  Some of the conflicted paths might have been
 759         * hand resolved in the working tree since then, but the
 760         * initial run would catch all and register their preimages.
 761         */
 762        for (i = 0; i < conflict.nr; i++) {
 763                struct rerere_id *id;
 764                unsigned char sha1[20];
 765                const char *path = conflict.items[i].string;
 766                int ret;
 767
 768                if (string_list_has_string(rr, path))
 769                        continue;
 770
 771                /*
 772                 * Ask handle_file() to scan and assign a
 773                 * conflict ID.  No need to write anything out
 774                 * yet.
 775                 */
 776                ret = handle_file(path, sha1, NULL);
 777                if (ret < 1)
 778                        continue;
 779
 780                id = new_rerere_id(sha1);
 781                string_list_insert(rr, path)->util = id;
 782
 783                /*
 784                 * If the directory does not exist, create
 785                 * it.  mkdir_in_gitdir() will fail with
 786                 * EEXIST if there already is one.
 787                 *
 788                 * NEEDSWORK: make sure "gc" does not remove
 789                 * preimage without removing the directory.
 790                 */
 791                if (mkdir_in_gitdir(rerere_path(id, NULL)))
 792                        continue;
 793
 794                /*
 795                 * We are the first to encounter this
 796                 * conflict.  Ask handle_file() to write the
 797                 * normalized contents to the "preimage" file.
 798                 */
 799                handle_file(path, NULL, rerere_path(id, "preimage"));
 800                fprintf(stderr, "Recorded preimage for '%s'\n", path);
 801        }
 802
 803        for (i = 0; i < rr->nr; i++)
 804                do_rerere_one_path(&rr->items[i], &update);
 805
 806        if (update.nr)
 807                update_paths(&update);
 808
 809        return write_rr(rr, fd);
 810}
 811
 812static void git_rerere_config(void)
 813{
 814        git_config_get_bool("rerere.enabled", &rerere_enabled);
 815        git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
 816        git_config(git_default_config, NULL);
 817}
 818
 819static int is_rerere_enabled(void)
 820{
 821        const char *rr_cache;
 822        int rr_cache_exists;
 823
 824        if (!rerere_enabled)
 825                return 0;
 826
 827        rr_cache = git_path("rr-cache");
 828        rr_cache_exists = is_directory(rr_cache);
 829        if (rerere_enabled < 0)
 830                return rr_cache_exists;
 831
 832        if (!rr_cache_exists && mkdir_in_gitdir(rr_cache))
 833                die("Could not create directory %s", rr_cache);
 834        return 1;
 835}
 836
 837int setup_rerere(struct string_list *merge_rr, int flags)
 838{
 839        int fd;
 840
 841        git_rerere_config();
 842        if (!is_rerere_enabled())
 843                return -1;
 844
 845        if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
 846                rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
 847        merge_rr_path = git_pathdup("MERGE_RR");
 848        fd = hold_lock_file_for_update(&write_lock, merge_rr_path,
 849                                       LOCK_DIE_ON_ERROR);
 850        read_rr(merge_rr);
 851        return fd;
 852}
 853
 854/*
 855 * The main entry point that is called internally from codepaths that
 856 * perform mergy operations, possibly leaving conflicted index entries
 857 * and working tree files.
 858 */
 859int rerere(int flags)
 860{
 861        struct string_list merge_rr = STRING_LIST_INIT_DUP;
 862        int fd, status;
 863
 864        fd = setup_rerere(&merge_rr, flags);
 865        if (fd < 0)
 866                return 0;
 867        status = do_plain_rerere(&merge_rr, fd);
 868        free_rerere_dirs();
 869        return status;
 870}
 871
 872static int rerere_forget_one_path(const char *path, struct string_list *rr)
 873{
 874        const char *filename;
 875        struct rerere_id *id;
 876        unsigned char sha1[20];
 877        int ret;
 878        struct string_list_item *item;
 879
 880        /*
 881         * Recreate the original conflict from the stages in the
 882         * index and compute the conflict ID
 883         */
 884        ret = handle_cache(path, sha1, NULL);
 885        if (ret < 1)
 886                return error("Could not parse conflict hunks in '%s'", path);
 887
 888        /* Nuke the recorded resolution for the conflict */
 889        id = new_rerere_id(sha1);
 890        filename = rerere_path(id, "postimage");
 891        if (unlink(filename))
 892                return (errno == ENOENT
 893                        ? error("no remembered resolution for %s", path)
 894                        : error("cannot unlink %s: %s", filename, strerror(errno)));
 895
 896        /*
 897         * Update the preimage so that the user can resolve the
 898         * conflict in the working tree, run us again to record
 899         * the postimage.
 900         */
 901        handle_cache(path, sha1, rerere_path(id, "preimage"));
 902        fprintf(stderr, "Updated preimage for '%s'\n", path);
 903
 904        /*
 905         * And remember that we can record resolution for this
 906         * conflict when the user is done.
 907         */
 908        item = string_list_insert(rr, path);
 909        free_rerere_id(item);
 910        item->util = id;
 911        fprintf(stderr, "Forgot resolution for %s\n", path);
 912        return 0;
 913}
 914
 915int rerere_forget(struct pathspec *pathspec)
 916{
 917        int i, fd;
 918        struct string_list conflict = STRING_LIST_INIT_DUP;
 919        struct string_list merge_rr = STRING_LIST_INIT_DUP;
 920
 921        if (read_cache() < 0)
 922                return error("Could not read index");
 923
 924        fd = setup_rerere(&merge_rr, RERERE_NOAUTOUPDATE);
 925
 926        /*
 927         * The paths may have been resolved (incorrectly);
 928         * recover the original conflicted state and then
 929         * find the conflicted paths.
 930         */
 931        unmerge_cache(pathspec);
 932        find_conflict(&conflict);
 933        for (i = 0; i < conflict.nr; i++) {
 934                struct string_list_item *it = &conflict.items[i];
 935                if (!match_pathspec(pathspec, it->string,
 936                                    strlen(it->string), 0, NULL, 0))
 937                        continue;
 938                rerere_forget_one_path(it->string, &merge_rr);
 939        }
 940        return write_rr(&merge_rr, fd);
 941}
 942
 943/*
 944 * Garbage collection support
 945 */
 946
 947/*
 948 * Note that this is not reentrant but is used only one-at-a-time
 949 * so it does not matter right now.
 950 */
 951static struct rerere_id *dirname_to_id(const char *name)
 952{
 953        static struct rerere_id id;
 954        id.collection = find_rerere_dir(name);
 955        return &id;
 956}
 957
 958static time_t rerere_created_at(const char *dir_name)
 959{
 960        struct stat st;
 961        struct rerere_id *id = dirname_to_id(dir_name);
 962
 963        return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
 964}
 965
 966static time_t rerere_last_used_at(const char *dir_name)
 967{
 968        struct stat st;
 969        struct rerere_id *id = dirname_to_id(dir_name);
 970
 971        return stat(rerere_path(id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
 972}
 973
 974/*
 975 * Remove the recorded resolution for a given conflict ID
 976 */
 977static void unlink_rr_item(struct rerere_id *id)
 978{
 979        unlink(rerere_path(id, "thisimage"));
 980        unlink(rerere_path(id, "preimage"));
 981        unlink(rerere_path(id, "postimage"));
 982        /*
 983         * NEEDSWORK: what if this rmdir() fails?  Wouldn't we then
 984         * assume that we already have preimage recorded in
 985         * do_plain_rerere()?
 986         */
 987        rmdir(rerere_path(id, NULL));
 988}
 989
 990void rerere_gc(struct string_list *rr)
 991{
 992        struct string_list to_remove = STRING_LIST_INIT_DUP;
 993        DIR *dir;
 994        struct dirent *e;
 995        int i, cutoff;
 996        time_t now = time(NULL), then;
 997        int cutoff_noresolve = 15;
 998        int cutoff_resolve = 60;
 999
1000        git_config_get_int("gc.rerereresolved", &cutoff_resolve);
1001        git_config_get_int("gc.rerereunresolved", &cutoff_noresolve);
1002        git_config(git_default_config, NULL);
1003        dir = opendir(git_path("rr-cache"));
1004        if (!dir)
1005                die_errno("unable to open rr-cache directory");
1006        /* Collect stale conflict IDs ... */
1007        while ((e = readdir(dir))) {
1008                if (is_dot_or_dotdot(e->d_name))
1009                        continue;
1010
1011                then = rerere_last_used_at(e->d_name);
1012                if (then) {
1013                        cutoff = cutoff_resolve;
1014                } else {
1015                        then = rerere_created_at(e->d_name);
1016                        if (!then)
1017                                continue;
1018                        cutoff = cutoff_noresolve;
1019                }
1020                if (then < now - cutoff * 86400)
1021                        string_list_append(&to_remove, e->d_name);
1022        }
1023        closedir(dir);
1024        /* ... and then remove them one-by-one */
1025        for (i = 0; i < to_remove.nr; i++)
1026                unlink_rr_item(dirname_to_id(to_remove.items[i].string));
1027        string_list_clear(&to_remove, 0);
1028}
1029
1030/*
1031 * During a conflict resolution, after "rerere" recorded the
1032 * preimages, abandon them if the user did not resolve them or
1033 * record their resolutions.  And drop $GIT_DIR/MERGE_RR.
1034 *
1035 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1036 */
1037void rerere_clear(struct string_list *merge_rr)
1038{
1039        int i;
1040
1041        for (i = 0; i < merge_rr->nr; i++) {
1042                struct rerere_id *id = merge_rr->items[i].util;
1043                if (!has_rerere_resolution(id))
1044                        unlink_rr_item(id);
1045        }
1046        unlink_or_warn(git_path("MERGE_RR"));
1047}