read-cache*.h: move declarations for read-cache.c functions from cache.h
[alt-git.git] / rerere.c
blob3bc9aedc286796914ebd2a83ed1cc52fa4d0ec10
1 #include "cache.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "copy.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "lockfile.h"
9 #include "string-list.h"
10 #include "read-cache-ll.h"
11 #include "rerere.h"
12 #include "xdiff-interface.h"
13 #include "dir.h"
14 #include "resolve-undo.h"
15 #include "ll-merge.h"
16 #include "attr.h"
17 #include "pathspec.h"
18 #include "object-file.h"
19 #include "object-store.h"
20 #include "hash-lookup.h"
21 #include "strmap.h"
22 #include "wrapper.h"
24 #define RESOLVED 0
25 #define PUNTED 1
26 #define THREE_STAGED 2
27 void *RERERE_RESOLVED = &RERERE_RESOLVED;
29 /* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
30 static int rerere_enabled = -1;
32 /* automatically update cleanly resolved paths to the index */
33 static int rerere_autoupdate;
35 #define RR_HAS_POSTIMAGE 1
36 #define RR_HAS_PREIMAGE 2
37 struct rerere_dir {
38 int status_alloc, status_nr;
39 unsigned char *status;
40 char name[FLEX_ARRAY];
43 static struct strmap rerere_dirs = STRMAP_INIT;
45 static void free_rerere_dirs(void)
47 struct hashmap_iter iter;
48 struct strmap_entry *ent;
50 strmap_for_each_entry(&rerere_dirs, &iter, ent) {
51 struct rerere_dir *rr_dir = ent->value;
52 free(rr_dir->status);
53 free(rr_dir);
55 strmap_clear(&rerere_dirs, 0);
58 static void free_rerere_id(struct string_list_item *item)
60 free(item->util);
63 static const char *rerere_id_hex(const struct rerere_id *id)
65 return id->collection->name;
68 static void fit_variant(struct rerere_dir *rr_dir, int variant)
70 variant++;
71 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
72 if (rr_dir->status_nr < variant) {
73 memset(rr_dir->status + rr_dir->status_nr,
74 '\0', variant - rr_dir->status_nr);
75 rr_dir->status_nr = variant;
79 static void assign_variant(struct rerere_id *id)
81 int variant;
82 struct rerere_dir *rr_dir = id->collection;
84 variant = id->variant;
85 if (variant < 0) {
86 for (variant = 0; variant < rr_dir->status_nr; variant++)
87 if (!rr_dir->status[variant])
88 break;
90 fit_variant(rr_dir, variant);
91 id->variant = variant;
94 const char *rerere_path(const struct rerere_id *id, const char *file)
96 if (!file)
97 return git_path("rr-cache/%s", rerere_id_hex(id));
99 if (id->variant <= 0)
100 return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
102 return git_path("rr-cache/%s/%s.%d",
103 rerere_id_hex(id), file, id->variant);
106 static int is_rr_file(const char *name, const char *filename, int *variant)
108 const char *suffix;
109 char *ep;
111 if (!strcmp(name, filename)) {
112 *variant = 0;
113 return 1;
115 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
116 return 0;
118 errno = 0;
119 *variant = strtol(suffix + 1, &ep, 10);
120 if (errno || *ep)
121 return 0;
122 return 1;
125 static void scan_rerere_dir(struct rerere_dir *rr_dir)
127 struct dirent *de;
128 DIR *dir = opendir(git_path("rr-cache/%s", rr_dir->name));
130 if (!dir)
131 return;
132 while ((de = readdir(dir)) != NULL) {
133 int variant;
135 if (is_rr_file(de->d_name, "postimage", &variant)) {
136 fit_variant(rr_dir, variant);
137 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
138 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
139 fit_variant(rr_dir, variant);
140 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
143 closedir(dir);
146 static struct rerere_dir *find_rerere_dir(const char *hex)
148 struct rerere_dir *rr_dir;
150 rr_dir = strmap_get(&rerere_dirs, hex);
151 if (!rr_dir) {
152 FLEX_ALLOC_STR(rr_dir, name, hex);
153 rr_dir->status = NULL;
154 rr_dir->status_nr = 0;
155 rr_dir->status_alloc = 0;
156 strmap_put(&rerere_dirs, hex, rr_dir);
158 scan_rerere_dir(rr_dir);
160 return rr_dir;
163 static int has_rerere_resolution(const struct rerere_id *id)
165 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
166 int variant = id->variant;
168 if (variant < 0)
169 return 0;
170 return ((id->collection->status[variant] & both) == both);
173 static struct rerere_id *new_rerere_id_hex(char *hex)
175 struct rerere_id *id = xmalloc(sizeof(*id));
176 id->collection = find_rerere_dir(hex);
177 id->variant = -1; /* not known yet */
178 return id;
181 static struct rerere_id *new_rerere_id(unsigned char *hash)
183 return new_rerere_id_hex(hash_to_hex(hash));
187 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
188 * "conflict ID", a HT and pathname, terminated with a NUL, and is
189 * used to keep track of the set of paths that "rerere" may need to
190 * work on (i.e. what is left by the previous invocation of "git
191 * rerere" during the current conflict resolution session).
193 static void read_rr(struct repository *r, struct string_list *rr)
195 struct strbuf buf = STRBUF_INIT;
196 FILE *in = fopen_or_warn(git_path_merge_rr(r), "r");
198 if (!in)
199 return;
200 while (!strbuf_getwholeline(&buf, in, '\0')) {
201 char *path;
202 unsigned char hash[GIT_MAX_RAWSZ];
203 struct rerere_id *id;
204 int variant;
205 const unsigned hexsz = the_hash_algo->hexsz;
207 /* There has to be the hash, tab, path and then NUL */
208 if (buf.len < hexsz + 2 || get_sha1_hex(buf.buf, hash))
209 die(_("corrupt MERGE_RR"));
211 if (buf.buf[hexsz] != '.') {
212 variant = 0;
213 path = buf.buf + hexsz;
214 } else {
215 errno = 0;
216 variant = strtol(buf.buf + hexsz + 1, &path, 10);
217 if (errno)
218 die(_("corrupt MERGE_RR"));
220 if (*(path++) != '\t')
221 die(_("corrupt MERGE_RR"));
222 buf.buf[hexsz] = '\0';
223 id = new_rerere_id_hex(buf.buf);
224 id->variant = variant;
225 string_list_insert(rr, path)->util = id;
227 strbuf_release(&buf);
228 fclose(in);
231 static struct lock_file write_lock;
233 static int write_rr(struct string_list *rr, int out_fd)
235 int i;
236 for (i = 0; i < rr->nr; i++) {
237 struct strbuf buf = STRBUF_INIT;
238 struct rerere_id *id;
240 assert(rr->items[i].util != RERERE_RESOLVED);
242 id = rr->items[i].util;
243 if (!id)
244 continue;
245 assert(id->variant >= 0);
246 if (0 < id->variant)
247 strbuf_addf(&buf, "%s.%d\t%s%c",
248 rerere_id_hex(id), id->variant,
249 rr->items[i].string, 0);
250 else
251 strbuf_addf(&buf, "%s\t%s%c",
252 rerere_id_hex(id),
253 rr->items[i].string, 0);
255 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
256 die(_("unable to write rerere record"));
258 strbuf_release(&buf);
260 if (commit_lock_file(&write_lock) != 0)
261 die(_("unable to write rerere record"));
262 return 0;
266 * "rerere" interacts with conflicted file contents using this I/O
267 * abstraction. It reads a conflicted contents from one place via
268 * "getline()" method, and optionally can write it out after
269 * normalizing the conflicted hunks to the "output". Subclasses of
270 * rerere_io embed this structure at the beginning of their own
271 * rerere_io object.
273 struct rerere_io {
274 int (*getline)(struct strbuf *, struct rerere_io *);
275 FILE *output;
276 int wrerror;
277 /* some more stuff */
280 static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
282 if (!count || *err)
283 return;
284 if (fwrite(p, count, 1, fp) != 1)
285 *err = errno;
288 static inline void ferr_puts(const char *s, FILE *fp, int *err)
290 ferr_write(s, strlen(s), fp, err);
293 static void rerere_io_putstr(const char *str, struct rerere_io *io)
295 if (io->output)
296 ferr_puts(str, io->output, &io->wrerror);
299 static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
301 if (io->output)
302 ferr_write(mem, sz, io->output, &io->wrerror);
306 * Subclass of rerere_io that reads from an on-disk file
308 struct rerere_io_file {
309 struct rerere_io io;
310 FILE *input;
314 * ... and its getline() method implementation
316 static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
318 struct rerere_io_file *io = (struct rerere_io_file *)io_;
319 return strbuf_getwholeline(sb, io->input, '\n');
323 * Require the exact number of conflict marker letters, no more, no
324 * less, followed by SP or any whitespace
325 * (including LF).
327 static int is_cmarker(char *buf, int marker_char, int marker_size)
329 int want_sp;
332 * The beginning of our version and the end of their version
333 * always are labeled like "<<<<< ours" or ">>>>> theirs",
334 * hence we set want_sp for them. Note that the version from
335 * the common ancestor in diff3-style output is not always
336 * labelled (e.g. "||||| common" is often seen but "|||||"
337 * alone is also valid), so we do not set want_sp.
339 want_sp = (marker_char == '<') || (marker_char == '>');
341 while (marker_size--)
342 if (*buf++ != marker_char)
343 return 0;
344 if (want_sp && *buf != ' ')
345 return 0;
346 return isspace(*buf);
349 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
351 strbuf_addchars(buf, ch, size);
352 strbuf_addch(buf, '\n');
355 static int handle_conflict(struct strbuf *out, struct rerere_io *io,
356 int marker_size, git_hash_ctx *ctx)
358 enum {
359 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
360 } hunk = RR_SIDE_1;
361 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
362 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
363 int has_conflicts = -1;
365 while (!io->getline(&buf, io)) {
366 if (is_cmarker(buf.buf, '<', marker_size)) {
367 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
368 break;
369 if (hunk == RR_SIDE_1)
370 strbuf_addbuf(&one, &conflict);
371 else
372 strbuf_addbuf(&two, &conflict);
373 strbuf_release(&conflict);
374 } else if (is_cmarker(buf.buf, '|', marker_size)) {
375 if (hunk != RR_SIDE_1)
376 break;
377 hunk = RR_ORIGINAL;
378 } else if (is_cmarker(buf.buf, '=', marker_size)) {
379 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
380 break;
381 hunk = RR_SIDE_2;
382 } else if (is_cmarker(buf.buf, '>', marker_size)) {
383 if (hunk != RR_SIDE_2)
384 break;
385 if (strbuf_cmp(&one, &two) > 0)
386 strbuf_swap(&one, &two);
387 has_conflicts = 1;
388 rerere_strbuf_putconflict(out, '<', marker_size);
389 strbuf_addbuf(out, &one);
390 rerere_strbuf_putconflict(out, '=', marker_size);
391 strbuf_addbuf(out, &two);
392 rerere_strbuf_putconflict(out, '>', marker_size);
393 if (ctx) {
394 the_hash_algo->update_fn(ctx, one.buf ?
395 one.buf : "",
396 one.len + 1);
397 the_hash_algo->update_fn(ctx, two.buf ?
398 two.buf : "",
399 two.len + 1);
401 break;
402 } else if (hunk == RR_SIDE_1)
403 strbuf_addbuf(&one, &buf);
404 else if (hunk == RR_ORIGINAL)
405 ; /* discard */
406 else if (hunk == RR_SIDE_2)
407 strbuf_addbuf(&two, &buf);
409 strbuf_release(&one);
410 strbuf_release(&two);
411 strbuf_release(&buf);
413 return has_conflicts;
417 * Read contents a file with conflicts, normalize the conflicts
418 * by (1) discarding the common ancestor version in diff3-style,
419 * (2) reordering our side and their side so that whichever sorts
420 * alphabetically earlier comes before the other one, while
421 * computing the "conflict ID", which is just an SHA-1 hash of
422 * one side of the conflict, NUL, the other side of the conflict,
423 * and NUL concatenated together.
425 * Return 1 if conflict hunks are found, 0 if there are no conflict
426 * hunks and -1 if an error occurred.
428 static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
430 git_hash_ctx ctx;
431 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
432 int has_conflicts = 0;
433 if (hash)
434 the_hash_algo->init_fn(&ctx);
436 while (!io->getline(&buf, io)) {
437 if (is_cmarker(buf.buf, '<', marker_size)) {
438 has_conflicts = handle_conflict(&out, io, marker_size,
439 hash ? &ctx : NULL);
440 if (has_conflicts < 0)
441 break;
442 rerere_io_putmem(out.buf, out.len, io);
443 strbuf_reset(&out);
444 } else
445 rerere_io_putstr(buf.buf, io);
447 strbuf_release(&buf);
448 strbuf_release(&out);
450 if (hash)
451 the_hash_algo->final_fn(hash, &ctx);
453 return has_conflicts;
457 * Scan the path for conflicts, do the "handle_path()" thing above, and
458 * return the number of conflict hunks found.
460 static int handle_file(struct index_state *istate,
461 const char *path, unsigned char *hash, const char *output)
463 int has_conflicts = 0;
464 struct rerere_io_file io;
465 int marker_size = ll_merge_marker_size(istate, path);
467 memset(&io, 0, sizeof(io));
468 io.io.getline = rerere_file_getline;
469 io.input = fopen(path, "r");
470 io.io.wrerror = 0;
471 if (!io.input)
472 return error_errno(_("could not open '%s'"), path);
474 if (output) {
475 io.io.output = fopen(output, "w");
476 if (!io.io.output) {
477 error_errno(_("could not write '%s'"), output);
478 fclose(io.input);
479 return -1;
483 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
485 fclose(io.input);
486 if (io.io.wrerror)
487 error(_("there were errors while writing '%s' (%s)"),
488 path, strerror(io.io.wrerror));
489 if (io.io.output && fclose(io.io.output))
490 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
492 if (has_conflicts < 0) {
493 if (output)
494 unlink_or_warn(output);
495 return error(_("could not parse conflict hunks in '%s'"), path);
497 if (io.io.wrerror)
498 return -1;
499 return has_conflicts;
503 * Look at a cache entry at "i" and see if it is not conflicting,
504 * conflicting and we are willing to handle, or conflicting and
505 * we are unable to handle, and return the determination in *type.
506 * Return the cache index to be looked at next, by skipping the
507 * stages we have already looked at in this invocation of this
508 * function.
510 static int check_one_conflict(struct index_state *istate, int i, int *type)
512 const struct cache_entry *e = istate->cache[i];
514 if (!ce_stage(e)) {
515 *type = RESOLVED;
516 return i + 1;
519 *type = PUNTED;
520 while (i < istate->cache_nr && ce_stage(istate->cache[i]) == 1)
521 i++;
523 /* Only handle regular files with both stages #2 and #3 */
524 if (i + 1 < istate->cache_nr) {
525 const struct cache_entry *e2 = istate->cache[i];
526 const struct cache_entry *e3 = istate->cache[i + 1];
527 if (ce_stage(e2) == 2 &&
528 ce_stage(e3) == 3 &&
529 ce_same_name(e, e3) &&
530 S_ISREG(e2->ce_mode) &&
531 S_ISREG(e3->ce_mode))
532 *type = THREE_STAGED;
535 /* Skip the entries with the same name */
536 while (i < istate->cache_nr && ce_same_name(e, istate->cache[i]))
537 i++;
538 return i;
542 * Scan the index and find paths that have conflicts that rerere can
543 * handle, i.e. the ones that has both stages #2 and #3.
545 * NEEDSWORK: we do not record or replay a previous "resolve by
546 * deletion" for a delete-modify conflict, as that is inherently risky
547 * without knowing what modification is being discarded. The only
548 * safe case, i.e. both side doing the deletion and modification that
549 * are identical to the previous round, might want to be handled,
550 * though.
552 static int find_conflict(struct repository *r, struct string_list *conflict)
554 int i;
556 if (repo_read_index(r) < 0)
557 return error(_("index file corrupt"));
559 for (i = 0; i < r->index->cache_nr;) {
560 int conflict_type;
561 const struct cache_entry *e = r->index->cache[i];
562 i = check_one_conflict(r->index, i, &conflict_type);
563 if (conflict_type == THREE_STAGED)
564 string_list_insert(conflict, (const char *)e->name);
566 return 0;
570 * The merge_rr list is meant to hold outstanding conflicted paths
571 * that rerere could handle. Abuse the list by adding other types of
572 * entries to allow the caller to show "rerere remaining".
574 * - Conflicted paths that rerere does not handle are added
575 * - Conflicted paths that have been resolved are marked as such
576 * by storing RERERE_RESOLVED to .util field (where conflict ID
577 * is expected to be stored).
579 * Do *not* write MERGE_RR file out after calling this function.
581 * NEEDSWORK: we may want to fix the caller that implements "rerere
582 * remaining" to do this without abusing merge_rr.
584 int rerere_remaining(struct repository *r, struct string_list *merge_rr)
586 int i;
588 if (setup_rerere(r, merge_rr, RERERE_READONLY))
589 return 0;
590 if (repo_read_index(r) < 0)
591 return error(_("index file corrupt"));
593 for (i = 0; i < r->index->cache_nr;) {
594 int conflict_type;
595 const struct cache_entry *e = r->index->cache[i];
596 i = check_one_conflict(r->index, i, &conflict_type);
597 if (conflict_type == PUNTED)
598 string_list_insert(merge_rr, (const char *)e->name);
599 else if (conflict_type == RESOLVED) {
600 struct string_list_item *it;
601 it = string_list_lookup(merge_rr, (const char *)e->name);
602 if (it) {
603 free_rerere_id(it);
604 it->util = RERERE_RESOLVED;
608 return 0;
612 * Try using the given conflict resolution "ID" to see
613 * if that recorded conflict resolves cleanly what we
614 * got in the "cur".
616 static int try_merge(struct index_state *istate,
617 const struct rerere_id *id, const char *path,
618 mmfile_t *cur, mmbuffer_t *result)
620 enum ll_merge_result ret;
621 mmfile_t base = {NULL, 0}, other = {NULL, 0};
623 if (read_mmfile(&base, rerere_path(id, "preimage")) ||
624 read_mmfile(&other, rerere_path(id, "postimage"))) {
625 ret = LL_MERGE_CONFLICT;
626 } else {
628 * A three-way merge. Note that this honors user-customizable
629 * low-level merge driver settings.
631 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "",
632 istate, NULL);
635 free(base.ptr);
636 free(other.ptr);
638 return ret;
642 * Find the conflict identified by "id"; the change between its
643 * "preimage" (i.e. a previous contents with conflict markers) and its
644 * "postimage" (i.e. the corresponding contents with conflicts
645 * resolved) may apply cleanly to the contents stored in "path", i.e.
646 * the conflict this time around.
648 * Returns 0 for successful replay of recorded resolution, or non-zero
649 * for failure.
651 static int merge(struct index_state *istate, const struct rerere_id *id, const char *path)
653 FILE *f;
654 int ret;
655 mmfile_t cur = {NULL, 0};
656 mmbuffer_t result = {NULL, 0};
659 * Normalize the conflicts in path and write it out to
660 * "thisimage" temporary file.
662 if ((handle_file(istate, path, NULL, rerere_path(id, "thisimage")) < 0) ||
663 read_mmfile(&cur, rerere_path(id, "thisimage"))) {
664 ret = 1;
665 goto out;
668 ret = try_merge(istate, id, path, &cur, &result);
669 if (ret)
670 goto out;
673 * A successful replay of recorded resolution.
674 * Mark that "postimage" was used to help gc.
676 if (utime(rerere_path(id, "postimage"), NULL) < 0)
677 warning_errno(_("failed utime() on '%s'"),
678 rerere_path(id, "postimage"));
680 /* Update "path" with the resolution */
681 f = fopen(path, "w");
682 if (!f)
683 return error_errno(_("could not open '%s'"), path);
684 if (fwrite(result.ptr, result.size, 1, f) != 1)
685 error_errno(_("could not write '%s'"), path);
686 if (fclose(f))
687 return error_errno(_("writing '%s' failed"), path);
689 out:
690 free(cur.ptr);
691 free(result.ptr);
693 return ret;
696 static void update_paths(struct repository *r, struct string_list *update)
698 struct lock_file index_lock = LOCK_INIT;
699 int i;
701 repo_hold_locked_index(r, &index_lock, LOCK_DIE_ON_ERROR);
703 for (i = 0; i < update->nr; i++) {
704 struct string_list_item *item = &update->items[i];
705 if (add_file_to_index(r->index, item->string, 0))
706 exit(128);
707 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
708 item->string);
711 if (write_locked_index(r->index, &index_lock,
712 COMMIT_LOCK | SKIP_IF_UNCHANGED))
713 die(_("unable to write new index file"));
716 static void remove_variant(struct rerere_id *id)
718 unlink_or_warn(rerere_path(id, "postimage"));
719 unlink_or_warn(rerere_path(id, "preimage"));
720 id->collection->status[id->variant] = 0;
724 * The path indicated by rr_item may still have conflict for which we
725 * have a recorded resolution, in which case replay it and optionally
726 * update it. Or it may have been resolved by the user and we may
727 * only have the preimage for that conflict, in which case the result
728 * needs to be recorded as a resolution in a postimage file.
730 static void do_rerere_one_path(struct index_state *istate,
731 struct string_list_item *rr_item,
732 struct string_list *update)
734 const char *path = rr_item->string;
735 struct rerere_id *id = rr_item->util;
736 struct rerere_dir *rr_dir = id->collection;
737 int variant;
739 variant = id->variant;
741 /* Has the user resolved it already? */
742 if (variant >= 0) {
743 if (!handle_file(istate, path, NULL, NULL)) {
744 copy_file(rerere_path(id, "postimage"), path, 0666);
745 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
746 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
747 free_rerere_id(rr_item);
748 rr_item->util = NULL;
749 return;
752 * There may be other variants that can cleanly
753 * replay. Try them and update the variant number for
754 * this one.
758 /* Does any existing resolution apply cleanly? */
759 for (variant = 0; variant < rr_dir->status_nr; variant++) {
760 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
761 struct rerere_id vid = *id;
763 if ((rr_dir->status[variant] & both) != both)
764 continue;
766 vid.variant = variant;
767 if (merge(istate, &vid, path))
768 continue; /* failed to replay */
771 * If there already is a different variant that applies
772 * cleanly, there is no point maintaining our own variant.
774 if (0 <= id->variant && id->variant != variant)
775 remove_variant(id);
777 if (rerere_autoupdate)
778 string_list_insert(update, path);
779 else
780 fprintf_ln(stderr,
781 _("Resolved '%s' using previous resolution."),
782 path);
783 free_rerere_id(rr_item);
784 rr_item->util = NULL;
785 return;
788 /* None of the existing one applies; we need a new variant */
789 assign_variant(id);
791 variant = id->variant;
792 handle_file(istate, path, NULL, rerere_path(id, "preimage"));
793 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
794 const char *path = rerere_path(id, "postimage");
795 if (unlink(path))
796 die_errno(_("cannot unlink stray '%s'"), path);
797 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
799 id->collection->status[variant] |= RR_HAS_PREIMAGE;
800 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
803 static int do_plain_rerere(struct repository *r,
804 struct string_list *rr, int fd)
806 struct string_list conflict = STRING_LIST_INIT_DUP;
807 struct string_list update = STRING_LIST_INIT_DUP;
808 int i;
810 find_conflict(r, &conflict);
813 * MERGE_RR records paths with conflicts immediately after
814 * merge failed. Some of the conflicted paths might have been
815 * hand resolved in the working tree since then, but the
816 * initial run would catch all and register their preimages.
818 for (i = 0; i < conflict.nr; i++) {
819 struct rerere_id *id;
820 unsigned char hash[GIT_MAX_RAWSZ];
821 const char *path = conflict.items[i].string;
822 int ret;
825 * Ask handle_file() to scan and assign a
826 * conflict ID. No need to write anything out
827 * yet.
829 ret = handle_file(r->index, path, hash, NULL);
830 if (ret != 0 && string_list_has_string(rr, path)) {
831 remove_variant(string_list_lookup(rr, path)->util);
832 string_list_remove(rr, path, 1);
834 if (ret < 1)
835 continue;
837 id = new_rerere_id(hash);
838 string_list_insert(rr, path)->util = id;
840 /* Ensure that the directory exists. */
841 mkdir_in_gitdir(rerere_path(id, NULL));
844 for (i = 0; i < rr->nr; i++)
845 do_rerere_one_path(r->index, &rr->items[i], &update);
847 if (update.nr)
848 update_paths(r, &update);
850 return write_rr(rr, fd);
853 static void git_rerere_config(void)
855 git_config_get_bool("rerere.enabled", &rerere_enabled);
856 git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
857 git_config(git_default_config, NULL);
860 static GIT_PATH_FUNC(git_path_rr_cache, "rr-cache")
862 static int is_rerere_enabled(void)
864 int rr_cache_exists;
866 if (!rerere_enabled)
867 return 0;
869 rr_cache_exists = is_directory(git_path_rr_cache());
870 if (rerere_enabled < 0)
871 return rr_cache_exists;
873 if (!rr_cache_exists && mkdir_in_gitdir(git_path_rr_cache()))
874 die(_("could not create directory '%s'"), git_path_rr_cache());
875 return 1;
878 int setup_rerere(struct repository *r, struct string_list *merge_rr, int flags)
880 int fd;
882 git_rerere_config();
883 if (!is_rerere_enabled())
884 return -1;
886 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
887 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
888 if (flags & RERERE_READONLY)
889 fd = 0;
890 else
891 fd = hold_lock_file_for_update(&write_lock,
892 git_path_merge_rr(r),
893 LOCK_DIE_ON_ERROR);
894 read_rr(r, merge_rr);
895 return fd;
899 * The main entry point that is called internally from codepaths that
900 * perform mergy operations, possibly leaving conflicted index entries
901 * and working tree files.
903 int repo_rerere(struct repository *r, int flags)
905 struct string_list merge_rr = STRING_LIST_INIT_DUP;
906 int fd, status;
908 fd = setup_rerere(r, &merge_rr, flags);
909 if (fd < 0)
910 return 0;
911 status = do_plain_rerere(r, &merge_rr, fd);
912 free_rerere_dirs();
913 return status;
917 * Subclass of rerere_io that reads from an in-core buffer that is a
918 * strbuf
920 struct rerere_io_mem {
921 struct rerere_io io;
922 struct strbuf input;
926 * ... and its getline() method implementation
928 static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
930 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
931 char *ep;
932 size_t len;
934 strbuf_release(sb);
935 if (!io->input.len)
936 return -1;
937 ep = memchr(io->input.buf, '\n', io->input.len);
938 if (!ep)
939 ep = io->input.buf + io->input.len;
940 else if (*ep == '\n')
941 ep++;
942 len = ep - io->input.buf;
943 strbuf_add(sb, io->input.buf, len);
944 strbuf_remove(&io->input, 0, len);
945 return 0;
948 static int handle_cache(struct index_state *istate,
949 const char *path, unsigned char *hash, const char *output)
951 mmfile_t mmfile[3] = {{NULL}};
952 mmbuffer_t result = {NULL, 0};
953 const struct cache_entry *ce;
954 int pos, len, i, has_conflicts;
955 struct rerere_io_mem io;
956 int marker_size = ll_merge_marker_size(istate, path);
959 * Reproduce the conflicted merge in-core
961 len = strlen(path);
962 pos = index_name_pos(istate, path, len);
963 if (0 <= pos)
964 return -1;
965 pos = -pos - 1;
967 while (pos < istate->cache_nr) {
968 enum object_type type;
969 unsigned long size;
971 ce = istate->cache[pos++];
972 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
973 break;
974 i = ce_stage(ce) - 1;
975 if (!mmfile[i].ptr) {
976 mmfile[i].ptr = repo_read_object_file(the_repository,
977 &ce->oid, &type,
978 &size);
979 mmfile[i].size = size;
982 for (i = 0; i < 3; i++)
983 if (!mmfile[i].ptr && !mmfile[i].size)
984 mmfile[i].ptr = xstrdup("");
987 * NEEDSWORK: handle conflicts from merges with
988 * merge.renormalize set, too?
990 ll_merge(&result, path, &mmfile[0], NULL,
991 &mmfile[1], "ours",
992 &mmfile[2], "theirs",
993 istate, NULL);
994 for (i = 0; i < 3; i++)
995 free(mmfile[i].ptr);
997 memset(&io, 0, sizeof(io));
998 io.io.getline = rerere_mem_getline;
999 if (output)
1000 io.io.output = fopen(output, "w");
1001 else
1002 io.io.output = NULL;
1003 strbuf_init(&io.input, 0);
1004 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1007 * Grab the conflict ID and optionally write the original
1008 * contents with conflict markers out.
1010 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1011 strbuf_release(&io.input);
1012 if (io.io.output)
1013 fclose(io.io.output);
1014 return has_conflicts;
1017 static int rerere_forget_one_path(struct index_state *istate,
1018 const char *path,
1019 struct string_list *rr)
1021 const char *filename;
1022 struct rerere_id *id;
1023 unsigned char hash[GIT_MAX_RAWSZ];
1024 int ret;
1025 struct string_list_item *item;
1028 * Recreate the original conflict from the stages in the
1029 * index and compute the conflict ID
1031 ret = handle_cache(istate, path, hash, NULL);
1032 if (ret < 1)
1033 return error(_("could not parse conflict hunks in '%s'"), path);
1035 /* Nuke the recorded resolution for the conflict */
1036 id = new_rerere_id(hash);
1038 for (id->variant = 0;
1039 id->variant < id->collection->status_nr;
1040 id->variant++) {
1041 mmfile_t cur = { NULL, 0 };
1042 mmbuffer_t result = {NULL, 0};
1043 int cleanly_resolved;
1045 if (!has_rerere_resolution(id))
1046 continue;
1048 handle_cache(istate, path, hash, rerere_path(id, "thisimage"));
1049 if (read_mmfile(&cur, rerere_path(id, "thisimage"))) {
1050 free(cur.ptr);
1051 error(_("failed to update conflicted state in '%s'"), path);
1052 goto fail_exit;
1054 cleanly_resolved = !try_merge(istate, id, path, &cur, &result);
1055 free(result.ptr);
1056 free(cur.ptr);
1057 if (cleanly_resolved)
1058 break;
1061 if (id->collection->status_nr <= id->variant) {
1062 error(_("no remembered resolution for '%s'"), path);
1063 goto fail_exit;
1066 filename = rerere_path(id, "postimage");
1067 if (unlink(filename)) {
1068 if (errno == ENOENT)
1069 error(_("no remembered resolution for '%s'"), path);
1070 else
1071 error_errno(_("cannot unlink '%s'"), filename);
1072 goto fail_exit;
1076 * Update the preimage so that the user can resolve the
1077 * conflict in the working tree, run us again to record
1078 * the postimage.
1080 handle_cache(istate, path, hash, rerere_path(id, "preimage"));
1081 fprintf_ln(stderr, _("Updated preimage for '%s'"), path);
1084 * And remember that we can record resolution for this
1085 * conflict when the user is done.
1087 item = string_list_insert(rr, path);
1088 free_rerere_id(item);
1089 item->util = id;
1090 fprintf(stderr, _("Forgot resolution for '%s'\n"), path);
1091 return 0;
1093 fail_exit:
1094 free(id);
1095 return -1;
1098 int rerere_forget(struct repository *r, struct pathspec *pathspec)
1100 int i, fd;
1101 struct string_list conflict = STRING_LIST_INIT_DUP;
1102 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1104 if (repo_read_index(r) < 0)
1105 return error(_("index file corrupt"));
1107 fd = setup_rerere(r, &merge_rr, RERERE_NOAUTOUPDATE);
1108 if (fd < 0)
1109 return 0;
1112 * The paths may have been resolved (incorrectly);
1113 * recover the original conflicted state and then
1114 * find the conflicted paths.
1116 unmerge_index(r->index, pathspec);
1117 find_conflict(r, &conflict);
1118 for (i = 0; i < conflict.nr; i++) {
1119 struct string_list_item *it = &conflict.items[i];
1120 if (!match_pathspec(r->index, pathspec, it->string,
1121 strlen(it->string), 0, NULL, 0))
1122 continue;
1123 rerere_forget_one_path(r->index, it->string, &merge_rr);
1125 return write_rr(&merge_rr, fd);
1129 * Garbage collection support
1132 static timestamp_t rerere_created_at(struct rerere_id *id)
1134 struct stat st;
1136 return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
1139 static timestamp_t rerere_last_used_at(struct rerere_id *id)
1141 struct stat st;
1143 return stat(rerere_path(id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
1147 * Remove the recorded resolution for a given conflict ID
1149 static void unlink_rr_item(struct rerere_id *id)
1151 unlink_or_warn(rerere_path(id, "thisimage"));
1152 remove_variant(id);
1153 id->collection->status[id->variant] = 0;
1156 static void prune_one(struct rerere_id *id,
1157 timestamp_t cutoff_resolve, timestamp_t cutoff_noresolve)
1159 timestamp_t then;
1160 timestamp_t cutoff;
1162 then = rerere_last_used_at(id);
1163 if (then)
1164 cutoff = cutoff_resolve;
1165 else {
1166 then = rerere_created_at(id);
1167 if (!then)
1168 return;
1169 cutoff = cutoff_noresolve;
1171 if (then < cutoff)
1172 unlink_rr_item(id);
1175 /* Does the basename in "path" look plausibly like an rr-cache entry? */
1176 static int is_rr_cache_dirname(const char *path)
1178 struct object_id oid;
1179 const char *end;
1180 return !parse_oid_hex(path, &oid, &end) && !*end;
1183 void rerere_gc(struct repository *r, struct string_list *rr)
1185 struct string_list to_remove = STRING_LIST_INIT_DUP;
1186 DIR *dir;
1187 struct dirent *e;
1188 int i;
1189 timestamp_t now = time(NULL);
1190 timestamp_t cutoff_noresolve = now - 15 * 86400;
1191 timestamp_t cutoff_resolve = now - 60 * 86400;
1193 if (setup_rerere(r, rr, 0) < 0)
1194 return;
1196 git_config_get_expiry_in_days("gc.rerereresolved", &cutoff_resolve, now);
1197 git_config_get_expiry_in_days("gc.rerereunresolved", &cutoff_noresolve, now);
1198 git_config(git_default_config, NULL);
1199 dir = opendir(git_path("rr-cache"));
1200 if (!dir)
1201 die_errno(_("unable to open rr-cache directory"));
1202 /* Collect stale conflict IDs ... */
1203 while ((e = readdir_skip_dot_and_dotdot(dir))) {
1204 struct rerere_dir *rr_dir;
1205 struct rerere_id id;
1206 int now_empty;
1208 if (!is_rr_cache_dirname(e->d_name))
1209 continue; /* or should we remove e->d_name? */
1211 rr_dir = find_rerere_dir(e->d_name);
1213 now_empty = 1;
1214 for (id.variant = 0, id.collection = rr_dir;
1215 id.variant < id.collection->status_nr;
1216 id.variant++) {
1217 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1218 if (id.collection->status[id.variant])
1219 now_empty = 0;
1221 if (now_empty)
1222 string_list_append(&to_remove, e->d_name);
1224 closedir(dir);
1226 /* ... and then remove the empty directories */
1227 for (i = 0; i < to_remove.nr; i++)
1228 rmdir(git_path("rr-cache/%s", to_remove.items[i].string));
1229 string_list_clear(&to_remove, 0);
1230 rollback_lock_file(&write_lock);
1234 * During a conflict resolution, after "rerere" recorded the
1235 * preimages, abandon them if the user did not resolve them or
1236 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1238 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1240 void rerere_clear(struct repository *r, struct string_list *merge_rr)
1242 int i;
1244 if (setup_rerere(r, merge_rr, 0) < 0)
1245 return;
1247 for (i = 0; i < merge_rr->nr; i++) {
1248 struct rerere_id *id = merge_rr->items[i].util;
1249 if (!has_rerere_resolution(id)) {
1250 unlink_rr_item(id);
1251 rmdir(rerere_path(id, NULL));
1254 unlink_or_warn(git_path_merge_rr(r));
1255 rollback_lock_file(&write_lock);