rerere: convert to use the_hash_algo
[git/git-svn.git] / rerere.c
blobceb98015ffa0617f11894dc00c62b174f45c5e4c
1 #include "cache.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "string-list.h"
5 #include "rerere.h"
6 #include "xdiff-interface.h"
7 #include "dir.h"
8 #include "resolve-undo.h"
9 #include "ll-merge.h"
10 #include "attr.h"
11 #include "pathspec.h"
12 #include "object-store.h"
13 #include "sha1-lookup.h"
15 #define RESOLVED 0
16 #define PUNTED 1
17 #define THREE_STAGED 2
18 void *RERERE_RESOLVED = &RERERE_RESOLVED;
20 /* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
21 static int rerere_enabled = -1;
23 /* automatically update cleanly resolved paths to the index */
24 static int rerere_autoupdate;
26 static int rerere_dir_nr;
27 static int rerere_dir_alloc;
29 #define RR_HAS_POSTIMAGE 1
30 #define RR_HAS_PREIMAGE 2
31 static struct rerere_dir {
32 unsigned char hash[GIT_MAX_HEXSZ];
33 int status_alloc, status_nr;
34 unsigned char *status;
35 } **rerere_dir;
37 static void free_rerere_dirs(void)
39 int i;
40 for (i = 0; i < rerere_dir_nr; i++) {
41 free(rerere_dir[i]->status);
42 free(rerere_dir[i]);
44 FREE_AND_NULL(rerere_dir);
45 rerere_dir_nr = rerere_dir_alloc = 0;
48 static void free_rerere_id(struct string_list_item *item)
50 free(item->util);
53 static const char *rerere_id_hex(const struct rerere_id *id)
55 return sha1_to_hex(id->collection->hash);
58 static void fit_variant(struct rerere_dir *rr_dir, int variant)
60 variant++;
61 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
62 if (rr_dir->status_nr < variant) {
63 memset(rr_dir->status + rr_dir->status_nr,
64 '\0', variant - rr_dir->status_nr);
65 rr_dir->status_nr = variant;
69 static void assign_variant(struct rerere_id *id)
71 int variant;
72 struct rerere_dir *rr_dir = id->collection;
74 variant = id->variant;
75 if (variant < 0) {
76 for (variant = 0; variant < rr_dir->status_nr; variant++)
77 if (!rr_dir->status[variant])
78 break;
80 fit_variant(rr_dir, variant);
81 id->variant = variant;
84 const char *rerere_path(const struct rerere_id *id, const char *file)
86 if (!file)
87 return git_path("rr-cache/%s", rerere_id_hex(id));
89 if (id->variant <= 0)
90 return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
92 return git_path("rr-cache/%s/%s.%d",
93 rerere_id_hex(id), file, id->variant);
96 static int is_rr_file(const char *name, const char *filename, int *variant)
98 const char *suffix;
99 char *ep;
101 if (!strcmp(name, filename)) {
102 *variant = 0;
103 return 1;
105 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
106 return 0;
108 errno = 0;
109 *variant = strtol(suffix + 1, &ep, 10);
110 if (errno || *ep)
111 return 0;
112 return 1;
115 static void scan_rerere_dir(struct rerere_dir *rr_dir)
117 struct dirent *de;
118 DIR *dir = opendir(git_path("rr-cache/%s", sha1_to_hex(rr_dir->hash)));
120 if (!dir)
121 return;
122 while ((de = readdir(dir)) != NULL) {
123 int variant;
125 if (is_rr_file(de->d_name, "postimage", &variant)) {
126 fit_variant(rr_dir, variant);
127 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
128 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
129 fit_variant(rr_dir, variant);
130 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
133 closedir(dir);
136 static const unsigned char *rerere_dir_hash(size_t i, void *table)
138 struct rerere_dir **rr_dir = table;
139 return rr_dir[i]->hash;
142 static struct rerere_dir *find_rerere_dir(const char *hex)
144 unsigned char hash[GIT_MAX_RAWSZ];
145 struct rerere_dir *rr_dir;
146 int pos;
148 if (get_sha1_hex(hex, hash))
149 return NULL; /* BUG */
150 pos = sha1_pos(hash, rerere_dir, rerere_dir_nr, rerere_dir_hash);
151 if (pos < 0) {
152 rr_dir = xmalloc(sizeof(*rr_dir));
153 hashcpy(rr_dir->hash, hash);
154 rr_dir->status = NULL;
155 rr_dir->status_nr = 0;
156 rr_dir->status_alloc = 0;
157 pos = -1 - pos;
159 /* Make sure the array is big enough ... */
160 ALLOC_GROW(rerere_dir, rerere_dir_nr + 1, rerere_dir_alloc);
161 /* ... and add it in. */
162 rerere_dir_nr++;
163 MOVE_ARRAY(rerere_dir + pos + 1, rerere_dir + pos,
164 rerere_dir_nr - pos - 1);
165 rerere_dir[pos] = rr_dir;
166 scan_rerere_dir(rr_dir);
168 return rerere_dir[pos];
171 static int has_rerere_resolution(const struct rerere_id *id)
173 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
174 int variant = id->variant;
176 if (variant < 0)
177 return 0;
178 return ((id->collection->status[variant] & both) == both);
181 static struct rerere_id *new_rerere_id_hex(char *hex)
183 struct rerere_id *id = xmalloc(sizeof(*id));
184 id->collection = find_rerere_dir(hex);
185 id->variant = -1; /* not known yet */
186 return id;
189 static struct rerere_id *new_rerere_id(unsigned char *sha1)
191 return new_rerere_id_hex(sha1_to_hex(sha1));
195 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
196 * "conflict ID", a HT and pathname, terminated with a NUL, and is
197 * used to keep track of the set of paths that "rerere" may need to
198 * work on (i.e. what is left by the previous invocation of "git
199 * rerere" during the current conflict resolution session).
201 static void read_rr(struct string_list *rr)
203 struct strbuf buf = STRBUF_INIT;
204 FILE *in = fopen_or_warn(git_path_merge_rr(the_repository), "r");
206 if (!in)
207 return;
208 while (!strbuf_getwholeline(&buf, in, '\0')) {
209 char *path;
210 unsigned char hash[GIT_MAX_RAWSZ];
211 struct rerere_id *id;
212 int variant;
213 const unsigned hexsz = the_hash_algo->hexsz;
215 /* There has to be the hash, tab, path and then NUL */
216 if (buf.len < hexsz + 2 || get_sha1_hex(buf.buf, hash))
217 die(_("corrupt MERGE_RR"));
219 if (buf.buf[hexsz] != '.') {
220 variant = 0;
221 path = buf.buf + hexsz;
222 } else {
223 errno = 0;
224 variant = strtol(buf.buf + hexsz + 1, &path, 10);
225 if (errno)
226 die(_("corrupt MERGE_RR"));
228 if (*(path++) != '\t')
229 die(_("corrupt MERGE_RR"));
230 buf.buf[hexsz] = '\0';
231 id = new_rerere_id_hex(buf.buf);
232 id->variant = variant;
233 string_list_insert(rr, path)->util = id;
235 strbuf_release(&buf);
236 fclose(in);
239 static struct lock_file write_lock;
241 static int write_rr(struct string_list *rr, int out_fd)
243 int i;
244 for (i = 0; i < rr->nr; i++) {
245 struct strbuf buf = STRBUF_INIT;
246 struct rerere_id *id;
248 assert(rr->items[i].util != RERERE_RESOLVED);
250 id = rr->items[i].util;
251 if (!id)
252 continue;
253 assert(id->variant >= 0);
254 if (0 < id->variant)
255 strbuf_addf(&buf, "%s.%d\t%s%c",
256 rerere_id_hex(id), id->variant,
257 rr->items[i].string, 0);
258 else
259 strbuf_addf(&buf, "%s\t%s%c",
260 rerere_id_hex(id),
261 rr->items[i].string, 0);
263 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
264 die(_("unable to write rerere record"));
266 strbuf_release(&buf);
268 if (commit_lock_file(&write_lock) != 0)
269 die(_("unable to write rerere record"));
270 return 0;
274 * "rerere" interacts with conflicted file contents using this I/O
275 * abstraction. It reads a conflicted contents from one place via
276 * "getline()" method, and optionally can write it out after
277 * normalizing the conflicted hunks to the "output". Subclasses of
278 * rerere_io embed this structure at the beginning of their own
279 * rerere_io object.
281 struct rerere_io {
282 int (*getline)(struct strbuf *, struct rerere_io *);
283 FILE *output;
284 int wrerror;
285 /* some more stuff */
288 static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
290 if (!count || *err)
291 return;
292 if (fwrite(p, count, 1, fp) != 1)
293 *err = errno;
296 static inline void ferr_puts(const char *s, FILE *fp, int *err)
298 ferr_write(s, strlen(s), fp, err);
301 static void rerere_io_putstr(const char *str, struct rerere_io *io)
303 if (io->output)
304 ferr_puts(str, io->output, &io->wrerror);
307 static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
309 if (io->output)
310 ferr_write(mem, sz, io->output, &io->wrerror);
314 * Subclass of rerere_io that reads from an on-disk file
316 struct rerere_io_file {
317 struct rerere_io io;
318 FILE *input;
322 * ... and its getline() method implementation
324 static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
326 struct rerere_io_file *io = (struct rerere_io_file *)io_;
327 return strbuf_getwholeline(sb, io->input, '\n');
331 * Require the exact number of conflict marker letters, no more, no
332 * less, followed by SP or any whitespace
333 * (including LF).
335 static int is_cmarker(char *buf, int marker_char, int marker_size)
337 int want_sp;
340 * The beginning of our version and the end of their version
341 * always are labeled like "<<<<< ours" or ">>>>> theirs",
342 * hence we set want_sp for them. Note that the version from
343 * the common ancestor in diff3-style output is not always
344 * labelled (e.g. "||||| common" is often seen but "|||||"
345 * alone is also valid), so we do not set want_sp.
347 want_sp = (marker_char == '<') || (marker_char == '>');
349 while (marker_size--)
350 if (*buf++ != marker_char)
351 return 0;
352 if (want_sp && *buf != ' ')
353 return 0;
354 return isspace(*buf);
357 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
359 strbuf_addchars(buf, ch, size);
360 strbuf_addch(buf, '\n');
363 static int handle_conflict(struct strbuf *out, struct rerere_io *io,
364 int marker_size, git_hash_ctx *ctx)
366 enum {
367 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
368 } hunk = RR_SIDE_1;
369 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
370 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
371 int has_conflicts = -1;
373 while (!io->getline(&buf, io)) {
374 if (is_cmarker(buf.buf, '<', marker_size)) {
375 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
376 break;
377 if (hunk == RR_SIDE_1)
378 strbuf_addbuf(&one, &conflict);
379 else
380 strbuf_addbuf(&two, &conflict);
381 strbuf_release(&conflict);
382 } else if (is_cmarker(buf.buf, '|', marker_size)) {
383 if (hunk != RR_SIDE_1)
384 break;
385 hunk = RR_ORIGINAL;
386 } else if (is_cmarker(buf.buf, '=', marker_size)) {
387 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
388 break;
389 hunk = RR_SIDE_2;
390 } else if (is_cmarker(buf.buf, '>', marker_size)) {
391 if (hunk != RR_SIDE_2)
392 break;
393 if (strbuf_cmp(&one, &two) > 0)
394 strbuf_swap(&one, &two);
395 has_conflicts = 1;
396 rerere_strbuf_putconflict(out, '<', marker_size);
397 strbuf_addbuf(out, &one);
398 rerere_strbuf_putconflict(out, '=', marker_size);
399 strbuf_addbuf(out, &two);
400 rerere_strbuf_putconflict(out, '>', marker_size);
401 if (ctx) {
402 the_hash_algo->update_fn(ctx, one.buf ?
403 one.buf : "",
404 one.len + 1);
405 the_hash_algo->update_fn(ctx, two.buf ?
406 two.buf : "",
407 two.len + 1);
409 break;
410 } else if (hunk == RR_SIDE_1)
411 strbuf_addbuf(&one, &buf);
412 else if (hunk == RR_ORIGINAL)
413 ; /* discard */
414 else if (hunk == RR_SIDE_2)
415 strbuf_addbuf(&two, &buf);
417 strbuf_release(&one);
418 strbuf_release(&two);
419 strbuf_release(&buf);
421 return has_conflicts;
425 * Read contents a file with conflicts, normalize the conflicts
426 * by (1) discarding the common ancestor version in diff3-style,
427 * (2) reordering our side and their side so that whichever sorts
428 * alphabetically earlier comes before the other one, while
429 * computing the "conflict ID", which is just an SHA-1 hash of
430 * one side of the conflict, NUL, the other side of the conflict,
431 * and NUL concatenated together.
433 * Return 1 if conflict hunks are found, 0 if there are no conflict
434 * hunks and -1 if an error occured.
436 static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
438 git_hash_ctx ctx;
439 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
440 int has_conflicts = 0;
441 if (hash)
442 the_hash_algo->init_fn(&ctx);
444 while (!io->getline(&buf, io)) {
445 if (is_cmarker(buf.buf, '<', marker_size)) {
446 has_conflicts = handle_conflict(&out, io, marker_size,
447 hash ? &ctx : NULL);
448 if (has_conflicts < 0)
449 break;
450 rerere_io_putmem(out.buf, out.len, io);
451 strbuf_reset(&out);
452 } else
453 rerere_io_putstr(buf.buf, io);
455 strbuf_release(&buf);
456 strbuf_release(&out);
458 if (hash)
459 the_hash_algo->final_fn(hash, &ctx);
461 return has_conflicts;
465 * Scan the path for conflicts, do the "handle_path()" thing above, and
466 * return the number of conflict hunks found.
468 static int handle_file(const char *path, unsigned char *hash, const char *output)
470 int has_conflicts = 0;
471 struct rerere_io_file io;
472 int marker_size = ll_merge_marker_size(path);
474 memset(&io, 0, sizeof(io));
475 io.io.getline = rerere_file_getline;
476 io.input = fopen(path, "r");
477 io.io.wrerror = 0;
478 if (!io.input)
479 return error_errno(_("could not open '%s'"), path);
481 if (output) {
482 io.io.output = fopen(output, "w");
483 if (!io.io.output) {
484 error_errno(_("could not write '%s'"), output);
485 fclose(io.input);
486 return -1;
490 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
492 fclose(io.input);
493 if (io.io.wrerror)
494 error(_("there were errors while writing '%s' (%s)"),
495 path, strerror(io.io.wrerror));
496 if (io.io.output && fclose(io.io.output))
497 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
499 if (has_conflicts < 0) {
500 if (output)
501 unlink_or_warn(output);
502 return error(_("could not parse conflict hunks in '%s'"), path);
504 if (io.io.wrerror)
505 return -1;
506 return has_conflicts;
510 * Look at a cache entry at "i" and see if it is not conflicting,
511 * conflicting and we are willing to handle, or conflicting and
512 * we are unable to handle, and return the determination in *type.
513 * Return the cache index to be looked at next, by skipping the
514 * stages we have already looked at in this invocation of this
515 * function.
517 static int check_one_conflict(int i, int *type)
519 const struct cache_entry *e = active_cache[i];
521 if (!ce_stage(e)) {
522 *type = RESOLVED;
523 return i + 1;
526 *type = PUNTED;
527 while (i < active_nr && ce_stage(active_cache[i]) == 1)
528 i++;
530 /* Only handle regular files with both stages #2 and #3 */
531 if (i + 1 < active_nr) {
532 const struct cache_entry *e2 = active_cache[i];
533 const struct cache_entry *e3 = active_cache[i + 1];
534 if (ce_stage(e2) == 2 &&
535 ce_stage(e3) == 3 &&
536 ce_same_name(e, e3) &&
537 S_ISREG(e2->ce_mode) &&
538 S_ISREG(e3->ce_mode))
539 *type = THREE_STAGED;
542 /* Skip the entries with the same name */
543 while (i < active_nr && ce_same_name(e, active_cache[i]))
544 i++;
545 return i;
549 * Scan the index and find paths that have conflicts that rerere can
550 * handle, i.e. the ones that has both stages #2 and #3.
552 * NEEDSWORK: we do not record or replay a previous "resolve by
553 * deletion" for a delete-modify conflict, as that is inherently risky
554 * without knowing what modification is being discarded. The only
555 * safe case, i.e. both side doing the deletion and modification that
556 * are identical to the previous round, might want to be handled,
557 * though.
559 static int find_conflict(struct string_list *conflict)
561 int i;
562 if (read_cache() < 0)
563 return error(_("index file corrupt"));
565 for (i = 0; i < active_nr;) {
566 int conflict_type;
567 const struct cache_entry *e = active_cache[i];
568 i = check_one_conflict(i, &conflict_type);
569 if (conflict_type == THREE_STAGED)
570 string_list_insert(conflict, (const char *)e->name);
572 return 0;
576 * The merge_rr list is meant to hold outstanding conflicted paths
577 * that rerere could handle. Abuse the list by adding other types of
578 * entries to allow the caller to show "rerere remaining".
580 * - Conflicted paths that rerere does not handle are added
581 * - Conflicted paths that have been resolved are marked as such
582 * by storing RERERE_RESOLVED to .util field (where conflict ID
583 * is expected to be stored).
585 * Do *not* write MERGE_RR file out after calling this function.
587 * NEEDSWORK: we may want to fix the caller that implements "rerere
588 * remaining" to do this without abusing merge_rr.
590 int rerere_remaining(struct string_list *merge_rr)
592 int i;
593 if (setup_rerere(merge_rr, RERERE_READONLY))
594 return 0;
595 if (read_cache() < 0)
596 return error(_("index file corrupt"));
598 for (i = 0; i < active_nr;) {
599 int conflict_type;
600 const struct cache_entry *e = active_cache[i];
601 i = check_one_conflict(i, &conflict_type);
602 if (conflict_type == PUNTED)
603 string_list_insert(merge_rr, (const char *)e->name);
604 else if (conflict_type == RESOLVED) {
605 struct string_list_item *it;
606 it = string_list_lookup(merge_rr, (const char *)e->name);
607 if (it != NULL) {
608 free_rerere_id(it);
609 it->util = RERERE_RESOLVED;
613 return 0;
617 * Try using the given conflict resolution "ID" to see
618 * if that recorded conflict resolves cleanly what we
619 * got in the "cur".
621 static int try_merge(const struct rerere_id *id, const char *path,
622 mmfile_t *cur, mmbuffer_t *result)
624 int ret;
625 mmfile_t base = {NULL, 0}, other = {NULL, 0};
627 if (read_mmfile(&base, rerere_path(id, "preimage")) ||
628 read_mmfile(&other, rerere_path(id, "postimage")))
629 ret = 1;
630 else
632 * A three-way merge. Note that this honors user-customizable
633 * low-level merge driver settings.
635 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "", NULL);
637 free(base.ptr);
638 free(other.ptr);
640 return ret;
644 * Find the conflict identified by "id"; the change between its
645 * "preimage" (i.e. a previous contents with conflict markers) and its
646 * "postimage" (i.e. the corresponding contents with conflicts
647 * resolved) may apply cleanly to the contents stored in "path", i.e.
648 * the conflict this time around.
650 * Returns 0 for successful replay of recorded resolution, or non-zero
651 * for failure.
653 static int merge(const struct rerere_id *id, const char *path)
655 FILE *f;
656 int ret;
657 mmfile_t cur = {NULL, 0};
658 mmbuffer_t result = {NULL, 0};
661 * Normalize the conflicts in path and write it out to
662 * "thisimage" temporary file.
664 if ((handle_file(path, NULL, rerere_path(id, "thisimage")) < 0) ||
665 read_mmfile(&cur, rerere_path(id, "thisimage"))) {
666 ret = 1;
667 goto out;
670 ret = try_merge(id, path, &cur, &result);
671 if (ret)
672 goto out;
675 * A successful replay of recorded resolution.
676 * Mark that "postimage" was used to help gc.
678 if (utime(rerere_path(id, "postimage"), NULL) < 0)
679 warning_errno(_("failed utime() on '%s'"),
680 rerere_path(id, "postimage"));
682 /* Update "path" with the resolution */
683 f = fopen(path, "w");
684 if (!f)
685 return error_errno(_("could not open '%s'"), path);
686 if (fwrite(result.ptr, result.size, 1, f) != 1)
687 error_errno(_("could not write '%s'"), path);
688 if (fclose(f))
689 return error_errno(_("writing '%s' failed"), path);
691 out:
692 free(cur.ptr);
693 free(result.ptr);
695 return ret;
698 static void update_paths(struct string_list *update)
700 struct lock_file index_lock = LOCK_INIT;
701 int i;
703 hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
705 for (i = 0; i < update->nr; i++) {
706 struct string_list_item *item = &update->items[i];
707 if (add_file_to_cache(item->string, 0))
708 exit(128);
709 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
710 item->string);
713 if (write_locked_index(&the_index, &index_lock,
714 COMMIT_LOCK | SKIP_IF_UNCHANGED))
715 die(_("unable to write new index file"));
718 static void remove_variant(struct rerere_id *id)
720 unlink_or_warn(rerere_path(id, "postimage"));
721 unlink_or_warn(rerere_path(id, "preimage"));
722 id->collection->status[id->variant] = 0;
726 * The path indicated by rr_item may still have conflict for which we
727 * have a recorded resolution, in which case replay it and optionally
728 * update it. Or it may have been resolved by the user and we may
729 * only have the preimage for that conflict, in which case the result
730 * needs to be recorded as a resolution in a postimage file.
732 static void do_rerere_one_path(struct string_list_item *rr_item,
733 struct string_list *update)
735 const char *path = rr_item->string;
736 struct rerere_id *id = rr_item->util;
737 struct rerere_dir *rr_dir = id->collection;
738 int variant;
740 variant = id->variant;
742 /* Has the user resolved it already? */
743 if (variant >= 0) {
744 if (!handle_file(path, NULL, NULL)) {
745 copy_file(rerere_path(id, "postimage"), path, 0666);
746 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
747 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
748 free_rerere_id(rr_item);
749 rr_item->util = NULL;
750 return;
753 * There may be other variants that can cleanly
754 * replay. Try them and update the variant number for
755 * this one.
759 /* Does any existing resolution apply cleanly? */
760 for (variant = 0; variant < rr_dir->status_nr; variant++) {
761 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
762 struct rerere_id vid = *id;
764 if ((rr_dir->status[variant] & both) != both)
765 continue;
767 vid.variant = variant;
768 if (merge(&vid, path))
769 continue; /* failed to replay */
772 * If there already is a different variant that applies
773 * cleanly, there is no point maintaining our own variant.
775 if (0 <= id->variant && id->variant != variant)
776 remove_variant(id);
778 if (rerere_autoupdate)
779 string_list_insert(update, path);
780 else
781 fprintf_ln(stderr,
782 _("Resolved '%s' using previous resolution."),
783 path);
784 free_rerere_id(rr_item);
785 rr_item->util = NULL;
786 return;
789 /* None of the existing one applies; we need a new variant */
790 assign_variant(id);
792 variant = id->variant;
793 handle_file(path, NULL, rerere_path(id, "preimage"));
794 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
795 const char *path = rerere_path(id, "postimage");
796 if (unlink(path))
797 die_errno(_("cannot unlink stray '%s'"), path);
798 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
800 id->collection->status[variant] |= RR_HAS_PREIMAGE;
801 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
804 static int do_plain_rerere(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(&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(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(&rr->items[i], &update);
847 if (update.nr)
848 update_paths(&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 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(the_repository),
893 LOCK_DIE_ON_ERROR);
894 read_rr(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 rerere(int flags)
905 struct string_list merge_rr = STRING_LIST_INIT_DUP;
906 int fd, status;
908 fd = setup_rerere(&merge_rr, flags);
909 if (fd < 0)
910 return 0;
911 status = do_plain_rerere(&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(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(path);
958 * Reproduce the conflicted merge in-core
960 len = strlen(path);
961 pos = cache_name_pos(path, len);
962 if (0 <= pos)
963 return -1;
964 pos = -pos - 1;
966 while (pos < active_nr) {
967 enum object_type type;
968 unsigned long size;
970 ce = active_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 = read_object_file(&ce->oid, &type,
976 &size);
977 mmfile[i].size = size;
980 for (i = 0; i < 3; i++)
981 if (!mmfile[i].ptr && !mmfile[i].size)
982 mmfile[i].ptr = xstrdup("");
985 * NEEDSWORK: handle conflicts from merges with
986 * merge.renormalize set, too?
988 ll_merge(&result, path, &mmfile[0], NULL,
989 &mmfile[1], "ours",
990 &mmfile[2], "theirs", NULL);
991 for (i = 0; i < 3; i++)
992 free(mmfile[i].ptr);
994 memset(&io, 0, sizeof(io));
995 io.io.getline = rerere_mem_getline;
996 if (output)
997 io.io.output = fopen(output, "w");
998 else
999 io.io.output = NULL;
1000 strbuf_init(&io.input, 0);
1001 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1004 * Grab the conflict ID and optionally write the original
1005 * contents with conflict markers out.
1007 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1008 strbuf_release(&io.input);
1009 if (io.io.output)
1010 fclose(io.io.output);
1011 return has_conflicts;
1014 static int rerere_forget_one_path(const char *path, struct string_list *rr)
1016 const char *filename;
1017 struct rerere_id *id;
1018 unsigned char hash[GIT_MAX_RAWSZ];
1019 int ret;
1020 struct string_list_item *item;
1023 * Recreate the original conflict from the stages in the
1024 * index and compute the conflict ID
1026 ret = handle_cache(path, hash, NULL);
1027 if (ret < 1)
1028 return error(_("could not parse conflict hunks in '%s'"), path);
1030 /* Nuke the recorded resolution for the conflict */
1031 id = new_rerere_id(hash);
1033 for (id->variant = 0;
1034 id->variant < id->collection->status_nr;
1035 id->variant++) {
1036 mmfile_t cur = { NULL, 0 };
1037 mmbuffer_t result = {NULL, 0};
1038 int cleanly_resolved;
1040 if (!has_rerere_resolution(id))
1041 continue;
1043 handle_cache(path, hash, rerere_path(id, "thisimage"));
1044 if (read_mmfile(&cur, rerere_path(id, "thisimage"))) {
1045 free(cur.ptr);
1046 error(_("failed to update conflicted state in '%s'"), path);
1047 goto fail_exit;
1049 cleanly_resolved = !try_merge(id, path, &cur, &result);
1050 free(result.ptr);
1051 free(cur.ptr);
1052 if (cleanly_resolved)
1053 break;
1056 if (id->collection->status_nr <= id->variant) {
1057 error(_("no remembered resolution for '%s'"), path);
1058 goto fail_exit;
1061 filename = rerere_path(id, "postimage");
1062 if (unlink(filename)) {
1063 if (errno == ENOENT)
1064 error(_("no remembered resolution for '%s'"), path);
1065 else
1066 error_errno(_("cannot unlink '%s'"), filename);
1067 goto fail_exit;
1071 * Update the preimage so that the user can resolve the
1072 * conflict in the working tree, run us again to record
1073 * the postimage.
1075 handle_cache(path, hash, rerere_path(id, "preimage"));
1076 fprintf_ln(stderr, _("Updated preimage for '%s'"), path);
1079 * And remember that we can record resolution for this
1080 * conflict when the user is done.
1082 item = string_list_insert(rr, path);
1083 free_rerere_id(item);
1084 item->util = id;
1085 fprintf(stderr, _("Forgot resolution for '%s'\n"), path);
1086 return 0;
1088 fail_exit:
1089 free(id);
1090 return -1;
1093 int rerere_forget(struct pathspec *pathspec)
1095 int i, fd;
1096 struct string_list conflict = STRING_LIST_INIT_DUP;
1097 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1099 if (read_cache() < 0)
1100 return error(_("index file corrupt"));
1102 fd = setup_rerere(&merge_rr, RERERE_NOAUTOUPDATE);
1103 if (fd < 0)
1104 return 0;
1107 * The paths may have been resolved (incorrectly);
1108 * recover the original conflicted state and then
1109 * find the conflicted paths.
1111 unmerge_cache(pathspec);
1112 find_conflict(&conflict);
1113 for (i = 0; i < conflict.nr; i++) {
1114 struct string_list_item *it = &conflict.items[i];
1115 if (!match_pathspec(&the_index, pathspec, it->string,
1116 strlen(it->string), 0, NULL, 0))
1117 continue;
1118 rerere_forget_one_path(it->string, &merge_rr);
1120 return write_rr(&merge_rr, fd);
1124 * Garbage collection support
1127 static timestamp_t rerere_created_at(struct rerere_id *id)
1129 struct stat st;
1131 return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
1134 static timestamp_t rerere_last_used_at(struct rerere_id *id)
1136 struct stat st;
1138 return stat(rerere_path(id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
1142 * Remove the recorded resolution for a given conflict ID
1144 static void unlink_rr_item(struct rerere_id *id)
1146 unlink_or_warn(rerere_path(id, "thisimage"));
1147 remove_variant(id);
1148 id->collection->status[id->variant] = 0;
1151 static void prune_one(struct rerere_id *id,
1152 timestamp_t cutoff_resolve, timestamp_t cutoff_noresolve)
1154 timestamp_t then;
1155 timestamp_t cutoff;
1157 then = rerere_last_used_at(id);
1158 if (then)
1159 cutoff = cutoff_resolve;
1160 else {
1161 then = rerere_created_at(id);
1162 if (!then)
1163 return;
1164 cutoff = cutoff_noresolve;
1166 if (then < cutoff)
1167 unlink_rr_item(id);
1170 void rerere_gc(struct string_list *rr)
1172 struct string_list to_remove = STRING_LIST_INIT_DUP;
1173 DIR *dir;
1174 struct dirent *e;
1175 int i;
1176 timestamp_t now = time(NULL);
1177 timestamp_t cutoff_noresolve = now - 15 * 86400;
1178 timestamp_t cutoff_resolve = now - 60 * 86400;
1180 if (setup_rerere(rr, 0) < 0)
1181 return;
1183 git_config_get_expiry_in_days("gc.rerereresolved", &cutoff_resolve, now);
1184 git_config_get_expiry_in_days("gc.rerereunresolved", &cutoff_noresolve, now);
1185 git_config(git_default_config, NULL);
1186 dir = opendir(git_path("rr-cache"));
1187 if (!dir)
1188 die_errno(_("unable to open rr-cache directory"));
1189 /* Collect stale conflict IDs ... */
1190 while ((e = readdir(dir))) {
1191 struct rerere_dir *rr_dir;
1192 struct rerere_id id;
1193 int now_empty;
1195 if (is_dot_or_dotdot(e->d_name))
1196 continue;
1197 rr_dir = find_rerere_dir(e->d_name);
1198 if (!rr_dir)
1199 continue; /* or should we remove e->d_name? */
1201 now_empty = 1;
1202 for (id.variant = 0, id.collection = rr_dir;
1203 id.variant < id.collection->status_nr;
1204 id.variant++) {
1205 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1206 if (id.collection->status[id.variant])
1207 now_empty = 0;
1209 if (now_empty)
1210 string_list_append(&to_remove, e->d_name);
1212 closedir(dir);
1214 /* ... and then remove the empty directories */
1215 for (i = 0; i < to_remove.nr; i++)
1216 rmdir(git_path("rr-cache/%s", to_remove.items[i].string));
1217 string_list_clear(&to_remove, 0);
1218 rollback_lock_file(&write_lock);
1222 * During a conflict resolution, after "rerere" recorded the
1223 * preimages, abandon them if the user did not resolve them or
1224 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1226 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1228 void rerere_clear(struct string_list *merge_rr)
1230 int i;
1232 if (setup_rerere(merge_rr, 0) < 0)
1233 return;
1235 for (i = 0; i < merge_rr->nr; i++) {
1236 struct rerere_id *id = merge_rr->items[i].util;
1237 if (!has_rerere_resolution(id)) {
1238 unlink_rr_item(id);
1239 rmdir(rerere_path(id, NULL));
1242 unlink_or_warn(git_path_merge_rr(the_repository));
1243 rollback_lock_file(&write_lock);