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