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