debian: new upstream release
[git/debian.git] / rerere.c
blob09e19412859b3edb7be4142947d3967fc76520cc
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "copy.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "lockfile.h"
8 #include "string-list.h"
9 #include "read-cache-ll.h"
10 #include "rerere.h"
11 #include "xdiff-interface.h"
12 #include "dir.h"
13 #include "resolve-undo.h"
14 #include "merge-ll.h"
15 #include "attr.h"
16 #include "path.h"
17 #include "pathspec.h"
18 #include "object-file.h"
19 #include "object-store-ll.h"
20 #include "hash-lookup.h"
21 #include "strmap.h"
23 #define RESOLVED 0
24 #define PUNTED 1
25 #define THREE_STAGED 2
26 void *RERERE_RESOLVED = &RERERE_RESOLVED;
28 /* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
29 static int rerere_enabled = -1;
31 /* automatically update cleanly resolved paths to the index */
32 static int rerere_autoupdate;
34 #define RR_HAS_POSTIMAGE 1
35 #define RR_HAS_PREIMAGE 2
36 struct rerere_dir {
37 int status_alloc, status_nr;
38 unsigned char *status;
39 char name[FLEX_ARRAY];
42 static struct strmap rerere_dirs = STRMAP_INIT;
44 static void free_rerere_dirs(void)
46 struct hashmap_iter iter;
47 struct strmap_entry *ent;
49 strmap_for_each_entry(&rerere_dirs, &iter, ent) {
50 struct rerere_dir *rr_dir = ent->value;
51 free(rr_dir->status);
52 free(rr_dir);
54 strmap_clear(&rerere_dirs, 0);
57 static void free_rerere_id(struct string_list_item *item)
59 free(item->util);
62 static const char *rerere_id_hex(const struct rerere_id *id)
64 return id->collection->name;
67 static void fit_variant(struct rerere_dir *rr_dir, int variant)
69 variant++;
70 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
71 if (rr_dir->status_nr < variant) {
72 memset(rr_dir->status + rr_dir->status_nr,
73 '\0', variant - rr_dir->status_nr);
74 rr_dir->status_nr = variant;
78 static void assign_variant(struct rerere_id *id)
80 int variant;
81 struct rerere_dir *rr_dir = id->collection;
83 variant = id->variant;
84 if (variant < 0) {
85 for (variant = 0; variant < rr_dir->status_nr; variant++)
86 if (!rr_dir->status[variant])
87 break;
89 fit_variant(rr_dir, variant);
90 id->variant = variant;
93 const char *rerere_path(const struct rerere_id *id, const char *file)
95 if (!file)
96 return git_path("rr-cache/%s", rerere_id_hex(id));
98 if (id->variant <= 0)
99 return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
101 return git_path("rr-cache/%s/%s.%d",
102 rerere_id_hex(id), file, id->variant);
105 static int is_rr_file(const char *name, const char *filename, int *variant)
107 const char *suffix;
108 char *ep;
110 if (!strcmp(name, filename)) {
111 *variant = 0;
112 return 1;
114 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
115 return 0;
117 errno = 0;
118 *variant = strtol(suffix + 1, &ep, 10);
119 if (errno || *ep)
120 return 0;
121 return 1;
124 static void scan_rerere_dir(struct rerere_dir *rr_dir)
126 struct dirent *de;
127 DIR *dir = opendir(git_path("rr-cache/%s", rr_dir->name));
129 if (!dir)
130 return;
131 while ((de = readdir(dir)) != NULL) {
132 int variant;
134 if (is_rr_file(de->d_name, "postimage", &variant)) {
135 fit_variant(rr_dir, variant);
136 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
137 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
138 fit_variant(rr_dir, variant);
139 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
142 closedir(dir);
145 static struct rerere_dir *find_rerere_dir(const char *hex)
147 struct rerere_dir *rr_dir;
149 rr_dir = strmap_get(&rerere_dirs, hex);
150 if (!rr_dir) {
151 FLEX_ALLOC_STR(rr_dir, name, hex);
152 rr_dir->status = NULL;
153 rr_dir->status_nr = 0;
154 rr_dir->status_alloc = 0;
155 strmap_put(&rerere_dirs, hex, rr_dir);
157 scan_rerere_dir(rr_dir);
159 return rr_dir;
162 static int has_rerere_resolution(const struct rerere_id *id)
164 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
165 int variant = id->variant;
167 if (variant < 0)
168 return 0;
169 return ((id->collection->status[variant] & both) == both);
172 static struct rerere_id *new_rerere_id_hex(char *hex)
174 struct rerere_id *id = xmalloc(sizeof(*id));
175 id->collection = find_rerere_dir(hex);
176 id->variant = -1; /* not known yet */
177 return id;
180 static struct rerere_id *new_rerere_id(unsigned char *hash)
182 return new_rerere_id_hex(hash_to_hex(hash));
186 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
187 * "conflict ID", a HT and pathname, terminated with a NUL, and is
188 * used to keep track of the set of paths that "rerere" may need to
189 * work on (i.e. what is left by the previous invocation of "git
190 * rerere" during the current conflict resolution session).
192 static void read_rr(struct repository *r, struct string_list *rr)
194 struct strbuf buf = STRBUF_INIT;
195 FILE *in = fopen_or_warn(git_path_merge_rr(r), "r");
197 if (!in)
198 return;
199 while (!strbuf_getwholeline(&buf, in, '\0')) {
200 char *path;
201 unsigned char hash[GIT_MAX_RAWSZ];
202 struct rerere_id *id;
203 int variant;
204 const unsigned hexsz = the_hash_algo->hexsz;
206 /* There has to be the hash, tab, path and then NUL */
207 if (buf.len < hexsz + 2 || get_hash_hex(buf.buf, hash))
208 die(_("corrupt MERGE_RR"));
210 if (buf.buf[hexsz] != '.') {
211 variant = 0;
212 path = buf.buf + hexsz;
213 } else {
214 errno = 0;
215 variant = strtol(buf.buf + hexsz + 1, &path, 10);
216 if (errno)
217 die(_("corrupt MERGE_RR"));
219 if (*(path++) != '\t')
220 die(_("corrupt MERGE_RR"));
221 buf.buf[hexsz] = '\0';
222 id = new_rerere_id_hex(buf.buf);
223 id->variant = variant;
224 string_list_insert(rr, path)->util = id;
226 strbuf_release(&buf);
227 fclose(in);
230 static struct lock_file write_lock;
232 static int write_rr(struct string_list *rr, int out_fd)
234 int i;
235 for (i = 0; i < rr->nr; i++) {
236 struct strbuf buf = STRBUF_INIT;
237 struct rerere_id *id;
239 assert(rr->items[i].util != RERERE_RESOLVED);
241 id = rr->items[i].util;
242 if (!id)
243 continue;
244 assert(id->variant >= 0);
245 if (0 < id->variant)
246 strbuf_addf(&buf, "%s.%d\t%s%c",
247 rerere_id_hex(id), id->variant,
248 rr->items[i].string, 0);
249 else
250 strbuf_addf(&buf, "%s\t%s%c",
251 rerere_id_hex(id),
252 rr->items[i].string, 0);
254 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
255 die(_("unable to write rerere record"));
257 strbuf_release(&buf);
259 if (commit_lock_file(&write_lock) != 0)
260 die(_("unable to write rerere record"));
261 return 0;
265 * "rerere" interacts with conflicted file contents using this I/O
266 * abstraction. It reads a conflicted contents from one place via
267 * "getline()" method, and optionally can write it out after
268 * normalizing the conflicted hunks to the "output". Subclasses of
269 * rerere_io embed this structure at the beginning of their own
270 * rerere_io object.
272 struct rerere_io {
273 int (*getline)(struct strbuf *, struct rerere_io *);
274 FILE *output;
275 int wrerror;
276 /* some more stuff */
279 static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
281 if (!count || *err)
282 return;
283 if (fwrite(p, count, 1, fp) != 1)
284 *err = errno;
287 static inline void ferr_puts(const char *s, FILE *fp, int *err)
289 ferr_write(s, strlen(s), fp, err);
292 static void rerere_io_putstr(const char *str, struct rerere_io *io)
294 if (io->output)
295 ferr_puts(str, io->output, &io->wrerror);
298 static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
300 if (io->output)
301 ferr_write(mem, sz, io->output, &io->wrerror);
305 * Subclass of rerere_io that reads from an on-disk file
307 struct rerere_io_file {
308 struct rerere_io io;
309 FILE *input;
313 * ... and its getline() method implementation
315 static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
317 struct rerere_io_file *io = (struct rerere_io_file *)io_;
318 return strbuf_getwholeline(sb, io->input, '\n');
322 * Require the exact number of conflict marker letters, no more, no
323 * less, followed by SP or any whitespace
324 * (including LF).
326 static int is_cmarker(char *buf, int marker_char, int marker_size)
328 int want_sp;
331 * The beginning of our version and the end of their version
332 * always are labeled like "<<<<< ours" or ">>>>> theirs",
333 * hence we set want_sp for them. Note that the version from
334 * the common ancestor in diff3-style output is not always
335 * labelled (e.g. "||||| common" is often seen but "|||||"
336 * alone is also valid), so we do not set want_sp.
338 want_sp = (marker_char == '<') || (marker_char == '>');
340 while (marker_size--)
341 if (*buf++ != marker_char)
342 return 0;
343 if (want_sp && *buf != ' ')
344 return 0;
345 return isspace(*buf);
348 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
350 strbuf_addchars(buf, ch, size);
351 strbuf_addch(buf, '\n');
354 static int handle_conflict(struct strbuf *out, struct rerere_io *io,
355 int marker_size, git_hash_ctx *ctx)
357 enum {
358 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
359 } hunk = RR_SIDE_1;
360 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
361 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
362 int has_conflicts = -1;
364 while (!io->getline(&buf, io)) {
365 if (is_cmarker(buf.buf, '<', marker_size)) {
366 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
367 break;
368 if (hunk == RR_SIDE_1)
369 strbuf_addbuf(&one, &conflict);
370 else
371 strbuf_addbuf(&two, &conflict);
372 strbuf_release(&conflict);
373 } else if (is_cmarker(buf.buf, '|', marker_size)) {
374 if (hunk != RR_SIDE_1)
375 break;
376 hunk = RR_ORIGINAL;
377 } else if (is_cmarker(buf.buf, '=', marker_size)) {
378 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
379 break;
380 hunk = RR_SIDE_2;
381 } else if (is_cmarker(buf.buf, '>', marker_size)) {
382 if (hunk != RR_SIDE_2)
383 break;
384 if (strbuf_cmp(&one, &two) > 0)
385 strbuf_swap(&one, &two);
386 has_conflicts = 1;
387 rerere_strbuf_putconflict(out, '<', marker_size);
388 strbuf_addbuf(out, &one);
389 rerere_strbuf_putconflict(out, '=', marker_size);
390 strbuf_addbuf(out, &two);
391 rerere_strbuf_putconflict(out, '>', marker_size);
392 if (ctx) {
393 the_hash_algo->update_fn(ctx, one.buf ?
394 one.buf : "",
395 one.len + 1);
396 the_hash_algo->update_fn(ctx, two.buf ?
397 two.buf : "",
398 two.len + 1);
400 break;
401 } else if (hunk == RR_SIDE_1)
402 strbuf_addbuf(&one, &buf);
403 else if (hunk == RR_ORIGINAL)
404 ; /* discard */
405 else if (hunk == RR_SIDE_2)
406 strbuf_addbuf(&two, &buf);
408 strbuf_release(&one);
409 strbuf_release(&two);
410 strbuf_release(&buf);
412 return has_conflicts;
416 * Read contents a file with conflicts, normalize the conflicts
417 * by (1) discarding the common ancestor version in diff3-style,
418 * (2) reordering our side and their side so that whichever sorts
419 * alphabetically earlier comes before the other one, while
420 * computing the "conflict ID", which is just an SHA-1 hash of
421 * one side of the conflict, NUL, the other side of the conflict,
422 * and NUL concatenated together.
424 * Return 1 if conflict hunks are found, 0 if there are no conflict
425 * hunks and -1 if an error occurred.
427 static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
429 git_hash_ctx ctx;
430 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
431 int has_conflicts = 0;
432 if (hash)
433 the_hash_algo->init_fn(&ctx);
435 while (!io->getline(&buf, io)) {
436 if (is_cmarker(buf.buf, '<', marker_size)) {
437 has_conflicts = handle_conflict(&out, io, marker_size,
438 hash ? &ctx : NULL);
439 if (has_conflicts < 0)
440 break;
441 rerere_io_putmem(out.buf, out.len, io);
442 strbuf_reset(&out);
443 } else
444 rerere_io_putstr(buf.buf, io);
446 strbuf_release(&buf);
447 strbuf_release(&out);
449 if (hash)
450 the_hash_algo->final_fn(hash, &ctx);
452 return has_conflicts;
456 * Scan the path for conflicts, do the "handle_path()" thing above, and
457 * return the number of conflict hunks found.
459 static int handle_file(struct index_state *istate,
460 const char *path, unsigned char *hash, const char *output)
462 int has_conflicts = 0;
463 struct rerere_io_file io;
464 int marker_size = ll_merge_marker_size(istate, path);
466 memset(&io, 0, sizeof(io));
467 io.io.getline = rerere_file_getline;
468 io.input = fopen(path, "r");
469 io.io.wrerror = 0;
470 if (!io.input)
471 return error_errno(_("could not open '%s'"), path);
473 if (output) {
474 io.io.output = fopen(output, "w");
475 if (!io.io.output) {
476 error_errno(_("could not write '%s'"), output);
477 fclose(io.input);
478 return -1;
482 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
484 fclose(io.input);
485 if (io.io.wrerror)
486 error(_("there were errors while writing '%s' (%s)"),
487 path, strerror(io.io.wrerror));
488 if (io.io.output && fclose(io.io.output))
489 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
491 if (has_conflicts < 0) {
492 if (output)
493 unlink_or_warn(output);
494 return error(_("could not parse conflict hunks in '%s'"), path);
496 if (io.io.wrerror)
497 return -1;
498 return has_conflicts;
502 * Look at a cache entry at "i" and see if it is not conflicting,
503 * conflicting and we are willing to handle, or conflicting and
504 * we are unable to handle, and return the determination in *type.
505 * Return the cache index to be looked at next, by skipping the
506 * stages we have already looked at in this invocation of this
507 * function.
509 static int check_one_conflict(struct index_state *istate, int i, int *type)
511 const struct cache_entry *e = istate->cache[i];
513 if (!ce_stage(e)) {
514 *type = RESOLVED;
515 return i + 1;
518 *type = PUNTED;
519 while (i < istate->cache_nr && ce_stage(istate->cache[i]) == 1)
520 i++;
522 /* Only handle regular files with both stages #2 and #3 */
523 if (i + 1 < istate->cache_nr) {
524 const struct cache_entry *e2 = istate->cache[i];
525 const struct cache_entry *e3 = istate->cache[i + 1];
526 if (ce_stage(e2) == 2 &&
527 ce_stage(e3) == 3 &&
528 ce_same_name(e, e3) &&
529 S_ISREG(e2->ce_mode) &&
530 S_ISREG(e3->ce_mode))
531 *type = THREE_STAGED;
534 /* Skip the entries with the same name */
535 while (i < istate->cache_nr && ce_same_name(e, istate->cache[i]))
536 i++;
537 return i;
541 * Scan the index and find paths that have conflicts that rerere can
542 * handle, i.e. the ones that has both stages #2 and #3.
544 * NEEDSWORK: we do not record or replay a previous "resolve by
545 * deletion" for a delete-modify conflict, as that is inherently risky
546 * without knowing what modification is being discarded. The only
547 * safe case, i.e. both side doing the deletion and modification that
548 * are identical to the previous round, might want to be handled,
549 * though.
551 static int find_conflict(struct repository *r, struct string_list *conflict)
553 int i;
555 if (repo_read_index(r) < 0)
556 return error(_("index file corrupt"));
558 for (i = 0; i < r->index->cache_nr;) {
559 int conflict_type;
560 const struct cache_entry *e = r->index->cache[i];
561 i = check_one_conflict(r->index, i, &conflict_type);
562 if (conflict_type == THREE_STAGED)
563 string_list_insert(conflict, (const char *)e->name);
565 return 0;
569 * The merge_rr list is meant to hold outstanding conflicted paths
570 * that rerere could handle. Abuse the list by adding other types of
571 * entries to allow the caller to show "rerere remaining".
573 * - Conflicted paths that rerere does not handle are added
574 * - Conflicted paths that have been resolved are marked as such
575 * by storing RERERE_RESOLVED to .util field (where conflict ID
576 * is expected to be stored).
578 * Do *not* write MERGE_RR file out after calling this function.
580 * NEEDSWORK: we may want to fix the caller that implements "rerere
581 * remaining" to do this without abusing merge_rr.
583 int rerere_remaining(struct repository *r, struct string_list *merge_rr)
585 int i;
587 if (setup_rerere(r, merge_rr, RERERE_READONLY))
588 return 0;
589 if (repo_read_index(r) < 0)
590 return error(_("index file corrupt"));
592 for (i = 0; i < r->index->cache_nr;) {
593 int conflict_type;
594 const struct cache_entry *e = r->index->cache[i];
595 i = check_one_conflict(r->index, i, &conflict_type);
596 if (conflict_type == PUNTED)
597 string_list_insert(merge_rr, (const char *)e->name);
598 else if (conflict_type == RESOLVED) {
599 struct string_list_item *it;
600 it = string_list_lookup(merge_rr, (const char *)e->name);
601 if (it) {
602 free_rerere_id(it);
603 it->util = RERERE_RESOLVED;
607 return 0;
611 * Try using the given conflict resolution "ID" to see
612 * if that recorded conflict resolves cleanly what we
613 * got in the "cur".
615 static int try_merge(struct index_state *istate,
616 const struct rerere_id *id, const char *path,
617 mmfile_t *cur, mmbuffer_t *result)
619 enum ll_merge_result ret;
620 mmfile_t base = {NULL, 0}, other = {NULL, 0};
622 if (read_mmfile(&base, rerere_path(id, "preimage")) ||
623 read_mmfile(&other, rerere_path(id, "postimage"))) {
624 ret = LL_MERGE_CONFLICT;
625 } else {
627 * A three-way merge. Note that this honors user-customizable
628 * low-level merge driver settings.
630 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "",
631 istate, NULL);
634 free(base.ptr);
635 free(other.ptr);
637 return ret;
641 * Find the conflict identified by "id"; the change between its
642 * "preimage" (i.e. a previous contents with conflict markers) and its
643 * "postimage" (i.e. the corresponding contents with conflicts
644 * resolved) may apply cleanly to the contents stored in "path", i.e.
645 * the conflict this time around.
647 * Returns 0 for successful replay of recorded resolution, or non-zero
648 * for failure.
650 static int merge(struct index_state *istate, const struct rerere_id *id, const char *path)
652 FILE *f;
653 int ret;
654 mmfile_t cur = {NULL, 0};
655 mmbuffer_t result = {NULL, 0};
658 * Normalize the conflicts in path and write it out to
659 * "thisimage" temporary file.
661 if ((handle_file(istate, path, NULL, rerere_path(id, "thisimage")) < 0) ||
662 read_mmfile(&cur, rerere_path(id, "thisimage"))) {
663 ret = 1;
664 goto out;
667 ret = try_merge(istate, id, path, &cur, &result);
668 if (ret)
669 goto out;
672 * A successful replay of recorded resolution.
673 * Mark that "postimage" was used to help gc.
675 if (utime(rerere_path(id, "postimage"), NULL) < 0)
676 warning_errno(_("failed utime() on '%s'"),
677 rerere_path(id, "postimage"));
679 /* Update "path" with the resolution */
680 f = fopen(path, "w");
681 if (!f)
682 return error_errno(_("could not open '%s'"), path);
683 if (fwrite(result.ptr, result.size, 1, f) != 1)
684 error_errno(_("could not write '%s'"), path);
685 if (fclose(f))
686 return error_errno(_("writing '%s' failed"), path);
688 out:
689 free(cur.ptr);
690 free(result.ptr);
692 return ret;
695 static void update_paths(struct repository *r, struct string_list *update)
697 struct lock_file index_lock = LOCK_INIT;
698 int i;
700 repo_hold_locked_index(r, &index_lock, LOCK_DIE_ON_ERROR);
702 for (i = 0; i < update->nr; i++) {
703 struct string_list_item *item = &update->items[i];
704 if (add_file_to_index(r->index, item->string, 0))
705 exit(128);
706 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
707 item->string);
710 if (write_locked_index(r->index, &index_lock,
711 COMMIT_LOCK | SKIP_IF_UNCHANGED))
712 die(_("unable to write new index file"));
715 static void remove_variant(struct rerere_id *id)
717 unlink_or_warn(rerere_path(id, "postimage"));
718 unlink_or_warn(rerere_path(id, "preimage"));
719 id->collection->status[id->variant] = 0;
723 * The path indicated by rr_item may still have conflict for which we
724 * have a recorded resolution, in which case replay it and optionally
725 * update it. Or it may have been resolved by the user and we may
726 * only have the preimage for that conflict, in which case the result
727 * needs to be recorded as a resolution in a postimage file.
729 static void do_rerere_one_path(struct index_state *istate,
730 struct string_list_item *rr_item,
731 struct string_list *update)
733 const char *path = rr_item->string;
734 struct rerere_id *id = rr_item->util;
735 struct rerere_dir *rr_dir = id->collection;
736 int variant;
738 variant = id->variant;
740 /* Has the user resolved it already? */
741 if (variant >= 0) {
742 if (!handle_file(istate, path, NULL, NULL)) {
743 copy_file(rerere_path(id, "postimage"), path, 0666);
744 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
745 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
746 free_rerere_id(rr_item);
747 rr_item->util = NULL;
748 return;
751 * There may be other variants that can cleanly
752 * replay. Try them and update the variant number for
753 * this one.
757 /* Does any existing resolution apply cleanly? */
758 for (variant = 0; variant < rr_dir->status_nr; variant++) {
759 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
760 struct rerere_id vid = *id;
762 if ((rr_dir->status[variant] & both) != both)
763 continue;
765 vid.variant = variant;
766 if (merge(istate, &vid, path))
767 continue; /* failed to replay */
770 * If there already is a different variant that applies
771 * cleanly, there is no point maintaining our own variant.
773 if (0 <= id->variant && id->variant != variant)
774 remove_variant(id);
776 if (rerere_autoupdate)
777 string_list_insert(update, path);
778 else
779 fprintf_ln(stderr,
780 _("Resolved '%s' using previous resolution."),
781 path);
782 free_rerere_id(rr_item);
783 rr_item->util = NULL;
784 return;
787 /* None of the existing one applies; we need a new variant */
788 assign_variant(id);
790 variant = id->variant;
791 handle_file(istate, path, NULL, rerere_path(id, "preimage"));
792 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
793 const char *path = rerere_path(id, "postimage");
794 if (unlink(path))
795 die_errno(_("cannot unlink stray '%s'"), path);
796 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
798 id->collection->status[variant] |= RR_HAS_PREIMAGE;
799 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
802 static int do_plain_rerere(struct repository *r,
803 struct string_list *rr, int fd)
805 struct string_list conflict = STRING_LIST_INIT_DUP;
806 struct string_list update = STRING_LIST_INIT_DUP;
807 int i;
809 find_conflict(r, &conflict);
812 * MERGE_RR records paths with conflicts immediately after
813 * merge failed. Some of the conflicted paths might have been
814 * hand resolved in the working tree since then, but the
815 * initial run would catch all and register their preimages.
817 for (i = 0; i < conflict.nr; i++) {
818 struct rerere_id *id;
819 unsigned char hash[GIT_MAX_RAWSZ];
820 const char *path = conflict.items[i].string;
821 int ret;
824 * Ask handle_file() to scan and assign a
825 * conflict ID. No need to write anything out
826 * yet.
828 ret = handle_file(r->index, path, hash, NULL);
829 if (ret != 0 && string_list_has_string(rr, path)) {
830 remove_variant(string_list_lookup(rr, path)->util);
831 string_list_remove(rr, path, 1);
833 if (ret < 1)
834 continue;
836 id = new_rerere_id(hash);
837 string_list_insert(rr, path)->util = id;
839 /* Ensure that the directory exists. */
840 mkdir_in_gitdir(rerere_path(id, NULL));
843 for (i = 0; i < rr->nr; i++)
844 do_rerere_one_path(r->index, &rr->items[i], &update);
846 if (update.nr)
847 update_paths(r, &update);
849 return write_rr(rr, fd);
852 static void git_rerere_config(void)
854 git_config_get_bool("rerere.enabled", &rerere_enabled);
855 git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
856 git_config(git_default_config, NULL);
859 static GIT_PATH_FUNC(git_path_rr_cache, "rr-cache")
861 static int is_rerere_enabled(void)
863 int rr_cache_exists;
865 if (!rerere_enabled)
866 return 0;
868 rr_cache_exists = is_directory(git_path_rr_cache());
869 if (rerere_enabled < 0)
870 return rr_cache_exists;
872 if (!rr_cache_exists && mkdir_in_gitdir(git_path_rr_cache()))
873 die(_("could not create directory '%s'"), git_path_rr_cache());
874 return 1;
877 int setup_rerere(struct repository *r, struct string_list *merge_rr, int flags)
879 int fd;
881 git_rerere_config();
882 if (!is_rerere_enabled())
883 return -1;
885 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
886 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
887 if (flags & RERERE_READONLY)
888 fd = 0;
889 else
890 fd = hold_lock_file_for_update(&write_lock,
891 git_path_merge_rr(r),
892 LOCK_DIE_ON_ERROR);
893 read_rr(r, merge_rr);
894 return fd;
898 * The main entry point that is called internally from codepaths that
899 * perform mergy operations, possibly leaving conflicted index entries
900 * and working tree files.
902 int repo_rerere(struct repository *r, int flags)
904 struct string_list merge_rr = STRING_LIST_INIT_DUP;
905 int fd, status;
907 fd = setup_rerere(r, &merge_rr, flags);
908 if (fd < 0)
909 return 0;
910 status = do_plain_rerere(r, &merge_rr, fd);
911 free_rerere_dirs();
912 return status;
916 * Subclass of rerere_io that reads from an in-core buffer that is a
917 * strbuf
919 struct rerere_io_mem {
920 struct rerere_io io;
921 struct strbuf input;
925 * ... and its getline() method implementation
927 static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
929 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
930 char *ep;
931 size_t len;
933 strbuf_release(sb);
934 if (!io->input.len)
935 return -1;
936 ep = memchr(io->input.buf, '\n', io->input.len);
937 if (!ep)
938 ep = io->input.buf + io->input.len;
939 else if (*ep == '\n')
940 ep++;
941 len = ep - io->input.buf;
942 strbuf_add(sb, io->input.buf, len);
943 strbuf_remove(&io->input, 0, len);
944 return 0;
947 static int handle_cache(struct index_state *istate,
948 const char *path, unsigned char *hash, const char *output)
950 mmfile_t mmfile[3] = {{NULL}};
951 mmbuffer_t result = {NULL, 0};
952 const struct cache_entry *ce;
953 int pos, len, i, has_conflicts;
954 struct rerere_io_mem io;
955 int marker_size = ll_merge_marker_size(istate, path);
958 * Reproduce the conflicted merge in-core
960 len = strlen(path);
961 pos = index_name_pos(istate, path, len);
962 if (0 <= pos)
963 return -1;
964 pos = -pos - 1;
966 while (pos < istate->cache_nr) {
967 enum object_type type;
968 unsigned long size;
970 ce = istate->cache[pos++];
971 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
972 break;
973 i = ce_stage(ce) - 1;
974 if (!mmfile[i].ptr) {
975 mmfile[i].ptr = repo_read_object_file(the_repository,
976 &ce->oid, &type,
977 &size);
978 mmfile[i].size = size;
981 for (i = 0; i < 3; i++)
982 if (!mmfile[i].ptr && !mmfile[i].size)
983 mmfile[i].ptr = xstrdup("");
986 * NEEDSWORK: handle conflicts from merges with
987 * merge.renormalize set, too?
989 ll_merge(&result, path, &mmfile[0], NULL,
990 &mmfile[1], "ours",
991 &mmfile[2], "theirs",
992 istate, NULL);
993 for (i = 0; i < 3; i++)
994 free(mmfile[i].ptr);
996 memset(&io, 0, sizeof(io));
997 io.io.getline = rerere_mem_getline;
998 if (output)
999 io.io.output = fopen(output, "w");
1000 else
1001 io.io.output = NULL;
1002 strbuf_init(&io.input, 0);
1003 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1006 * Grab the conflict ID and optionally write the original
1007 * contents with conflict markers out.
1009 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1010 strbuf_release(&io.input);
1011 if (io.io.output)
1012 fclose(io.io.output);
1013 return has_conflicts;
1016 static int rerere_forget_one_path(struct index_state *istate,
1017 const char *path,
1018 struct string_list *rr)
1020 const char *filename;
1021 struct rerere_id *id;
1022 unsigned char hash[GIT_MAX_RAWSZ];
1023 int ret;
1024 struct string_list_item *item;
1027 * Recreate the original conflict from the stages in the
1028 * index and compute the conflict ID
1030 ret = handle_cache(istate, path, hash, NULL);
1031 if (ret < 1)
1032 return error(_("could not parse conflict hunks in '%s'"), path);
1034 /* Nuke the recorded resolution for the conflict */
1035 id = new_rerere_id(hash);
1037 for (id->variant = 0;
1038 id->variant < id->collection->status_nr;
1039 id->variant++) {
1040 mmfile_t cur = { NULL, 0 };
1041 mmbuffer_t result = {NULL, 0};
1042 int cleanly_resolved;
1044 if (!has_rerere_resolution(id))
1045 continue;
1047 handle_cache(istate, path, hash, rerere_path(id, "thisimage"));
1048 if (read_mmfile(&cur, rerere_path(id, "thisimage"))) {
1049 free(cur.ptr);
1050 error(_("failed to update conflicted state in '%s'"), path);
1051 goto fail_exit;
1053 cleanly_resolved = !try_merge(istate, id, path, &cur, &result);
1054 free(result.ptr);
1055 free(cur.ptr);
1056 if (cleanly_resolved)
1057 break;
1060 if (id->collection->status_nr <= id->variant) {
1061 error(_("no remembered resolution for '%s'"), path);
1062 goto fail_exit;
1065 filename = rerere_path(id, "postimage");
1066 if (unlink(filename)) {
1067 if (errno == ENOENT)
1068 error(_("no remembered resolution for '%s'"), path);
1069 else
1070 error_errno(_("cannot unlink '%s'"), filename);
1071 goto fail_exit;
1075 * Update the preimage so that the user can resolve the
1076 * conflict in the working tree, run us again to record
1077 * the postimage.
1079 handle_cache(istate, path, hash, rerere_path(id, "preimage"));
1080 fprintf_ln(stderr, _("Updated preimage for '%s'"), path);
1083 * And remember that we can record resolution for this
1084 * conflict when the user is done.
1086 item = string_list_insert(rr, path);
1087 free_rerere_id(item);
1088 item->util = id;
1089 fprintf(stderr, _("Forgot resolution for '%s'\n"), path);
1090 return 0;
1092 fail_exit:
1093 free(id);
1094 return -1;
1097 int rerere_forget(struct repository *r, struct pathspec *pathspec)
1099 int i, fd;
1100 struct string_list conflict = STRING_LIST_INIT_DUP;
1101 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1103 if (repo_read_index(r) < 0)
1104 return error(_("index file corrupt"));
1106 fd = setup_rerere(r, &merge_rr, RERERE_NOAUTOUPDATE);
1107 if (fd < 0)
1108 return 0;
1111 * The paths may have been resolved (incorrectly);
1112 * recover the original conflicted state and then
1113 * find the conflicted paths.
1115 unmerge_index(r->index, pathspec, 0);
1116 find_conflict(r, &conflict);
1117 for (i = 0; i < conflict.nr; i++) {
1118 struct string_list_item *it = &conflict.items[i];
1119 if (!match_pathspec(r->index, pathspec, it->string,
1120 strlen(it->string), 0, NULL, 0))
1121 continue;
1122 rerere_forget_one_path(r->index, it->string, &merge_rr);
1124 return write_rr(&merge_rr, fd);
1128 * Garbage collection support
1131 static timestamp_t rerere_created_at(struct rerere_id *id)
1133 struct stat st;
1135 return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
1138 static timestamp_t rerere_last_used_at(struct rerere_id *id)
1140 struct stat st;
1142 return stat(rerere_path(id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
1146 * Remove the recorded resolution for a given conflict ID
1148 static void unlink_rr_item(struct rerere_id *id)
1150 unlink_or_warn(rerere_path(id, "thisimage"));
1151 remove_variant(id);
1152 id->collection->status[id->variant] = 0;
1155 static void prune_one(struct rerere_id *id,
1156 timestamp_t cutoff_resolve, timestamp_t cutoff_noresolve)
1158 timestamp_t then;
1159 timestamp_t cutoff;
1161 then = rerere_last_used_at(id);
1162 if (then)
1163 cutoff = cutoff_resolve;
1164 else {
1165 then = rerere_created_at(id);
1166 if (!then)
1167 return;
1168 cutoff = cutoff_noresolve;
1170 if (then < cutoff)
1171 unlink_rr_item(id);
1174 /* Does the basename in "path" look plausibly like an rr-cache entry? */
1175 static int is_rr_cache_dirname(const char *path)
1177 struct object_id oid;
1178 const char *end;
1179 return !parse_oid_hex(path, &oid, &end) && !*end;
1182 void rerere_gc(struct repository *r, struct string_list *rr)
1184 struct string_list to_remove = STRING_LIST_INIT_DUP;
1185 DIR *dir;
1186 struct dirent *e;
1187 int i;
1188 timestamp_t now = time(NULL);
1189 timestamp_t cutoff_noresolve = now - 15 * 86400;
1190 timestamp_t cutoff_resolve = now - 60 * 86400;
1192 if (setup_rerere(r, rr, 0) < 0)
1193 return;
1195 git_config_get_expiry_in_days("gc.rerereresolved", &cutoff_resolve, now);
1196 git_config_get_expiry_in_days("gc.rerereunresolved", &cutoff_noresolve, now);
1197 git_config(git_default_config, NULL);
1198 dir = opendir(git_path("rr-cache"));
1199 if (!dir)
1200 die_errno(_("unable to open rr-cache directory"));
1201 /* Collect stale conflict IDs ... */
1202 while ((e = readdir_skip_dot_and_dotdot(dir))) {
1203 struct rerere_dir *rr_dir;
1204 struct rerere_id id;
1205 int now_empty;
1207 if (!is_rr_cache_dirname(e->d_name))
1208 continue; /* or should we remove e->d_name? */
1210 rr_dir = find_rerere_dir(e->d_name);
1212 now_empty = 1;
1213 for (id.variant = 0, id.collection = rr_dir;
1214 id.variant < id.collection->status_nr;
1215 id.variant++) {
1216 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1217 if (id.collection->status[id.variant])
1218 now_empty = 0;
1220 if (now_empty)
1221 string_list_append(&to_remove, e->d_name);
1223 closedir(dir);
1225 /* ... and then remove the empty directories */
1226 for (i = 0; i < to_remove.nr; i++)
1227 rmdir(git_path("rr-cache/%s", to_remove.items[i].string));
1228 string_list_clear(&to_remove, 0);
1229 rollback_lock_file(&write_lock);
1233 * During a conflict resolution, after "rerere" recorded the
1234 * preimages, abandon them if the user did not resolve them or
1235 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1237 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1239 void rerere_clear(struct repository *r, struct string_list *merge_rr)
1241 int i;
1243 if (setup_rerere(r, merge_rr, 0) < 0)
1244 return;
1246 for (i = 0; i < merge_rr->nr; i++) {
1247 struct rerere_id *id = merge_rr->items[i].util;
1248 if (!has_rerere_resolution(id)) {
1249 unlink_rr_item(id);
1250 rmdir(rerere_path(id, NULL));
1253 unlink_or_warn(git_path_merge_rr(r));
1254 rollback_lock_file(&write_lock);