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