Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "config.h"
7 #include "copy.h"
8 #include "environment.h"
9 #include "gettext.h"
10 #include "hex.h"
11 #include "lockfile.h"
12 #include "string-list.h"
13 #include "read-cache-ll.h"
14 #include "rerere.h"
15 #include "xdiff-interface.h"
16 #include "dir.h"
17 #include "resolve-undo.h"
18 #include "merge-ll.h"
19 #include "path.h"
20 #include "pathspec.h"
21 #include "object-file.h"
22 #include "odb.h"
23 #include "strmap.h"
24
25 #define RESOLVED 0
26 #define PUNTED 1
27 #define THREE_STAGED 2
28 void *RERERE_RESOLVED = &RERERE_RESOLVED;
29
30 /* if rerere_enabled == -1, fall back to detection of .git/rr-cache */
31 static int rerere_enabled = -1;
32
33 /* automatically update cleanly resolved paths to the index */
34 static int rerere_autoupdate;
35
36 #define RR_HAS_POSTIMAGE 1
37 #define RR_HAS_PREIMAGE 2
38 struct rerere_dir {
39 int status_alloc, status_nr;
40 unsigned char *status;
41 char name[FLEX_ARRAY];
42 };
43
44 static struct strmap rerere_dirs = STRMAP_INIT;
45
46 static void free_rerere_dirs(void)
47 {
48 struct hashmap_iter iter;
49 struct strmap_entry *ent;
50
51 strmap_for_each_entry(&rerere_dirs, &iter, ent) {
52 struct rerere_dir *rr_dir = ent->value;
53 free(rr_dir->status);
54 free(rr_dir);
55 }
56 strmap_clear(&rerere_dirs, 0);
57 }
58
59 static void free_rerere_id(struct string_list_item *item)
60 {
61 free(item->util);
62 }
63
64 static const char *rerere_id_hex(const struct rerere_id *id)
65 {
66 return id->collection->name;
67 }
68
69 static void fit_variant(struct rerere_dir *rr_dir, int variant)
70 {
71 variant++;
72 ALLOC_GROW(rr_dir->status, variant, rr_dir->status_alloc);
73 if (rr_dir->status_nr < variant) {
74 memset(rr_dir->status + rr_dir->status_nr,
75 '\0', variant - rr_dir->status_nr);
76 rr_dir->status_nr = variant;
77 }
78 }
79
80 static void assign_variant(struct rerere_id *id)
81 {
82 int variant;
83 struct rerere_dir *rr_dir = id->collection;
84
85 variant = id->variant;
86 if (variant < 0) {
87 for (variant = 0; variant < rr_dir->status_nr; variant++)
88 if (!rr_dir->status[variant])
89 break;
90 }
91 fit_variant(rr_dir, variant);
92 id->variant = variant;
93 }
94
95 const char *rerere_path(struct strbuf *buf, const struct rerere_id *id, const char *file)
96 {
97 if (!file)
98 return repo_git_path_replace(the_repository, buf, "rr-cache/%s",
99 rerere_id_hex(id));
100
101 if (id->variant <= 0)
102 return repo_git_path_replace(the_repository, buf, "rr-cache/%s/%s",
103 rerere_id_hex(id), file);
104
105 return repo_git_path_replace(the_repository, buf, "rr-cache/%s/%s.%d",
106 rerere_id_hex(id), file, id->variant);
107 }
108
109 static int is_rr_file(const char *name, const char *filename, int *variant)
110 {
111 const char *suffix;
112 char *ep;
113
114 if (!strcmp(name, filename)) {
115 *variant = 0;
116 return 1;
117 }
118 if (!skip_prefix(name, filename, &suffix) || *suffix != '.')
119 return 0;
120
121 errno = 0;
122 *variant = strtol(suffix + 1, &ep, 10);
123 if (errno || *ep)
124 return 0;
125 return 1;
126 }
127
128 static void scan_rerere_dir(struct rerere_dir *rr_dir)
129 {
130 struct dirent *de;
131 char *path;
132 DIR *dir;
133
134 path = repo_git_path(the_repository, "rr-cache/%s", rr_dir->name);
135 dir = opendir(path);
136 free(path);
137 if (!dir)
138 return;
139 while ((de = readdir(dir)) != NULL) {
140 int variant;
141
142 if (is_rr_file(de->d_name, "postimage", &variant)) {
143 fit_variant(rr_dir, variant);
144 rr_dir->status[variant] |= RR_HAS_POSTIMAGE;
145 } else if (is_rr_file(de->d_name, "preimage", &variant)) {
146 fit_variant(rr_dir, variant);
147 rr_dir->status[variant] |= RR_HAS_PREIMAGE;
148 }
149 }
150 closedir(dir);
151 }
152
153 static struct rerere_dir *find_rerere_dir(const char *hex)
154 {
155 struct rerere_dir *rr_dir;
156
157 rr_dir = strmap_get(&rerere_dirs, hex);
158 if (!rr_dir) {
159 FLEX_ALLOC_STR(rr_dir, name, hex);
160 rr_dir->status = NULL;
161 rr_dir->status_nr = 0;
162 rr_dir->status_alloc = 0;
163 strmap_put(&rerere_dirs, hex, rr_dir);
164
165 scan_rerere_dir(rr_dir);
166 }
167 return rr_dir;
168 }
169
170 static int has_rerere_resolution(const struct rerere_id *id)
171 {
172 const int both = RR_HAS_POSTIMAGE|RR_HAS_PREIMAGE;
173 int variant = id->variant;
174
175 if (variant < 0)
176 return 0;
177 return ((id->collection->status[variant] & both) == both);
178 }
179
180 static struct rerere_id *new_rerere_id_hex(char *hex)
181 {
182 struct rerere_id *id = xmalloc(sizeof(*id));
183 id->collection = find_rerere_dir(hex);
184 id->variant = -1; /* not known yet */
185 return id;
186 }
187
188 static struct rerere_id *new_rerere_id(unsigned char *hash)
189 {
190 return new_rerere_id_hex(hash_to_hex(hash));
191 }
192
193 /*
194 * $GIT_DIR/MERGE_RR file is a collection of records, each of which is
195 * "conflict ID", a HT and pathname, terminated with a NUL, and is
196 * used to keep track of the set of paths that "rerere" may need to
197 * work on (i.e. what is left by the previous invocation of "git
198 * rerere" during the current conflict resolution session).
199 */
200 static void read_rr(struct repository *r, struct string_list *rr)
201 {
202 struct strbuf buf = STRBUF_INIT;
203 FILE *in = fopen_or_warn(git_path_merge_rr(r), "r");
204
205 if (!in)
206 return;
207 while (!strbuf_getwholeline(&buf, in, '\0')) {
208 char *path;
209 unsigned char hash[GIT_MAX_RAWSZ];
210 struct rerere_id *id;
211 int variant;
212 const unsigned hexsz = the_hash_algo->hexsz;
213
214 /* There has to be the hash, tab, path and then NUL */
215 if (buf.len < hexsz + 2 || get_hash_hex(buf.buf, hash))
216 die(_("corrupt MERGE_RR"));
217
218 if (buf.buf[hexsz] != '.') {
219 variant = 0;
220 path = buf.buf + hexsz;
221 } else {
222 errno = 0;
223 variant = strtol(buf.buf + hexsz + 1, &path, 10);
224 if (errno)
225 die(_("corrupt MERGE_RR"));
226 }
227 if (*(path++) != '\t')
228 die(_("corrupt MERGE_RR"));
229 buf.buf[hexsz] = '\0';
230 id = new_rerere_id_hex(buf.buf);
231 id->variant = variant;
232 /*
233 * make sure id->collection->status has enough space
234 * for the variant we are interested in
235 */
236 fit_variant(id->collection, variant);
237 string_list_insert(rr, path)->util = id;
238 }
239 strbuf_release(&buf);
240 fclose(in);
241 }
242
243 static struct lock_file write_lock;
244
245 static int write_rr(struct string_list *rr, int out_fd)
246 {
247 int i;
248 for (i = 0; i < rr->nr; i++) {
249 struct strbuf buf = STRBUF_INIT;
250 struct rerere_id *id;
251
252 assert(rr->items[i].util != RERERE_RESOLVED);
253
254 id = rr->items[i].util;
255 if (!id)
256 continue;
257 assert(id->variant >= 0);
258 if (0 < id->variant)
259 strbuf_addf(&buf, "%s.%d\t%s%c",
260 rerere_id_hex(id), id->variant,
261 rr->items[i].string, 0);
262 else
263 strbuf_addf(&buf, "%s\t%s%c",
264 rerere_id_hex(id),
265 rr->items[i].string, 0);
266
267 if (write_in_full(out_fd, buf.buf, buf.len) < 0)
268 die(_("unable to write rerere record"));
269
270 strbuf_release(&buf);
271 }
272 if (commit_lock_file(&write_lock) != 0)
273 die(_("unable to write rerere record"));
274 return 0;
275 }
276
277 /*
278 * "rerere" interacts with conflicted file contents using this I/O
279 * abstraction. It reads a conflicted contents from one place via
280 * "getline()" method, and optionally can write it out after
281 * normalizing the conflicted hunks to the "output". Subclasses of
282 * rerere_io embed this structure at the beginning of their own
283 * rerere_io object.
284 */
285 struct rerere_io {
286 int (*getline)(struct strbuf *, struct rerere_io *);
287 FILE *output;
288 int wrerror;
289 /* some more stuff */
290 };
291
292 static void ferr_write(const void *p, size_t count, FILE *fp, int *err)
293 {
294 if (!count || *err)
295 return;
296 if (fwrite(p, count, 1, fp) != 1)
297 *err = errno;
298 }
299
300 static inline void ferr_puts(const char *s, FILE *fp, int *err)
301 {
302 ferr_write(s, strlen(s), fp, err);
303 }
304
305 static void rerere_io_putstr(const char *str, struct rerere_io *io)
306 {
307 if (io->output)
308 ferr_puts(str, io->output, &io->wrerror);
309 }
310
311 static void rerere_io_putmem(const char *mem, size_t sz, struct rerere_io *io)
312 {
313 if (io->output)
314 ferr_write(mem, sz, io->output, &io->wrerror);
315 }
316
317 /*
318 * Subclass of rerere_io that reads from an on-disk file
319 */
320 struct rerere_io_file {
321 struct rerere_io io;
322 FILE *input;
323 };
324
325 /*
326 * ... and its getline() method implementation
327 */
328 static int rerere_file_getline(struct strbuf *sb, struct rerere_io *io_)
329 {
330 struct rerere_io_file *io = (struct rerere_io_file *)io_;
331 return strbuf_getwholeline(sb, io->input, '\n');
332 }
333
334 static void rerere_strbuf_putconflict(struct strbuf *buf, int ch, size_t size)
335 {
336 strbuf_addchars(buf, ch, size);
337 strbuf_addch(buf, '\n');
338 }
339
340 static int handle_conflict(struct strbuf *out, struct rerere_io *io,
341 int marker_size, struct git_hash_ctx *ctx)
342 {
343 enum {
344 RR_SIDE_1 = 0, RR_SIDE_2, RR_ORIGINAL
345 } hunk = RR_SIDE_1;
346 struct strbuf one = STRBUF_INIT, two = STRBUF_INIT;
347 struct strbuf buf = STRBUF_INIT, conflict = STRBUF_INIT;
348 int has_conflicts = -1;
349
350 while (!io->getline(&buf, io)) {
351 int marker = is_conflict_marker_line(buf.buf, buf.len, marker_size);
352 if (marker == '<') {
353 if (handle_conflict(&conflict, io, marker_size, NULL) < 0)
354 break;
355 if (hunk == RR_SIDE_1)
356 strbuf_addbuf(&one, &conflict);
357 else
358 strbuf_addbuf(&two, &conflict);
359 strbuf_release(&conflict);
360 } else if (marker == '|') {
361 if (hunk != RR_SIDE_1)
362 break;
363 hunk = RR_ORIGINAL;
364 } else if (marker == '=') {
365 if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL)
366 break;
367 hunk = RR_SIDE_2;
368 } else if (marker == '>') {
369 if (hunk != RR_SIDE_2)
370 break;
371 if (strbuf_cmp(&one, &two) > 0)
372 strbuf_swap(&one, &two);
373 has_conflicts = 1;
374 rerere_strbuf_putconflict(out, '<', marker_size);
375 strbuf_addbuf(out, &one);
376 rerere_strbuf_putconflict(out, '=', marker_size);
377 strbuf_addbuf(out, &two);
378 rerere_strbuf_putconflict(out, '>', marker_size);
379 if (ctx) {
380 git_hash_update(ctx, one.buf, one.len + 1);
381 git_hash_update(ctx, two.buf, two.len + 1);
382 }
383 break;
384 } else if (hunk == RR_SIDE_1)
385 strbuf_addbuf(&one, &buf);
386 else if (hunk == RR_ORIGINAL)
387 ; /* discard */
388 else if (hunk == RR_SIDE_2)
389 strbuf_addbuf(&two, &buf);
390 }
391 strbuf_release(&one);
392 strbuf_release(&two);
393 strbuf_release(&buf);
394
395 return has_conflicts;
396 }
397
398 /*
399 * Read contents a file with conflicts, normalize the conflicts
400 * by (1) discarding the common ancestor version in diff3-style,
401 * (2) reordering our side and their side so that whichever sorts
402 * alphabetically earlier comes before the other one, while
403 * computing the "conflict ID", which is just an SHA-1 hash of
404 * one side of the conflict, NUL, the other side of the conflict,
405 * and NUL concatenated together.
406 *
407 * Return 1 if conflict hunks are found, 0 if there are no conflict
408 * hunks and -1 if an error occurred.
409 */
410 static int handle_path(unsigned char *hash, struct rerere_io *io, int marker_size)
411 {
412 struct git_hash_ctx ctx;
413 struct strbuf buf = STRBUF_INIT, out = STRBUF_INIT;
414 int has_conflicts = 0;
415 if (hash)
416 git_hash_init(&ctx, the_hash_algo);
417
418 while (!io->getline(&buf, io)) {
419 if (is_conflict_marker_line(buf.buf, buf.len, marker_size) == '<') {
420 has_conflicts = handle_conflict(&out, io, marker_size,
421 hash ? &ctx : NULL);
422 if (has_conflicts < 0)
423 break;
424 rerere_io_putmem(out.buf, out.len, io);
425 strbuf_reset(&out);
426 } else
427 rerere_io_putstr(buf.buf, io);
428 }
429 strbuf_release(&buf);
430 strbuf_release(&out);
431
432 if (hash)
433 git_hash_final(hash, &ctx);
434
435 return has_conflicts;
436 }
437
438 /*
439 * Scan the path for conflicts, do the "handle_path()" thing above, and
440 * return the number of conflict hunks found.
441 */
442 static int handle_file(struct index_state *istate,
443 const char *path, unsigned char *hash, const char *output)
444 {
445 int has_conflicts = 0;
446 struct rerere_io_file io;
447 int marker_size = ll_merge_marker_size(istate, path);
448
449 memset(&io, 0, sizeof(io));
450 io.io.getline = rerere_file_getline;
451 io.input = fopen(path, "r");
452 io.io.wrerror = 0;
453 if (!io.input)
454 return error_errno(_("could not open '%s'"), path);
455
456 if (output) {
457 io.io.output = fopen(output, "w");
458 if (!io.io.output) {
459 error_errno(_("could not write '%s'"), output);
460 fclose(io.input);
461 return -1;
462 }
463 }
464
465 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
466
467 fclose(io.input);
468 if (io.io.wrerror)
469 error(_("there were errors while writing '%s' (%s)"),
470 path, strerror(io.io.wrerror));
471 if (io.io.output && fclose(io.io.output))
472 io.io.wrerror = error_errno(_("failed to flush '%s'"), path);
473
474 if (has_conflicts < 0) {
475 if (output)
476 unlink_or_warn(output);
477 return error(_("could not parse conflict hunks in '%s'"), path);
478 }
479 if (io.io.wrerror)
480 return -1;
481 return has_conflicts;
482 }
483
484 /*
485 * Look at a cache entry at "i" and see if it is not conflicting,
486 * conflicting and we are willing to handle, or conflicting and
487 * we are unable to handle, and return the determination in *type.
488 * Return the cache index to be looked at next, by skipping the
489 * stages we have already looked at in this invocation of this
490 * function.
491 */
492 static int check_one_conflict(struct index_state *istate, int i, int *type)
493 {
494 const struct cache_entry *e = istate->cache[i];
495
496 if (!ce_stage(e)) {
497 *type = RESOLVED;
498 return i + 1;
499 }
500
501 *type = PUNTED;
502 while (i < istate->cache_nr && ce_stage(istate->cache[i]) == 1)
503 i++;
504
505 /* Only handle regular files with both stages #2 and #3 */
506 if (i + 1 < istate->cache_nr) {
507 const struct cache_entry *e2 = istate->cache[i];
508 const struct cache_entry *e3 = istate->cache[i + 1];
509 if (ce_stage(e2) == 2 &&
510 ce_stage(e3) == 3 &&
511 ce_same_name(e, e3) &&
512 S_ISREG(e2->ce_mode) &&
513 S_ISREG(e3->ce_mode))
514 *type = THREE_STAGED;
515 }
516
517 /* Skip the entries with the same name */
518 while (i < istate->cache_nr && ce_same_name(e, istate->cache[i]))
519 i++;
520 return i;
521 }
522
523 /*
524 * Scan the index and find paths that have conflicts that rerere can
525 * handle, i.e. the ones that have both stages #2 and #3.
526 *
527 * NEEDSWORK: we do not record or replay a previous "resolve by
528 * deletion" for a delete-modify conflict, as that is inherently risky
529 * without knowing what modification is being discarded. The only
530 * safe case, i.e. both side doing the deletion and modification that
531 * are identical to the previous round, might want to be handled,
532 * though.
533 */
534 static int find_conflict(struct repository *r, struct string_list *conflict)
535 {
536 int i;
537
538 if (repo_read_index(r) < 0)
539 return error(_("index file corrupt"));
540
541 for (i = 0; i < r->index->cache_nr;) {
542 int conflict_type;
543 const struct cache_entry *e = r->index->cache[i];
544 i = check_one_conflict(r->index, i, &conflict_type);
545 if (conflict_type == THREE_STAGED)
546 string_list_insert(conflict, (const char *)e->name);
547 }
548 return 0;
549 }
550
551 /*
552 * The merge_rr list is meant to hold outstanding conflicted paths
553 * that rerere could handle. Abuse the list by adding other types of
554 * entries to allow the caller to show "rerere remaining".
555 *
556 * - Conflicted paths that rerere does not handle are added
557 * - Conflicted paths that have been resolved are marked as such
558 * by storing RERERE_RESOLVED to .util field (where conflict ID
559 * is expected to be stored).
560 *
561 * Do *not* write MERGE_RR file out after calling this function.
562 *
563 * NEEDSWORK: we may want to fix the caller that implements "rerere
564 * remaining" to do this without abusing merge_rr.
565 */
566 int rerere_remaining(struct repository *r, struct string_list *merge_rr)
567 {
568 int i;
569
570 if (setup_rerere(r, merge_rr, RERERE_READONLY))
571 return 0;
572 if (repo_read_index(r) < 0)
573 return error(_("index file corrupt"));
574
575 for (i = 0; i < r->index->cache_nr;) {
576 int conflict_type;
577 const struct cache_entry *e = r->index->cache[i];
578 i = check_one_conflict(r->index, i, &conflict_type);
579 if (conflict_type == PUNTED)
580 string_list_insert(merge_rr, (const char *)e->name);
581 else if (conflict_type == RESOLVED) {
582 struct string_list_item *it;
583 it = string_list_lookup(merge_rr, (const char *)e->name);
584 if (it) {
585 free_rerere_id(it);
586 it->util = RERERE_RESOLVED;
587 }
588 }
589 }
590 return 0;
591 }
592
593 /*
594 * Try using the given conflict resolution "ID" to see
595 * if that recorded conflict resolves cleanly what we
596 * got in the "cur".
597 */
598 static int try_merge(struct index_state *istate,
599 const struct rerere_id *id, const char *path,
600 mmfile_t *cur, mmbuffer_t *result)
601 {
602 enum ll_merge_result ret;
603 mmfile_t base = {NULL, 0}, other = {NULL, 0};
604 struct strbuf buf = STRBUF_INIT;
605
606 if (read_mmfile(&base, rerere_path(&buf, id, "preimage")) ||
607 read_mmfile(&other, rerere_path(&buf, id, "postimage"))) {
608 ret = LL_MERGE_CONFLICT;
609 } else {
610 /*
611 * A three-way merge. Note that this honors user-customizable
612 * low-level merge driver settings.
613 */
614 ret = ll_merge(result, path, &base, NULL, cur, "", &other, "",
615 istate, NULL);
616 }
617
618 strbuf_release(&buf);
619 free(base.ptr);
620 free(other.ptr);
621
622 return ret;
623 }
624
625 /*
626 * Find the conflict identified by "id"; the change between its
627 * "preimage" (i.e. a previous contents with conflict markers) and its
628 * "postimage" (i.e. the corresponding contents with conflicts
629 * resolved) may apply cleanly to the contents stored in "path", i.e.
630 * the conflict this time around.
631 *
632 * Returns 0 for successful replay of recorded resolution, or non-zero
633 * for failure.
634 */
635 static int merge(struct index_state *istate, const struct rerere_id *id, const char *path)
636 {
637 FILE *f;
638 int ret;
639 struct strbuf buf = STRBUF_INIT;
640 mmfile_t cur = {NULL, 0};
641 mmbuffer_t result = {NULL, 0};
642
643 /*
644 * Normalize the conflicts in path and write it out to
645 * "thisimage" temporary file.
646 */
647 if ((handle_file(istate, path, NULL, rerere_path(&buf, id, "thisimage")) < 0) ||
648 read_mmfile(&cur, rerere_path(&buf, id, "thisimage"))) {
649 ret = 1;
650 goto out;
651 }
652
653 ret = try_merge(istate, id, path, &cur, &result);
654 if (ret)
655 goto out;
656
657 /*
658 * A successful replay of recorded resolution.
659 * Mark that "postimage" was used to help gc.
660 */
661 if (utime(rerere_path(&buf, id, "postimage"), NULL) < 0)
662 warning_errno(_("failed utime() on '%s'"),
663 rerere_path(&buf, id, "postimage"));
664
665 /* Update "path" with the resolution */
666 f = fopen(path, "w");
667 if (!f)
668 return error_errno(_("could not open '%s'"), path);
669 if (fwrite(result.ptr, result.size, 1, f) != 1)
670 error_errno(_("could not write '%s'"), path);
671 if (fclose(f))
672 return error_errno(_("writing '%s' failed"), path);
673
674 out:
675 free(cur.ptr);
676 free(result.ptr);
677 strbuf_release(&buf);
678
679 return ret;
680 }
681
682 static void update_paths(struct repository *r, struct string_list *update)
683 {
684 struct lock_file index_lock = LOCK_INIT;
685 int i;
686
687 repo_hold_locked_index(r, &index_lock, LOCK_DIE_ON_ERROR);
688
689 for (i = 0; i < update->nr; i++) {
690 struct string_list_item *item = &update->items[i];
691 if (add_file_to_index(r->index, item->string, 0))
692 exit(128);
693 fprintf_ln(stderr, _("Staged '%s' using previous resolution."),
694 item->string);
695 }
696
697 if (write_locked_index(r->index, &index_lock,
698 COMMIT_LOCK | SKIP_IF_UNCHANGED))
699 die(_("unable to write new index file"));
700 }
701
702 static void remove_variant(struct rerere_id *id)
703 {
704 struct strbuf buf = STRBUF_INIT;
705 unlink_or_warn(rerere_path(&buf, id, "postimage"));
706 unlink_or_warn(rerere_path(&buf, id, "preimage"));
707 id->collection->status[id->variant] = 0;
708 strbuf_release(&buf);
709 }
710
711 /*
712 * The path indicated by rr_item may still have conflict for which we
713 * have a recorded resolution, in which case replay it and optionally
714 * update it. Or it may have been resolved by the user and we may
715 * only have the preimage for that conflict, in which case the result
716 * needs to be recorded as a resolution in a postimage file.
717 */
718 static void do_rerere_one_path(struct index_state *istate,
719 struct string_list_item *rr_item,
720 struct string_list *update)
721 {
722 const char *path = rr_item->string;
723 struct rerere_id *id = rr_item->util;
724 struct rerere_dir *rr_dir = id->collection;
725 struct strbuf buf = STRBUF_INIT;
726 int variant;
727
728 variant = id->variant;
729
730 /* Has the user resolved it already? */
731 if (variant >= 0) {
732 if (!handle_file(istate, path, NULL, NULL)) {
733 copy_file(the_repository, rerere_path(&buf, id, "postimage"), path, 0666);
734 id->collection->status[variant] |= RR_HAS_POSTIMAGE;
735 fprintf_ln(stderr, _("Recorded resolution for '%s'."), path);
736 free_rerere_id(rr_item);
737 rr_item->util = NULL;
738 goto out;
739 }
740 /*
741 * There may be other variants that can cleanly
742 * replay. Try them and update the variant number for
743 * this one.
744 */
745 }
746
747 /* Does any existing resolution apply cleanly? */
748 for (variant = 0; variant < rr_dir->status_nr; variant++) {
749 const int both = RR_HAS_PREIMAGE | RR_HAS_POSTIMAGE;
750 struct rerere_id vid = *id;
751
752 if ((rr_dir->status[variant] & both) != both)
753 continue;
754
755 vid.variant = variant;
756 if (merge(istate, &vid, path))
757 continue; /* failed to replay */
758
759 /*
760 * If there already is a different variant that applies
761 * cleanly, there is no point maintaining our own variant.
762 */
763 if (0 <= id->variant && id->variant != variant)
764 remove_variant(id);
765
766 if (rerere_autoupdate)
767 string_list_insert(update, path);
768 else
769 fprintf_ln(stderr,
770 _("Resolved '%s' using previous resolution."),
771 path);
772 free_rerere_id(rr_item);
773 rr_item->util = NULL;
774 goto out;
775 }
776
777 /* None of the existing one applies; we need a new variant */
778 assign_variant(id);
779
780 variant = id->variant;
781 handle_file(istate, path, NULL, rerere_path(&buf, id, "preimage"));
782 if (id->collection->status[variant] & RR_HAS_POSTIMAGE) {
783 const char *path = rerere_path(&buf, id, "postimage");
784 if (unlink(path))
785 die_errno(_("cannot unlink stray '%s'"), path);
786 id->collection->status[variant] &= ~RR_HAS_POSTIMAGE;
787 }
788 id->collection->status[variant] |= RR_HAS_PREIMAGE;
789 fprintf_ln(stderr, _("Recorded preimage for '%s'"), path);
790
791 out:
792 strbuf_release(&buf);
793 }
794
795 static int do_plain_rerere(struct repository *r,
796 struct string_list *rr, int fd)
797 {
798 struct string_list conflict = STRING_LIST_INIT_DUP;
799 struct string_list update = STRING_LIST_INIT_DUP;
800 struct strbuf buf = STRBUF_INIT;
801 int i;
802
803 find_conflict(r, &conflict);
804
805 /*
806 * MERGE_RR records paths with conflicts immediately after
807 * merge failed. Some of the conflicted paths might have been
808 * hand resolved in the working tree since then, but the
809 * initial run would catch all and register their preimages.
810 */
811 for (i = 0; i < conflict.nr; i++) {
812 struct rerere_id *id;
813 unsigned char hash[GIT_MAX_RAWSZ];
814 const char *path = conflict.items[i].string;
815 int ret;
816
817 /*
818 * Ask handle_file() to scan and assign a
819 * conflict ID. No need to write anything out
820 * yet.
821 */
822 ret = handle_file(r->index, path, hash, NULL);
823 if (ret != 0 && string_list_has_string(rr, path)) {
824 remove_variant(string_list_lookup(rr, path)->util);
825 string_list_remove(rr, path, 1);
826 }
827 if (ret < 1)
828 continue;
829
830 id = new_rerere_id(hash);
831 string_list_insert(rr, path)->util = id;
832
833 /* Ensure that the directory exists. */
834 safe_create_dir_in_gitdir(the_repository, rerere_path(&buf, id, NULL));
835 }
836
837 for (i = 0; i < rr->nr; i++)
838 do_rerere_one_path(r->index, &rr->items[i], &update);
839
840 if (update.nr)
841 update_paths(r, &update);
842
843 string_list_clear(&conflict, 0);
844 string_list_clear(&update, 0);
845 strbuf_release(&buf);
846 return write_rr(rr, fd);
847 }
848
849 static void git_rerere_config(void)
850 {
851 repo_config_get_bool(the_repository, "rerere.enabled", &rerere_enabled);
852 repo_config_get_bool(the_repository, "rerere.autoupdate", &rerere_autoupdate);
853 repo_config(the_repository, git_default_config, NULL);
854 }
855
856 static GIT_PATH_FUNC(git_path_rr_cache, "rr-cache")
857
858 static int is_rerere_enabled(void)
859 {
860 int rr_cache_exists;
861
862 if (!rerere_enabled)
863 return 0;
864
865 rr_cache_exists = is_directory(git_path_rr_cache());
866 if (rerere_enabled < 0)
867 return rr_cache_exists;
868
869 if (!rr_cache_exists &&
870 safe_create_dir_in_gitdir(the_repository, git_path_rr_cache()))
871 die(_("could not create directory '%s'"), git_path_rr_cache());
872 return 1;
873 }
874
875 int setup_rerere(struct repository *r, struct string_list *merge_rr, int flags)
876 {
877 int fd;
878
879 git_rerere_config();
880 if (!is_rerere_enabled())
881 return -1;
882
883 if (flags & (RERERE_AUTOUPDATE|RERERE_NOAUTOUPDATE))
884 rerere_autoupdate = !!(flags & RERERE_AUTOUPDATE);
885 if (flags & RERERE_READONLY)
886 fd = 0;
887 else
888 fd = repo_hold_lock_file_for_update(r, &write_lock,
889 git_path_merge_rr(r),
890 LOCK_DIE_ON_ERROR);
891 read_rr(r, merge_rr);
892 return fd;
893 }
894
895 /*
896 * The main entry point that is called internally from codepaths that
897 * perform mergy operations, possibly leaving conflicted index entries
898 * and working tree files.
899 */
900 int repo_rerere(struct repository *r, int flags)
901 {
902 struct string_list merge_rr = STRING_LIST_INIT_DUP;
903 int fd, status;
904
905 fd = setup_rerere(r, &merge_rr, flags);
906 if (fd < 0)
907 return 0;
908 status = do_plain_rerere(r, &merge_rr, fd);
909 free_rerere_dirs();
910 string_list_clear(&merge_rr, 1);
911 return status;
912 }
913
914 /*
915 * Subclass of rerere_io that reads from an in-core buffer that is a
916 * strbuf
917 */
918 struct rerere_io_mem {
919 struct rerere_io io;
920 struct strbuf input;
921 };
922
923 /*
924 * ... and its getline() method implementation
925 */
926 static int rerere_mem_getline(struct strbuf *sb, struct rerere_io *io_)
927 {
928 struct rerere_io_mem *io = (struct rerere_io_mem *)io_;
929 char *ep;
930 size_t len;
931
932 strbuf_release(sb);
933 if (!io->input.len)
934 return -1;
935 ep = memchr(io->input.buf, '\n', io->input.len);
936 if (!ep)
937 ep = io->input.buf + io->input.len;
938 else if (*ep == '\n')
939 ep++;
940 len = ep - io->input.buf;
941 strbuf_add(sb, io->input.buf, len);
942 strbuf_remove(&io->input, 0, len);
943 return 0;
944 }
945
946 static int handle_cache(struct index_state *istate,
947 const char *path, unsigned char *hash, const char *output)
948 {
949 mmfile_t mmfile[3] = {{NULL}};
950 mmbuffer_t result = {NULL, 0};
951 const struct cache_entry *ce;
952 int pos, len, i, has_conflicts;
953 struct rerere_io_mem io;
954 int marker_size = ll_merge_marker_size(istate, path);
955
956 /*
957 * Reproduce the conflicted merge in-core
958 */
959 len = strlen(path);
960 pos = index_name_pos(istate, path, len);
961 if (0 <= pos)
962 return -1;
963 pos = -pos - 1;
964
965 while (pos < istate->cache_nr) {
966 enum object_type type;
967 size_t size;
968
969 ce = istate->cache[pos++];
970 if (ce_namelen(ce) != len || memcmp(ce->name, path, len))
971 break;
972 i = ce_stage(ce) - 1;
973 if (!mmfile[i].ptr) {
974 mmfile[i].ptr = odb_read_object(the_repository->objects,
975 &ce->oid, &type, &size);
976 if (!mmfile[i].ptr)
977 die(_("unable to read %s"),
978 oid_to_hex(&ce->oid));
979 mmfile[i].size = size;
980 }
981 }
982 for (i = 0; i < 3; i++)
983 if (!mmfile[i].ptr && !mmfile[i].size)
984 mmfile[i].ptr = xstrdup("");
985
986 /*
987 * NEEDSWORK: handle conflicts from merges with
988 * merge.renormalize set, too?
989 */
990 ll_merge(&result, path, &mmfile[0], NULL,
991 &mmfile[1], "ours",
992 &mmfile[2], "theirs",
993 istate, NULL);
994 for (i = 0; i < 3; i++)
995 free(mmfile[i].ptr);
996
997 memset(&io, 0, sizeof(io));
998 io.io.getline = rerere_mem_getline;
999 if (output)
1000 io.io.output = fopen(output, "w");
1001 else
1002 io.io.output = NULL;
1003 strbuf_init(&io.input, 0);
1004 strbuf_attach(&io.input, result.ptr, result.size, result.size);
1005
1006 /*
1007 * Grab the conflict ID and optionally write the original
1008 * contents with conflict markers out.
1009 */
1010 has_conflicts = handle_path(hash, (struct rerere_io *)&io, marker_size);
1011 strbuf_release(&io.input);
1012 if (io.io.output)
1013 fclose(io.io.output);
1014 return has_conflicts;
1015 }
1016
1017 static int rerere_forget_one_path(struct index_state *istate,
1018 const char *path,
1019 struct string_list *rr)
1020 {
1021 const char *filename;
1022 struct rerere_id *id;
1023 unsigned char hash[GIT_MAX_RAWSZ];
1024 int ret;
1025 struct strbuf buf = STRBUF_INIT;
1026 struct string_list_item *item;
1027
1028 /*
1029 * Recreate the original conflict from the stages in the
1030 * index and compute the conflict ID
1031 */
1032 ret = handle_cache(istate, path, hash, NULL);
1033 if (ret < 1)
1034 return error(_("could not parse conflict hunks in '%s'"), path);
1035
1036 /* Nuke the recorded resolution for the conflict */
1037 id = new_rerere_id(hash);
1038
1039 for (id->variant = 0;
1040 id->variant < id->collection->status_nr;
1041 id->variant++) {
1042 mmfile_t cur = { NULL, 0 };
1043 mmbuffer_t result = {NULL, 0};
1044 int cleanly_resolved;
1045
1046 if (!has_rerere_resolution(id))
1047 continue;
1048
1049 handle_cache(istate, path, hash, rerere_path(&buf, id, "thisimage"));
1050 if (read_mmfile(&cur, rerere_path(&buf, id, "thisimage"))) {
1051 free(cur.ptr);
1052 error(_("failed to update conflicted state in '%s'"), path);
1053 goto fail_exit;
1054 }
1055 cleanly_resolved = !try_merge(istate, id, path, &cur, &result);
1056 free(result.ptr);
1057 free(cur.ptr);
1058 if (cleanly_resolved)
1059 break;
1060 }
1061
1062 if (id->collection->status_nr <= id->variant) {
1063 error(_("no remembered resolution for '%s'"), path);
1064 goto fail_exit;
1065 }
1066
1067 filename = rerere_path(&buf, id, "postimage");
1068 if (unlink(filename)) {
1069 if (errno == ENOENT)
1070 error(_("no remembered resolution for '%s'"), path);
1071 else
1072 error_errno(_("cannot unlink '%s'"), filename);
1073 goto fail_exit;
1074 }
1075
1076 /*
1077 * Update the preimage so that the user can resolve the
1078 * conflict in the working tree, run us again to record
1079 * the postimage.
1080 */
1081 handle_cache(istate, path, hash, rerere_path(&buf, id, "preimage"));
1082 fprintf_ln(stderr, _("Updated preimage for '%s'"), path);
1083
1084 /*
1085 * And remember that we can record resolution for this
1086 * conflict when the user is done.
1087 */
1088 item = string_list_insert(rr, path);
1089 free_rerere_id(item);
1090 item->util = id;
1091 fprintf(stderr, _("Forgot resolution for '%s'\n"), path);
1092 strbuf_release(&buf);
1093 return 0;
1094
1095 fail_exit:
1096 strbuf_release(&buf);
1097 free(id);
1098 return -1;
1099 }
1100
1101 int rerere_forget(struct repository *r, struct pathspec *pathspec)
1102 {
1103 int i, fd, ret;
1104 struct string_list conflict = STRING_LIST_INIT_DUP;
1105 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1106
1107 if (repo_read_index(r) < 0)
1108 return error(_("index file corrupt"));
1109
1110 fd = setup_rerere(r, &merge_rr, RERERE_NOAUTOUPDATE);
1111 if (fd < 0)
1112 return 0;
1113
1114 /*
1115 * The paths may have been resolved (incorrectly);
1116 * recover the original conflicted state and then
1117 * find the conflicted paths.
1118 */
1119 unmerge_index(r->index, pathspec, 0);
1120 find_conflict(r, &conflict);
1121 for (i = 0; i < conflict.nr; i++) {
1122 struct string_list_item *it = &conflict.items[i];
1123 if (!match_pathspec(r->index, pathspec, it->string,
1124 strlen(it->string), 0, NULL, 0))
1125 continue;
1126 rerere_forget_one_path(r->index, it->string, &merge_rr);
1127 }
1128
1129 ret = write_rr(&merge_rr, fd);
1130
1131 string_list_clear(&conflict, 0);
1132 string_list_clear(&merge_rr, 1);
1133 return ret;
1134 }
1135
1136 /*
1137 * Garbage collection support
1138 */
1139
1140 static timestamp_t rerere_created_at(struct rerere_id *id)
1141 {
1142 struct strbuf buf = STRBUF_INIT;
1143 struct stat st;
1144 timestamp_t ret;
1145
1146 ret = stat(rerere_path(&buf, id, "preimage"), &st) ? (time_t) 0 : st.st_mtime;
1147
1148 strbuf_release(&buf);
1149 return ret;
1150 }
1151
1152 static timestamp_t rerere_last_used_at(struct rerere_id *id)
1153 {
1154 struct strbuf buf = STRBUF_INIT;
1155 struct stat st;
1156 timestamp_t ret;
1157
1158 ret = stat(rerere_path(&buf, id, "postimage"), &st) ? (time_t) 0 : st.st_mtime;
1159
1160 strbuf_release(&buf);
1161 return ret;
1162 }
1163
1164 /*
1165 * Remove the recorded resolution for a given conflict ID
1166 */
1167 static void unlink_rr_item(struct rerere_id *id)
1168 {
1169 struct strbuf buf = STRBUF_INIT;
1170 unlink_or_warn(rerere_path(&buf, id, "thisimage"));
1171 remove_variant(id);
1172 id->collection->status[id->variant] = 0;
1173 strbuf_release(&buf);
1174 }
1175
1176 static void prune_one(struct rerere_id *id,
1177 timestamp_t cutoff_resolve, timestamp_t cutoff_noresolve)
1178 {
1179 timestamp_t then;
1180 timestamp_t cutoff;
1181
1182 then = rerere_last_used_at(id);
1183 if (then)
1184 cutoff = cutoff_resolve;
1185 else {
1186 then = rerere_created_at(id);
1187 if (!then)
1188 return;
1189 cutoff = cutoff_noresolve;
1190 }
1191 if (then < cutoff)
1192 unlink_rr_item(id);
1193 }
1194
1195 /* Does the basename in "path" look plausibly like an rr-cache entry? */
1196 static int is_rr_cache_dirname(const char *path)
1197 {
1198 struct object_id oid;
1199 const char *end;
1200 return !parse_oid_hex(path, &oid, &end) && !*end;
1201 }
1202
1203 void rerere_gc(struct repository *r, struct string_list *rr)
1204 {
1205 struct string_list to_remove = STRING_LIST_INIT_DUP;
1206 DIR *dir;
1207 struct dirent *e;
1208 int i;
1209 timestamp_t now = time(NULL);
1210 timestamp_t cutoff_noresolve = now - 15 * 86400;
1211 timestamp_t cutoff_resolve = now - 60 * 86400;
1212 struct strbuf buf = STRBUF_INIT;
1213
1214 if (setup_rerere(r, rr, 0) < 0)
1215 return;
1216
1217 repo_config_get_expiry_in_days(the_repository, "gc.rerereresolved",
1218 &cutoff_resolve, now);
1219 repo_config_get_expiry_in_days(the_repository, "gc.rerereunresolved",
1220 &cutoff_noresolve, now);
1221 repo_config(the_repository, git_default_config, NULL);
1222 dir = opendir(repo_git_path_replace(the_repository, &buf, "rr-cache"));
1223 if (!dir)
1224 die_errno(_("unable to open rr-cache directory"));
1225 /* Collect stale conflict IDs ... */
1226 while ((e = readdir_skip_dot_and_dotdot(dir))) {
1227 struct rerere_dir *rr_dir;
1228 struct rerere_id id;
1229 int now_empty;
1230
1231 if (!is_rr_cache_dirname(e->d_name))
1232 continue; /* or should we remove e->d_name? */
1233
1234 rr_dir = find_rerere_dir(e->d_name);
1235
1236 now_empty = 1;
1237 for (id.variant = 0, id.collection = rr_dir;
1238 id.variant < id.collection->status_nr;
1239 id.variant++) {
1240 prune_one(&id, cutoff_resolve, cutoff_noresolve);
1241 if (id.collection->status[id.variant])
1242 now_empty = 0;
1243 }
1244 if (now_empty)
1245 string_list_append(&to_remove, e->d_name);
1246 }
1247 closedir(dir);
1248
1249 /* ... and then remove the empty directories */
1250 for (i = 0; i < to_remove.nr; i++)
1251 rmdir(repo_git_path_replace(the_repository, &buf,
1252 "rr-cache/%s", to_remove.items[i].string));
1253
1254 string_list_clear(&to_remove, 0);
1255 rollback_lock_file(&write_lock);
1256 strbuf_release(&buf);
1257 }
1258
1259 /*
1260 * During a conflict resolution, after "rerere" recorded the
1261 * preimages, abandon them if the user did not resolve them or
1262 * record their resolutions. And drop $GIT_DIR/MERGE_RR.
1263 *
1264 * NEEDSWORK: shouldn't we be calling this from "reset --hard"?
1265 */
1266 void rerere_clear(struct repository *r, struct string_list *merge_rr)
1267 {
1268 int i;
1269
1270 if (setup_rerere(r, merge_rr, 0) < 0)
1271 return;
1272
1273 for (i = 0; i < merge_rr->nr; i++) {
1274 struct rerere_id *id = merge_rr->items[i].util;
1275 struct strbuf buf = STRBUF_INIT;
1276
1277 if (!has_rerere_resolution(id)) {
1278 unlink_rr_item(id);
1279 rmdir(rerere_path(&buf, id, NULL));
1280 }
1281
1282 strbuf_release(&buf);
1283 }
1284 unlink_or_warn(git_path_merge_rr(r));
1285 rollback_lock_file(&write_lock);
1286 }