]> git.ipfire.org Git - thirdparty/git.git/blame - rerere.c
rerere: split conflict ID further
[thirdparty/git.git] / rerere.c
CommitLineData
5b2fd956 1#include "cache.h"
697cc8ef 2#include "lockfile.h"
c455c87c 3#include "string-list.h"
5b2fd956 4#include "rerere.h"
5b2fd956 5#include "xdiff-interface.h"
dea4562b
JH
6#include "dir.h"
7#include "resolve-undo.h"
8#include "ll-merge.h"
8588567c 9#include "attr.h"
01a10b0a 10#include "pathspec.h"
1869bbe1 11#include "sha1-lookup.h"
5b2fd956 12
ac49f5ca
MZ
13#define RESOLVED 0
14#define PUNTED 1
15#define THREE_STAGED 2
16void *RERERE_RESOLVED = &RERERE_RESOLVED;
17
5b2fd956
SB
18/* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
19static int rerere_enabled = -1;
20
21/* automatically update cleanly resolved paths to the index */
22static int rerere_autoupdate;
23
24static char *merge_rr_path;
25
1869bbe1
JH
26static int rerere_dir_nr;
27static int rerere_dir_alloc;
28
29static struct rerere_dir {
30 unsigned char sha1[20];
31} **rerere_dir;
32
33static void free_rerere_dirs(void)
34{
35 int i;
36 for (i = 0; i < rerere_dir_nr; i++)
37 free(rerere_dir[i]);
38 free(rerere_dir);
39 rerere_dir_nr = rerere_dir_alloc = 0;
40 rerere_dir = NULL;
41}
42
1d51eced 43static void free_rerere_id(struct string_list_item *item)
5b2fd956 44{
1d51eced
JH
45 free(item->util);
46}
47
48static const char *rerere_id_hex(const struct rerere_id *id)
49{
1869bbe1 50 return sha1_to_hex(id->collection->sha1);
1d51eced
JH
51}
52
53const char *rerere_path(const struct rerere_id *id, const char *file)
54{
55 if (!file)
56 return git_path("rr-cache/%s", rerere_id_hex(id));
57
58 return git_path("rr-cache/%s/%s", rerere_id_hex(id), file);
5b2fd956
SB
59}
60
1869bbe1
JH
61static const unsigned char *rerere_dir_sha1(size_t i, void *table)
62{
63 struct rerere_dir **rr_dir = table;
64 return rr_dir[i]->sha1;
65}
66
67static struct rerere_dir *find_rerere_dir(const char *hex)
68{
69 unsigned char sha1[20];
70 struct rerere_dir *rr_dir;
71 int pos;
72
73 if (get_sha1_hex(hex, sha1))
74 return NULL; /* BUG */
75 pos = sha1_pos(sha1, rerere_dir, rerere_dir_nr, rerere_dir_sha1);
76 if (pos < 0) {
77 rr_dir = xmalloc(sizeof(*rr_dir));
78 hashcpy(rr_dir->sha1, sha1);
79 pos = -1 - pos;
80
81 /* Make sure the array is big enough ... */
82 ALLOC_GROW(rerere_dir, rerere_dir_nr + 1, rerere_dir_alloc);
83 /* ... and add it in. */
84 rerere_dir_nr++;
85 memmove(rerere_dir + pos + 1, rerere_dir + pos,
86 (rerere_dir_nr - pos - 1) * sizeof(*rerere_dir));
87 rerere_dir[pos] = rr_dir;
88 }
89 return rerere_dir[pos];
90}
91
1d51eced 92static int has_rerere_resolution(const struct rerere_id *id)
5b2fd956
SB
93{
94 struct stat st;
1d51eced 95
18bb9934 96 return !stat(rerere_path(id, "postimage"), &st);
5b2fd956
SB
97}
98
1d51eced
JH
99static struct rerere_id *new_rerere_id_hex(char *hex)
100{
101 struct rerere_id *id = xmalloc(sizeof(*id));
1869bbe1 102 id->collection = find_rerere_dir(hex);
1d51eced
JH
103 return id;
104}
105
106static struct rerere_id *new_rerere_id(unsigned char *sha1)
107{
108 return new_rerere_id_hex(sha1_to_hex(sha1));
109}
110
4b68c2a0
JH
111/*
112 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
113 * "conflict ID", a HT and pathname, terminated with a NUL, and is
114 * used to keep track of the set of paths that "rerere" may need to
115 * work on (i.e. what is left by the previous invocation of "git
116 * rerere" during the current conflict resolution session).
117 */
c455c87c 118static void read_rr(struct string_list *rr)
5b2fd956 119{
f5800f6a 120 struct strbuf buf = STRBUF_INIT;
5b2fd956 121 FILE *in = fopen(merge_rr_path, "r");
f5800f6a 122
5b2fd956
SB
123 if (!in)
124 return;
f5800f6a
JH
125 while (!strbuf_getwholeline(&buf, in, '\0')) {
126 char *path;
127 unsigned char sha1[20];
1d51eced 128 struct rerere_id *id;
f5800f6a
JH
129
130 /* There has to be the hash, tab, path and then NUL */
131 if (buf.len < 42 || get_sha1_hex(buf.buf, sha1))
5b2fd956 132 die("corrupt MERGE_RR");
f5800f6a
JH
133
134 if (buf.buf[40] != '\t')
5b2fd956 135 die("corrupt MERGE_RR");
f5800f6a
JH
136 buf.buf[40] = '\0';
137 path = buf.buf + 41;
1d51eced
JH
138 id = new_rerere_id_hex(buf.buf);
139 string_list_insert(rr, path)->util = id;
5b2fd956 140 }
f5800f6a 141 strbuf_release(&buf);
5b2fd956
SB
142 fclose(in);
143}
144
145static struct lock_file write_lock;
146
c455c87c 147static int write_rr(struct string_list *rr, int out_fd)
5b2fd956
SB
148{
149 int i;
150 for (i = 0; i < rr->nr; i++) {
e2cb6a95 151 struct strbuf buf = STRBUF_INIT;
1d51eced 152 struct rerere_id *id;
e2cb6a95
JH
153
154 assert(rr->items[i].util != RERERE_RESOLVED);
1d51eced
JH
155
156 id = rr->items[i].util;
157 if (!id)
5b2fd956 158 continue;
e2cb6a95 159 strbuf_addf(&buf, "%s\t%s%c",
1d51eced 160 rerere_id_hex(id),
e2cb6a95
JH
161 rr->items[i].string, 0);
162 if (write_in_full(out_fd, buf.buf, buf.len) != buf.len)
5b2fd956 163 die("unable to write rerere record");
e2cb6a95
JH
164
165 strbuf_release(&buf);
5b2fd956
SB
166 }
167 if (commit_lock_file(&write_lock) != 0)
168 die("unable to write rerere record");
169 return 0;
170}
171
a96847cc
JH
172/*
173 * "rerere" interacts with conflicted file contents using this I/O
174 * abstraction. It reads a conflicted contents from one place via
175 * "getline()" method, and optionally can write it out after
176 * normalizing the conflicted hunks to the "output". Subclasses of
177 * rerere_io embed this structure at the beginning of their own
178 * rerere_io object.
179 */
180struct rerere_io {
181 int (*getline)(struct strbuf *, struct rerere_io *);
182 FILE *output;
183 int wrerror;
184 /* some more stuff */
185};
186
47d32af2
AR
187static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
188{
189 if (!count || *err)
190 return;
191 if (fwrite(p, count, 1, fp) != 1)
192 *err = errno;
193}
194
195static inline void ferr_puts(const char *s, FILE *fp, int *err)
196{
197 ferr_write(s, strlen(s), fp, err);
198}
199
27d6b085
JH
200static void rerere_io_putstr(const char *str, struct rerere_io *io)
201{
202 if (io->output)
203 ferr_puts(str, io->output, &io->wrerror);
204}
205
a96847cc
JH
206/*
207 * Write a conflict marker to io->output (if defined).
208 */
191f2417
JH
209static void rerere_io_putconflict(int ch, int size, struct rerere_io *io)
210{
211 char buf[64];
212
213 while (size) {
d3c2749d 214 if (size <= sizeof(buf) - 2) {
191f2417
JH
215 memset(buf, ch, size);
216 buf[size] = '\n';
217 buf[size + 1] = '\0';
218 size = 0;
219 } else {
220 int sz = sizeof(buf) - 1;
d3c2749d
JH
221
222 /*
223 * Make sure we will not write everything out
224 * in this round by leaving at least 1 byte
225 * for the next round, giving the next round
226 * a chance to add the terminating LF. Yuck.
227 */
191f2417
JH
228 if (size <= sz)
229 sz -= (sz - size) + 1;
230 memset(buf, ch, sz);
231 buf[sz] = '\0';
232 size -= sz;
233 }
234 rerere_io_putstr(buf, io);
235 }
236}
237
27d6b085
JH
238static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
239{
240 if (io->output)
241 ferr_write(mem, sz, io->output, &io->wrerror);
242}
243
a96847cc
JH
244/*
245 * Subclass of rerere_io that reads from an on-disk file
246 */
27d6b085
JH
247struct rerere_io_file {
248 struct rerere_io io;
249 FILE *input;
250};
251
a96847cc
JH
252/*
253 * ... and its getline() method implementation
254 */
27d6b085
JH
255static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
256{
257 struct rerere_io_file *io = (struct rerere_io_file *)io_;
258 return strbuf_getwholeline(sb, io->input, '\n');
259}
260
67711cdc
JH
261/*
262 * Require the exact number of conflict marker letters, no more, no
263 * less, followed by SP or any whitespace
264 * (including LF).
265 */
266static int is_cmarker(char *buf, int marker_char, int marker_size)
191f2417 267{
67711cdc
JH
268 int want_sp;
269
270 /*
271 * The beginning of our version and the end of their version
272 * always are labeled like "<<<<< ours" or ">>>>> theirs",
273 * hence we set want_sp for them. Note that the version from
274 * the common ancestor in diff3-style output is not always
275 * labelled (e.g. "||||| common" is often seen but "|||||"
276 * alone is also valid), so we do not set want_sp.
277 */
278 want_sp = (marker_char == '<') || (marker_char == '>');
279
191f2417
JH
280 while (marker_size--)
281 if (*buf++ != marker_char)
282 return 0;
283 if (want_sp && *buf != ' ')
284 return 0;
285 return isspace(*buf);
286}
287
cc899eca
JH
288/*
289 * Read contents a file with conflicts, normalize the conflicts
290 * by (1) discarding the common ancestor version in diff3-style,
291 * (2) reordering our side and their side so that whichever sorts
292 * alphabetically earlier comes before the other one, while
293 * computing the "conflict ID", which is just an SHA-1 hash of
294 * one side of the conflict, NUL, the other side of the conflict,
295 * and NUL concatenated together.
296 *
297 * Return the number of conflict hunks found.
298 *
299 * NEEDSWORK: the logic and theory of operation behind this conflict
300 * normalization may deserve to be documented somewhere, perhaps in
301 * Documentation/technical/rerere.txt.
302 */
191f2417 303static int handle_path(unsigned char *sha1, struct rerere_io *io, int marker_size)
5b2fd956 304{
9126f009 305 git_SHA_CTX ctx;
cc58d7df
JH
306 int hunk_no = 0;
307 enum {
4b05548f 308 RR_CONTEXT = 0, RR_SIDE_1, RR_SIDE_2, RR_ORIGINAL
cc58d7df 309 } hunk = RR_CONTEXT;
f285a2d7 310 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
d58ee6db 311 struct strbuf buf = STRBUF_INIT;
5b2fd956
SB
312
313 if (sha1)
9126f009 314 git_SHA1_Init(&ctx);
5b2fd956 315
27d6b085 316 while (!io->getline(&buf, io)) {
67711cdc 317 if (is_cmarker(buf.buf, '<', marker_size)) {
cc58d7df 318 if (hunk != RR_CONTEXT)
5b2fd956 319 goto bad;
cc58d7df 320 hunk = RR_SIDE_1;
67711cdc 321 } else if (is_cmarker(buf.buf, '|', marker_size)) {
cc58d7df 322 if (hunk != RR_SIDE_1)
5b2fd956 323 goto bad;
387c9d49 324 hunk = RR_ORIGINAL;
67711cdc 325 } else if (is_cmarker(buf.buf, '=', marker_size)) {
387c9d49 326 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
5b2fd956 327 goto bad;
cc58d7df 328 hunk = RR_SIDE_2;
67711cdc 329 } else if (is_cmarker(buf.buf, '>', marker_size)) {
cc58d7df 330 if (hunk != RR_SIDE_2)
5b2fd956
SB
331 goto bad;
332 if (strbuf_cmp(&one, &two) > 0)
333 strbuf_swap(&one, &two);
334 hunk_no++;
cc58d7df 335 hunk = RR_CONTEXT;
191f2417 336 rerere_io_putconflict('<', marker_size, io);
27d6b085 337 rerere_io_putmem(one.buf, one.len, io);
191f2417 338 rerere_io_putconflict('=', marker_size, io);
27d6b085 339 rerere_io_putmem(two.buf, two.len, io);
191f2417 340 rerere_io_putconflict('>', marker_size, io);
5b2fd956 341 if (sha1) {
9126f009 342 git_SHA1_Update(&ctx, one.buf ? one.buf : "",
5b2fd956 343 one.len + 1);
9126f009 344 git_SHA1_Update(&ctx, two.buf ? two.buf : "",
5b2fd956
SB
345 two.len + 1);
346 }
347 strbuf_reset(&one);
348 strbuf_reset(&two);
cc58d7df 349 } else if (hunk == RR_SIDE_1)
e992d1eb 350 strbuf_addbuf(&one, &buf);
387c9d49
JH
351 else if (hunk == RR_ORIGINAL)
352 ; /* discard */
cc58d7df 353 else if (hunk == RR_SIDE_2)
e992d1eb 354 strbuf_addbuf(&two, &buf);
27d6b085
JH
355 else
356 rerere_io_putstr(buf.buf, io);
5b2fd956
SB
357 continue;
358 bad:
359 hunk = 99; /* force error exit */
360 break;
361 }
362 strbuf_release(&one);
363 strbuf_release(&two);
d58ee6db 364 strbuf_release(&buf);
5b2fd956 365
5b2fd956 366 if (sha1)
9126f009 367 git_SHA1_Final(sha1, &ctx);
27d6b085
JH
368 if (hunk != RR_CONTEXT)
369 return -1;
370 return hunk_no;
371}
372
cc899eca
JH
373/*
374 * Scan the path for conflicts, do the "handle_path()" thing above, and
375 * return the number of conflict hunks found.
376 */
27d6b085
JH
377static int handle_file(const char *path, unsigned char *sha1, const char *output)
378{
379 int hunk_no = 0;
380 struct rerere_io_file io;
8588567c 381 int marker_size = ll_merge_marker_size(path);
27d6b085
JH
382
383 memset(&io, 0, sizeof(io));
384 io.io.getline = rerere_file_getline;
385 io.input = fopen(path, "r");
386 io.io.wrerror = 0;
387 if (!io.input)
388 return error("Could not open %s", path);
389
390 if (output) {
391 io.io.output = fopen(output, "w");
392 if (!io.io.output) {
393 fclose(io.input);
394 return error("Could not write %s", output);
395 }
396 }
397
191f2417 398 hunk_no = handle_path(sha1, (struct rerere_io *)&io, marker_size);
27d6b085
JH
399
400 fclose(io.input);
401 if (io.io.wrerror)
402 error("There were errors while writing %s (%s)",
403 path, strerror(io.io.wrerror));
404 if (io.io.output && fclose(io.io.output))
405 io.io.wrerror = error("Failed to flush %s: %s",
406 path, strerror(errno));
407
408 if (hunk_no < 0) {
5b2fd956 409 if (output)
691f1a28 410 unlink_or_warn(output);
5b2fd956
SB
411 return error("Could not parse conflict hunks in %s", path);
412 }
27d6b085 413 if (io.io.wrerror)
47d32af2 414 return -1;
5b2fd956
SB
415 return hunk_no;
416}
417
a96847cc
JH
418/*
419 * Subclass of rerere_io that reads from an in-core buffer that is a
420 * strbuf
421 */
dea4562b
JH
422struct rerere_io_mem {
423 struct rerere_io io;
424 struct strbuf input;
425};
426
a96847cc
JH
427/*
428 * ... and its getline() method implementation
429 */
dea4562b
JH
430static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
431{
432 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
433 char *ep;
434 size_t len;
435
436 strbuf_release(sb);
437 if (!io->input.len)
438 return -1;
53d8afaf
JS
439 ep = memchr(io->input.buf, '\n', io->input.len);
440 if (!ep)
441 ep = io->input.buf + io->input.len;
442 else if (*ep == '\n')
dea4562b
JH
443 ep++;
444 len = ep - io->input.buf;
445 strbuf_add(sb, io->input.buf, len);
446 strbuf_remove(&io->input, 0, len);
447 return 0;
448}
449
450static int handle_cache(const char *path, unsigned char *sha1, const char *output)
451{
b9e31f59 452 mmfile_t mmfile[3] = {{NULL}};
dea4562b 453 mmbuffer_t result = {NULL, 0};
9c5e6c80 454 const struct cache_entry *ce;
dea4562b
JH
455 int pos, len, i, hunk_no;
456 struct rerere_io_mem io;
8588567c 457 int marker_size = ll_merge_marker_size(path);
dea4562b
JH
458
459 /*
460 * Reproduce the conflicted merge in-core
461 */
462 len = strlen(path);
463 pos = cache_name_pos(path, len);
464 if (0 <= pos)
47d32af2 465 return -1;
dea4562b
JH
466 pos = -pos - 1;
467
74444d4e 468 while (pos < active_nr) {
dea4562b
JH
469 enum object_type type;
470 unsigned long size;
471
dea4562b 472 ce = active_cache[pos++];
b9e31f59 473 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
74444d4e
JH
474 break;
475 i = ce_stage(ce) - 1;
7d4053b6
JH
476 if (!mmfile[i].ptr) {
477 mmfile[i].ptr = read_sha1_file(ce->sha1, &type, &size);
478 mmfile[i].size = size;
479 }
dea4562b 480 }
74444d4e 481 for (i = 0; i < 3; i++)
dea4562b
JH
482 if (!mmfile[i].ptr && !mmfile[i].size)
483 mmfile[i].ptr = xstrdup("");
74444d4e 484
18b037a5
JN
485 /*
486 * NEEDSWORK: handle conflicts from merges with
487 * merge.renormalize set, too
488 */
f01de62e 489 ll_merge(&result, path, &mmfile[0], NULL,
dea4562b 490 &mmfile[1], "ours",
712516bc 491 &mmfile[2], "theirs", NULL);
dea4562b
JH
492 for (i = 0; i < 3; i++)
493 free(mmfile[i].ptr);
494
af86debc 495 memset(&io, 0, sizeof(io));
dea4562b
JH
496 io.io.getline = rerere_mem_getline;
497 if (output)
498 io.io.output = fopen(output, "w");
499 else
500 io.io.output = NULL;
501 strbuf_init(&io.input, 0);
502 strbuf_attach(&io.input, result.ptr, result.size, result.size);
503
963ec003
JH
504 /*
505 * Grab the conflict ID and optionally write the original
506 * contents with conflict markers out.
507 */
191f2417 508 hunk_no = handle_path(sha1, (struct rerere_io *)&io, marker_size);
dea4562b
JH
509 strbuf_release(&io.input);
510 if (io.io.output)
511 fclose(io.io.output);
5b2fd956
SB
512 return hunk_no;
513}
514
4b68c2a0
JH
515/*
516 * Look at a cache entry at "i" and see if it is not conflicting,
517 * conflicting and we are willing to handle, or conflicting and
518 * we are unable to handle, and return the determination in *type.
519 * Return the cache index to be looked at next, by skipping the
520 * stages we have already looked at in this invocation of this
521 * function.
522 */
ac49f5ca 523static int check_one_conflict(int i, int *type)
5b2fd956 524{
9c5e6c80 525 const struct cache_entry *e = active_cache[i];
ac49f5ca
MZ
526
527 if (!ce_stage(e)) {
528 *type = RESOLVED;
529 return i + 1;
530 }
531
532 *type = PUNTED;
5eda906b 533 while (ce_stage(active_cache[i]) == 1)
fb70a06d 534 i++;
ac49f5ca
MZ
535
536 /* Only handle regular files with both stages #2 and #3 */
537 if (i + 1 < active_nr) {
9c5e6c80
NTND
538 const struct cache_entry *e2 = active_cache[i];
539 const struct cache_entry *e3 = active_cache[i + 1];
5b2fd956
SB
540 if (ce_stage(e2) == 2 &&
541 ce_stage(e3) == 3 &&
ac49f5ca 542 ce_same_name(e, e3) &&
5b2fd956 543 S_ISREG(e2->ce_mode) &&
ac49f5ca
MZ
544 S_ISREG(e3->ce_mode))
545 *type = THREE_STAGED;
546 }
547
548 /* Skip the entries with the same name */
549 while (i < active_nr && ce_same_name(e, active_cache[i]))
550 i++;
551 return i;
552}
553
4b68c2a0
JH
554/*
555 * Scan the index and find paths that have conflicts that rerere can
556 * handle, i.e. the ones that has both stages #2 and #3.
557 *
558 * NEEDSWORK: we do not record or replay a previous "resolve by
559 * deletion" for a delete-modify conflict, as that is inherently risky
560 * without knowing what modification is being discarded. The only
561 * safe case, i.e. both side doing the deletion and modification that
562 * are identical to the previous round, might want to be handled,
563 * though.
564 */
ac49f5ca
MZ
565static int find_conflict(struct string_list *conflict)
566{
567 int i;
568 if (read_cache() < 0)
569 return error("Could not read index");
570
571 for (i = 0; i < active_nr;) {
572 int conflict_type;
9c5e6c80 573 const struct cache_entry *e = active_cache[i];
ac49f5ca
MZ
574 i = check_one_conflict(i, &conflict_type);
575 if (conflict_type == THREE_STAGED)
576 string_list_insert(conflict, (const char *)e->name);
577 }
578 return 0;
579}
580
4b68c2a0
JH
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 */
ac49f5ca
MZ
596int rerere_remaining(struct string_list *merge_rr)
597{
598 int i;
599 if (read_cache() < 0)
600 return error("Could not read index");
601
602 for (i = 0; i < active_nr;) {
603 int conflict_type;
9c5e6c80 604 const struct cache_entry *e = active_cache[i];
ac49f5ca
MZ
605 i = check_one_conflict(i, &conflict_type);
606 if (conflict_type == PUNTED)
607 string_list_insert(merge_rr, (const char *)e->name);
608 else if (conflict_type == RESOLVED) {
609 struct string_list_item *it;
610 it = string_list_lookup(merge_rr, (const char *)e->name);
611 if (it != NULL) {
1d51eced 612 free_rerere_id(it);
ac49f5ca
MZ
613 it->util = RERERE_RESOLVED;
614 }
5b2fd956
SB
615 }
616 }
617 return 0;
618}
619
cc899eca 620/*
18bb9934 621 * Find the conflict identified by "id"; the change between its
cc899eca
JH
622 * "preimage" (i.e. a previous contents with conflict markers) and its
623 * "postimage" (i.e. the corresponding contents with conflicts
624 * resolved) may apply cleanly to the contents stored in "path", i.e.
625 * the conflict this time around.
626 *
627 * Returns 0 for successful replay of recorded resolution, or non-zero
628 * for failure.
629 */
1d51eced 630static int merge(const struct rerere_id *id, const char *path)
5b2fd956 631{
15ed07d5 632 FILE *f;
5b2fd956 633 int ret;
689b8c29 634 mmfile_t cur = {NULL, 0}, base = {NULL, 0}, other = {NULL, 0};
5b2fd956 635 mmbuffer_t result = {NULL, 0};
5b2fd956 636
cc899eca
JH
637 /*
638 * Normalize the conflicts in path and write it out to
639 * "thisimage" temporary file.
640 */
15ed07d5
JH
641 if (handle_file(path, NULL, rerere_path(id, "thisimage")) < 0) {
642 ret = 1;
643 goto out;
644 }
5b2fd956 645
18bb9934
JH
646 if (read_mmfile(&cur, rerere_path(id, "thisimage")) ||
647 read_mmfile(&base, rerere_path(id, "preimage")) ||
648 read_mmfile(&other, rerere_path(id, "postimage"))) {
689b8c29
BW
649 ret = 1;
650 goto out;
651 }
cc899eca
JH
652
653 /*
654 * A three-way merge. Note that this honors user-customizable
655 * low-level merge driver settings.
656 */
1e4cd68c 657 ret = ll_merge(&result, path, &base, NULL, &cur, "", &other, "", NULL);
15ed07d5
JH
658 if (ret)
659 goto out;
660
661 /*
662 * A successful replay of recorded resolution.
663 * Mark that "postimage" was used to help gc.
664 */
665 if (utime(rerere_path(id, "postimage"), NULL) < 0)
666 warning("failed utime() on %s: %s",
667 rerere_path(id, "postimage"),
668 strerror(errno));
669
670 /* Update "path" with the resolution */
671 f = fopen(path, "w");
672 if (!f)
673 return error("Could not open %s: %s", path,
674 strerror(errno));
675 if (fwrite(result.ptr, result.size, 1, f) != 1)
676 error("Could not write %s: %s", path, strerror(errno));
677 if (fclose(f))
678 return error("Writing %s failed: %s", path,
679 strerror(errno));
5b2fd956 680
689b8c29 681out:
5b2fd956
SB
682 free(cur.ptr);
683 free(base.ptr);
684 free(other.ptr);
685 free(result.ptr);
686
687 return ret;
688}
689
690static struct lock_file index_lock;
691
89ea9035 692static void update_paths(struct string_list *update)
5b2fd956
SB
693{
694 int i;
5b2fd956 695
89ea9035 696 hold_locked_index(&index_lock, 1);
5b2fd956
SB
697
698 for (i = 0; i < update->nr; i++) {
c455c87c 699 struct string_list_item *item = &update->items[i];
89ea9035
JN
700 if (add_file_to_cache(item->string, 0))
701 exit(128);
a14c7ab8
JH
702 fprintf(stderr, "Staged '%s' using previous resolution.\n",
703 item->string);
5b2fd956
SB
704 }
705
89ea9035 706 if (active_cache_changed) {
03b86647 707 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
5b2fd956 708 die("Unable to write new index file");
89ea9035 709 } else
5b2fd956 710 rollback_lock_file(&index_lock);
5b2fd956
SB
711}
712
8e7768b2
JH
713/*
714 * The path indicated by rr_item may still have conflict for which we
715 * have a recorded resolution, in which case replay it and optionally
716 * update it. Or it may have been resolved by the user and we may
717 * only have the preimage for that conflict, in which case the result
718 * needs to be recorded as a resolution in a postimage file.
719 */
720static void do_rerere_one_path(struct string_list_item *rr_item,
721 struct string_list *update)
722{
723 const char *path = rr_item->string;
1d51eced 724 const struct rerere_id *id = rr_item->util;
8e7768b2
JH
725
726 /* Is there a recorded resolution we could attempt to apply? */
18bb9934
JH
727 if (has_rerere_resolution(id)) {
728 if (merge(id, path))
8e7768b2
JH
729 return; /* failed to replay */
730
731 if (rerere_autoupdate)
732 string_list_insert(update, path);
733 else
734 fprintf(stderr,
735 "Resolved '%s' using previous resolution.\n",
736 path);
925d73c4
JH
737 } else if (!handle_file(path, NULL, NULL)) {
738 /* The user has resolved it. */
18bb9934 739 copy_file(rerere_path(id, "postimage"), path, 0666);
925d73c4
JH
740 fprintf(stderr, "Recorded resolution for '%s'.\n", path);
741 } else {
742 return;
8e7768b2 743 }
1d51eced 744 free_rerere_id(rr_item);
8e7768b2
JH
745 rr_item->util = NULL;
746}
747
c455c87c 748static int do_plain_rerere(struct string_list *rr, int fd)
5b2fd956 749{
183113a5
TF
750 struct string_list conflict = STRING_LIST_INIT_DUP;
751 struct string_list update = STRING_LIST_INIT_DUP;
5b2fd956
SB
752 int i;
753
754 find_conflict(&conflict);
755
756 /*
cc899eca
JH
757 * MERGE_RR records paths with conflicts immediately after
758 * merge failed. Some of the conflicted paths might have been
759 * hand resolved in the working tree since then, but the
760 * initial run would catch all and register their preimages.
5b2fd956 761 */
5b2fd956 762 for (i = 0; i < conflict.nr; i++) {
1d51eced 763 struct rerere_id *id;
c7a25d37 764 unsigned char sha1[20];
c455c87c 765 const char *path = conflict.items[i].string;
1d51eced 766 int ret;
cc899eca 767
c7a25d37
JH
768 if (string_list_has_string(rr, path))
769 continue;
cc899eca 770
c7a25d37
JH
771 /*
772 * Ask handle_file() to scan and assign a
773 * conflict ID. No need to write anything out
774 * yet.
775 */
776 ret = handle_file(path, sha1, NULL);
777 if (ret < 1)
778 continue;
1d51eced
JH
779
780 id = new_rerere_id(sha1);
18bb9934 781 string_list_insert(rr, path)->util = id;
cc899eca 782
c7a25d37
JH
783 /*
784 * If the directory does not exist, create
785 * it. mkdir_in_gitdir() will fail with
786 * EEXIST if there already is one.
787 *
788 * NEEDSWORK: make sure "gc" does not remove
789 * preimage without removing the directory.
790 */
1d51eced 791 if (mkdir_in_gitdir(rerere_path(id, NULL)))
c7a25d37
JH
792 continue;
793
794 /*
795 * We are the first to encounter this
796 * conflict. Ask handle_file() to write the
797 * normalized contents to the "preimage" file.
798 */
18bb9934 799 handle_file(path, NULL, rerere_path(id, "preimage"));
c7a25d37 800 fprintf(stderr, "Recorded preimage for '%s'\n", path);
5b2fd956
SB
801 }
802
8e7768b2
JH
803 for (i = 0; i < rr->nr; i++)
804 do_rerere_one_path(&rr->items[i], &update);
5b2fd956
SB
805
806 if (update.nr)
807 update_paths(&update);
808
809 return write_rr(rr, fd);
810}
811
633e5ad3 812static void git_rerere_config(void)
5b2fd956 813{
633e5ad3
TA
814 git_config_get_bool("rerere.enabled", &rerere_enabled);
815 git_config_get_bool("rerere.autoupdate", &rerere_autoupdate);
816 git_config(git_default_config, NULL);
5b2fd956
SB
817}
818
819static int is_rerere_enabled(void)
820{
5b2fd956
SB
821 const char *rr_cache;
822 int rr_cache_exists;
823
824 if (!rerere_enabled)
825 return 0;
826
827 rr_cache = git_path("rr-cache");
90b4a71c 828 rr_cache_exists = is_directory(rr_cache);
5b2fd956
SB
829 if (rerere_enabled < 0)
830 return rr_cache_exists;
831
90a6464b 832 if (!rr_cache_exists && mkdir_in_gitdir(rr_cache))
5b2fd956
SB
833 die("Could not create directory %s", rr_cache);
834 return 1;
835}
836
cb6020bb 837int setup_rerere(struct string_list *merge_rr, int flags)
5b2fd956
SB
838{
839 int fd;
840
633e5ad3 841 git_rerere_config();
5b2fd956
SB
842 if (!is_rerere_enabled())
843 return -1;
844
cb6020bb
JH
845 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
846 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
a4f34cbb 847 merge_rr_path = git_pathdup("MERGE_RR");
acd3b9ec
JH
848 fd = hold_lock_file_for_update(&write_lock, merge_rr_path,
849 LOCK_DIE_ON_ERROR);
5b2fd956
SB
850 read_rr(merge_rr);
851 return fd;
852}
853
cc899eca
JH
854/*
855 * The main entry point that is called internally from codepaths that
856 * perform mergy operations, possibly leaving conflicted index entries
857 * and working tree files.
858 */
cb6020bb 859int rerere(int flags)
5b2fd956 860{
183113a5 861 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1869bbe1 862 int fd, status;
5b2fd956 863
cb6020bb 864 fd = setup_rerere(&merge_rr, flags);
5b2fd956
SB
865 if (fd < 0)
866 return 0;
1869bbe1
JH
867 status = do_plain_rerere(&merge_rr, fd);
868 free_rerere_dirs();
869 return status;
5b2fd956 870}
dea4562b
JH
871
872static int rerere_forget_one_path(const char *path, struct string_list *rr)
873{
874 const char *filename;
1d51eced 875 struct rerere_id *id;
dea4562b
JH
876 unsigned char sha1[20];
877 int ret;
8d9b5a4a 878 struct string_list_item *item;
dea4562b 879
963ec003
JH
880 /*
881 * Recreate the original conflict from the stages in the
882 * index and compute the conflict ID
883 */
dea4562b
JH
884 ret = handle_cache(path, sha1, NULL);
885 if (ret < 1)
886 return error("Could not parse conflict hunks in '%s'", path);
963ec003
JH
887
888 /* Nuke the recorded resolution for the conflict */
1d51eced 889 id = new_rerere_id(sha1);
18bb9934 890 filename = rerere_path(id, "postimage");
dea4562b
JH
891 if (unlink(filename))
892 return (errno == ENOENT
893 ? error("no remembered resolution for %s", path)
894 : error("cannot unlink %s: %s", filename, strerror(errno)));
895
963ec003
JH
896 /*
897 * Update the preimage so that the user can resolve the
898 * conflict in the working tree, run us again to record
899 * the postimage.
900 */
18bb9934 901 handle_cache(path, sha1, rerere_path(id, "preimage"));
dea4562b
JH
902 fprintf(stderr, "Updated preimage for '%s'\n", path);
903
963ec003
JH
904 /*
905 * And remember that we can record resolution for this
906 * conflict when the user is done.
907 */
8d9b5a4a 908 item = string_list_insert(rr, path);
1d51eced 909 free_rerere_id(item);
18bb9934 910 item->util = id;
dea4562b
JH
911 fprintf(stderr, "Forgot resolution for %s\n", path);
912 return 0;
913}
914
01a10b0a 915int rerere_forget(struct pathspec *pathspec)
dea4562b
JH
916{
917 int i, fd;
183113a5
TF
918 struct string_list conflict = STRING_LIST_INIT_DUP;
919 struct string_list merge_rr = STRING_LIST_INIT_DUP;
dea4562b
JH
920
921 if (read_cache() < 0)
922 return error("Could not read index");
923
6751e047 924 fd = setup_rerere(&merge_rr, RERERE_NOAUTOUPDATE);
dea4562b 925
963ec003
JH
926 /*
927 * The paths may have been resolved (incorrectly);
928 * recover the original conflicted state and then
929 * find the conflicted paths.
930 */
dea4562b
JH
931 unmerge_cache(pathspec);
932 find_conflict(&conflict);
933 for (i = 0; i < conflict.nr; i++) {
934 struct string_list_item *it = &conflict.items[i];
854b0959 935 if (!match_pathspec(pathspec, it->string,
ae8d0824 936 strlen(it->string), 0, NULL, 0))
dea4562b
JH
937 continue;
938 rerere_forget_one_path(it->string, &merge_rr);
939 }
940 return write_rr(&merge_rr, fd);
941}
0f891e7d 942
e828de82
JH
943/*
944 * Garbage collection support
945 */
1d51eced
JH
946
947/*
948 * Note that this is not reentrant but is used only one-at-a-time
949 * so it does not matter right now.
950 */
951static struct rerere_id *dirname_to_id(const char *name)
952{
953 static struct rerere_id id;
1869bbe1 954 id.collection = find_rerere_dir(name);
1d51eced
JH
955 return &id;
956}
957
958static time_t rerere_created_at(const char *dir_name)
0f891e7d
JH
959{
960 struct stat st;
1d51eced
JH
961 struct rerere_id *id = dirname_to_id(dir_name);
962
18bb9934 963 return stat(rerere_path(id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
0f891e7d
JH
964}
965
1d51eced 966static time_t rerere_last_used_at(const char *dir_name)
0f891e7d
JH
967{
968 struct stat st;
1d51eced
JH
969 struct rerere_id *id = dirname_to_id(dir_name);
970
18bb9934 971 return stat(rerere_path(id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
0f891e7d
JH
972}
973
e828de82
JH
974/*
975 * Remove the recorded resolution for a given conflict ID
976 */
1d51eced 977static void unlink_rr_item(struct rerere_id *id)
0f891e7d 978{
18bb9934
JH
979 unlink(rerere_path(id, "thisimage"));
980 unlink(rerere_path(id, "preimage"));
981 unlink(rerere_path(id, "postimage"));
e828de82
JH
982 /*
983 * NEEDSWORK: what if this rmdir() fails? Wouldn't we then
984 * assume that we already have preimage recorded in
985 * do_plain_rerere()?
986 */
1d51eced 987 rmdir(rerere_path(id, NULL));
0f891e7d
JH
988}
989
0f891e7d
JH
990void rerere_gc(struct string_list *rr)
991{
992 struct string_list to_remove = STRING_LIST_INIT_DUP;
993 DIR *dir;
994 struct dirent *e;
995 int i, cutoff;
996 time_t now = time(NULL), then;
633e5ad3
TA
997 int cutoff_noresolve = 15;
998 int cutoff_resolve = 60;
0f891e7d 999
633e5ad3
TA
1000 git_config_get_int("gc.rerereresolved", &cutoff_resolve);
1001 git_config_get_int("gc.rerereunresolved", &cutoff_noresolve);
1002 git_config(git_default_config, NULL);
0f891e7d
JH
1003 dir = opendir(git_path("rr-cache"));
1004 if (!dir)
1005 die_errno("unable to open rr-cache directory");
e828de82 1006 /* Collect stale conflict IDs ... */
0f891e7d
JH
1007 while ((e = readdir(dir))) {
1008 if (is_dot_or_dotdot(e->d_name))
1009 continue;
1010
1011 then = rerere_last_used_at(e->d_name);
1012 if (then) {
633e5ad3 1013 cutoff = cutoff_resolve;
0f891e7d
JH
1014 } else {
1015 then = rerere_created_at(e->d_name);
1016 if (!then)
1017 continue;
633e5ad3 1018 cutoff = cutoff_noresolve;
0f891e7d
JH
1019 }
1020 if (then < now - cutoff * 86400)
1021 string_list_append(&to_remove, e->d_name);
1022 }
a9930e35 1023 closedir(dir);
e828de82 1024 /* ... and then remove them one-by-one */
0f891e7d 1025 for (i = 0; i < to_remove.nr; i++)
1d51eced 1026 unlink_rr_item(dirname_to_id(to_remove.items[i].string));
0f891e7d
JH
1027 string_list_clear(&to_remove, 0);
1028}
1029
e828de82
JH
1030/*
1031 * During a conflict resolution, after "rerere" recorded the
1032 * preimages, abandon them if the user did not resolve them or
1033 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1034 *
1035 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1036 */
0f891e7d
JH
1037void rerere_clear(struct string_list *merge_rr)
1038{
1039 int i;
1040
1041 for (i = 0; i < merge_rr->nr; i++) {
1d51eced 1042 struct rerere_id *id = merge_rr->items[i].util;
18bb9934
JH
1043 if (!has_rerere_resolution(id))
1044 unlink_rr_item(id);
0f891e7d
JH
1045 }
1046 unlink_or_warn(git_path("MERGE_RR"));
1047}