THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1256 lines
32KB

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