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