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