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