Git fork
1#define USE_THE_REPOSITORY_VARIABLE
2#define DISABLE_SIGN_COMPARE_WARNINGS
3
4#include "git-compat-util.h"
5#include "abspath.h"
6#include "config.h"
7#include "copy.h"
8#include "environment.h"
9#include "gettext.h"
10#include "hex.h"
11#include "lockfile.h"
12#include "string-list.h"
13#include "read-cache-ll.h"
14#include "rerere.h"
15#include "xdiff-interface.h"
16#include "dir.h"
17#include "resolve-undo.h"
18#include "merge-ll.h"
19#include "path.h"
20#include "pathspec.h"
21#include "object-file.h"
22#include "odb.h"
23#include "strmap.h"
24
25#define RESOLVED 0
26#define PUNTED 1
27#define THREE_STAGED 2
28void *RERERE_RESOLVED = &RERERE_RESOLVED;
29
30/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
31static int rerere_enabled = -1;
32
33/* automatically update cleanly resolved paths to the index */
34static int rerere_autoupdate;
35
36#define RR_HAS_POSTIMAGE 1
37#define RR_HAS_PREIMAGE 2
38struct rerere_dir {
39 int status_alloc, status_nr;
40 unsigned char *status;
41 char name[FLEX_ARRAY];
42};
43
44static struct strmap rerere_dirs = STRMAP_INIT;
45
46static void free_rerere_dirs(void)
47{
48 struct hashmap_iter iter;
49 struct strmap_entry *ent;
50
51 strmap_for_each_entry(&rerere_dirs, &iter, ent) {
52 struct rerere_dir *rr_dir = ent->value;
53 free(rr_dir->status);
54 free(rr_dir);
55 }
56 strmap_clear(&rerere_dirs, 0);
57}
58
59static void free_rerere_id(struct string_list_item *item)
60{
61 free(item->util);
62}
63
64static const char *rerere_id_hex(const struct rerere_id *id)
65{
66 return id->collection->name;
67}
68
69static void fit_variant(struct rerere_dir *rr_dir, int variant)
70{
71 variant++;
72 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
73 if (rr_dir->status_nr < variant) {
74 memset(rr_dir->status + rr_dir->status_nr,
75 '\0', variant - rr_dir->status_nr);
76 rr_dir->status_nr = variant;
77 }
78}
79
80static void assign_variant(struct rerere_id *id)
81{
82 int variant;
83 struct rerere_dir *rr_dir = id->collection;
84
85 variant = id->variant;
86 if (variant < 0) {
87 for (variant = 0; variant < rr_dir->status_nr; variant++)
88 if (!rr_dir->status[variant])
89 break;
90 }
91 fit_variant(rr_dir, variant);
92 id->variant = variant;
93}
94
95const char *rerere_path(struct strbuf *buf, const struct rerere_id *id, const char *file)
96{
97 if (!file)
98 return repo_git_path_replace(the_repository, buf, "rr-cache/%s",
99 rerere_id_hex(id));
100
101 if (id->variant <= 0)
102 return repo_git_path_replace(the_repository, buf, "rr-cache/%s/%s",
103 rerere_id_hex(id), file);
104
105 return repo_git_path_replace(the_repository, buf, "rr-cache/%s/%s.%d",
106 rerere_id_hex(id), file, id->variant);
107}
108
109static int is_rr_file(const char *name, const char *filename, int *variant)
110{
111 const char *suffix;
112 char *ep;
113
114 if (!strcmp(name, filename)) {
115 *variant = 0;
116 return 1;
117 }
118 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
119 return 0;
120
121 errno = 0;
122 *variant = strtol(suffix + 1, &ep, 10);
123 if (errno || *ep)
124 return 0;
125 return 1;
126}
127
128static void scan_rerere_dir(struct rerere_dir *rr_dir)
129{
130 struct dirent *de;
131 char *path;
132 DIR *dir;
133
134 path = repo_git_path(the_repository, "rr-cache/%s", rr_dir->name);
135 dir = opendir(path);
136 free(path);
137 if (!dir)
138 return;
139 while ((de = readdir(dir)) != NULL) {
140 int variant;
141
142 if (is_rr_file(de->d_name, "postimage", &variant)) {
143 fit_variant(rr_dir, variant);
144 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
145 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
146 fit_variant(rr_dir, variant);
147 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
148 }
149 }
150 closedir(dir);
151}
152
153static struct rerere_dir *find_rerere_dir(const char *hex)
154{
155 struct rerere_dir *rr_dir;
156
157 rr_dir = strmap_get(&rerere_dirs, hex);
158 if (!rr_dir) {
159 FLEX_ALLOC_STR(rr_dir, name, hex);
160 rr_dir->status = NULL;
161 rr_dir->status_nr = 0;
162 rr_dir->status_alloc = 0;
163 strmap_put(&rerere_dirs, hex, rr_dir);
164
165 scan_rerere_dir(rr_dir);
166 }
167 return rr_dir;
168}
169
170static int has_rerere_resolution(const struct rerere_id *id)
171{
172 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
173 int variant = id->variant;
174
175 if (variant < 0)
176 return 0;
177 return ((id->collection->status[variant] & both) == both);
178}
179
180static struct rerere_id *new_rerere_id_hex(char *hex)
181{
182 struct rerere_id *id = xmalloc(sizeof(*id));
183 id->collection = find_rerere_dir(hex);
184 id->variant = -1; /* not known yet */
185 return id;
186}
187
188static struct rerere_id *new_rerere_id(unsigned char *hash)
189{
190 return new_rerere_id_hex(hash_to_hex(hash));
191}
192
193/*
194 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
195 * "conflict ID", a HT and pathname, terminated with a NUL, and is
196 * used to keep track of the set of paths that "rerere" may need to
197 * work on (i.e. what is left by the previous invocation of "git
198 * rerere" during the current conflict resolution session).
199 */
200static void read_rr(struct repository *r, struct string_list *rr)
201{
202 struct strbuf buf = STRBUF_INIT;
203 FILE *in = fopen_or_warn(git_path_merge_rr(r), "r");
204
205 if (!in)
206 return;
207 while (!strbuf_getwholeline(&buf, in, '\0')) {
208 char *path;
209 unsigned char hash[GIT_MAX_RAWSZ];
210 struct rerere_id *id;
211 int variant;
212 const unsigned hexsz = the_hash_algo->hexsz;
213
214 /* There has to be the hash, tab, path and then NUL */
215 if (buf.len < hexsz + 2 || get_hash_hex(buf.buf, hash))
216 die(_("corrupt MERGE_RR"));
217
218 if (buf.buf[hexsz] != '.') {
219 variant = 0;
220 path = buf.buf + hexsz;
221 } else {
222 errno = 0;
223 variant = strtol(buf.buf + hexsz + 1, &path, 10);
224 if (errno)
225 die(_("corrupt MERGE_RR"));
226 }
227 if (*(path++) != '\t')
228 die(_("corrupt MERGE_RR"));
229 buf.buf[hexsz] = '\0';
230 id = new_rerere_id_hex(buf.buf);
231 id->variant = variant;
232 /*
233 * make sure id->collection->status has enough space
234 * for the variant we are interested in
235 */
236 fit_variant(id->collection, variant);
237 string_list_insert(rr, path)->util = id;
238 }
239 strbuf_release(&buf);
240 fclose(in);
241}
242
243static struct lock_file write_lock;
244
245static int write_rr(struct string_list *rr, int out_fd)
246{
247 int i;
248 for (i = 0; i < rr->nr; i++) {
249 struct strbuf buf = STRBUF_INIT;
250 struct rerere_id *id;
251
252 assert(rr->items[i].util != RERERE_RESOLVED);
253
254 id = rr->items[i].util;
255 if (!id)
256 continue;
257 assert(id->variant >= 0);
258 if (0 < id->variant)
259 strbuf_addf(&buf, "%s.%d\t%s%c",
260 rerere_id_hex(id), id->variant,
261 rr->items[i].string, 0);
262 else
263 strbuf_addf(&buf, "%s\t%s%c",
264 rerere_id_hex(id),
265 rr->items[i].string, 0);
266
267 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
268 die(_("unable to write rerere record"));
269
270 strbuf_release(&buf);
271 }
272 if (commit_lock_file(&write_lock) != 0)
273 die(_("unable to write rerere record"));
274 return 0;
275}
276
277/*
278 * "rerere" interacts with conflicted file contents using this I/O
279 * abstraction. It reads a conflicted contents from one place via
280 * "getline()" method, and optionally can write it out after
281 * normalizing the conflicted hunks to the "output". Subclasses of
282 * rerere_io embed this structure at the beginning of their own
283 * rerere_io object.
284 */
285struct rerere_io {
286 int (*getline)(struct strbuf *, struct rerere_io *);
287 FILE *output;
288 int wrerror;
289 /* some more stuff */
290};
291
292static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
293{
294 if (!count || *err)
295 return;
296 if (fwrite(p, count, 1, fp) != 1)
297 *err = errno;
298}
299
300static inline void ferr_puts(const char *s, FILE *fp, int *err)
301{
302 ferr_write(s, strlen(s), fp, err);
303}
304
305static void rerere_io_putstr(const char *str, struct rerere_io *io)
306{
307 if (io->output)
308 ferr_puts(str, io->output, &io->wrerror);
309}
310
311static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
312{
313 if (io->output)
314 ferr_write(mem, sz, io->output, &io->wrerror);
315}
316
317/*
318 * Subclass of rerere_io that reads from an on-disk file
319 */
320struct rerere_io_file {
321 struct rerere_io io;
322 FILE *input;
323};
324
325/*
326 * ... and its getline() method implementation
327 */
328static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
329{
330 struct rerere_io_file *io = (struct rerere_io_file *)io_;
331 return strbuf_getwholeline(sb, io->input, '\n');
332}
333
334/*
335 * Require the exact number of conflict marker letters, no more, no
336 * less, followed by SP or any whitespace
337 * (including LF).
338 */
339static int is_cmarker(char *buf, int marker_char, int marker_size)
340{
341 int want_sp;
342
343 /*
344 * The beginning of our version and the end of their version
345 * always are labeled like "<<<<< ours" or ">>>>> theirs",
346 * hence we set want_sp for them. Note that the version from
347 * the common ancestor in diff3-style output is not always
348 * labelled (e.g. "||||| common" is often seen but "|||||"
349 * alone is also valid), so we do not set want_sp.
350 */
351 want_sp = (marker_char == '<') || (marker_char == '>');
352
353 while (marker_size--)
354 if (*buf++ != marker_char)
355 return 0;
356 if (want_sp && *buf != ' ')
357 return 0;
358 return isspace(*buf);
359}
360
361static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
362{
363 strbuf_addchars(buf, ch, size);
364 strbuf_addch(buf, '\n');
365}
366
367static int handle_conflict(struct strbuf *out, struct rerere_io *io,
368 int marker_size, struct git_hash_ctx *ctx)
369{
370 enum {
371 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
372 } hunk = RR_SIDE_1;
373 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
374 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
375 int has_conflicts = -1;
376
377 while (!io->getline(&buf, io)) {
378 if (is_cmarker(buf.buf, '<', marker_size)) {
379 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
380 break;
381 if (hunk == RR_SIDE_1)
382 strbuf_addbuf(&one, &conflict);
383 else
384 strbuf_addbuf(&two, &conflict);
385 strbuf_release(&conflict);
386 } else if (is_cmarker(buf.buf, '|', marker_size)) {
387 if (hunk != RR_SIDE_1)
388 break;
389 hunk = RR_ORIGINAL;
390 } else if (is_cmarker(buf.buf, '=', marker_size)) {
391 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
392 break;
393 hunk = RR_SIDE_2;
394 } else if (is_cmarker(buf.buf, '>', marker_size)) {
395 if (hunk != RR_SIDE_2)
396 break;
397 if (strbuf_cmp(&one, &two) > 0)
398 strbuf_swap(&one, &two);
399 has_conflicts = 1;
400 rerere_strbuf_putconflict(out, '<', marker_size);
401 strbuf_addbuf(out, &one);
402 rerere_strbuf_putconflict(out, '=', marker_size);
403 strbuf_addbuf(out, &two);
404 rerere_strbuf_putconflict(out, '>', marker_size);
405 if (ctx) {
406 git_hash_update(ctx, one.buf ?
407 one.buf : "",
408 one.len + 1);
409 git_hash_update(ctx, two.buf ?
410 two.buf : "",
411 two.len + 1);
412 }
413 break;
414 } else if (hunk == RR_SIDE_1)
415 strbuf_addbuf(&one, &buf);
416 else if (hunk == RR_ORIGINAL)
417 ; /* discard */
418 else if (hunk == RR_SIDE_2)
419 strbuf_addbuf(&two, &buf);
420 }
421 strbuf_release(&one);
422 strbuf_release(&two);
423 strbuf_release(&buf);
424
425 return has_conflicts;
426}
427
428/*
429 * Read contents a file with conflicts, normalize the conflicts
430 * by (1) discarding the common ancestor version in diff3-style,
431 * (2) reordering our side and their side so that whichever sorts
432 * alphabetically earlier comes before the other one, while
433 * computing the "conflict ID", which is just an SHA-1 hash of
434 * one side of the conflict, NUL, the other side of the conflict,
435 * and NUL concatenated together.
436 *
437 * Return 1 if conflict hunks are found, 0 if there are no conflict
438 * hunks and -1 if an error occurred.
439 */
440static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
441{
442 struct git_hash_ctx ctx;
443 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
444 int has_conflicts = 0;
445 if (hash)
446 the_hash_algo->init_fn(&ctx);
447
448 while (!io->getline(&buf, io)) {
449 if (is_cmarker(buf.buf, '<', marker_size)) {
450 has_conflicts = handle_conflict(&out, io, marker_size,
451 hash ? &ctx : NULL);
452 if (has_conflicts < 0)
453 break;
454 rerere_io_putmem(out.buf, out.len, io);
455 strbuf_reset(&out);
456 } else
457 rerere_io_putstr(buf.buf, io);
458 }
459 strbuf_release(&buf);
460 strbuf_release(&out);
461
462 if (hash)
463 git_hash_final(hash, &ctx);
464
465 return has_conflicts;
466}
467
468/*
469 * Scan the path for conflicts, do the "handle_path()" thing above, and
470 * return the number of conflict hunks found.
471 */
472static int handle_file(struct index_state *istate,
473 const char *path, unsigned char *hash, const char *output)
474{
475 int has_conflicts = 0;
476 struct rerere_io_file io;
477 int marker_size = ll_merge_marker_size(istate, path);
478
479 memset(&io, 0, sizeof(io));
480 io.io.getline = rerere_file_getline;
481 io.input = fopen(path, "r");
482 io.io.wrerror = 0;
483 if (!io.input)
484 return error_errno(_("could not open '%s'"), path);
485
486 if (output) {
487 io.io.output = fopen(output, "w");
488 if (!io.io.output) {
489 error_errno(_("could not write '%s'"), output);
490 fclose(io.input);
491 return -1;
492 }
493 }
494
495 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
496
497 fclose(io.input);
498 if (io.io.wrerror)
499 error(_("there were errors while writing '%s' (%s)"),
500 path, strerror(io.io.wrerror));
501 if (io.io.output && fclose(io.io.output))
502 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
503
504 if (has_conflicts < 0) {
505 if (output)
506 unlink_or_warn(output);
507 return error(_("could not parse conflict hunks in '%s'"), path);
508 }
509 if (io.io.wrerror)
510 return -1;
511 return has_conflicts;
512}
513
514/*
515 * Look at a cache entry at "i" and see if it is not conflicting,
516 * conflicting and we are willing to handle, or conflicting and
517 * we are unable to handle, and return the determination in *type.
518 * Return the cache index to be looked at next, by skipping the
519 * stages we have already looked at in this invocation of this
520 * function.
521 */
522static int check_one_conflict(struct index_state *istate, int i, int *type)
523{
524 const struct cache_entry *e = istate->cache[i];
525
526 if (!ce_stage(e)) {
527 *type = RESOLVED;
528 return i + 1;
529 }
530
531 *type = PUNTED;
532 while (i < istate->cache_nr && ce_stage(istate->cache[i]) == 1)
533 i++;
534
535 /* Only handle regular files with both stages #2 and #3 */
536 if (i + 1 < istate->cache_nr) {
537 const struct cache_entry *e2 = istate->cache[i];
538 const struct cache_entry *e3 = istate->cache[i + 1];
539 if (ce_stage(e2) == 2 &&
540 ce_stage(e3) == 3 &&
541 ce_same_name(e, e3) &&
542 S_ISREG(e2->ce_mode) &&
543 S_ISREG(e3->ce_mode))
544 *type = THREE_STAGED;
545 }
546
547 /* Skip the entries with the same name */
548 while (i < istate->cache_nr && ce_same_name(e, istate->cache[i]))
549 i++;
550 return i;
551}
552
553/*
554 * Scan the index and find paths that have conflicts that rerere can
555 * handle, i.e. the ones that has both stages #2 and #3.
556 *
557 * NEEDSWORK: we do not record or replay a previous "resolve by
558 * deletion" for a delete-modify conflict, as that is inherently risky
559 * without knowing what modification is being discarded. The only
560 * safe case, i.e. both side doing the deletion and modification that
561 * are identical to the previous round, might want to be handled,
562 * though.
563 */
564static int find_conflict(struct repository *r, struct string_list *conflict)
565{
566 int i;
567
568 if (repo_read_index(r) < 0)
569 return error(_("index file corrupt"));
570
571 for (i = 0; i < r->index->cache_nr;) {
572 int conflict_type;
573 const struct cache_entry *e = r->index->cache[i];
574 i = check_one_conflict(r->index, i, &conflict_type);
575 if (conflict_type == THREE_STAGED)
576 string_list_insert(conflict, (const char *)e->name);
577 }
578 return 0;
579}
580
581/*
582 * The merge_rr list is meant to hold outstanding conflicted paths
583 * that rerere could handle. Abuse the list by adding other types of
584 * entries to allow the caller to show "rerere remaining".
585 *
586 * - Conflicted paths that rerere does not handle are added
587 * - Conflicted paths that have been resolved are marked as such
588 * by storing RERERE_RESOLVED to .util field (where conflict ID
589 * is expected to be stored).
590 *
591 * Do *not* write MERGE_RR file out after calling this function.
592 *
593 * NEEDSWORK: we may want to fix the caller that implements "rerere
594 * remaining" to do this without abusing merge_rr.
595 */
596int rerere_remaining(struct repository *r, struct string_list *merge_rr)
597{
598 int i;
599
600 if (setup_rerere(r, merge_rr, RERERE_READONLY))
601 return 0;
602 if (repo_read_index(r) < 0)
603 return error(_("index file corrupt"));
604
605 for (i = 0; i < r->index->cache_nr;) {
606 int conflict_type;
607 const struct cache_entry *e = r->index->cache[i];
608 i = check_one_conflict(r->index, i, &conflict_type);
609 if (conflict_type == PUNTED)
610 string_list_insert(merge_rr, (const char *)e->name);
611 else if (conflict_type == RESOLVED) {
612 struct string_list_item *it;
613 it = string_list_lookup(merge_rr, (const char *)e->name);
614 if (it) {
615 free_rerere_id(it);
616 it->util = RERERE_RESOLVED;
617 }
618 }
619 }
620 return 0;
621}
622
623/*
624 * Try using the given conflict resolution "ID" to see
625 * if that recorded conflict resolves cleanly what we
626 * got in the "cur".
627 */
628static int try_merge(struct index_state *istate,
629 const struct rerere_id *id, const char *path,
630 mmfile_t *cur, mmbuffer_t *result)
631{
632 enum ll_merge_result ret;
633 mmfile_t base = {NULL, 0}, other = {NULL, 0};
634 struct strbuf buf = STRBUF_INIT;
635
636 if (read_mmfile(&base, rerere_path(&buf, id, "preimage")) ||
637 read_mmfile(&other, rerere_path(&buf, id, "postimage"))) {
638 ret = LL_MERGE_CONFLICT;
639 } else {
640 /*
641 * A three-way merge. Note that this honors user-customizable
642 * low-level merge driver settings.
643 */
644 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "",
645 istate, NULL);
646 }
647
648 strbuf_release(&buf);
649 free(base.ptr);
650 free(other.ptr);
651
652 return ret;
653}
654
655/*
656 * Find the conflict identified by "id"; the change between its
657 * "preimage" (i.e. a previous contents with conflict markers) and its
658 * "postimage" (i.e. the corresponding contents with conflicts
659 * resolved) may apply cleanly to the contents stored in "path", i.e.
660 * the conflict this time around.
661 *
662 * Returns 0 for successful replay of recorded resolution, or non-zero
663 * for failure.
664 */
665static int merge(struct index_state *istate, const struct rerere_id *id, const char *path)
666{
667 FILE *f;
668 int ret;
669 struct strbuf buf = STRBUF_INIT;
670 mmfile_t cur = {NULL, 0};
671 mmbuffer_t result = {NULL, 0};
672
673 /*
674 * Normalize the conflicts in path and write it out to
675 * "thisimage" temporary file.
676 */
677 if ((handle_file(istate, path, NULL, rerere_path(&buf, id, "thisimage")) < 0) ||
678 read_mmfile(&cur, rerere_path(&buf, id, "thisimage"))) {
679 ret = 1;
680 goto out;
681 }
682
683 ret = try_merge(istate, id, path, &cur, &result);
684 if (ret)
685 goto out;
686
687 /*
688 * A successful replay of recorded resolution.
689 * Mark that "postimage" was used to help gc.
690 */
691 if (utime(rerere_path(&buf, id, "postimage"), NULL) < 0)
692 warning_errno(_("failed utime() on '%s'"),
693 rerere_path(&buf, id, "postimage"));
694
695 /* Update "path" with the resolution */
696 f = fopen(path, "w");
697 if (!f)
698 return error_errno(_("could not open '%s'"), path);
699 if (fwrite(result.ptr, result.size, 1, f) != 1)
700 error_errno(_("could not write '%s'"), path);
701 if (fclose(f))
702 return error_errno(_("writing '%s' failed"), path);
703
704out:
705 free(cur.ptr);
706 free(result.ptr);
707 strbuf_release(&buf);
708
709 return ret;
710}
711
712static void update_paths(struct repository *r, struct string_list *update)
713{
714 struct lock_file index_lock = LOCK_INIT;
715 int i;
716
717 repo_hold_locked_index(r, &index_lock, LOCK_DIE_ON_ERROR);
718
719 for (i = 0; i < update->nr; i++) {
720 struct string_list_item *item = &update->items[i];
721 if (add_file_to_index(r->index, item->string, 0))
722 exit(128);
723 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
724 item->string);
725 }
726
727 if (write_locked_index(r->index, &index_lock,
728 COMMIT_LOCK | SKIP_IF_UNCHANGED))
729 die(_("unable to write new index file"));
730}
731
732static void remove_variant(struct rerere_id *id)
733{
734 struct strbuf buf = STRBUF_INIT;
735 unlink_or_warn(rerere_path(&buf, id, "postimage"));
736 unlink_or_warn(rerere_path(&buf, id, "preimage"));
737 id->collection->status[id->variant] = 0;
738 strbuf_release(&buf);
739}
740
741/*
742 * The path indicated by rr_item may still have conflict for which we
743 * have a recorded resolution, in which case replay it and optionally
744 * update it. Or it may have been resolved by the user and we may
745 * only have the preimage for that conflict, in which case the result
746 * needs to be recorded as a resolution in a postimage file.
747 */
748static void do_rerere_one_path(struct index_state *istate,
749 struct string_list_item *rr_item,
750 struct string_list *update)
751{
752 const char *path = rr_item->string;
753 struct rerere_id *id = rr_item->util;
754 struct rerere_dir *rr_dir = id->collection;
755 struct strbuf buf = STRBUF_INIT;
756 int variant;
757
758 variant = id->variant;
759
760 /* Has the user resolved it already? */
761 if (variant >= 0) {
762 if (!handle_file(istate, path, NULL, NULL)) {
763 copy_file(rerere_path(&buf, id, "postimage"), path, 0666);
764 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
765 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
766 free_rerere_id(rr_item);
767 rr_item->util = NULL;
768 goto out;
769 }
770 /*
771 * There may be other variants that can cleanly
772 * replay. Try them and update the variant number for
773 * this one.
774 */
775 }
776
777 /* Does any existing resolution apply cleanly? */
778 for (variant = 0; variant < rr_dir->status_nr; variant++) {
779 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
780 struct rerere_id vid = *id;
781
782 if ((rr_dir->status[variant] & both) != both)
783 continue;
784
785 vid.variant = variant;
786 if (merge(istate, &vid, path))
787 continue; /* failed to replay */
788
789 /*
790 * If there already is a different variant that applies
791 * cleanly, there is no point maintaining our own variant.
792 */
793 if (0 <= id->variant && id->variant != variant)
794 remove_variant(id);
795
796 if (rerere_autoupdate)
797 string_list_insert(update, path);
798 else
799 fprintf_ln(stderr,
800 _("Resolved '%s' using previous resolution."),
801 path);
802 free_rerere_id(rr_item);
803 rr_item->util = NULL;
804 goto out;
805 }
806
807 /* None of the existing one applies; we need a new variant */
808 assign_variant(id);
809
810 variant = id->variant;
811 handle_file(istate, path, NULL, rerere_path(&buf, id, "preimage"));
812 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
813 const char *path = rerere_path(&buf, id, "postimage");
814 if (unlink(path))
815 die_errno(_("cannot unlink stray '%s'"), path);
816 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
817 }
818 id->collection->status[variant] |= RR_HAS_PREIMAGE;
819 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
820
821out:
822 strbuf_release(&buf);
823}
824
825static int do_plain_rerere(struct repository *r,
826 struct string_list *rr, int fd)
827{
828 struct string_list conflict = STRING_LIST_INIT_DUP;
829 struct string_list update = STRING_LIST_INIT_DUP;
830 struct strbuf buf = STRBUF_INIT;
831 int i;
832
833 find_conflict(r, &conflict);
834
835 /*
836 * MERGE_RR records paths with conflicts immediately after
837 * merge failed. Some of the conflicted paths might have been
838 * hand resolved in the working tree since then, but the
839 * initial run would catch all and register their preimages.
840 */
841 for (i = 0; i < conflict.nr; i++) {
842 struct rerere_id *id;
843 unsigned char hash[GIT_MAX_RAWSZ];
844 const char *path = conflict.items[i].string;
845 int ret;
846
847 /*
848 * Ask handle_file() to scan and assign a
849 * conflict ID. No need to write anything out
850 * yet.
851 */
852 ret = handle_file(r->index, path, hash, NULL);
853 if (ret != 0 && string_list_has_string(rr, path)) {
854 remove_variant(string_list_lookup(rr, path)->util);
855 string_list_remove(rr, path, 1);
856 }
857 if (ret < 1)
858 continue;
859
860 id = new_rerere_id(hash);
861 string_list_insert(rr, path)->util = id;
862
863 /* Ensure that the directory exists. */
864 safe_create_dir_in_gitdir(the_repository, rerere_path(&buf, id, NULL));
865 }
866
867 for (i = 0; i < rr->nr; i++)
868 do_rerere_one_path(r->index, &rr->items[i], &update);
869
870 if (update.nr)
871 update_paths(r, &update);
872
873 string_list_clear(&conflict, 0);
874 string_list_clear(&update, 0);
875 strbuf_release(&buf);
876 return write_rr(rr, fd);
877}
878
879static void git_rerere_config(void)
880{
881 repo_config_get_bool(the_repository, "rerere.enabled", &rerere_enabled);
882 repo_config_get_bool(the_repository, "rerere.autoupdate", &rerere_autoupdate);
883 repo_config(the_repository, git_default_config, NULL);
884}
885
886static GIT_PATH_FUNC(git_path_rr_cache, "rr-cache")
887
888static int is_rerere_enabled(void)
889{
890 int rr_cache_exists;
891
892 if (!rerere_enabled)
893 return 0;
894
895 rr_cache_exists = is_directory(git_path_rr_cache());
896 if (rerere_enabled < 0)
897 return rr_cache_exists;
898
899 if (!rr_cache_exists &&
900 safe_create_dir_in_gitdir(the_repository, git_path_rr_cache()))
901 die(_("could not create directory '%s'"), git_path_rr_cache());
902 return 1;
903}
904
905int setup_rerere(struct repository *r, struct string_list *merge_rr, int flags)
906{
907 int fd;
908
909 git_rerere_config();
910 if (!is_rerere_enabled())
911 return -1;
912
913 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
914 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
915 if (flags & RERERE_READONLY)
916 fd = 0;
917 else
918 fd = hold_lock_file_for_update(&write_lock,
919 git_path_merge_rr(r),
920 LOCK_DIE_ON_ERROR);
921 read_rr(r, merge_rr);
922 return fd;
923}
924
925/*
926 * The main entry point that is called internally from codepaths that
927 * perform mergy operations, possibly leaving conflicted index entries
928 * and working tree files.
929 */
930int repo_rerere(struct repository *r, int flags)
931{
932 struct string_list merge_rr = STRING_LIST_INIT_DUP;
933 int fd, status;
934
935 fd = setup_rerere(r, &merge_rr, flags);
936 if (fd < 0)
937 return 0;
938 status = do_plain_rerere(r, &merge_rr, fd);
939 free_rerere_dirs();
940 string_list_clear(&merge_rr, 1);
941 return status;
942}
943
944/*
945 * Subclass of rerere_io that reads from an in-core buffer that is a
946 * strbuf
947 */
948struct rerere_io_mem {
949 struct rerere_io io;
950 struct strbuf input;
951};
952
953/*
954 * ... and its getline() method implementation
955 */
956static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
957{
958 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
959 char *ep;
960 size_t len;
961
962 strbuf_release(sb);
963 if (!io->input.len)
964 return -1;
965 ep = memchr(io->input.buf, '\n', io->input.len);
966 if (!ep)
967 ep = io->input.buf + io->input.len;
968 else if (*ep == '\n')
969 ep++;
970 len = ep - io->input.buf;
971 strbuf_add(sb, io->input.buf, len);
972 strbuf_remove(&io->input, 0, len);
973 return 0;
974}
975
976static int handle_cache(struct index_state *istate,
977 const char *path, unsigned char *hash, const char *output)
978{
979 mmfile_t mmfile[3] = {{NULL}};
980 mmbuffer_t result = {NULL, 0};
981 const struct cache_entry *ce;
982 int pos, len, i, has_conflicts;
983 struct rerere_io_mem io;
984 int marker_size = ll_merge_marker_size(istate, path);
985
986 /*
987 * Reproduce the conflicted merge in-core
988 */
989 len = strlen(path);
990 pos = index_name_pos(istate, path, len);
991 if (0 <= pos)
992 return -1;
993 pos = -pos - 1;
994
995 while (pos < istate->cache_nr) {
996 enum object_type type;
997 unsigned long size;
998
999 ce = istate->cache[pos++];
1000 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
1001 break;
1002 i = ce_stage(ce) - 1;
1003 if (!mmfile[i].ptr) {
1004 mmfile[i].ptr = odb_read_object(the_repository->objects,
1005 &ce->oid, &type, &size);
1006 if (!mmfile[i].ptr)
1007 die(_("unable to read %s"),
1008 oid_to_hex(&ce->oid));
1009 mmfile[i].size = size;
1010 }
1011 }
1012 for (i = 0; i < 3; i++)
1013 if (!mmfile[i].ptr && !mmfile[i].size)
1014 mmfile[i].ptr = xstrdup("");
1015
1016 /*
1017 * NEEDSWORK: handle conflicts from merges with
1018 * merge.renormalize set, too?
1019 */
1020 ll_merge(&result, path, &mmfile[0], NULL,
1021 &mmfile[1], "ours",
1022 &mmfile[2], "theirs",
1023 istate, NULL);
1024 for (i = 0; i < 3; i++)
1025 free(mmfile[i].ptr);
1026
1027 memset(&io, 0, sizeof(io));
1028 io.io.getline = rerere_mem_getline;
1029 if (output)
1030 io.io.output = fopen(output, "w");
1031 else
1032 io.io.output = NULL;
1033 strbuf_init(&io.input, 0);
1034 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1035
1036 /*
1037 * Grab the conflict ID and optionally write the original
1038 * contents with conflict markers out.
1039 */
1040 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1041 strbuf_release(&io.input);
1042 if (io.io.output)
1043 fclose(io.io.output);
1044 return has_conflicts;
1045}
1046
1047static int rerere_forget_one_path(struct index_state *istate,
1048 const char *path,
1049 struct string_list *rr)
1050{
1051 const char *filename;
1052 struct rerere_id *id;
1053 unsigned char hash[GIT_MAX_RAWSZ];
1054 int ret;
1055 struct strbuf buf = STRBUF_INIT;
1056 struct string_list_item *item;
1057
1058 /*
1059 * Recreate the original conflict from the stages in the
1060 * index and compute the conflict ID
1061 */
1062 ret = handle_cache(istate, path, hash, NULL);
1063 if (ret < 1)
1064 return error(_("could not parse conflict hunks in '%s'"), path);
1065
1066 /* Nuke the recorded resolution for the conflict */
1067 id = new_rerere_id(hash);
1068
1069 for (id->variant = 0;
1070 id->variant < id->collection->status_nr;
1071 id->variant++) {
1072 mmfile_t cur = { NULL, 0 };
1073 mmbuffer_t result = {NULL, 0};
1074 int cleanly_resolved;
1075
1076 if (!has_rerere_resolution(id))
1077 continue;
1078
1079 handle_cache(istate, path, hash, rerere_path(&buf, id, "thisimage"));
1080 if (read_mmfile(&cur, rerere_path(&buf, id, "thisimage"))) {
1081 free(cur.ptr);
1082 error(_("failed to update conflicted state in '%s'"), path);
1083 goto fail_exit;
1084 }
1085 cleanly_resolved = !try_merge(istate, id, path, &cur, &result);
1086 free(result.ptr);
1087 free(cur.ptr);
1088 if (cleanly_resolved)
1089 break;
1090 }
1091
1092 if (id->collection->status_nr <= id->variant) {
1093 error(_("no remembered resolution for '%s'"), path);
1094 goto fail_exit;
1095 }
1096
1097 filename = rerere_path(&buf, id, "postimage");
1098 if (unlink(filename)) {
1099 if (errno == ENOENT)
1100 error(_("no remembered resolution for '%s'"), path);
1101 else
1102 error_errno(_("cannot unlink '%s'"), filename);
1103 goto fail_exit;
1104 }
1105
1106 /*
1107 * Update the preimage so that the user can resolve the
1108 * conflict in the working tree, run us again to record
1109 * the postimage.
1110 */
1111 handle_cache(istate, path, hash, rerere_path(&buf, id, "preimage"));
1112 fprintf_ln(stderr, _("Updated preimage for '%s'"), path);
1113
1114 /*
1115 * And remember that we can record resolution for this
1116 * conflict when the user is done.
1117 */
1118 item = string_list_insert(rr, path);
1119 free_rerere_id(item);
1120 item->util = id;
1121 fprintf(stderr, _("Forgot resolution for '%s'\n"), path);
1122 strbuf_release(&buf);
1123 return 0;
1124
1125fail_exit:
1126 strbuf_release(&buf);
1127 free(id);
1128 return -1;
1129}
1130
1131int rerere_forget(struct repository *r, struct pathspec *pathspec)
1132{
1133 int i, fd, ret;
1134 struct string_list conflict = STRING_LIST_INIT_DUP;
1135 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1136
1137 if (repo_read_index(r) < 0)
1138 return error(_("index file corrupt"));
1139
1140 fd = setup_rerere(r, &merge_rr, RERERE_NOAUTOUPDATE);
1141 if (fd < 0)
1142 return 0;
1143
1144 /*
1145 * The paths may have been resolved (incorrectly);
1146 * recover the original conflicted state and then
1147 * find the conflicted paths.
1148 */
1149 unmerge_index(r->index, pathspec, 0);
1150 find_conflict(r, &conflict);
1151 for (i = 0; i < conflict.nr; i++) {
1152 struct string_list_item *it = &conflict.items[i];
1153 if (!match_pathspec(r->index, pathspec, it->string,
1154 strlen(it->string), 0, NULL, 0))
1155 continue;
1156 rerere_forget_one_path(r->index, it->string, &merge_rr);
1157 }
1158
1159 ret = write_rr(&merge_rr, fd);
1160
1161 string_list_clear(&conflict, 0);
1162 string_list_clear(&merge_rr, 1);
1163 return ret;
1164}
1165
1166/*
1167 * Garbage collection support
1168 */
1169
1170static timestamp_t rerere_created_at(struct rerere_id *id)
1171{
1172 struct strbuf buf = STRBUF_INIT;
1173 struct stat st;
1174 timestamp_t ret;
1175
1176 ret = stat(rerere_path(&buf, id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
1177
1178 strbuf_release(&buf);
1179 return ret;
1180}
1181
1182static timestamp_t rerere_last_used_at(struct rerere_id *id)
1183{
1184 struct strbuf buf = STRBUF_INIT;
1185 struct stat st;
1186 timestamp_t ret;
1187
1188 ret = stat(rerere_path(&buf, id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
1189
1190 strbuf_release(&buf);
1191 return ret;
1192}
1193
1194/*
1195 * Remove the recorded resolution for a given conflict ID
1196 */
1197static void unlink_rr_item(struct rerere_id *id)
1198{
1199 struct strbuf buf = STRBUF_INIT;
1200 unlink_or_warn(rerere_path(&buf, id, "thisimage"));
1201 remove_variant(id);
1202 id->collection->status[id->variant] = 0;
1203 strbuf_release(&buf);
1204}
1205
1206static void prune_one(struct rerere_id *id,
1207 timestamp_t cutoff_resolve, timestamp_t cutoff_noresolve)
1208{
1209 timestamp_t then;
1210 timestamp_t cutoff;
1211
1212 then = rerere_last_used_at(id);
1213 if (then)
1214 cutoff = cutoff_resolve;
1215 else {
1216 then = rerere_created_at(id);
1217 if (!then)
1218 return;
1219 cutoff = cutoff_noresolve;
1220 }
1221 if (then < cutoff)
1222 unlink_rr_item(id);
1223}
1224
1225/* Does the basename in "path" look plausibly like an rr-cache entry? */
1226static int is_rr_cache_dirname(const char *path)
1227{
1228 struct object_id oid;
1229 const char *end;
1230 return !parse_oid_hex(path, &oid, &end) && !*end;
1231}
1232
1233void rerere_gc(struct repository *r, struct string_list *rr)
1234{
1235 struct string_list to_remove = STRING_LIST_INIT_DUP;
1236 DIR *dir;
1237 struct dirent *e;
1238 int i;
1239 timestamp_t now = time(NULL);
1240 timestamp_t cutoff_noresolve = now - 15 * 86400;
1241 timestamp_t cutoff_resolve = now - 60 * 86400;
1242 struct strbuf buf = STRBUF_INIT;
1243
1244 if (setup_rerere(r, rr, 0) < 0)
1245 return;
1246
1247 repo_config_get_expiry_in_days(the_repository, "gc.rerereresolved",
1248 &cutoff_resolve, now);
1249 repo_config_get_expiry_in_days(the_repository, "gc.rerereunresolved",
1250 &cutoff_noresolve, now);
1251 repo_config(the_repository, git_default_config, NULL);
1252 dir = opendir(repo_git_path_replace(the_repository, &buf, "rr-cache"));
1253 if (!dir)
1254 die_errno(_("unable to open rr-cache directory"));
1255 /* Collect stale conflict IDs ... */
1256 while ((e = readdir_skip_dot_and_dotdot(dir))) {
1257 struct rerere_dir *rr_dir;
1258 struct rerere_id id;
1259 int now_empty;
1260
1261 if (!is_rr_cache_dirname(e->d_name))
1262 continue; /* or should we remove e->d_name? */
1263
1264 rr_dir = find_rerere_dir(e->d_name);
1265
1266 now_empty = 1;
1267 for (id.variant = 0, id.collection = rr_dir;
1268 id.variant < id.collection->status_nr;
1269 id.variant++) {
1270 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1271 if (id.collection->status[id.variant])
1272 now_empty = 0;
1273 }
1274 if (now_empty)
1275 string_list_append(&to_remove, e->d_name);
1276 }
1277 closedir(dir);
1278
1279 /* ... and then remove the empty directories */
1280 for (i = 0; i < to_remove.nr; i++)
1281 rmdir(repo_git_path_replace(the_repository, &buf,
1282 "rr-cache/%s", to_remove.items[i].string));
1283
1284 string_list_clear(&to_remove, 0);
1285 rollback_lock_file(&write_lock);
1286 strbuf_release(&buf);
1287}
1288
1289/*
1290 * During a conflict resolution, after "rerere" recorded the
1291 * preimages, abandon them if the user did not resolve them or
1292 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1293 *
1294 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1295 */
1296void rerere_clear(struct repository *r, struct string_list *merge_rr)
1297{
1298 int i;
1299
1300 if (setup_rerere(r, merge_rr, 0) < 0)
1301 return;
1302
1303 for (i = 0; i < merge_rr->nr; i++) {
1304 struct rerere_id *id = merge_rr->items[i].util;
1305 struct strbuf buf = STRBUF_INIT;
1306
1307 if (!has_rerere_resolution(id)) {
1308 unlink_rr_item(id);
1309 rmdir(rerere_path(&buf, id, NULL));
1310 }
1311
1312 strbuf_release(&buf);
1313 }
1314 unlink_or_warn(git_path_merge_rr(r));
1315 rollback_lock_file(&write_lock);
1316}