addc5c73df0fd909d6e8e3aa799b73028819f0b7
   1#include "builtin.h"
   2#include "cache.h"
   3#include "path-list.h"
   4#include "xdiff/xdiff.h"
   5#include "xdiff-interface.h"
   6
   7#include <time.h>
   8
   9static const char git_rerere_usage[] =
  10"git-rerere [clear | status | diff | gc]";
  11
  12/* these values are days */
  13static int cutoff_noresolve = 15;
  14static int cutoff_resolve = 60;
  15
  16/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
  17static int rerere_enabled = -1;
  18
  19static char *merge_rr_path;
  20
  21static const char *rr_path(const char *name, const char *file)
  22{
  23        return git_path("rr-cache/%s/%s", name, file);
  24}
  25
  26static time_t rerere_created_at(const char *name)
  27{
  28        struct stat st;
  29        return stat(rr_path(name, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
  30}
  31
  32static int has_resolution(const char *name)
  33{
  34        struct stat st;
  35        return !stat(rr_path(name, "postimage"), &st);
  36}
  37
  38static void read_rr(struct path_list *rr)
  39{
  40        unsigned char sha1[20];
  41        char buf[PATH_MAX];
  42        FILE *in = fopen(merge_rr_path, "r");
  43        if (!in)
  44                return;
  45        while (fread(buf, 40, 1, in) == 1) {
  46                int i;
  47                char *name;
  48                if (get_sha1_hex(buf, sha1))
  49                        die("corrupt MERGE_RR");
  50                buf[40] = '\0';
  51                name = xstrdup(buf);
  52                if (fgetc(in) != '\t')
  53                        die("corrupt MERGE_RR");
  54                for (i = 0; i < sizeof(buf) && (buf[i] = fgetc(in)); i++)
  55                        ; /* do nothing */
  56                if (i == sizeof(buf))
  57                        die("filename too long");
  58                path_list_insert(buf, rr)->util = name;
  59        }
  60        fclose(in);
  61}
  62
  63static struct lock_file write_lock;
  64
  65static int write_rr(struct path_list *rr, int out_fd)
  66{
  67        int i;
  68        for (i = 0; i < rr->nr; i++) {
  69                const char *path = rr->items[i].path;
  70                int length = strlen(path) + 1;
  71                if (write_in_full(out_fd, rr->items[i].util, 40) != 40 ||
  72                    write_in_full(out_fd, "\t", 1) != 1 ||
  73                    write_in_full(out_fd, path, length) != length)
  74                        die("unable to write rerere record");
  75        }
  76        if (commit_lock_file(&write_lock) != 0)
  77                die("unable to write rerere record");
  78        return 0;
  79}
  80
  81static int handle_file(const char *path,
  82         unsigned char *sha1, const char *output)
  83{
  84        SHA_CTX ctx;
  85        char buf[1024];
  86        int hunk = 0, hunk_no = 0;
  87        struct strbuf one, two;
  88        FILE *f = fopen(path, "r");
  89        FILE *out = NULL;
  90
  91        if (!f)
  92                return error("Could not open %s", path);
  93
  94        if (output) {
  95                out = fopen(output, "w");
  96                if (!out) {
  97                        fclose(f);
  98                        return error("Could not write %s", output);
  99                }
 100        }
 101
 102        if (sha1)
 103                SHA1_Init(&ctx);
 104
 105        strbuf_init(&one, 0);
 106        strbuf_init(&two,  0);
 107        while (fgets(buf, sizeof(buf), f)) {
 108                if (!prefixcmp(buf, "<<<<<<< "))
 109                        hunk = 1;
 110                else if (!prefixcmp(buf, "======="))
 111                        hunk = 2;
 112                else if (!prefixcmp(buf, ">>>>>>> ")) {
 113                        if (strbuf_cmp(&one, &two) > 0)
 114                                strbuf_swap(&one, &two);
 115                        hunk_no++;
 116                        hunk = 0;
 117                        if (out) {
 118                                fputs("<<<<<<<\n", out);
 119                                fwrite(one.buf, one.len, 1, out);
 120                                fputs("=======\n", out);
 121                                fwrite(two.buf, two.len, 1, out);
 122                                fputs(">>>>>>>\n", out);
 123                        }
 124                        if (sha1) {
 125                                SHA1_Update(&ctx, one.buf ? one.buf : "",
 126                                            one.len + 1);
 127                                SHA1_Update(&ctx, two.buf ? two.buf : "",
 128                                            two.len + 1);
 129                        }
 130                        strbuf_reset(&one);
 131                        strbuf_reset(&two);
 132                } else if (hunk == 1)
 133                        strbuf_addstr(&one, buf);
 134                else if (hunk == 2)
 135                        strbuf_addstr(&two, buf);
 136                else if (out)
 137                        fputs(buf, out);
 138        }
 139        strbuf_release(&one);
 140        strbuf_release(&two);
 141
 142        fclose(f);
 143        if (out)
 144                fclose(out);
 145        if (sha1)
 146                SHA1_Final(sha1, &ctx);
 147        if (hunk) {
 148                if (output)
 149                        unlink(output);
 150                return error("Could not parse conflict hunks in %s", path);
 151        }
 152        return hunk_no;
 153}
 154
 155static int find_conflict(struct path_list *conflict)
 156{
 157        int i;
 158        if (read_cache() < 0)
 159                return error("Could not read index");
 160        for (i = 0; i+1 < active_nr; i++) {
 161                struct cache_entry *e2 = active_cache[i];
 162                struct cache_entry *e3 = active_cache[i+1];
 163                if (ce_stage(e2) == 2 &&
 164                    ce_stage(e3) == 3 &&
 165                    ce_same_name(e2, e3) &&
 166                    S_ISREG(e2->ce_mode) &&
 167                    S_ISREG(e3->ce_mode)) {
 168                        path_list_insert((const char *)e2->name, conflict);
 169                        i++; /* skip over both #2 and #3 */
 170                }
 171        }
 172        return 0;
 173}
 174
 175static int merge(const char *name, const char *path)
 176{
 177        int ret;
 178        mmfile_t cur, base, other;
 179        mmbuffer_t result = {NULL, 0};
 180        xpparam_t xpp = {XDF_NEED_MINIMAL};
 181
 182        if (handle_file(path, NULL, rr_path(name, "thisimage")) < 0)
 183                return 1;
 184
 185        if (read_mmfile(&cur, rr_path(name, "thisimage")) ||
 186                        read_mmfile(&base, rr_path(name, "preimage")) ||
 187                        read_mmfile(&other, rr_path(name, "postimage")))
 188                return 1;
 189        ret = xdl_merge(&base, &cur, "", &other, "",
 190                        &xpp, XDL_MERGE_ZEALOUS, &result);
 191        if (!ret) {
 192                FILE *f = fopen(path, "w");
 193                if (!f)
 194                        return error("Could not write to %s", path);
 195                fwrite(result.ptr, result.size, 1, f);
 196                fclose(f);
 197        }
 198
 199        free(cur.ptr);
 200        free(base.ptr);
 201        free(other.ptr);
 202        free(result.ptr);
 203
 204        return ret;
 205}
 206
 207static void unlink_rr_item(const char *name)
 208{
 209        unlink(rr_path(name, "thisimage"));
 210        unlink(rr_path(name, "preimage"));
 211        unlink(rr_path(name, "postimage"));
 212        rmdir(git_path("rr-cache/%s", name));
 213}
 214
 215static void garbage_collect(struct path_list *rr)
 216{
 217        struct path_list to_remove = { NULL, 0, 0, 1 };
 218        DIR *dir;
 219        struct dirent *e;
 220        int i, cutoff;
 221        time_t now = time(NULL), then;
 222
 223        dir = opendir(git_path("rr-cache"));
 224        while ((e = readdir(dir))) {
 225                const char *name = e->d_name;
 226                if (name[0] == '.' &&
 227                    (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')))
 228                        continue;
 229                then = rerere_created_at(name);
 230                if (!then)
 231                        continue;
 232                cutoff = (has_resolution(name)
 233                          ? cutoff_resolve : cutoff_noresolve);
 234                if (then < now - cutoff * 86400)
 235                        path_list_append(name, &to_remove);
 236        }
 237        for (i = 0; i < to_remove.nr; i++)
 238                unlink_rr_item(to_remove.items[i].path);
 239        path_list_clear(&to_remove, 0);
 240}
 241
 242static int outf(void *dummy, mmbuffer_t *ptr, int nbuf)
 243{
 244        int i;
 245        for (i = 0; i < nbuf; i++)
 246                if (write_in_full(1, ptr[i].ptr, ptr[i].size) != ptr[i].size)
 247                        return -1;
 248        return 0;
 249}
 250
 251static int diff_two(const char *file1, const char *label1,
 252                const char *file2, const char *label2)
 253{
 254        xpparam_t xpp;
 255        xdemitconf_t xecfg;
 256        xdemitcb_t ecb;
 257        mmfile_t minus, plus;
 258
 259        if (read_mmfile(&minus, file1) || read_mmfile(&plus, file2))
 260                return 1;
 261
 262        printf("--- a/%s\n+++ b/%s\n", label1, label2);
 263        fflush(stdout);
 264        xpp.flags = XDF_NEED_MINIMAL;
 265        memset(&xecfg, 0, sizeof(xecfg));
 266        xecfg.ctxlen = 3;
 267        ecb.outf = outf;
 268        xdi_diff(&minus, &plus, &xpp, &xecfg, &ecb);
 269
 270        free(minus.ptr);
 271        free(plus.ptr);
 272        return 0;
 273}
 274
 275static int do_plain_rerere(struct path_list *rr, int fd)
 276{
 277        struct path_list conflict = { NULL, 0, 0, 1 };
 278        int i;
 279
 280        find_conflict(&conflict);
 281
 282        /*
 283         * MERGE_RR records paths with conflicts immediately after merge
 284         * failed.  Some of the conflicted paths might have been hand resolved
 285         * in the working tree since then, but the initial run would catch all
 286         * and register their preimages.
 287         */
 288
 289        for (i = 0; i < conflict.nr; i++) {
 290                const char *path = conflict.items[i].path;
 291                if (!path_list_has_path(rr, path)) {
 292                        unsigned char sha1[20];
 293                        char *hex;
 294                        int ret;
 295                        ret = handle_file(path, sha1, NULL);
 296                        if (ret < 1)
 297                                continue;
 298                        hex = xstrdup(sha1_to_hex(sha1));
 299                        path_list_insert(path, rr)->util = hex;
 300                        if (mkdir(git_path("rr-cache/%s", hex), 0755))
 301                                continue;;
 302                        handle_file(path, NULL, rr_path(hex, "preimage"));
 303                        fprintf(stderr, "Recorded preimage for '%s'\n", path);
 304                }
 305        }
 306
 307        /*
 308         * Now some of the paths that had conflicts earlier might have been
 309         * hand resolved.  Others may be similar to a conflict already that
 310         * was resolved before.
 311         */
 312
 313        for (i = 0; i < rr->nr; i++) {
 314                int ret;
 315                const char *path = rr->items[i].path;
 316                const char *name = (const char *)rr->items[i].util;
 317
 318                if (has_resolution(name)) {
 319                        if (!merge(name, path)) {
 320                                fprintf(stderr, "Resolved '%s' using "
 321                                                "previous resolution.\n", path);
 322                                goto tail_optimization;
 323                        }
 324                }
 325
 326                /* Let's see if we have resolved it. */
 327                ret = handle_file(path, NULL, NULL);
 328                if (ret)
 329                        continue;
 330
 331                fprintf(stderr, "Recorded resolution for '%s'.\n", path);
 332                copy_file(rr_path(name, "postimage"), path, 0666);
 333tail_optimization:
 334                if (i < rr->nr - 1)
 335                        memmove(rr->items + i,
 336                                rr->items + i + 1,
 337                                sizeof(rr->items[0]) * (rr->nr - i - 1));
 338                rr->nr--;
 339                i--;
 340        }
 341
 342        return write_rr(rr, fd);
 343}
 344
 345static int git_rerere_config(const char *var, const char *value, void *cb)
 346{
 347        if (!strcmp(var, "gc.rerereresolved"))
 348                cutoff_resolve = git_config_int(var, value);
 349        else if (!strcmp(var, "gc.rerereunresolved"))
 350                cutoff_noresolve = git_config_int(var, value);
 351        else if (!strcmp(var, "rerere.enabled"))
 352                rerere_enabled = git_config_bool(var, value);
 353        else
 354                return git_default_config(var, value, cb);
 355        return 0;
 356}
 357
 358static int is_rerere_enabled(void)
 359{
 360        struct stat st;
 361        const char *rr_cache;
 362        int rr_cache_exists;
 363
 364        if (!rerere_enabled)
 365                return 0;
 366
 367        rr_cache = git_path("rr-cache");
 368        rr_cache_exists = !stat(rr_cache, &st) && S_ISDIR(st.st_mode);
 369        if (rerere_enabled < 0)
 370                return rr_cache_exists;
 371
 372        if (!rr_cache_exists &&
 373            (mkdir(rr_cache, 0777) || adjust_shared_perm(rr_cache)))
 374                die("Could not create directory %s", rr_cache);
 375        return 1;
 376}
 377
 378static int setup_rerere(struct path_list *merge_rr)
 379{
 380        int fd;
 381
 382        git_config(git_rerere_config, NULL);
 383        if (!is_rerere_enabled())
 384                return -1;
 385
 386        merge_rr_path = xstrdup(git_path("rr-cache/MERGE_RR"));
 387        fd = hold_lock_file_for_update(&write_lock, merge_rr_path, 1);
 388        read_rr(merge_rr);
 389        return fd;
 390}
 391
 392int rerere(void)
 393{
 394        struct path_list merge_rr = { NULL, 0, 0, 1 };
 395        int fd;
 396
 397        fd = setup_rerere(&merge_rr);
 398        if (fd < 0)
 399                return 0;
 400        return do_plain_rerere(&merge_rr, fd);
 401}
 402
 403int cmd_rerere(int argc, const char **argv, const char *prefix)
 404{
 405        struct path_list merge_rr = { NULL, 0, 0, 1 };
 406        int i, fd;
 407
 408        fd = setup_rerere(&merge_rr);
 409        if (fd < 0)
 410                return 0;
 411
 412        if (argc < 2)
 413                return do_plain_rerere(&merge_rr, fd);
 414        else if (!strcmp(argv[1], "clear")) {
 415                for (i = 0; i < merge_rr.nr; i++) {
 416                        const char *name = (const char *)merge_rr.items[i].util;
 417                        if (!has_resolution(name))
 418                                unlink_rr_item(name);
 419                }
 420                unlink(merge_rr_path);
 421        } else if (!strcmp(argv[1], "gc"))
 422                garbage_collect(&merge_rr);
 423        else if (!strcmp(argv[1], "status"))
 424                for (i = 0; i < merge_rr.nr; i++)
 425                        printf("%s\n", merge_rr.items[i].path);
 426        else if (!strcmp(argv[1], "diff"))
 427                for (i = 0; i < merge_rr.nr; i++) {
 428                        const char *path = merge_rr.items[i].path;
 429                        const char *name = (const char *)merge_rr.items[i].util;
 430                        diff_two(rr_path(name, "preimage"), path, path, path);
 431                }
 432        else
 433                usage(git_rerere_usage);
 434
 435        path_list_clear(&merge_rr, 1);
 436        return 0;
 437}