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