Merge branch 'fc/doc-use-datestamp-in-commit'
[git.git] / rerere.c
blob7abc94bf444dc18fe0eb4d170845bf54c9a7370e
1 #include "cache.h"
2 #include "abspath.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "gettext.h"
6 #include "hex.h"
7 #include "lockfile.h"
8 #include "string-list.h"
9 #include "rerere.h"
10 #include "xdiff-interface.h"
11 #include "dir.h"
12 #include "resolve-undo.h"
13 #include "ll-merge.h"
14 #include "attr.h"
15 #include "pathspec.h"
16 #include "object-file.h"
17 #include "object-store.h"
18 #include "hash-lookup.h"
19 #include "strmap.h"
20 #include "wrapper.h"
22 #define RESOLVED 0
23 #define PUNTED 1
24 #define THREE_STAGED 2
25 void *RERERE_RESOLVED = &RERERE_RESOLVED;
27 /* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
28 static int rerere_enabled = -1;
30 /* automatically update cleanly resolved paths to the index */
31 static int rerere_autoupdate;
33 #define RR_HAS_POSTIMAGE 1
34 #define RR_HAS_PREIMAGE 2
35 struct rerere_dir {
36 int status_alloc, status_nr;
37 unsigned char *status;
38 char name[FLEX_ARRAY];
41 static struct strmap rerere_dirs = STRMAP_INIT;
43 static void free_rerere_dirs(void)
45 struct hashmap_iter iter;
46 struct strmap_entry *ent;
48 strmap_for_each_entry(&rerere_dirs, &iter, ent) {
49 struct rerere_dir *rr_dir = ent->value;
50 free(rr_dir->status);
51 free(rr_dir);
53 strmap_clear(&rerere_dirs, 0);
56 static void free_rerere_id(struct string_list_item *item)
58 free(item->util);
61 static const char *rerere_id_hex(const struct rerere_id *id)
63 return id->collection->name;
66 static void fit_variant(struct rerere_dir *rr_dir, int variant)
68 variant++;
69 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
70 if (rr_dir->status_nr < variant) {
71 memset(rr_dir->status + rr_dir->status_nr,
72 '\0', variant - rr_dir->status_nr);
73 rr_dir->status_nr = variant;
77 static void assign_variant(struct rerere_id *id)
79 int variant;
80 struct rerere_dir *rr_dir = id->collection;
82 variant = id->variant;
83 if (variant < 0) {
84 for (variant = 0; variant < rr_dir->status_nr; variant++)
85 if (!rr_dir->status[variant])
86 break;
88 fit_variant(rr_dir, variant);
89 id->variant = variant;
92 const char *rerere_path(const struct rerere_id *id, const char *file)
94 if (!file)
95 return git_path("rr-cache/%s", rerere_id_hex(id));
97 if (id->variant <= 0)
98 return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
100 return git_path("rr-cache/%s/%s.%d",
101 rerere_id_hex(id), file, id->variant);
104 static int is_rr_file(const char *name, const char *filename, int *variant)
106 const char *suffix;
107 char *ep;
109 if (!strcmp(name, filename)) {
110 *variant = 0;
111 return 1;
113 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
114 return 0;
116 errno = 0;
117 *variant = strtol(suffix + 1, &ep, 10);
118 if (errno || *ep)
119 return 0;
120 return 1;
123 static void scan_rerere_dir(struct rerere_dir *rr_dir)
125 struct dirent *de;
126 DIR *dir = opendir(git_path("rr-cache/%s", rr_dir->name));
128 if (!dir)
129 return;
130 while ((de = readdir(dir)) != NULL) {
131 int variant;
133 if (is_rr_file(de->d_name, "postimage", &variant)) {
134 fit_variant(rr_dir, variant);
135 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
136 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
137 fit_variant(rr_dir, variant);
138 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
141 closedir(dir);
144 static struct rerere_dir *find_rerere_dir(const char *hex)
146 struct rerere_dir *rr_dir;
148 rr_dir = strmap_get(&rerere_dirs, hex);
149 if (!rr_dir) {
150 FLEX_ALLOC_STR(rr_dir, name, hex);
151 rr_dir->status = NULL;
152 rr_dir->status_nr = 0;
153 rr_dir->status_alloc = 0;
154 strmap_put(&rerere_dirs, hex, rr_dir);
156 scan_rerere_dir(rr_dir);
158 return rr_dir;
161 static int has_rerere_resolution(const struct rerere_id *id)
163 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
164 int variant = id->variant;
166 if (variant < 0)
167 return 0;
168 return ((id->collection->status[variant] & both) == both);
171 static struct rerere_id *new_rerere_id_hex(char *hex)
173 struct rerere_id *id = xmalloc(sizeof(*id));
174 id->collection = find_rerere_dir(hex);
175 id->variant = -1; /* not known yet */
176 return id;
179 static struct rerere_id *new_rerere_id(unsigned char *hash)
181 return new_rerere_id_hex(hash_to_hex(hash));
185 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
186 * "conflict ID", a HT and pathname, terminated with a NUL, and is
187 * used to keep track of the set of paths that "rerere" may need to
188 * work on (i.e. what is left by the previous invocation of "git
189 * rerere" during the current conflict resolution session).
191 static void read_rr(struct repository *r, struct string_list *rr)
193 struct strbuf buf = STRBUF_INIT;
194 FILE *in = fopen_or_warn(git_path_merge_rr(r), "r");
196 if (!in)
197 return;
198 while (!strbuf_getwholeline(&buf, in, '\0')) {
199 char *path;
200 unsigned char hash[GIT_MAX_RAWSZ];
201 struct rerere_id *id;
202 int variant;
203 const unsigned hexsz = the_hash_algo->hexsz;
205 /* There has to be the hash, tab, path and then NUL */
206 if (buf.len < hexsz + 2 || get_sha1_hex(buf.buf, hash))
207 die(_("corrupt MERGE_RR"));
209 if (buf.buf[hexsz] != '.') {
210 variant = 0;
211 path = buf.buf + hexsz;
212 } else {
213 errno = 0;
214 variant = strtol(buf.buf + hexsz + 1, &path, 10);
215 if (errno)
216 die(_("corrupt MERGE_RR"));
218 if (*(path++) != '\t')
219 die(_("corrupt MERGE_RR"));
220 buf.buf[hexsz] = '\0';
221 id = new_rerere_id_hex(buf.buf);
222 id->variant = variant;
223 string_list_insert(rr, path)->util = id;
225 strbuf_release(&buf);
226 fclose(in);
229 static struct lock_file write_lock;
231 static int write_rr(struct string_list *rr, int out_fd)
233 int i;
234 for (i = 0; i < rr->nr; i++) {
235 struct strbuf buf = STRBUF_INIT;
236 struct rerere_id *id;
238 assert(rr->items[i].util != RERERE_RESOLVED);
240 id = rr->items[i].util;
241 if (!id)
242 continue;
243 assert(id->variant >= 0);
244 if (0 < id->variant)
245 strbuf_addf(&buf, "%s.%d\t%s%c",
246 rerere_id_hex(id), id->variant,
247 rr->items[i].string, 0);
248 else
249 strbuf_addf(&buf, "%s\t%s%c",
250 rerere_id_hex(id),
251 rr->items[i].string, 0);
253 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
254 die(_("unable to write rerere record"));
256 strbuf_release(&buf);
258 if (commit_lock_file(&write_lock) != 0)
259 die(_("unable to write rerere record"));
260 return 0;
264 * "rerere" interacts with conflicted file contents using this I/O
265 * abstraction. It reads a conflicted contents from one place via
266 * "getline()" method, and optionally can write it out after
267 * normalizing the conflicted hunks to the "output". Subclasses of
268 * rerere_io embed this structure at the beginning of their own
269 * rerere_io object.
271 struct rerere_io {
272 int (*getline)(struct strbuf *, struct rerere_io *);
273 FILE *output;
274 int wrerror;
275 /* some more stuff */
278 static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
280 if (!count || *err)
281 return;
282 if (fwrite(p, count, 1, fp) != 1)
283 *err = errno;
286 static inline void ferr_puts(const char *s, FILE *fp, int *err)
288 ferr_write(s, strlen(s), fp, err);
291 static void rerere_io_putstr(const char *str, struct rerere_io *io)
293 if (io->output)
294 ferr_puts(str, io->output, &io->wrerror);
297 static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
299 if (io->output)
300 ferr_write(mem, sz, io->output, &io->wrerror);
304 * Subclass of rerere_io that reads from an on-disk file
306 struct rerere_io_file {
307 struct rerere_io io;
308 FILE *input;
312 * ... and its getline() method implementation
314 static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
316 struct rerere_io_file *io = (struct rerere_io_file *)io_;
317 return strbuf_getwholeline(sb, io->input, '\n');
321 * Require the exact number of conflict marker letters, no more, no
322 * less, followed by SP or any whitespace
323 * (including LF).
325 static int is_cmarker(char *buf, int marker_char, int marker_size)
327 int want_sp;
330 * The beginning of our version and the end of their version
331 * always are labeled like "<<<<< ours" or ">>>>> theirs",
332 * hence we set want_sp for them. Note that the version from
333 * the common ancestor in diff3-style output is not always
334 * labelled (e.g. "||||| common" is often seen but "|||||"
335 * alone is also valid), so we do not set want_sp.
337 want_sp = (marker_char == '<') || (marker_char == '>');
339 while (marker_size--)
340 if (*buf++ != marker_char)
341 return 0;
342 if (want_sp && *buf != ' ')
343 return 0;
344 return isspace(*buf);
347 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
349 strbuf_addchars(buf, ch, size);
350 strbuf_addch(buf, '\n');
353 static int handle_conflict(struct strbuf *out, struct rerere_io *io,
354 int marker_size, git_hash_ctx *ctx)
356 enum {
357 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
358 } hunk = RR_SIDE_1;
359 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
360 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
361 int has_conflicts = -1;
363 while (!io->getline(&buf, io)) {
364 if (is_cmarker(buf.buf, '<', marker_size)) {
365 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
366 break;
367 if (hunk == RR_SIDE_1)
368 strbuf_addbuf(&one, &conflict);
369 else
370 strbuf_addbuf(&two, &conflict);
371 strbuf_release(&conflict);
372 } else if (is_cmarker(buf.buf, '|', marker_size)) {
373 if (hunk != RR_SIDE_1)
374 break;
375 hunk = RR_ORIGINAL;
376 } else if (is_cmarker(buf.buf, '=', marker_size)) {
377 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
378 break;
379 hunk = RR_SIDE_2;
380 } else if (is_cmarker(buf.buf, '>', marker_size)) {
381 if (hunk != RR_SIDE_2)
382 break;
383 if (strbuf_cmp(&one, &two) > 0)
384 strbuf_swap(&one, &two);
385 has_conflicts = 1;
386 rerere_strbuf_putconflict(out, '<', marker_size);
387 strbuf_addbuf(out, &one);
388 rerere_strbuf_putconflict(out, '=', marker_size);
389 strbuf_addbuf(out, &two);
390 rerere_strbuf_putconflict(out, '>', marker_size);
391 if (ctx) {
392 the_hash_algo->update_fn(ctx, one.buf ?
393 one.buf : "",
394 one.len + 1);
395 the_hash_algo->update_fn(ctx, two.buf ?
396 two.buf : "",
397 two.len + 1);
399 break;
400 } else if (hunk == RR_SIDE_1)
401 strbuf_addbuf(&one, &buf);
402 else if (hunk == RR_ORIGINAL)
403 ; /* discard */
404 else if (hunk == RR_SIDE_2)
405 strbuf_addbuf(&two, &buf);
407 strbuf_release(&one);
408 strbuf_release(&two);
409 strbuf_release(&buf);
411 return has_conflicts;
415 * Read contents a file with conflicts, normalize the conflicts
416 * by (1) discarding the common ancestor version in diff3-style,
417 * (2) reordering our side and their side so that whichever sorts
418 * alphabetically earlier comes before the other one, while
419 * computing the "conflict ID", which is just an SHA-1 hash of
420 * one side of the conflict, NUL, the other side of the conflict,
421 * and NUL concatenated together.
423 * Return 1 if conflict hunks are found, 0 if there are no conflict
424 * hunks and -1 if an error occurred.
426 static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
428 git_hash_ctx ctx;
429 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
430 int has_conflicts = 0;
431 if (hash)
432 the_hash_algo->init_fn(&ctx);
434 while (!io->getline(&buf, io)) {
435 if (is_cmarker(buf.buf, '<', marker_size)) {
436 has_conflicts = handle_conflict(&out, io, marker_size,
437 hash ? &ctx : NULL);
438 if (has_conflicts < 0)
439 break;
440 rerere_io_putmem(out.buf, out.len, io);
441 strbuf_reset(&out);
442 } else
443 rerere_io_putstr(buf.buf, io);
445 strbuf_release(&buf);
446 strbuf_release(&out);
448 if (hash)
449 the_hash_algo->final_fn(hash, &ctx);
451 return has_conflicts;
455 * Scan the path for conflicts, do the "handle_path()" thing above, and
456 * return the number of conflict hunks found.
458 static int handle_file(struct index_state *istate,
459 const char *path, unsigned char *hash, const char *output)
461 int has_conflicts = 0;
462 struct rerere_io_file io;
463 int marker_size = ll_merge_marker_size(istate, path);
465 memset(&io, 0, sizeof(io));
466 io.io.getline = rerere_file_getline;
467 io.input = fopen(path, "r");
468 io.io.wrerror = 0;
469 if (!io.input)
470 return error_errno(_("could not open '%s'"), path);
472 if (output) {
473 io.io.output = fopen(output, "w");
474 if (!io.io.output) {
475 error_errno(_("could not write '%s'"), output);
476 fclose(io.input);
477 return -1;
481 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
483 fclose(io.input);
484 if (io.io.wrerror)
485 error(_("there were errors while writing '%s' (%s)"),
486 path, strerror(io.io.wrerror));
487 if (io.io.output && fclose(io.io.output))
488 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
490 if (has_conflicts < 0) {
491 if (output)
492 unlink_or_warn(output);
493 return error(_("could not parse conflict hunks in '%s'"), path);
495 if (io.io.wrerror)
496 return -1;
497 return has_conflicts;
501 * Look at a cache entry at "i" and see if it is not conflicting,
502 * conflicting and we are willing to handle, or conflicting and
503 * we are unable to handle, and return the determination in *type.
504 * Return the cache index to be looked at next, by skipping the
505 * stages we have already looked at in this invocation of this
506 * function.
508 static int check_one_conflict(struct index_state *istate, int i, int *type)
510 const struct cache_entry *e = istate->cache[i];
512 if (!ce_stage(e)) {
513 *type = RESOLVED;
514 return i + 1;
517 *type = PUNTED;
518 while (i < istate->cache_nr && ce_stage(istate->cache[i]) == 1)
519 i++;
521 /* Only handle regular files with both stages #2 and #3 */
522 if (i + 1 < istate->cache_nr) {
523 const struct cache_entry *e2 = istate->cache[i];
524 const struct cache_entry *e3 = istate->cache[i + 1];
525 if (ce_stage(e2) == 2 &&
526 ce_stage(e3) == 3 &&
527 ce_same_name(e, e3) &&
528 S_ISREG(e2->ce_mode) &&
529 S_ISREG(e3->ce_mode))
530 *type = THREE_STAGED;
533 /* Skip the entries with the same name */
534 while (i < istate->cache_nr && ce_same_name(e, istate->cache[i]))
535 i++;
536 return i;
540 * Scan the index and find paths that have conflicts that rerere can
541 * handle, i.e. the ones that has both stages #2 and #3.
543 * NEEDSWORK: we do not record or replay a previous "resolve by
544 * deletion" for a delete-modify conflict, as that is inherently risky
545 * without knowing what modification is being discarded. The only
546 * safe case, i.e. both side doing the deletion and modification that
547 * are identical to the previous round, might want to be handled,
548 * though.
550 static int find_conflict(struct repository *r, struct string_list *conflict)
552 int i;
554 if (repo_read_index(r) < 0)
555 return error(_("index file corrupt"));
557 for (i = 0; i < r->index->cache_nr;) {
558 int conflict_type;
559 const struct cache_entry *e = r->index->cache[i];
560 i = check_one_conflict(r->index, i, &conflict_type);
561 if (conflict_type == THREE_STAGED)
562 string_list_insert(conflict, (const char *)e->name);
564 return 0;
568 * The merge_rr list is meant to hold outstanding conflicted paths
569 * that rerere could handle. Abuse the list by adding other types of
570 * entries to allow the caller to show "rerere remaining".
572 * - Conflicted paths that rerere does not handle are added
573 * - Conflicted paths that have been resolved are marked as such
574 * by storing RERERE_RESOLVED to .util field (where conflict ID
575 * is expected to be stored).
577 * Do *not* write MERGE_RR file out after calling this function.
579 * NEEDSWORK: we may want to fix the caller that implements "rerere
580 * remaining" to do this without abusing merge_rr.
582 int rerere_remaining(struct repository *r, struct string_list *merge_rr)
584 int i;
586 if (setup_rerere(r, merge_rr, RERERE_READONLY))
587 return 0;
588 if (repo_read_index(r) < 0)
589 return error(_("index file corrupt"));
591 for (i = 0; i < r->index->cache_nr;) {
592 int conflict_type;
593 const struct cache_entry *e = r->index->cache[i];
594 i = check_one_conflict(r->index, i, &conflict_type);
595 if (conflict_type == PUNTED)
596 string_list_insert(merge_rr, (const char *)e->name);
597 else if (conflict_type == RESOLVED) {
598 struct string_list_item *it;
599 it = string_list_lookup(merge_rr, (const char *)e->name);
600 if (it) {
601 free_rerere_id(it);
602 it->util = RERERE_RESOLVED;
606 return 0;
610 * Try using the given conflict resolution "ID" to see
611 * if that recorded conflict resolves cleanly what we
612 * got in the "cur".
614 static int try_merge(struct index_state *istate,
615 const struct rerere_id *id, const char *path,
616 mmfile_t *cur, mmbuffer_t *result)
618 enum ll_merge_result ret;
619 mmfile_t base = {NULL, 0}, other = {NULL, 0};
621 if (read_mmfile(&base, rerere_path(id, "preimage")) ||
622 read_mmfile(&other, rerere_path(id, "postimage"))) {
623 ret = LL_MERGE_CONFLICT;
624 } else {
626 * A three-way merge. Note that this honors user-customizable
627 * low-level merge driver settings.
629 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "",
630 istate, NULL);
633 free(base.ptr);
634 free(other.ptr);
636 return ret;
640 * Find the conflict identified by "id"; the change between its
641 * "preimage" (i.e. a previous contents with conflict markers) and its
642 * "postimage" (i.e. the corresponding contents with conflicts
643 * resolved) may apply cleanly to the contents stored in "path", i.e.
644 * the conflict this time around.
646 * Returns 0 for successful replay of recorded resolution, or non-zero
647 * for failure.
649 static int merge(struct index_state *istate, const struct rerere_id *id, const char *path)
651 FILE *f;
652 int ret;
653 mmfile_t cur = {NULL, 0};
654 mmbuffer_t result = {NULL, 0};
657 * Normalize the conflicts in path and write it out to
658 * "thisimage" temporary file.
660 if ((handle_file(istate, path, NULL, rerere_path(id, "thisimage")) < 0) ||
661 read_mmfile(&cur, rerere_path(id, "thisimage"))) {
662 ret = 1;
663 goto out;
666 ret = try_merge(istate, id, path, &cur, &result);
667 if (ret)
668 goto out;
671 * A successful replay of recorded resolution.
672 * Mark that "postimage" was used to help gc.
674 if (utime(rerere_path(id, "postimage"), NULL) < 0)
675 warning_errno(_("failed utime() on '%s'"),
676 rerere_path(id, "postimage"));
678 /* Update "path" with the resolution */
679 f = fopen(path, "w");
680 if (!f)
681 return error_errno(_("could not open '%s'"), path);
682 if (fwrite(result.ptr, result.size, 1, f) != 1)
683 error_errno(_("could not write '%s'"), path);
684 if (fclose(f))
685 return error_errno(_("writing '%s' failed"), path);
687 out:
688 free(cur.ptr);
689 free(result.ptr);
691 return ret;
694 static void update_paths(struct repository *r, struct string_list *update)
696 struct lock_file index_lock = LOCK_INIT;
697 int i;
699 repo_hold_locked_index(r, &index_lock, LOCK_DIE_ON_ERROR);
701 for (i = 0; i < update->nr; i++) {
702 struct string_list_item *item = &update->items[i];
703 if (add_file_to_index(r->index, item->string, 0))
704 exit(128);
705 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
706 item->string);
709 if (write_locked_index(r->index, &index_lock,
710 COMMIT_LOCK | SKIP_IF_UNCHANGED))
711 die(_("unable to write new index file"));
714 static void remove_variant(struct rerere_id *id)
716 unlink_or_warn(rerere_path(id, "postimage"));
717 unlink_or_warn(rerere_path(id, "preimage"));
718 id->collection->status[id->variant] = 0;
722 * The path indicated by rr_item may still have conflict for which we
723 * have a recorded resolution, in which case replay it and optionally
724 * update it. Or it may have been resolved by the user and we may
725 * only have the preimage for that conflict, in which case the result
726 * needs to be recorded as a resolution in a postimage file.
728 static void do_rerere_one_path(struct index_state *istate,
729 struct string_list_item *rr_item,
730 struct string_list *update)
732 const char *path = rr_item->string;
733 struct rerere_id *id = rr_item->util;
734 struct rerere_dir *rr_dir = id->collection;
735 int variant;
737 variant = id->variant;
739 /* Has the user resolved it already? */
740 if (variant >= 0) {
741 if (!handle_file(istate, path, NULL, NULL)) {
742 copy_file(rerere_path(id, "postimage"), path, 0666);
743 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
744 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
745 free_rerere_id(rr_item);
746 rr_item->util = NULL;
747 return;
750 * There may be other variants that can cleanly
751 * replay. Try them and update the variant number for
752 * this one.
756 /* Does any existing resolution apply cleanly? */
757 for (variant = 0; variant < rr_dir->status_nr; variant++) {
758 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
759 struct rerere_id vid = *id;
761 if ((rr_dir->status[variant] & both) != both)
762 continue;
764 vid.variant = variant;
765 if (merge(istate, &vid, path))
766 continue; /* failed to replay */
769 * If there already is a different variant that applies
770 * cleanly, there is no point maintaining our own variant.
772 if (0 <= id->variant && id->variant != variant)
773 remove_variant(id);
775 if (rerere_autoupdate)
776 string_list_insert(update, path);
777 else
778 fprintf_ln(stderr,
779 _("Resolved '%s' using previous resolution."),
780 path);
781 free_rerere_id(rr_item);
782 rr_item->util = NULL;
783 return;
786 /* None of the existing one applies; we need a new variant */
787 assign_variant(id);
789 variant = id->variant;
790 handle_file(istate, path, NULL, rerere_path(id, "preimage"));
791 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
792 const char *path = rerere_path(id, "postimage");
793 if (unlink(path))
794 die_errno(_("cannot unlink stray '%s'"), path);
795 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
797 id->collection->status[variant] |= RR_HAS_PREIMAGE;
798 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
801 static int do_plain_rerere(struct repository *r,
802 struct string_list *rr, int fd)
804 struct string_list conflict = STRING_LIST_INIT_DUP;
805 struct string_list update = STRING_LIST_INIT_DUP;
806 int i;
808 find_conflict(r, &conflict);
811 * MERGE_RR records paths with conflicts immediately after
812 * merge failed. Some of the conflicted paths might have been
813 * hand resolved in the working tree since then, but the
814 * initial run would catch all and register their preimages.
816 for (i = 0; i < conflict.nr; i++) {
817 struct rerere_id *id;
818 unsigned char hash[GIT_MAX_RAWSZ];
819 const char *path = conflict.items[i].string;
820 int ret;
823 * Ask handle_file() to scan and assign a
824 * conflict ID. No need to write anything out
825 * yet.
827 ret = handle_file(r->index, path, hash, NULL);
828 if (ret != 0 && string_list_has_string(rr, path)) {
829 remove_variant(string_list_lookup(rr, path)->util);
830 string_list_remove(rr, path, 1);
832 if (ret < 1)
833 continue;
835 id = new_rerere_id(hash);
836 string_list_insert(rr, path)->util = id;
838 /* Ensure that the directory exists. */
839 mkdir_in_gitdir(rerere_path(id, NULL));
842 for (i = 0; i < rr->nr; i++)
843 do_rerere_one_path(r->index, &rr->items[i], &update);
845 if (update.nr)
846 update_paths(r, &update);
848 return write_rr(rr, fd);
851 static void git_rerere_config(void)
853 git_config_get_bool("rerere.enabled", &rerere_enabled);
854 git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
855 git_config(git_default_config, NULL);
858 static GIT_PATH_FUNC(git_path_rr_cache, "rr-cache")
860 static int is_rerere_enabled(void)
862 int rr_cache_exists;
864 if (!rerere_enabled)
865 return 0;
867 rr_cache_exists = is_directory(git_path_rr_cache());
868 if (rerere_enabled < 0)
869 return rr_cache_exists;
871 if (!rr_cache_exists && mkdir_in_gitdir(git_path_rr_cache()))
872 die(_("could not create directory '%s'"), git_path_rr_cache());
873 return 1;
876 int setup_rerere(struct repository *r, struct string_list *merge_rr, int flags)
878 int fd;
880 git_rerere_config();
881 if (!is_rerere_enabled())
882 return -1;
884 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
885 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
886 if (flags & RERERE_READONLY)
887 fd = 0;
888 else
889 fd = hold_lock_file_for_update(&write_lock,
890 git_path_merge_rr(r),
891 LOCK_DIE_ON_ERROR);
892 read_rr(r, merge_rr);
893 return fd;
897 * The main entry point that is called internally from codepaths that
898 * perform mergy operations, possibly leaving conflicted index entries
899 * and working tree files.
901 int repo_rerere(struct repository *r, int flags)
903 struct string_list merge_rr = STRING_LIST_INIT_DUP;
904 int fd, status;
906 fd = setup_rerere(r, &merge_rr, flags);
907 if (fd < 0)
908 return 0;
909 status = do_plain_rerere(r, &merge_rr, fd);
910 free_rerere_dirs();
911 return status;
915 * Subclass of rerere_io that reads from an in-core buffer that is a
916 * strbuf
918 struct rerere_io_mem {
919 struct rerere_io io;
920 struct strbuf input;
924 * ... and its getline() method implementation
926 static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
928 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
929 char *ep;
930 size_t len;
932 strbuf_release(sb);
933 if (!io->input.len)
934 return -1;
935 ep = memchr(io->input.buf, '\n', io->input.len);
936 if (!ep)
937 ep = io->input.buf + io->input.len;
938 else if (*ep == '\n')
939 ep++;
940 len = ep - io->input.buf;
941 strbuf_add(sb, io->input.buf, len);
942 strbuf_remove(&io->input, 0, len);
943 return 0;
946 static int handle_cache(struct index_state *istate,
947 const char *path, unsigned char *hash, const char *output)
949 mmfile_t mmfile[3] = {{NULL}};
950 mmbuffer_t result = {NULL, 0};
951 const struct cache_entry *ce;
952 int pos, len, i, has_conflicts;
953 struct rerere_io_mem io;
954 int marker_size = ll_merge_marker_size(istate, path);
957 * Reproduce the conflicted merge in-core
959 len = strlen(path);
960 pos = index_name_pos(istate, path, len);
961 if (0 <= pos)
962 return -1;
963 pos = -pos - 1;
965 while (pos < istate->cache_nr) {
966 enum object_type type;
967 unsigned long size;
969 ce = istate->cache[pos++];
970 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
971 break;
972 i = ce_stage(ce) - 1;
973 if (!mmfile[i].ptr) {
974 mmfile[i].ptr = repo_read_object_file(the_repository,
975 &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",
991 istate, NULL);
992 for (i = 0; i < 3; i++)
993 free(mmfile[i].ptr);
995 memset(&io, 0, sizeof(io));
996 io.io.getline = rerere_mem_getline;
997 if (output)
998 io.io.output = fopen(output, "w");
999 else
1000 io.io.output = NULL;
1001 strbuf_init(&io.input, 0);
1002 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1005 * Grab the conflict ID and optionally write the original
1006 * contents with conflict markers out.
1008 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1009 strbuf_release(&io.input);
1010 if (io.io.output)
1011 fclose(io.io.output);
1012 return has_conflicts;
1015 static int rerere_forget_one_path(struct index_state *istate,
1016 const char *path,
1017 struct string_list *rr)
1019 const char *filename;
1020 struct rerere_id *id;
1021 unsigned char hash[GIT_MAX_RAWSZ];
1022 int ret;
1023 struct string_list_item *item;
1026 * Recreate the original conflict from the stages in the
1027 * index and compute the conflict ID
1029 ret = handle_cache(istate, path, hash, NULL);
1030 if (ret < 1)
1031 return error(_("could not parse conflict hunks in '%s'"), path);
1033 /* Nuke the recorded resolution for the conflict */
1034 id = new_rerere_id(hash);
1036 for (id->variant = 0;
1037 id->variant < id->collection->status_nr;
1038 id->variant++) {
1039 mmfile_t cur = { NULL, 0 };
1040 mmbuffer_t result = {NULL, 0};
1041 int cleanly_resolved;
1043 if (!has_rerere_resolution(id))
1044 continue;
1046 handle_cache(istate, path, hash, rerere_path(id, "thisimage"));
1047 if (read_mmfile(&cur, rerere_path(id, "thisimage"))) {
1048 free(cur.ptr);
1049 error(_("failed to update conflicted state in '%s'"), path);
1050 goto fail_exit;
1052 cleanly_resolved = !try_merge(istate, id, path, &cur, &result);
1053 free(result.ptr);
1054 free(cur.ptr);
1055 if (cleanly_resolved)
1056 break;
1059 if (id->collection->status_nr <= id->variant) {
1060 error(_("no remembered resolution for '%s'"), path);
1061 goto fail_exit;
1064 filename = rerere_path(id, "postimage");
1065 if (unlink(filename)) {
1066 if (errno == ENOENT)
1067 error(_("no remembered resolution for '%s'"), path);
1068 else
1069 error_errno(_("cannot unlink '%s'"), filename);
1070 goto fail_exit;
1074 * Update the preimage so that the user can resolve the
1075 * conflict in the working tree, run us again to record
1076 * the postimage.
1078 handle_cache(istate, path, hash, rerere_path(id, "preimage"));
1079 fprintf_ln(stderr, _("Updated preimage for '%s'"), path);
1082 * And remember that we can record resolution for this
1083 * conflict when the user is done.
1085 item = string_list_insert(rr, path);
1086 free_rerere_id(item);
1087 item->util = id;
1088 fprintf(stderr, _("Forgot resolution for '%s'\n"), path);
1089 return 0;
1091 fail_exit:
1092 free(id);
1093 return -1;
1096 int rerere_forget(struct repository *r, struct pathspec *pathspec)
1098 int i, fd;
1099 struct string_list conflict = STRING_LIST_INIT_DUP;
1100 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1102 if (repo_read_index(r) < 0)
1103 return error(_("index file corrupt"));
1105 fd = setup_rerere(r, &merge_rr, RERERE_NOAUTOUPDATE);
1106 if (fd < 0)
1107 return 0;
1110 * The paths may have been resolved (incorrectly);
1111 * recover the original conflicted state and then
1112 * find the conflicted paths.
1114 unmerge_index(r->index, pathspec);
1115 find_conflict(r, &conflict);
1116 for (i = 0; i < conflict.nr; i++) {
1117 struct string_list_item *it = &conflict.items[i];
1118 if (!match_pathspec(r->index, pathspec, it->string,
1119 strlen(it->string), 0, NULL, 0))
1120 continue;
1121 rerere_forget_one_path(r->index, it->string, &merge_rr);
1123 return write_rr(&merge_rr, fd);
1127 * Garbage collection support
1130 static timestamp_t rerere_created_at(struct rerere_id *id)
1132 struct stat st;
1134 return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
1137 static timestamp_t rerere_last_used_at(struct rerere_id *id)
1139 struct stat st;
1141 return stat(rerere_path(id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
1145 * Remove the recorded resolution for a given conflict ID
1147 static void unlink_rr_item(struct rerere_id *id)
1149 unlink_or_warn(rerere_path(id, "thisimage"));
1150 remove_variant(id);
1151 id->collection->status[id->variant] = 0;
1154 static void prune_one(struct rerere_id *id,
1155 timestamp_t cutoff_resolve, timestamp_t cutoff_noresolve)
1157 timestamp_t then;
1158 timestamp_t cutoff;
1160 then = rerere_last_used_at(id);
1161 if (then)
1162 cutoff = cutoff_resolve;
1163 else {
1164 then = rerere_created_at(id);
1165 if (!then)
1166 return;
1167 cutoff = cutoff_noresolve;
1169 if (then < cutoff)
1170 unlink_rr_item(id);
1173 /* Does the basename in "path" look plausibly like an rr-cache entry? */
1174 static int is_rr_cache_dirname(const char *path)
1176 struct object_id oid;
1177 const char *end;
1178 return !parse_oid_hex(path, &oid, &end) && !*end;
1181 void rerere_gc(struct repository *r, struct string_list *rr)
1183 struct string_list to_remove = STRING_LIST_INIT_DUP;
1184 DIR *dir;
1185 struct dirent *e;
1186 int i;
1187 timestamp_t now = time(NULL);
1188 timestamp_t cutoff_noresolve = now - 15 * 86400;
1189 timestamp_t cutoff_resolve = now - 60 * 86400;
1191 if (setup_rerere(r, rr, 0) < 0)
1192 return;
1194 git_config_get_expiry_in_days("gc.rerereresolved", &cutoff_resolve, now);
1195 git_config_get_expiry_in_days("gc.rerereunresolved", &cutoff_noresolve, now);
1196 git_config(git_default_config, NULL);
1197 dir = opendir(git_path("rr-cache"));
1198 if (!dir)
1199 die_errno(_("unable to open rr-cache directory"));
1200 /* Collect stale conflict IDs ... */
1201 while ((e = readdir_skip_dot_and_dotdot(dir))) {
1202 struct rerere_dir *rr_dir;
1203 struct rerere_id id;
1204 int now_empty;
1206 if (!is_rr_cache_dirname(e->d_name))
1207 continue; /* or should we remove e->d_name? */
1209 rr_dir = find_rerere_dir(e->d_name);
1211 now_empty = 1;
1212 for (id.variant = 0, id.collection = rr_dir;
1213 id.variant < id.collection->status_nr;
1214 id.variant++) {
1215 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1216 if (id.collection->status[id.variant])
1217 now_empty = 0;
1219 if (now_empty)
1220 string_list_append(&to_remove, e->d_name);
1222 closedir(dir);
1224 /* ... and then remove the empty directories */
1225 for (i = 0; i < to_remove.nr; i++)
1226 rmdir(git_path("rr-cache/%s", to_remove.items[i].string));
1227 string_list_clear(&to_remove, 0);
1228 rollback_lock_file(&write_lock);
1232 * During a conflict resolution, after "rerere" recorded the
1233 * preimages, abandon them if the user did not resolve them or
1234 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1236 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1238 void rerere_clear(struct repository *r, struct string_list *merge_rr)
1240 int i;
1242 if (setup_rerere(r, merge_rr, 0) < 0)
1243 return;
1245 for (i = 0; i < merge_rr->nr; i++) {
1246 struct rerere_id *id = merge_rr->items[i].util;
1247 if (!has_rerere_resolution(id)) {
1248 unlink_rr_item(id);
1249 rmdir(rerere_path(id, NULL));
1252 unlink_or_warn(git_path_merge_rr(r));
1253 rollback_lock_file(&write_lock);