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