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