abspath.h: move absolute path functions from cache.h
[git/debian.git] / rerere.c
blobc3258e13902d47a71b5bc94d39e50790a264b6be
1 #include "git-compat-util.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-store.h"
17 #include "hash-lookup.h"
18 #include "strmap.h"
20 #define RESOLVED 0
21 #define PUNTED 1
22 #define THREE_STAGED 2
23 void *RERERE_RESOLVED = &RERERE_RESOLVED;
25 /* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
26 static int rerere_enabled = -1;
28 /* automatically update cleanly resolved paths to the index */
29 static int rerere_autoupdate;
31 #define RR_HAS_POSTIMAGE 1
32 #define RR_HAS_PREIMAGE 2
33 struct rerere_dir {
34 int status_alloc, status_nr;
35 unsigned char *status;
36 char name[FLEX_ARRAY];
39 static struct strmap rerere_dirs = STRMAP_INIT;
41 static void free_rerere_dirs(void)
43 struct hashmap_iter iter;
44 struct strmap_entry *ent;
46 strmap_for_each_entry(&rerere_dirs, &iter, ent) {
47 struct rerere_dir *rr_dir = ent->value;
48 free(rr_dir->status);
49 free(rr_dir);
51 strmap_clear(&rerere_dirs, 0);
54 static void free_rerere_id(struct string_list_item *item)
56 free(item->util);
59 static const char *rerere_id_hex(const struct rerere_id *id)
61 return id->collection->name;
64 static void fit_variant(struct rerere_dir *rr_dir, int variant)
66 variant++;
67 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
68 if (rr_dir->status_nr < variant) {
69 memset(rr_dir->status + rr_dir->status_nr,
70 '\0', variant - rr_dir->status_nr);
71 rr_dir->status_nr = variant;
75 static void assign_variant(struct rerere_id *id)
77 int variant;
78 struct rerere_dir *rr_dir = id->collection;
80 variant = id->variant;
81 if (variant < 0) {
82 for (variant = 0; variant < rr_dir->status_nr; variant++)
83 if (!rr_dir->status[variant])
84 break;
86 fit_variant(rr_dir, variant);
87 id->variant = variant;
90 const char *rerere_path(const struct rerere_id *id, const char *file)
92 if (!file)
93 return git_path("rr-cache/%s", rerere_id_hex(id));
95 if (id->variant <= 0)
96 return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
98 return git_path("rr-cache/%s/%s.%d",
99 rerere_id_hex(id), file, id->variant);
102 static int is_rr_file(const char *name, const char *filename, int *variant)
104 const char *suffix;
105 char *ep;
107 if (!strcmp(name, filename)) {
108 *variant = 0;
109 return 1;
111 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
112 return 0;
114 errno = 0;
115 *variant = strtol(suffix + 1, &ep, 10);
116 if (errno || *ep)
117 return 0;
118 return 1;
121 static void scan_rerere_dir(struct rerere_dir *rr_dir)
123 struct dirent *de;
124 DIR *dir = opendir(git_path("rr-cache/%s", rr_dir->name));
126 if (!dir)
127 return;
128 while ((de = readdir(dir)) != NULL) {
129 int variant;
131 if (is_rr_file(de->d_name, "postimage", &variant)) {
132 fit_variant(rr_dir, variant);
133 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
134 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
135 fit_variant(rr_dir, variant);
136 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
139 closedir(dir);
142 static struct rerere_dir *find_rerere_dir(const char *hex)
144 struct rerere_dir *rr_dir;
146 rr_dir = strmap_get(&rerere_dirs, hex);
147 if (!rr_dir) {
148 FLEX_ALLOC_STR(rr_dir, name, hex);
149 rr_dir->status = NULL;
150 rr_dir->status_nr = 0;
151 rr_dir->status_alloc = 0;
152 strmap_put(&rerere_dirs, hex, rr_dir);
154 scan_rerere_dir(rr_dir);
156 return rr_dir;
159 static int has_rerere_resolution(const struct rerere_id *id)
161 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
162 int variant = id->variant;
164 if (variant < 0)
165 return 0;
166 return ((id->collection->status[variant] & both) == both);
169 static struct rerere_id *new_rerere_id_hex(char *hex)
171 struct rerere_id *id = xmalloc(sizeof(*id));
172 id->collection = find_rerere_dir(hex);
173 id->variant = -1; /* not known yet */
174 return id;
177 static struct rerere_id *new_rerere_id(unsigned char *hash)
179 return new_rerere_id_hex(hash_to_hex(hash));
183 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
184 * "conflict ID", a HT and pathname, terminated with a NUL, and is
185 * used to keep track of the set of paths that "rerere" may need to
186 * work on (i.e. what is left by the previous invocation of "git
187 * rerere" during the current conflict resolution session).
189 static void read_rr(struct repository *r, struct string_list *rr)
191 struct strbuf buf = STRBUF_INIT;
192 FILE *in = fopen_or_warn(git_path_merge_rr(r), "r");
194 if (!in)
195 return;
196 while (!strbuf_getwholeline(&buf, in, '\0')) {
197 char *path;
198 unsigned char hash[GIT_MAX_RAWSZ];
199 struct rerere_id *id;
200 int variant;
201 const unsigned hexsz = the_hash_algo->hexsz;
203 /* There has to be the hash, tab, path and then NUL */
204 if (buf.len < hexsz + 2 || get_sha1_hex(buf.buf, hash))
205 die(_("corrupt MERGE_RR"));
207 if (buf.buf[hexsz] != '.') {
208 variant = 0;
209 path = buf.buf + hexsz;
210 } else {
211 errno = 0;
212 variant = strtol(buf.buf + hexsz + 1, &path, 10);
213 if (errno)
214 die(_("corrupt MERGE_RR"));
216 if (*(path++) != '\t')
217 die(_("corrupt MERGE_RR"));
218 buf.buf[hexsz] = '\0';
219 id = new_rerere_id_hex(buf.buf);
220 id->variant = variant;
221 string_list_insert(rr, path)->util = id;
223 strbuf_release(&buf);
224 fclose(in);
227 static struct lock_file write_lock;
229 static int write_rr(struct string_list *rr, int out_fd)
231 int i;
232 for (i = 0; i < rr->nr; i++) {
233 struct strbuf buf = STRBUF_INIT;
234 struct rerere_id *id;
236 assert(rr->items[i].util != RERERE_RESOLVED);
238 id = rr->items[i].util;
239 if (!id)
240 continue;
241 assert(id->variant >= 0);
242 if (0 < id->variant)
243 strbuf_addf(&buf, "%s.%d\t%s%c",
244 rerere_id_hex(id), id->variant,
245 rr->items[i].string, 0);
246 else
247 strbuf_addf(&buf, "%s\t%s%c",
248 rerere_id_hex(id),
249 rr->items[i].string, 0);
251 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
252 die(_("unable to write rerere record"));
254 strbuf_release(&buf);
256 if (commit_lock_file(&write_lock) != 0)
257 die(_("unable to write rerere record"));
258 return 0;
262 * "rerere" interacts with conflicted file contents using this I/O
263 * abstraction. It reads a conflicted contents from one place via
264 * "getline()" method, and optionally can write it out after
265 * normalizing the conflicted hunks to the "output". Subclasses of
266 * rerere_io embed this structure at the beginning of their own
267 * rerere_io object.
269 struct rerere_io {
270 int (*getline)(struct strbuf *, struct rerere_io *);
271 FILE *output;
272 int wrerror;
273 /* some more stuff */
276 static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
278 if (!count || *err)
279 return;
280 if (fwrite(p, count, 1, fp) != 1)
281 *err = errno;
284 static inline void ferr_puts(const char *s, FILE *fp, int *err)
286 ferr_write(s, strlen(s), fp, err);
289 static void rerere_io_putstr(const char *str, struct rerere_io *io)
291 if (io->output)
292 ferr_puts(str, io->output, &io->wrerror);
295 static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
297 if (io->output)
298 ferr_write(mem, sz, io->output, &io->wrerror);
302 * Subclass of rerere_io that reads from an on-disk file
304 struct rerere_io_file {
305 struct rerere_io io;
306 FILE *input;
310 * ... and its getline() method implementation
312 static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
314 struct rerere_io_file *io = (struct rerere_io_file *)io_;
315 return strbuf_getwholeline(sb, io->input, '\n');
319 * Require the exact number of conflict marker letters, no more, no
320 * less, followed by SP or any whitespace
321 * (including LF).
323 static int is_cmarker(char *buf, int marker_char, int marker_size)
325 int want_sp;
328 * The beginning of our version and the end of their version
329 * always are labeled like "<<<<< ours" or ">>>>> theirs",
330 * hence we set want_sp for them. Note that the version from
331 * the common ancestor in diff3-style output is not always
332 * labelled (e.g. "||||| common" is often seen but "|||||"
333 * alone is also valid), so we do not set want_sp.
335 want_sp = (marker_char == '<') || (marker_char == '>');
337 while (marker_size--)
338 if (*buf++ != marker_char)
339 return 0;
340 if (want_sp && *buf != ' ')
341 return 0;
342 return isspace(*buf);
345 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
347 strbuf_addchars(buf, ch, size);
348 strbuf_addch(buf, '\n');
351 static int handle_conflict(struct strbuf *out, struct rerere_io *io,
352 int marker_size, git_hash_ctx *ctx)
354 enum {
355 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
356 } hunk = RR_SIDE_1;
357 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
358 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
359 int has_conflicts = -1;
361 while (!io->getline(&buf, io)) {
362 if (is_cmarker(buf.buf, '<', marker_size)) {
363 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
364 break;
365 if (hunk == RR_SIDE_1)
366 strbuf_addbuf(&one, &conflict);
367 else
368 strbuf_addbuf(&two, &conflict);
369 strbuf_release(&conflict);
370 } else if (is_cmarker(buf.buf, '|', marker_size)) {
371 if (hunk != RR_SIDE_1)
372 break;
373 hunk = RR_ORIGINAL;
374 } else if (is_cmarker(buf.buf, '=', marker_size)) {
375 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
376 break;
377 hunk = RR_SIDE_2;
378 } else if (is_cmarker(buf.buf, '>', marker_size)) {
379 if (hunk != RR_SIDE_2)
380 break;
381 if (strbuf_cmp(&one, &two) > 0)
382 strbuf_swap(&one, &two);
383 has_conflicts = 1;
384 rerere_strbuf_putconflict(out, '<', marker_size);
385 strbuf_addbuf(out, &one);
386 rerere_strbuf_putconflict(out, '=', marker_size);
387 strbuf_addbuf(out, &two);
388 rerere_strbuf_putconflict(out, '>', marker_size);
389 if (ctx) {
390 the_hash_algo->update_fn(ctx, one.buf ?
391 one.buf : "",
392 one.len + 1);
393 the_hash_algo->update_fn(ctx, two.buf ?
394 two.buf : "",
395 two.len + 1);
397 break;
398 } else if (hunk == RR_SIDE_1)
399 strbuf_addbuf(&one, &buf);
400 else if (hunk == RR_ORIGINAL)
401 ; /* discard */
402 else if (hunk == RR_SIDE_2)
403 strbuf_addbuf(&two, &buf);
405 strbuf_release(&one);
406 strbuf_release(&two);
407 strbuf_release(&buf);
409 return has_conflicts;
413 * Read contents a file with conflicts, normalize the conflicts
414 * by (1) discarding the common ancestor version in diff3-style,
415 * (2) reordering our side and their side so that whichever sorts
416 * alphabetically earlier comes before the other one, while
417 * computing the "conflict ID", which is just an SHA-1 hash of
418 * one side of the conflict, NUL, the other side of the conflict,
419 * and NUL concatenated together.
421 * Return 1 if conflict hunks are found, 0 if there are no conflict
422 * hunks and -1 if an error occurred.
424 static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
426 git_hash_ctx ctx;
427 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
428 int has_conflicts = 0;
429 if (hash)
430 the_hash_algo->init_fn(&ctx);
432 while (!io->getline(&buf, io)) {
433 if (is_cmarker(buf.buf, '<', marker_size)) {
434 has_conflicts = handle_conflict(&out, io, marker_size,
435 hash ? &ctx : NULL);
436 if (has_conflicts < 0)
437 break;
438 rerere_io_putmem(out.buf, out.len, io);
439 strbuf_reset(&out);
440 } else
441 rerere_io_putstr(buf.buf, io);
443 strbuf_release(&buf);
444 strbuf_release(&out);
446 if (hash)
447 the_hash_algo->final_fn(hash, &ctx);
449 return has_conflicts;
453 * Scan the path for conflicts, do the "handle_path()" thing above, and
454 * return the number of conflict hunks found.
456 static int handle_file(struct index_state *istate,
457 const char *path, unsigned char *hash, const char *output)
459 int has_conflicts = 0;
460 struct rerere_io_file io;
461 int marker_size = ll_merge_marker_size(istate, path);
463 memset(&io, 0, sizeof(io));
464 io.io.getline = rerere_file_getline;
465 io.input = fopen(path, "r");
466 io.io.wrerror = 0;
467 if (!io.input)
468 return error_errno(_("could not open '%s'"), path);
470 if (output) {
471 io.io.output = fopen(output, "w");
472 if (!io.io.output) {
473 error_errno(_("could not write '%s'"), output);
474 fclose(io.input);
475 return -1;
479 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
481 fclose(io.input);
482 if (io.io.wrerror)
483 error(_("there were errors while writing '%s' (%s)"),
484 path, strerror(io.io.wrerror));
485 if (io.io.output && fclose(io.io.output))
486 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
488 if (has_conflicts < 0) {
489 if (output)
490 unlink_or_warn(output);
491 return error(_("could not parse conflict hunks in '%s'"), path);
493 if (io.io.wrerror)
494 return -1;
495 return has_conflicts;
499 * Look at a cache entry at "i" and see if it is not conflicting,
500 * conflicting and we are willing to handle, or conflicting and
501 * we are unable to handle, and return the determination in *type.
502 * Return the cache index to be looked at next, by skipping the
503 * stages we have already looked at in this invocation of this
504 * function.
506 static int check_one_conflict(struct index_state *istate, int i, int *type)
508 const struct cache_entry *e = istate->cache[i];
510 if (!ce_stage(e)) {
511 *type = RESOLVED;
512 return i + 1;
515 *type = PUNTED;
516 while (i < istate->cache_nr && ce_stage(istate->cache[i]) == 1)
517 i++;
519 /* Only handle regular files with both stages #2 and #3 */
520 if (i + 1 < istate->cache_nr) {
521 const struct cache_entry *e2 = istate->cache[i];
522 const struct cache_entry *e3 = istate->cache[i + 1];
523 if (ce_stage(e2) == 2 &&
524 ce_stage(e3) == 3 &&
525 ce_same_name(e, e3) &&
526 S_ISREG(e2->ce_mode) &&
527 S_ISREG(e3->ce_mode))
528 *type = THREE_STAGED;
531 /* Skip the entries with the same name */
532 while (i < istate->cache_nr && ce_same_name(e, istate->cache[i]))
533 i++;
534 return i;
538 * Scan the index and find paths that have conflicts that rerere can
539 * handle, i.e. the ones that has both stages #2 and #3.
541 * NEEDSWORK: we do not record or replay a previous "resolve by
542 * deletion" for a delete-modify conflict, as that is inherently risky
543 * without knowing what modification is being discarded. The only
544 * safe case, i.e. both side doing the deletion and modification that
545 * are identical to the previous round, might want to be handled,
546 * though.
548 static int find_conflict(struct repository *r, struct string_list *conflict)
550 int i;
552 if (repo_read_index(r) < 0)
553 return error(_("index file corrupt"));
555 for (i = 0; i < r->index->cache_nr;) {
556 int conflict_type;
557 const struct cache_entry *e = r->index->cache[i];
558 i = check_one_conflict(r->index, i, &conflict_type);
559 if (conflict_type == THREE_STAGED)
560 string_list_insert(conflict, (const char *)e->name);
562 return 0;
566 * The merge_rr list is meant to hold outstanding conflicted paths
567 * that rerere could handle. Abuse the list by adding other types of
568 * entries to allow the caller to show "rerere remaining".
570 * - Conflicted paths that rerere does not handle are added
571 * - Conflicted paths that have been resolved are marked as such
572 * by storing RERERE_RESOLVED to .util field (where conflict ID
573 * is expected to be stored).
575 * Do *not* write MERGE_RR file out after calling this function.
577 * NEEDSWORK: we may want to fix the caller that implements "rerere
578 * remaining" to do this without abusing merge_rr.
580 int rerere_remaining(struct repository *r, struct string_list *merge_rr)
582 int i;
584 if (setup_rerere(r, merge_rr, RERERE_READONLY))
585 return 0;
586 if (repo_read_index(r) < 0)
587 return error(_("index file corrupt"));
589 for (i = 0; i < r->index->cache_nr;) {
590 int conflict_type;
591 const struct cache_entry *e = r->index->cache[i];
592 i = check_one_conflict(r->index, i, &conflict_type);
593 if (conflict_type == PUNTED)
594 string_list_insert(merge_rr, (const char *)e->name);
595 else if (conflict_type == RESOLVED) {
596 struct string_list_item *it;
597 it = string_list_lookup(merge_rr, (const char *)e->name);
598 if (it) {
599 free_rerere_id(it);
600 it->util = RERERE_RESOLVED;
604 return 0;
608 * Try using the given conflict resolution "ID" to see
609 * if that recorded conflict resolves cleanly what we
610 * got in the "cur".
612 static int try_merge(struct index_state *istate,
613 const struct rerere_id *id, const char *path,
614 mmfile_t *cur, mmbuffer_t *result)
616 enum ll_merge_result ret;
617 mmfile_t base = {NULL, 0}, other = {NULL, 0};
619 if (read_mmfile(&base, rerere_path(id, "preimage")) ||
620 read_mmfile(&other, rerere_path(id, "postimage"))) {
621 ret = LL_MERGE_CONFLICT;
622 } else {
624 * A three-way merge. Note that this honors user-customizable
625 * low-level merge driver settings.
627 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "",
628 istate, NULL);
631 free(base.ptr);
632 free(other.ptr);
634 return ret;
638 * Find the conflict identified by "id"; the change between its
639 * "preimage" (i.e. a previous contents with conflict markers) and its
640 * "postimage" (i.e. the corresponding contents with conflicts
641 * resolved) may apply cleanly to the contents stored in "path", i.e.
642 * the conflict this time around.
644 * Returns 0 for successful replay of recorded resolution, or non-zero
645 * for failure.
647 static int merge(struct index_state *istate, const struct rerere_id *id, const char *path)
649 FILE *f;
650 int ret;
651 mmfile_t cur = {NULL, 0};
652 mmbuffer_t result = {NULL, 0};
655 * Normalize the conflicts in path and write it out to
656 * "thisimage" temporary file.
658 if ((handle_file(istate, path, NULL, rerere_path(id, "thisimage")) < 0) ||
659 read_mmfile(&cur, rerere_path(id, "thisimage"))) {
660 ret = 1;
661 goto out;
664 ret = try_merge(istate, id, path, &cur, &result);
665 if (ret)
666 goto out;
669 * A successful replay of recorded resolution.
670 * Mark that "postimage" was used to help gc.
672 if (utime(rerere_path(id, "postimage"), NULL) < 0)
673 warning_errno(_("failed utime() on '%s'"),
674 rerere_path(id, "postimage"));
676 /* Update "path" with the resolution */
677 f = fopen(path, "w");
678 if (!f)
679 return error_errno(_("could not open '%s'"), path);
680 if (fwrite(result.ptr, result.size, 1, f) != 1)
681 error_errno(_("could not write '%s'"), path);
682 if (fclose(f))
683 return error_errno(_("writing '%s' failed"), path);
685 out:
686 free(cur.ptr);
687 free(result.ptr);
689 return ret;
692 static void update_paths(struct repository *r, struct string_list *update)
694 struct lock_file index_lock = LOCK_INIT;
695 int i;
697 repo_hold_locked_index(r, &index_lock, LOCK_DIE_ON_ERROR);
699 for (i = 0; i < update->nr; i++) {
700 struct string_list_item *item = &update->items[i];
701 if (add_file_to_index(r->index, item->string, 0))
702 exit(128);
703 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
704 item->string);
707 if (write_locked_index(r->index, &index_lock,
708 COMMIT_LOCK | SKIP_IF_UNCHANGED))
709 die(_("unable to write new index file"));
712 static void remove_variant(struct rerere_id *id)
714 unlink_or_warn(rerere_path(id, "postimage"));
715 unlink_or_warn(rerere_path(id, "preimage"));
716 id->collection->status[id->variant] = 0;
720 * The path indicated by rr_item may still have conflict for which we
721 * have a recorded resolution, in which case replay it and optionally
722 * update it. Or it may have been resolved by the user and we may
723 * only have the preimage for that conflict, in which case the result
724 * needs to be recorded as a resolution in a postimage file.
726 static void do_rerere_one_path(struct index_state *istate,
727 struct string_list_item *rr_item,
728 struct string_list *update)
730 const char *path = rr_item->string;
731 struct rerere_id *id = rr_item->util;
732 struct rerere_dir *rr_dir = id->collection;
733 int variant;
735 variant = id->variant;
737 /* Has the user resolved it already? */
738 if (variant >= 0) {
739 if (!handle_file(istate, path, NULL, NULL)) {
740 copy_file(rerere_path(id, "postimage"), path, 0666);
741 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
742 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
743 free_rerere_id(rr_item);
744 rr_item->util = NULL;
745 return;
748 * There may be other variants that can cleanly
749 * replay. Try them and update the variant number for
750 * this one.
754 /* Does any existing resolution apply cleanly? */
755 for (variant = 0; variant < rr_dir->status_nr; variant++) {
756 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
757 struct rerere_id vid = *id;
759 if ((rr_dir->status[variant] & both) != both)
760 continue;
762 vid.variant = variant;
763 if (merge(istate, &vid, path))
764 continue; /* failed to replay */
767 * If there already is a different variant that applies
768 * cleanly, there is no point maintaining our own variant.
770 if (0 <= id->variant && id->variant != variant)
771 remove_variant(id);
773 if (rerere_autoupdate)
774 string_list_insert(update, path);
775 else
776 fprintf_ln(stderr,
777 _("Resolved '%s' using previous resolution."),
778 path);
779 free_rerere_id(rr_item);
780 rr_item->util = NULL;
781 return;
784 /* None of the existing one applies; we need a new variant */
785 assign_variant(id);
787 variant = id->variant;
788 handle_file(istate, path, NULL, rerere_path(id, "preimage"));
789 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
790 const char *path = rerere_path(id, "postimage");
791 if (unlink(path))
792 die_errno(_("cannot unlink stray '%s'"), path);
793 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
795 id->collection->status[variant] |= RR_HAS_PREIMAGE;
796 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
799 static int do_plain_rerere(struct repository *r,
800 struct string_list *rr, int fd)
802 struct string_list conflict = STRING_LIST_INIT_DUP;
803 struct string_list update = STRING_LIST_INIT_DUP;
804 int i;
806 find_conflict(r, &conflict);
809 * MERGE_RR records paths with conflicts immediately after
810 * merge failed. Some of the conflicted paths might have been
811 * hand resolved in the working tree since then, but the
812 * initial run would catch all and register their preimages.
814 for (i = 0; i < conflict.nr; i++) {
815 struct rerere_id *id;
816 unsigned char hash[GIT_MAX_RAWSZ];
817 const char *path = conflict.items[i].string;
818 int ret;
821 * Ask handle_file() to scan and assign a
822 * conflict ID. No need to write anything out
823 * yet.
825 ret = handle_file(r->index, path, hash, NULL);
826 if (ret != 0 && string_list_has_string(rr, path)) {
827 remove_variant(string_list_lookup(rr, path)->util);
828 string_list_remove(rr, path, 1);
830 if (ret < 1)
831 continue;
833 id = new_rerere_id(hash);
834 string_list_insert(rr, path)->util = id;
836 /* Ensure that the directory exists. */
837 mkdir_in_gitdir(rerere_path(id, NULL));
840 for (i = 0; i < rr->nr; i++)
841 do_rerere_one_path(r->index, &rr->items[i], &update);
843 if (update.nr)
844 update_paths(r, &update);
846 return write_rr(rr, fd);
849 static void git_rerere_config(void)
851 git_config_get_bool("rerere.enabled", &rerere_enabled);
852 git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
853 git_config(git_default_config, NULL);
856 static GIT_PATH_FUNC(git_path_rr_cache, "rr-cache")
858 static int is_rerere_enabled(void)
860 int rr_cache_exists;
862 if (!rerere_enabled)
863 return 0;
865 rr_cache_exists = is_directory(git_path_rr_cache());
866 if (rerere_enabled < 0)
867 return rr_cache_exists;
869 if (!rr_cache_exists && mkdir_in_gitdir(git_path_rr_cache()))
870 die(_("could not create directory '%s'"), git_path_rr_cache());
871 return 1;
874 int setup_rerere(struct repository *r, struct string_list *merge_rr, int flags)
876 int fd;
878 git_rerere_config();
879 if (!is_rerere_enabled())
880 return -1;
882 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
883 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
884 if (flags & RERERE_READONLY)
885 fd = 0;
886 else
887 fd = hold_lock_file_for_update(&write_lock,
888 git_path_merge_rr(r),
889 LOCK_DIE_ON_ERROR);
890 read_rr(r, merge_rr);
891 return fd;
895 * The main entry point that is called internally from codepaths that
896 * perform mergy operations, possibly leaving conflicted index entries
897 * and working tree files.
899 int repo_rerere(struct repository *r, int flags)
901 struct string_list merge_rr = STRING_LIST_INIT_DUP;
902 int fd, status;
904 fd = setup_rerere(r, &merge_rr, flags);
905 if (fd < 0)
906 return 0;
907 status = do_plain_rerere(r, &merge_rr, fd);
908 free_rerere_dirs();
909 return status;
913 * Subclass of rerere_io that reads from an in-core buffer that is a
914 * strbuf
916 struct rerere_io_mem {
917 struct rerere_io io;
918 struct strbuf input;
922 * ... and its getline() method implementation
924 static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
926 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
927 char *ep;
928 size_t len;
930 strbuf_release(sb);
931 if (!io->input.len)
932 return -1;
933 ep = memchr(io->input.buf, '\n', io->input.len);
934 if (!ep)
935 ep = io->input.buf + io->input.len;
936 else if (*ep == '\n')
937 ep++;
938 len = ep - io->input.buf;
939 strbuf_add(sb, io->input.buf, len);
940 strbuf_remove(&io->input, 0, len);
941 return 0;
944 static int handle_cache(struct index_state *istate,
945 const char *path, unsigned char *hash, const char *output)
947 mmfile_t mmfile[3] = {{NULL}};
948 mmbuffer_t result = {NULL, 0};
949 const struct cache_entry *ce;
950 int pos, len, i, has_conflicts;
951 struct rerere_io_mem io;
952 int marker_size = ll_merge_marker_size(istate, path);
955 * Reproduce the conflicted merge in-core
957 len = strlen(path);
958 pos = index_name_pos(istate, path, len);
959 if (0 <= pos)
960 return -1;
961 pos = -pos - 1;
963 while (pos < istate->cache_nr) {
964 enum object_type type;
965 unsigned long size;
967 ce = istate->cache[pos++];
968 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
969 break;
970 i = ce_stage(ce) - 1;
971 if (!mmfile[i].ptr) {
972 mmfile[i].ptr = read_object_file(&ce->oid, &type,
973 &size);
974 mmfile[i].size = size;
977 for (i = 0; i < 3; i++)
978 if (!mmfile[i].ptr && !mmfile[i].size)
979 mmfile[i].ptr = xstrdup("");
982 * NEEDSWORK: handle conflicts from merges with
983 * merge.renormalize set, too?
985 ll_merge(&result, path, &mmfile[0], NULL,
986 &mmfile[1], "ours",
987 &mmfile[2], "theirs",
988 istate, NULL);
989 for (i = 0; i < 3; i++)
990 free(mmfile[i].ptr);
992 memset(&io, 0, sizeof(io));
993 io.io.getline = rerere_mem_getline;
994 if (output)
995 io.io.output = fopen(output, "w");
996 else
997 io.io.output = NULL;
998 strbuf_init(&io.input, 0);
999 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1002 * Grab the conflict ID and optionally write the original
1003 * contents with conflict markers out.
1005 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1006 strbuf_release(&io.input);
1007 if (io.io.output)
1008 fclose(io.io.output);
1009 return has_conflicts;
1012 static int rerere_forget_one_path(struct index_state *istate,
1013 const char *path,
1014 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(istate, 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(istate, 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(istate, 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(istate, 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 repository *r, 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 (repo_read_index(r) < 0)
1100 return error(_("index file corrupt"));
1102 fd = setup_rerere(r, &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_index(r->index, pathspec);
1112 find_conflict(r, &conflict);
1113 for (i = 0; i < conflict.nr; i++) {
1114 struct string_list_item *it = &conflict.items[i];
1115 if (!match_pathspec(r->index, pathspec, it->string,
1116 strlen(it->string), 0, NULL, 0))
1117 continue;
1118 rerere_forget_one_path(r->index, 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 /* Does the basename in "path" look plausibly like an rr-cache entry? */
1171 static int is_rr_cache_dirname(const char *path)
1173 struct object_id oid;
1174 const char *end;
1175 return !parse_oid_hex(path, &oid, &end) && !*end;
1178 void rerere_gc(struct repository *r, struct string_list *rr)
1180 struct string_list to_remove = STRING_LIST_INIT_DUP;
1181 DIR *dir;
1182 struct dirent *e;
1183 int i;
1184 timestamp_t now = time(NULL);
1185 timestamp_t cutoff_noresolve = now - 15 * 86400;
1186 timestamp_t cutoff_resolve = now - 60 * 86400;
1188 if (setup_rerere(r, rr, 0) < 0)
1189 return;
1191 git_config_get_expiry_in_days("gc.rerereresolved", &cutoff_resolve, now);
1192 git_config_get_expiry_in_days("gc.rerereunresolved", &cutoff_noresolve, now);
1193 git_config(git_default_config, NULL);
1194 dir = opendir(git_path("rr-cache"));
1195 if (!dir)
1196 die_errno(_("unable to open rr-cache directory"));
1197 /* Collect stale conflict IDs ... */
1198 while ((e = readdir_skip_dot_and_dotdot(dir))) {
1199 struct rerere_dir *rr_dir;
1200 struct rerere_id id;
1201 int now_empty;
1203 if (!is_rr_cache_dirname(e->d_name))
1204 continue; /* or should we remove e->d_name? */
1206 rr_dir = find_rerere_dir(e->d_name);
1208 now_empty = 1;
1209 for (id.variant = 0, id.collection = rr_dir;
1210 id.variant < id.collection->status_nr;
1211 id.variant++) {
1212 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1213 if (id.collection->status[id.variant])
1214 now_empty = 0;
1216 if (now_empty)
1217 string_list_append(&to_remove, e->d_name);
1219 closedir(dir);
1221 /* ... and then remove the empty directories */
1222 for (i = 0; i < to_remove.nr; i++)
1223 rmdir(git_path("rr-cache/%s", to_remove.items[i].string));
1224 string_list_clear(&to_remove, 0);
1225 rollback_lock_file(&write_lock);
1229 * During a conflict resolution, after "rerere" recorded the
1230 * preimages, abandon them if the user did not resolve them or
1231 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1233 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1235 void rerere_clear(struct repository *r, struct string_list *merge_rr)
1237 int i;
1239 if (setup_rerere(r, merge_rr, 0) < 0)
1240 return;
1242 for (i = 0; i < merge_rr->nr; i++) {
1243 struct rerere_id *id = merge_rr->items[i].util;
1244 if (!has_rerere_resolution(id)) {
1245 unlink_rr_item(id);
1246 rmdir(rerere_path(id, NULL));
1249 unlink_or_warn(git_path_merge_rr(r));
1250 rollback_lock_file(&write_lock);