6fd8c5d3afd08a3daaea8c1f83f4ae149bcff1e2
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "string-list.h"
   4#include "rerere.h"
   5#include "xdiff-interface.h"
   6#include "dir.h"
   7#include "resolve-undo.h"
   8#include "ll-merge.h"
   9#include "attr.h"
  10#include "pathspec.h"
  11
  12#define RESOLVED 0
  13#define PUNTED 1
  14#define THREE_STAGED 2
  15void *RERERE_RESOLVED = &RERERE_RESOLVED;
  16
  17/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
  18static int rerere_enabled = -1;
  19
  20/* automatically update cleanly resolved paths to the index */
  21static int rerere_autoupdate;
  22
  23static char *merge_rr_path;
  24
  25const char *rerere_path(const char *hex, const char *file)
  26{
  27        return git_path("rr-cache/%s/%s", hex, file);
  28}
  29
  30static int has_rerere_resolution(const char *hex)
  31{
  32        struct stat st;
  33        return !stat(rerere_path(hex, "postimage"), &st);
  34}
  35
  36static void read_rr(struct string_list *rr)
  37{
  38        struct strbuf buf = STRBUF_INIT;
  39        FILE *in = fopen(merge_rr_path, "r");
  40
  41        if (!in)
  42                return;
  43        while (!strbuf_getwholeline(&buf, in, '\0')) {
  44                char *path;
  45                unsigned char sha1[20];
  46
  47                /* There has to be the hash, tab, path and then NUL */
  48                if (buf.len < 42 || get_sha1_hex(buf.buf, sha1))
  49                        die("corrupt MERGE_RR");
  50
  51                if (buf.buf[40] != '\t')
  52                        die("corrupt MERGE_RR");
  53                buf.buf[40] = '\0';
  54                path = buf.buf + 41;
  55
  56                string_list_insert(rr, path)->util = xstrdup(buf.buf);
  57        }
  58        strbuf_release(&buf);
  59        fclose(in);
  60}
  61
  62static struct lock_file write_lock;
  63
  64static int write_rr(struct string_list *rr, int out_fd)
  65{
  66        int i;
  67        for (i = 0; i < rr->nr; i++) {
  68                struct strbuf buf = STRBUF_INIT;
  69
  70                assert(rr->items[i].util != RERERE_RESOLVED);
  71                if (!rr->items[i].util)
  72                        continue;
  73                strbuf_addf(&buf, "%s\t%s%c",
  74                            (char *)rr->items[i].util,
  75                            rr->items[i].string, 0);
  76                if (write_in_full(out_fd, buf.buf, buf.len) != buf.len)
  77                        die("unable to write rerere record");
  78
  79                strbuf_release(&buf);
  80        }
  81        if (commit_lock_file(&write_lock) != 0)
  82                die("unable to write rerere record");
  83        return 0;
  84}
  85
  86/*
  87 * "rerere" interacts with conflicted file contents using this I/O
  88 * abstraction.  It reads a conflicted contents from one place via
  89 * "getline()" method, and optionally can write it out after
  90 * normalizing the conflicted hunks to the "output".  Subclasses of
  91 * rerere_io embed this structure at the beginning of their own
  92 * rerere_io object.
  93 */
  94struct rerere_io {
  95        int (*getline)(struct strbuf *, struct rerere_io *);
  96        FILE *output;
  97        int wrerror;
  98        /* some more stuff */
  99};
 100
 101static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
 102{
 103        if (!count || *err)
 104                return;
 105        if (fwrite(p, count, 1, fp) != 1)
 106                *err = errno;
 107}
 108
 109static inline void ferr_puts(const char *s, FILE *fp, int *err)
 110{
 111        ferr_write(s, strlen(s), fp, err);
 112}
 113
 114static void rerere_io_putstr(const char *str, struct rerere_io *io)
 115{
 116        if (io->output)
 117                ferr_puts(str, io->output, &io->wrerror);
 118}
 119
 120/*
 121 * Write a conflict marker to io->output (if defined).
 122 */
 123static void rerere_io_putconflict(int ch, int size, struct rerere_io *io)
 124{
 125        char buf[64];
 126
 127        while (size) {
 128                if (size <= sizeof(buf) - 2) {
 129                        memset(buf, ch, size);
 130                        buf[size] = '\n';
 131                        buf[size + 1] = '\0';
 132                        size = 0;
 133                } else {
 134                        int sz = sizeof(buf) - 1;
 135
 136                        /*
 137                         * Make sure we will not write everything out
 138                         * in this round by leaving at least 1 byte
 139                         * for the next round, giving the next round
 140                         * a chance to add the terminating LF.  Yuck.
 141                         */
 142                        if (size <= sz)
 143                                sz -= (sz - size) + 1;
 144                        memset(buf, ch, sz);
 145                        buf[sz] = '\0';
 146                        size -= sz;
 147                }
 148                rerere_io_putstr(buf, io);
 149        }
 150}
 151
 152static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
 153{
 154        if (io->output)
 155                ferr_write(mem, sz, io->output, &io->wrerror);
 156}
 157
 158/*
 159 * Subclass of rerere_io that reads from an on-disk file
 160 */
 161struct rerere_io_file {
 162        struct rerere_io io;
 163        FILE *input;
 164};
 165
 166/*
 167 * ... and its getline() method implementation
 168 */
 169static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
 170{
 171        struct rerere_io_file *io = (struct rerere_io_file *)io_;
 172        return strbuf_getwholeline(sb, io->input, '\n');
 173}
 174
 175/*
 176 * Require the exact number of conflict marker letters, no more, no
 177 * less, followed by SP or any whitespace
 178 * (including LF).
 179 */
 180static int is_cmarker(char *buf, int marker_char, int marker_size)
 181{
 182        int want_sp;
 183
 184        /*
 185         * The beginning of our version and the end of their version
 186         * always are labeled like "<<<<< ours" or ">>>>> theirs",
 187         * hence we set want_sp for them.  Note that the version from
 188         * the common ancestor in diff3-style output is not always
 189         * labelled (e.g. "||||| common" is often seen but "|||||"
 190         * alone is also valid), so we do not set want_sp.
 191         */
 192        want_sp = (marker_char == '<') || (marker_char == '>');
 193
 194        while (marker_size--)
 195                if (*buf++ != marker_char)
 196                        return 0;
 197        if (want_sp && *buf != ' ')
 198                return 0;
 199        return isspace(*buf);
 200}
 201
 202static int handle_path(unsigned char *sha1, struct rerere_io *io, int marker_size)
 203{
 204        git_SHA_CTX ctx;
 205        int hunk_no = 0;
 206        enum {
 207                RR_CONTEXT = 0, RR_SIDE_1, RR_SIDE_2, RR_ORIGINAL
 208        } hunk = RR_CONTEXT;
 209        struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
 210        struct strbuf buf = STRBUF_INIT;
 211
 212        if (sha1)
 213                git_SHA1_Init(&ctx);
 214
 215        while (!io->getline(&buf, io)) {
 216                if (is_cmarker(buf.buf, '<', marker_size)) {
 217                        if (hunk != RR_CONTEXT)
 218                                goto bad;
 219                        hunk = RR_SIDE_1;
 220                } else if (is_cmarker(buf.buf, '|', marker_size)) {
 221                        if (hunk != RR_SIDE_1)
 222                                goto bad;
 223                        hunk = RR_ORIGINAL;
 224                } else if (is_cmarker(buf.buf, '=', marker_size)) {
 225                        if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
 226                                goto bad;
 227                        hunk = RR_SIDE_2;
 228                } else if (is_cmarker(buf.buf, '>', marker_size)) {
 229                        if (hunk != RR_SIDE_2)
 230                                goto bad;
 231                        if (strbuf_cmp(&one, &two) > 0)
 232                                strbuf_swap(&one, &two);
 233                        hunk_no++;
 234                        hunk = RR_CONTEXT;
 235                        rerere_io_putconflict('<', marker_size, io);
 236                        rerere_io_putmem(one.buf, one.len, io);
 237                        rerere_io_putconflict('=', marker_size, io);
 238                        rerere_io_putmem(two.buf, two.len, io);
 239                        rerere_io_putconflict('>', marker_size, io);
 240                        if (sha1) {
 241                                git_SHA1_Update(&ctx, one.buf ? one.buf : "",
 242                                            one.len + 1);
 243                                git_SHA1_Update(&ctx, two.buf ? two.buf : "",
 244                                            two.len + 1);
 245                        }
 246                        strbuf_reset(&one);
 247                        strbuf_reset(&two);
 248                } else if (hunk == RR_SIDE_1)
 249                        strbuf_addbuf(&one, &buf);
 250                else if (hunk == RR_ORIGINAL)
 251                        ; /* discard */
 252                else if (hunk == RR_SIDE_2)
 253                        strbuf_addbuf(&two, &buf);
 254                else
 255                        rerere_io_putstr(buf.buf, io);
 256                continue;
 257        bad:
 258                hunk = 99; /* force error exit */
 259                break;
 260        }
 261        strbuf_release(&one);
 262        strbuf_release(&two);
 263        strbuf_release(&buf);
 264
 265        if (sha1)
 266                git_SHA1_Final(sha1, &ctx);
 267        if (hunk != RR_CONTEXT)
 268                return -1;
 269        return hunk_no;
 270}
 271
 272static int handle_file(const char *path, unsigned char *sha1, const char *output)
 273{
 274        int hunk_no = 0;
 275        struct rerere_io_file io;
 276        int marker_size = ll_merge_marker_size(path);
 277
 278        memset(&io, 0, sizeof(io));
 279        io.io.getline = rerere_file_getline;
 280        io.input = fopen(path, "r");
 281        io.io.wrerror = 0;
 282        if (!io.input)
 283                return error("Could not open %s", path);
 284
 285        if (output) {
 286                io.io.output = fopen(output, "w");
 287                if (!io.io.output) {
 288                        fclose(io.input);
 289                        return error("Could not write %s", output);
 290                }
 291        }
 292
 293        hunk_no = handle_path(sha1, (struct rerere_io *)&io, marker_size);
 294
 295        fclose(io.input);
 296        if (io.io.wrerror)
 297                error("There were errors while writing %s (%s)",
 298                      path, strerror(io.io.wrerror));
 299        if (io.io.output && fclose(io.io.output))
 300                io.io.wrerror = error("Failed to flush %s: %s",
 301                                      path, strerror(errno));
 302
 303        if (hunk_no < 0) {
 304                if (output)
 305                        unlink_or_warn(output);
 306                return error("Could not parse conflict hunks in %s", path);
 307        }
 308        if (io.io.wrerror)
 309                return -1;
 310        return hunk_no;
 311}
 312
 313/*
 314 * Subclass of rerere_io that reads from an in-core buffer that is a
 315 * strbuf
 316 */
 317struct rerere_io_mem {
 318        struct rerere_io io;
 319        struct strbuf input;
 320};
 321
 322/*
 323 * ... and its getline() method implementation
 324 */
 325static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
 326{
 327        struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
 328        char *ep;
 329        size_t len;
 330
 331        strbuf_release(sb);
 332        if (!io->input.len)
 333                return -1;
 334        ep = memchr(io->input.buf, '\n', io->input.len);
 335        if (!ep)
 336                ep = io->input.buf + io->input.len;
 337        else if (*ep == '\n')
 338                ep++;
 339        len = ep - io->input.buf;
 340        strbuf_add(sb, io->input.buf, len);
 341        strbuf_remove(&io->input, 0, len);
 342        return 0;
 343}
 344
 345static int handle_cache(const char *path, unsigned char *sha1, const char *output)
 346{
 347        mmfile_t mmfile[3] = {{NULL}};
 348        mmbuffer_t result = {NULL, 0};
 349        const struct cache_entry *ce;
 350        int pos, len, i, hunk_no;
 351        struct rerere_io_mem io;
 352        int marker_size = ll_merge_marker_size(path);
 353
 354        /*
 355         * Reproduce the conflicted merge in-core
 356         */
 357        len = strlen(path);
 358        pos = cache_name_pos(path, len);
 359        if (0 <= pos)
 360                return -1;
 361        pos = -pos - 1;
 362
 363        while (pos < active_nr) {
 364                enum object_type type;
 365                unsigned long size;
 366
 367                ce = active_cache[pos++];
 368                if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
 369                        break;
 370                i = ce_stage(ce) - 1;
 371                if (!mmfile[i].ptr) {
 372                        mmfile[i].ptr = read_sha1_file(ce->sha1, &type, &size);
 373                        mmfile[i].size = size;
 374                }
 375        }
 376        for (i = 0; i < 3; i++)
 377                if (!mmfile[i].ptr && !mmfile[i].size)
 378                        mmfile[i].ptr = xstrdup("");
 379
 380        /*
 381         * NEEDSWORK: handle conflicts from merges with
 382         * merge.renormalize set, too
 383         */
 384        ll_merge(&result, path, &mmfile[0], NULL,
 385                 &mmfile[1], "ours",
 386                 &mmfile[2], "theirs", NULL);
 387        for (i = 0; i < 3; i++)
 388                free(mmfile[i].ptr);
 389
 390        memset(&io, 0, sizeof(io));
 391        io.io.getline = rerere_mem_getline;
 392        if (output)
 393                io.io.output = fopen(output, "w");
 394        else
 395                io.io.output = NULL;
 396        strbuf_init(&io.input, 0);
 397        strbuf_attach(&io.input, result.ptr, result.size, result.size);
 398
 399        hunk_no = handle_path(sha1, (struct rerere_io *)&io, marker_size);
 400        strbuf_release(&io.input);
 401        if (io.io.output)
 402                fclose(io.io.output);
 403        return hunk_no;
 404}
 405
 406static int check_one_conflict(int i, int *type)
 407{
 408        const struct cache_entry *e = active_cache[i];
 409
 410        if (!ce_stage(e)) {
 411                *type = RESOLVED;
 412                return i + 1;
 413        }
 414
 415        *type = PUNTED;
 416        while (ce_stage(active_cache[i]) == 1)
 417                i++;
 418
 419        /* Only handle regular files with both stages #2 and #3 */
 420        if (i + 1 < active_nr) {
 421                const struct cache_entry *e2 = active_cache[i];
 422                const struct cache_entry *e3 = active_cache[i + 1];
 423                if (ce_stage(e2) == 2 &&
 424                    ce_stage(e3) == 3 &&
 425                    ce_same_name(e, e3) &&
 426                    S_ISREG(e2->ce_mode) &&
 427                    S_ISREG(e3->ce_mode))
 428                        *type = THREE_STAGED;
 429        }
 430
 431        /* Skip the entries with the same name */
 432        while (i < active_nr && ce_same_name(e, active_cache[i]))
 433                i++;
 434        return i;
 435}
 436
 437static int find_conflict(struct string_list *conflict)
 438{
 439        int i;
 440        if (read_cache() < 0)
 441                return error("Could not read index");
 442
 443        for (i = 0; i < active_nr;) {
 444                int conflict_type;
 445                const struct cache_entry *e = active_cache[i];
 446                i = check_one_conflict(i, &conflict_type);
 447                if (conflict_type == THREE_STAGED)
 448                        string_list_insert(conflict, (const char *)e->name);
 449        }
 450        return 0;
 451}
 452
 453int rerere_remaining(struct string_list *merge_rr)
 454{
 455        int i;
 456        if (read_cache() < 0)
 457                return error("Could not read index");
 458
 459        for (i = 0; i < active_nr;) {
 460                int conflict_type;
 461                const struct cache_entry *e = active_cache[i];
 462                i = check_one_conflict(i, &conflict_type);
 463                if (conflict_type == PUNTED)
 464                        string_list_insert(merge_rr, (const char *)e->name);
 465                else if (conflict_type == RESOLVED) {
 466                        struct string_list_item *it;
 467                        it = string_list_lookup(merge_rr, (const char *)e->name);
 468                        if (it != NULL) {
 469                                free(it->util);
 470                                it->util = RERERE_RESOLVED;
 471                        }
 472                }
 473        }
 474        return 0;
 475}
 476
 477static int merge(const char *name, const char *path)
 478{
 479        int ret;
 480        mmfile_t cur = {NULL, 0}, base = {NULL, 0}, other = {NULL, 0};
 481        mmbuffer_t result = {NULL, 0};
 482
 483        if (handle_file(path, NULL, rerere_path(name, "thisimage")) < 0)
 484                return 1;
 485
 486        if (read_mmfile(&cur, rerere_path(name, "thisimage")) ||
 487                        read_mmfile(&base, rerere_path(name, "preimage")) ||
 488                        read_mmfile(&other, rerere_path(name, "postimage"))) {
 489                ret = 1;
 490                goto out;
 491        }
 492        ret = ll_merge(&result, path, &base, NULL, &cur, "", &other, "", NULL);
 493        if (!ret) {
 494                FILE *f;
 495
 496                if (utime(rerere_path(name, "postimage"), NULL) < 0)
 497                        warning("failed utime() on %s: %s",
 498                                        rerere_path(name, "postimage"),
 499                                        strerror(errno));
 500                f = fopen(path, "w");
 501                if (!f)
 502                        return error("Could not open %s: %s", path,
 503                                     strerror(errno));
 504                if (fwrite(result.ptr, result.size, 1, f) != 1)
 505                        error("Could not write %s: %s", path, strerror(errno));
 506                if (fclose(f))
 507                        return error("Writing %s failed: %s", path,
 508                                     strerror(errno));
 509        }
 510
 511out:
 512        free(cur.ptr);
 513        free(base.ptr);
 514        free(other.ptr);
 515        free(result.ptr);
 516
 517        return ret;
 518}
 519
 520static struct lock_file index_lock;
 521
 522static void update_paths(struct string_list *update)
 523{
 524        int i;
 525
 526        hold_locked_index(&index_lock, 1);
 527
 528        for (i = 0; i < update->nr; i++) {
 529                struct string_list_item *item = &update->items[i];
 530                if (add_file_to_cache(item->string, 0))
 531                        exit(128);
 532                fprintf(stderr, "Staged '%s' using previous resolution.\n",
 533                        item->string);
 534        }
 535
 536        if (active_cache_changed) {
 537                if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
 538                        die("Unable to write new index file");
 539        } else
 540                rollback_lock_file(&index_lock);
 541}
 542
 543static int do_plain_rerere(struct string_list *rr, int fd)
 544{
 545        struct string_list conflict = STRING_LIST_INIT_DUP;
 546        struct string_list update = STRING_LIST_INIT_DUP;
 547        int i;
 548
 549        find_conflict(&conflict);
 550
 551        /*
 552         * MERGE_RR records paths with conflicts immediately after merge
 553         * failed.  Some of the conflicted paths might have been hand resolved
 554         * in the working tree since then, but the initial run would catch all
 555         * and register their preimages.
 556         */
 557
 558        for (i = 0; i < conflict.nr; i++) {
 559                const char *path = conflict.items[i].string;
 560                if (!string_list_has_string(rr, path)) {
 561                        unsigned char sha1[20];
 562                        char *hex;
 563                        int ret;
 564                        ret = handle_file(path, sha1, NULL);
 565                        if (ret < 1)
 566                                continue;
 567                        hex = xstrdup(sha1_to_hex(sha1));
 568                        string_list_insert(rr, path)->util = hex;
 569                        if (mkdir_in_gitdir(git_path("rr-cache/%s", hex)))
 570                                continue;
 571                        handle_file(path, NULL, rerere_path(hex, "preimage"));
 572                        fprintf(stderr, "Recorded preimage for '%s'\n", path);
 573                }
 574        }
 575
 576        /*
 577         * Now some of the paths that had conflicts earlier might have been
 578         * hand resolved.  Others may be similar to a conflict already that
 579         * was resolved before.
 580         */
 581
 582        for (i = 0; i < rr->nr; i++) {
 583                int ret;
 584                const char *path = rr->items[i].string;
 585                const char *name = (const char *)rr->items[i].util;
 586
 587                if (has_rerere_resolution(name)) {
 588                        if (merge(name, path))
 589                                continue;
 590
 591                        if (rerere_autoupdate)
 592                                string_list_insert(&update, path);
 593                        else
 594                                fprintf(stderr,
 595                                        "Resolved '%s' using previous resolution.\n",
 596                                        path);
 597                        goto mark_resolved;
 598                }
 599
 600                /* Let's see if we have resolved it. */
 601                ret = handle_file(path, NULL, NULL);
 602                if (ret)
 603                        continue;
 604
 605                fprintf(stderr, "Recorded resolution for '%s'.\n", path);
 606                copy_file(rerere_path(name, "postimage"), path, 0666);
 607        mark_resolved:
 608                free(rr->items[i].util);
 609                rr->items[i].util = NULL;
 610        }
 611
 612        if (update.nr)
 613                update_paths(&update);
 614
 615        return write_rr(rr, fd);
 616}
 617
 618static void git_rerere_config(void)
 619{
 620        git_config_get_bool("rerere.enabled", &rerere_enabled);
 621        git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
 622        git_config(git_default_config, NULL);
 623}
 624
 625static int is_rerere_enabled(void)
 626{
 627        const char *rr_cache;
 628        int rr_cache_exists;
 629
 630        if (!rerere_enabled)
 631                return 0;
 632
 633        rr_cache = git_path("rr-cache");
 634        rr_cache_exists = is_directory(rr_cache);
 635        if (rerere_enabled < 0)
 636                return rr_cache_exists;
 637
 638        if (!rr_cache_exists && mkdir_in_gitdir(rr_cache))
 639                die("Could not create directory %s", rr_cache);
 640        return 1;
 641}
 642
 643int setup_rerere(struct string_list *merge_rr, int flags)
 644{
 645        int fd;
 646
 647        git_rerere_config();
 648        if (!is_rerere_enabled())
 649                return -1;
 650
 651        if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
 652                rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
 653        merge_rr_path = git_pathdup("MERGE_RR");
 654        fd = hold_lock_file_for_update(&write_lock, merge_rr_path,
 655                                       LOCK_DIE_ON_ERROR);
 656        read_rr(merge_rr);
 657        return fd;
 658}
 659
 660int rerere(int flags)
 661{
 662        struct string_list merge_rr = STRING_LIST_INIT_DUP;
 663        int fd;
 664
 665        fd = setup_rerere(&merge_rr, flags);
 666        if (fd < 0)
 667                return 0;
 668        return do_plain_rerere(&merge_rr, fd);
 669}
 670
 671static int rerere_forget_one_path(const char *path, struct string_list *rr)
 672{
 673        const char *filename;
 674        char *hex;
 675        unsigned char sha1[20];
 676        int ret;
 677        struct string_list_item *item;
 678
 679        ret = handle_cache(path, sha1, NULL);
 680        if (ret < 1)
 681                return error("Could not parse conflict hunks in '%s'", path);
 682        hex = xstrdup(sha1_to_hex(sha1));
 683        filename = rerere_path(hex, "postimage");
 684        if (unlink(filename))
 685                return (errno == ENOENT
 686                        ? error("no remembered resolution for %s", path)
 687                        : error("cannot unlink %s: %s", filename, strerror(errno)));
 688
 689        handle_cache(path, sha1, rerere_path(hex, "preimage"));
 690        fprintf(stderr, "Updated preimage for '%s'\n", path);
 691
 692        item = string_list_insert(rr, path);
 693        free(item->util);
 694        item->util = hex;
 695        fprintf(stderr, "Forgot resolution for %s\n", path);
 696        return 0;
 697}
 698
 699int rerere_forget(struct pathspec *pathspec)
 700{
 701        int i, fd;
 702        struct string_list conflict = STRING_LIST_INIT_DUP;
 703        struct string_list merge_rr = STRING_LIST_INIT_DUP;
 704
 705        if (read_cache() < 0)
 706                return error("Could not read index");
 707
 708        fd = setup_rerere(&merge_rr, RERERE_NOAUTOUPDATE);
 709
 710        unmerge_cache(pathspec);
 711        find_conflict(&conflict);
 712        for (i = 0; i < conflict.nr; i++) {
 713                struct string_list_item *it = &conflict.items[i];
 714                if (!match_pathspec(pathspec, it->string,
 715                                    strlen(it->string), 0, NULL, 0))
 716                        continue;
 717                rerere_forget_one_path(it->string, &merge_rr);
 718        }
 719        return write_rr(&merge_rr, fd);
 720}
 721
 722static time_t rerere_created_at(const char *name)
 723{
 724        struct stat st;
 725        return stat(rerere_path(name, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
 726}
 727
 728static time_t rerere_last_used_at(const char *name)
 729{
 730        struct stat st;
 731        return stat(rerere_path(name, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
 732}
 733
 734static void unlink_rr_item(const char *name)
 735{
 736        unlink(rerere_path(name, "thisimage"));
 737        unlink(rerere_path(name, "preimage"));
 738        unlink(rerere_path(name, "postimage"));
 739        rmdir(git_path("rr-cache/%s", name));
 740}
 741
 742void rerere_gc(struct string_list *rr)
 743{
 744        struct string_list to_remove = STRING_LIST_INIT_DUP;
 745        DIR *dir;
 746        struct dirent *e;
 747        int i, cutoff;
 748        time_t now = time(NULL), then;
 749        int cutoff_noresolve = 15;
 750        int cutoff_resolve = 60;
 751
 752        git_config_get_int("gc.rerereresolved", &cutoff_resolve);
 753        git_config_get_int("gc.rerereunresolved", &cutoff_noresolve);
 754        git_config(git_default_config, NULL);
 755        dir = opendir(git_path("rr-cache"));
 756        if (!dir)
 757                die_errno("unable to open rr-cache directory");
 758        while ((e = readdir(dir))) {
 759                if (is_dot_or_dotdot(e->d_name))
 760                        continue;
 761
 762                then = rerere_last_used_at(e->d_name);
 763                if (then) {
 764                        cutoff = cutoff_resolve;
 765                } else {
 766                        then = rerere_created_at(e->d_name);
 767                        if (!then)
 768                                continue;
 769                        cutoff = cutoff_noresolve;
 770                }
 771                if (then < now - cutoff * 86400)
 772                        string_list_append(&to_remove, e->d_name);
 773        }
 774        closedir(dir);
 775        for (i = 0; i < to_remove.nr; i++)
 776                unlink_rr_item(to_remove.items[i].string);
 777        string_list_clear(&to_remove, 0);
 778}
 779
 780void rerere_clear(struct string_list *merge_rr)
 781{
 782        int i;
 783
 784        for (i = 0; i < merge_rr->nr; i++) {
 785                const char *name = (const char *)merge_rr->items[i].util;
 786                if (!has_rerere_resolution(name))
 787                        unlink_rr_item(name);
 788        }
 789        unlink_or_warn(git_path("MERGE_RR"));
 790}