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