Code

remote: "rename o foo" should not rename ref "origin/bar"
[git.git] / notes-merge.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "refs.h"
4 #include "diff.h"
5 #include "diffcore.h"
6 #include "xdiff-interface.h"
7 #include "ll-merge.h"
8 #include "dir.h"
9 #include "notes.h"
10 #include "notes-merge.h"
11 #include "strbuf.h"
13 struct notes_merge_pair {
14         unsigned char obj[20], base[20], local[20], remote[20];
15 };
17 void init_notes_merge_options(struct notes_merge_options *o)
18 {
19         memset(o, 0, sizeof(struct notes_merge_options));
20         strbuf_init(&(o->commit_msg), 0);
21         o->verbosity = NOTES_MERGE_VERBOSITY_DEFAULT;
22 }
24 #define OUTPUT(o, v, ...) \
25         do { \
26                 if ((o)->verbosity >= (v)) { \
27                         printf(__VA_ARGS__); \
28                         puts(""); \
29                 } \
30         } while (0)
32 static int path_to_sha1(const char *path, unsigned char *sha1)
33 {
34         char hex_sha1[40];
35         int i = 0;
36         while (*path && i < 40) {
37                 if (*path != '/')
38                         hex_sha1[i++] = *path;
39                 path++;
40         }
41         if (*path || i != 40)
42                 return -1;
43         return get_sha1_hex(hex_sha1, sha1);
44 }
46 static int verify_notes_filepair(struct diff_filepair *p, unsigned char *sha1)
47 {
48         switch (p->status) {
49         case DIFF_STATUS_MODIFIED:
50                 assert(p->one->mode == p->two->mode);
51                 assert(!is_null_sha1(p->one->sha1));
52                 assert(!is_null_sha1(p->two->sha1));
53                 break;
54         case DIFF_STATUS_ADDED:
55                 assert(is_null_sha1(p->one->sha1));
56                 break;
57         case DIFF_STATUS_DELETED:
58                 assert(is_null_sha1(p->two->sha1));
59                 break;
60         default:
61                 return -1;
62         }
63         assert(!strcmp(p->one->path, p->two->path));
64         return path_to_sha1(p->one->path, sha1);
65 }
67 static struct notes_merge_pair *find_notes_merge_pair_pos(
68                 struct notes_merge_pair *list, int len, unsigned char *obj,
69                 int insert_new, int *occupied)
70 {
71         /*
72          * Both diff_tree_remote() and diff_tree_local() tend to process
73          * merge_pairs in ascending order. Therefore, cache last returned
74          * index, and search sequentially from there until the appropriate
75          * position is found.
76          *
77          * Since inserts only happen from diff_tree_remote() (which mainly
78          * _appends_), we don't care that inserting into the middle of the
79          * list is expensive (using memmove()).
80          */
81         static int last_index;
82         int i = last_index < len ? last_index : len - 1;
83         int prev_cmp = 0, cmp = -1;
84         while (i >= 0 && i < len) {
85                 cmp = hashcmp(obj, list[i].obj);
86                 if (!cmp) /* obj belongs @ i */
87                         break;
88                 else if (cmp < 0 && prev_cmp <= 0) /* obj belongs < i */
89                         i--;
90                 else if (cmp < 0) /* obj belongs between i-1 and i */
91                         break;
92                 else if (cmp > 0 && prev_cmp >= 0) /* obj belongs > i */
93                         i++;
94                 else /* if (cmp > 0) */ { /* obj belongs between i and i+1 */
95                         i++;
96                         break;
97                 }
98                 prev_cmp = cmp;
99         }
100         if (i < 0)
101                 i = 0;
102         /* obj belongs at, or immediately preceding, index i (0 <= i <= len) */
104         if (!cmp)
105                 *occupied = 1;
106         else {
107                 *occupied = 0;
108                 if (insert_new && i < len) {
109                         memmove(list + i + 1, list + i,
110                                 (len - i) * sizeof(struct notes_merge_pair));
111                         memset(list + i, 0, sizeof(struct notes_merge_pair));
112                 }
113         }
114         last_index = i;
115         return list + i;
118 static unsigned char uninitialized[20] =
119         "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" \
120         "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";
122 static struct notes_merge_pair *diff_tree_remote(struct notes_merge_options *o,
123                                                  const unsigned char *base,
124                                                  const unsigned char *remote,
125                                                  int *num_changes)
127         struct diff_options opt;
128         struct notes_merge_pair *changes;
129         int i, len = 0;
131         trace_printf("\tdiff_tree_remote(base = %.7s, remote = %.7s)\n",
132                sha1_to_hex(base), sha1_to_hex(remote));
134         diff_setup(&opt);
135         DIFF_OPT_SET(&opt, RECURSIVE);
136         opt.output_format = DIFF_FORMAT_NO_OUTPUT;
137         if (diff_setup_done(&opt) < 0)
138                 die("diff_setup_done failed");
139         diff_tree_sha1(base, remote, "", &opt);
140         diffcore_std(&opt);
142         changes = xcalloc(diff_queued_diff.nr, sizeof(struct notes_merge_pair));
144         for (i = 0; i < diff_queued_diff.nr; i++) {
145                 struct diff_filepair *p = diff_queued_diff.queue[i];
146                 struct notes_merge_pair *mp;
147                 int occupied;
148                 unsigned char obj[20];
150                 if (verify_notes_filepair(p, obj)) {
151                         trace_printf("\t\tCannot merge entry '%s' (%c): "
152                                "%.7s -> %.7s. Skipping!\n", p->one->path,
153                                p->status, sha1_to_hex(p->one->sha1),
154                                sha1_to_hex(p->two->sha1));
155                         continue;
156                 }
157                 mp = find_notes_merge_pair_pos(changes, len, obj, 1, &occupied);
158                 if (occupied) {
159                         /* We've found an addition/deletion pair */
160                         assert(!hashcmp(mp->obj, obj));
161                         if (is_null_sha1(p->one->sha1)) { /* addition */
162                                 assert(is_null_sha1(mp->remote));
163                                 hashcpy(mp->remote, p->two->sha1);
164                         } else if (is_null_sha1(p->two->sha1)) { /* deletion */
165                                 assert(is_null_sha1(mp->base));
166                                 hashcpy(mp->base, p->one->sha1);
167                         } else
168                                 assert(!"Invalid existing change recorded");
169                 } else {
170                         hashcpy(mp->obj, obj);
171                         hashcpy(mp->base, p->one->sha1);
172                         hashcpy(mp->local, uninitialized);
173                         hashcpy(mp->remote, p->two->sha1);
174                         len++;
175                 }
176                 trace_printf("\t\tStored remote change for %s: %.7s -> %.7s\n",
177                        sha1_to_hex(mp->obj), sha1_to_hex(mp->base),
178                        sha1_to_hex(mp->remote));
179         }
180         diff_flush(&opt);
181         diff_tree_release_paths(&opt);
183         *num_changes = len;
184         return changes;
187 static void diff_tree_local(struct notes_merge_options *o,
188                             struct notes_merge_pair *changes, int len,
189                             const unsigned char *base,
190                             const unsigned char *local)
192         struct diff_options opt;
193         int i;
195         trace_printf("\tdiff_tree_local(len = %i, base = %.7s, local = %.7s)\n",
196                len, sha1_to_hex(base), sha1_to_hex(local));
198         diff_setup(&opt);
199         DIFF_OPT_SET(&opt, RECURSIVE);
200         opt.output_format = DIFF_FORMAT_NO_OUTPUT;
201         if (diff_setup_done(&opt) < 0)
202                 die("diff_setup_done failed");
203         diff_tree_sha1(base, local, "", &opt);
204         diffcore_std(&opt);
206         for (i = 0; i < diff_queued_diff.nr; i++) {
207                 struct diff_filepair *p = diff_queued_diff.queue[i];
208                 struct notes_merge_pair *mp;
209                 int match;
210                 unsigned char obj[20];
212                 if (verify_notes_filepair(p, obj)) {
213                         trace_printf("\t\tCannot merge entry '%s' (%c): "
214                                "%.7s -> %.7s. Skipping!\n", p->one->path,
215                                p->status, sha1_to_hex(p->one->sha1),
216                                sha1_to_hex(p->two->sha1));
217                         continue;
218                 }
219                 mp = find_notes_merge_pair_pos(changes, len, obj, 0, &match);
220                 if (!match) {
221                         trace_printf("\t\tIgnoring local-only change for %s: "
222                                "%.7s -> %.7s\n", sha1_to_hex(obj),
223                                sha1_to_hex(p->one->sha1),
224                                sha1_to_hex(p->two->sha1));
225                         continue;
226                 }
228                 assert(!hashcmp(mp->obj, obj));
229                 if (is_null_sha1(p->two->sha1)) { /* deletion */
230                         /*
231                          * Either this is a true deletion (1), or it is part
232                          * of an A/D pair (2), or D/A pair (3):
233                          *
234                          * (1) mp->local is uninitialized; set it to null_sha1
235                          * (2) mp->local is not uninitialized; don't touch it
236                          * (3) mp->local is uninitialized; set it to null_sha1
237                          *     (will be overwritten by following addition)
238                          */
239                         if (!hashcmp(mp->local, uninitialized))
240                                 hashclr(mp->local);
241                 } else if (is_null_sha1(p->one->sha1)) { /* addition */
242                         /*
243                          * Either this is a true addition (1), or it is part
244                          * of an A/D pair (2), or D/A pair (3):
245                          *
246                          * (1) mp->local is uninitialized; set to p->two->sha1
247                          * (2) mp->local is uninitialized; set to p->two->sha1
248                          * (3) mp->local is null_sha1;     set to p->two->sha1
249                          */
250                         assert(is_null_sha1(mp->local) ||
251                                !hashcmp(mp->local, uninitialized));
252                         hashcpy(mp->local, p->two->sha1);
253                 } else { /* modification */
254                         /*
255                          * This is a true modification. p->one->sha1 shall
256                          * match mp->base, and mp->local shall be uninitialized.
257                          * Set mp->local to p->two->sha1.
258                          */
259                         assert(!hashcmp(p->one->sha1, mp->base));
260                         assert(!hashcmp(mp->local, uninitialized));
261                         hashcpy(mp->local, p->two->sha1);
262                 }
263                 trace_printf("\t\tStored local change for %s: %.7s -> %.7s\n",
264                        sha1_to_hex(mp->obj), sha1_to_hex(mp->base),
265                        sha1_to_hex(mp->local));
266         }
267         diff_flush(&opt);
268         diff_tree_release_paths(&opt);
271 static void check_notes_merge_worktree(struct notes_merge_options *o)
273         if (!o->has_worktree) {
274                 /*
275                  * Must establish NOTES_MERGE_WORKTREE.
276                  * Abort if NOTES_MERGE_WORKTREE already exists
277                  */
278                 if (file_exists(git_path(NOTES_MERGE_WORKTREE))) {
279                         if (advice_resolve_conflict)
280                                 die("You have not concluded your previous "
281                                     "notes merge (%s exists).\nPlease, use "
282                                     "'git notes merge --commit' or 'git notes "
283                                     "merge --abort' to commit/abort the "
284                                     "previous merge before you start a new "
285                                     "notes merge.", git_path("NOTES_MERGE_*"));
286                         else
287                                 die("You have not concluded your notes merge "
288                                     "(%s exists).", git_path("NOTES_MERGE_*"));
289                 }
291                 if (safe_create_leading_directories(git_path(
292                                 NOTES_MERGE_WORKTREE "/.test")))
293                         die_errno("unable to create directory %s",
294                                   git_path(NOTES_MERGE_WORKTREE));
295                 o->has_worktree = 1;
296         } else if (!file_exists(git_path(NOTES_MERGE_WORKTREE)))
297                 /* NOTES_MERGE_WORKTREE should already be established */
298                 die("missing '%s'. This should not happen",
299                     git_path(NOTES_MERGE_WORKTREE));
302 static void write_buf_to_worktree(const unsigned char *obj,
303                                   const char *buf, unsigned long size)
305         int fd;
306         char *path = git_path(NOTES_MERGE_WORKTREE "/%s", sha1_to_hex(obj));
307         if (safe_create_leading_directories(path))
308                 die_errno("unable to create directory for '%s'", path);
309         if (file_exists(path))
310                 die("found existing file at '%s'", path);
312         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, 0666);
313         if (fd < 0)
314                 die_errno("failed to open '%s'", path);
316         while (size > 0) {
317                 long ret = write_in_full(fd, buf, size);
318                 if (ret < 0) {
319                         /* Ignore epipe */
320                         if (errno == EPIPE)
321                                 break;
322                         die_errno("notes-merge");
323                 } else if (!ret) {
324                         die("notes-merge: disk full?");
325                 }
326                 size -= ret;
327                 buf += ret;
328         }
330         close(fd);
333 static void write_note_to_worktree(const unsigned char *obj,
334                                    const unsigned char *note)
336         enum object_type type;
337         unsigned long size;
338         void *buf = read_sha1_file(note, &type, &size);
340         if (!buf)
341                 die("cannot read note %s for object %s",
342                     sha1_to_hex(note), sha1_to_hex(obj));
343         if (type != OBJ_BLOB)
344                 die("blob expected in note %s for object %s",
345                     sha1_to_hex(note), sha1_to_hex(obj));
346         write_buf_to_worktree(obj, buf, size);
347         free(buf);
350 static int ll_merge_in_worktree(struct notes_merge_options *o,
351                                 struct notes_merge_pair *p)
353         mmbuffer_t result_buf;
354         mmfile_t base, local, remote;
355         int status;
357         read_mmblob(&base, p->base);
358         read_mmblob(&local, p->local);
359         read_mmblob(&remote, p->remote);
361         status = ll_merge(&result_buf, sha1_to_hex(p->obj), &base, NULL,
362                           &local, o->local_ref, &remote, o->remote_ref, NULL);
364         free(base.ptr);
365         free(local.ptr);
366         free(remote.ptr);
368         if ((status < 0) || !result_buf.ptr)
369                 die("Failed to execute internal merge");
371         write_buf_to_worktree(p->obj, result_buf.ptr, result_buf.size);
372         free(result_buf.ptr);
374         return status;
377 static int merge_one_change_manual(struct notes_merge_options *o,
378                                    struct notes_merge_pair *p,
379                                    struct notes_tree *t)
381         const char *lref = o->local_ref ? o->local_ref : "local version";
382         const char *rref = o->remote_ref ? o->remote_ref : "remote version";
384         trace_printf("\t\t\tmerge_one_change_manual(obj = %.7s, base = %.7s, "
385                "local = %.7s, remote = %.7s)\n",
386                sha1_to_hex(p->obj), sha1_to_hex(p->base),
387                sha1_to_hex(p->local), sha1_to_hex(p->remote));
389         /* add "Conflicts:" section to commit message first time through */
390         if (!o->has_worktree)
391                 strbuf_addstr(&(o->commit_msg), "\n\nConflicts:\n");
393         strbuf_addf(&(o->commit_msg), "\t%s\n", sha1_to_hex(p->obj));
395         OUTPUT(o, 2, "Auto-merging notes for %s", sha1_to_hex(p->obj));
396         check_notes_merge_worktree(o);
397         if (is_null_sha1(p->local)) {
398                 /* D/F conflict, checkout p->remote */
399                 assert(!is_null_sha1(p->remote));
400                 OUTPUT(o, 1, "CONFLICT (delete/modify): Notes for object %s "
401                        "deleted in %s and modified in %s. Version from %s "
402                        "left in tree.", sha1_to_hex(p->obj), lref, rref, rref);
403                 write_note_to_worktree(p->obj, p->remote);
404         } else if (is_null_sha1(p->remote)) {
405                 /* D/F conflict, checkout p->local */
406                 assert(!is_null_sha1(p->local));
407                 OUTPUT(o, 1, "CONFLICT (delete/modify): Notes for object %s "
408                        "deleted in %s and modified in %s. Version from %s "
409                        "left in tree.", sha1_to_hex(p->obj), rref, lref, lref);
410                 write_note_to_worktree(p->obj, p->local);
411         } else {
412                 /* "regular" conflict, checkout result of ll_merge() */
413                 const char *reason = "content";
414                 if (is_null_sha1(p->base))
415                         reason = "add/add";
416                 assert(!is_null_sha1(p->local));
417                 assert(!is_null_sha1(p->remote));
418                 OUTPUT(o, 1, "CONFLICT (%s): Merge conflict in notes for "
419                        "object %s", reason, sha1_to_hex(p->obj));
420                 ll_merge_in_worktree(o, p);
421         }
423         trace_printf("\t\t\tremoving from partial merge result\n");
424         remove_note(t, p->obj);
426         return 1;
429 static int merge_one_change(struct notes_merge_options *o,
430                             struct notes_merge_pair *p, struct notes_tree *t)
432         /*
433          * Return 0 if change is successfully resolved (stored in notes_tree).
434          * Return 1 is change results in a conflict (NOT stored in notes_tree,
435          * but instead written to NOTES_MERGE_WORKTREE with conflict markers).
436          */
437         switch (o->strategy) {
438         case NOTES_MERGE_RESOLVE_MANUAL:
439                 return merge_one_change_manual(o, p, t);
440         case NOTES_MERGE_RESOLVE_OURS:
441                 OUTPUT(o, 2, "Using local notes for %s", sha1_to_hex(p->obj));
442                 /* nothing to do */
443                 return 0;
444         case NOTES_MERGE_RESOLVE_THEIRS:
445                 OUTPUT(o, 2, "Using remote notes for %s", sha1_to_hex(p->obj));
446                 if (add_note(t, p->obj, p->remote, combine_notes_overwrite))
447                         die("BUG: combine_notes_overwrite failed");
448                 return 0;
449         case NOTES_MERGE_RESOLVE_UNION:
450                 OUTPUT(o, 2, "Concatenating local and remote notes for %s",
451                        sha1_to_hex(p->obj));
452                 if (add_note(t, p->obj, p->remote, combine_notes_concatenate))
453                         die("failed to concatenate notes "
454                             "(combine_notes_concatenate)");
455                 return 0;
456         case NOTES_MERGE_RESOLVE_CAT_SORT_UNIQ:
457                 OUTPUT(o, 2, "Concatenating unique lines in local and remote "
458                        "notes for %s", sha1_to_hex(p->obj));
459                 if (add_note(t, p->obj, p->remote, combine_notes_cat_sort_uniq))
460                         die("failed to concatenate notes "
461                             "(combine_notes_cat_sort_uniq)");
462                 return 0;
463         }
464         die("Unknown strategy (%i).", o->strategy);
467 static int merge_changes(struct notes_merge_options *o,
468                          struct notes_merge_pair *changes, int *num_changes,
469                          struct notes_tree *t)
471         int i, conflicts = 0;
473         trace_printf("\tmerge_changes(num_changes = %i)\n", *num_changes);
474         for (i = 0; i < *num_changes; i++) {
475                 struct notes_merge_pair *p = changes + i;
476                 trace_printf("\t\t%.7s: %.7s -> %.7s/%.7s\n",
477                        sha1_to_hex(p->obj), sha1_to_hex(p->base),
478                        sha1_to_hex(p->local), sha1_to_hex(p->remote));
480                 if (!hashcmp(p->base, p->remote)) {
481                         /* no remote change; nothing to do */
482                         trace_printf("\t\t\tskipping (no remote change)\n");
483                 } else if (!hashcmp(p->local, p->remote)) {
484                         /* same change in local and remote; nothing to do */
485                         trace_printf("\t\t\tskipping (local == remote)\n");
486                 } else if (!hashcmp(p->local, uninitialized) ||
487                            !hashcmp(p->local, p->base)) {
488                         /* no local change; adopt remote change */
489                         trace_printf("\t\t\tno local change, adopted remote\n");
490                         if (add_note(t, p->obj, p->remote,
491                                      combine_notes_overwrite))
492                                 die("BUG: combine_notes_overwrite failed");
493                 } else {
494                         /* need file-level merge between local and remote */
495                         trace_printf("\t\t\tneed content-level merge\n");
496                         conflicts += merge_one_change(o, p, t);
497                 }
498         }
500         return conflicts;
503 static int merge_from_diffs(struct notes_merge_options *o,
504                             const unsigned char *base,
505                             const unsigned char *local,
506                             const unsigned char *remote, struct notes_tree *t)
508         struct notes_merge_pair *changes;
509         int num_changes, conflicts;
511         trace_printf("\tmerge_from_diffs(base = %.7s, local = %.7s, "
512                "remote = %.7s)\n", sha1_to_hex(base), sha1_to_hex(local),
513                sha1_to_hex(remote));
515         changes = diff_tree_remote(o, base, remote, &num_changes);
516         diff_tree_local(o, changes, num_changes, base, local);
518         conflicts = merge_changes(o, changes, &num_changes, t);
519         free(changes);
521         OUTPUT(o, 4, "Merge result: %i unmerged notes and a %s notes tree",
522                conflicts, t->dirty ? "dirty" : "clean");
524         return conflicts ? -1 : 1;
527 void create_notes_commit(struct notes_tree *t, struct commit_list *parents,
528                          const char *msg, unsigned char *result_sha1)
530         unsigned char tree_sha1[20];
532         assert(t->initialized);
534         if (write_notes_tree(t, tree_sha1))
535                 die("Failed to write notes tree to database");
537         if (!parents) {
538                 /* Deduce parent commit from t->ref */
539                 unsigned char parent_sha1[20];
540                 if (!read_ref(t->ref, parent_sha1)) {
541                         struct commit *parent = lookup_commit(parent_sha1);
542                         if (!parent || parse_commit(parent))
543                                 die("Failed to find/parse commit %s", t->ref);
544                         commit_list_insert(parent, &parents);
545                 }
546                 /* else: t->ref points to nothing, assume root/orphan commit */
547         }
549         if (commit_tree(msg, tree_sha1, parents, result_sha1, NULL))
550                 die("Failed to commit notes tree to database");
553 int notes_merge(struct notes_merge_options *o,
554                 struct notes_tree *local_tree,
555                 unsigned char *result_sha1)
557         unsigned char local_sha1[20], remote_sha1[20];
558         struct commit *local, *remote;
559         struct commit_list *bases = NULL;
560         const unsigned char *base_sha1, *base_tree_sha1;
561         int result = 0;
563         assert(o->local_ref && o->remote_ref);
564         assert(!strcmp(o->local_ref, local_tree->ref));
565         hashclr(result_sha1);
567         trace_printf("notes_merge(o->local_ref = %s, o->remote_ref = %s)\n",
568                o->local_ref, o->remote_ref);
570         /* Dereference o->local_ref into local_sha1 */
571         if (!resolve_ref(o->local_ref, local_sha1, 0, NULL))
572                 die("Failed to resolve local notes ref '%s'", o->local_ref);
573         else if (!check_ref_format(o->local_ref) && is_null_sha1(local_sha1))
574                 local = NULL; /* local_sha1 == null_sha1 indicates unborn ref */
575         else if (!(local = lookup_commit_reference(local_sha1)))
576                 die("Could not parse local commit %s (%s)",
577                     sha1_to_hex(local_sha1), o->local_ref);
578         trace_printf("\tlocal commit: %.7s\n", sha1_to_hex(local_sha1));
580         /* Dereference o->remote_ref into remote_sha1 */
581         if (get_sha1(o->remote_ref, remote_sha1)) {
582                 /*
583                  * Failed to get remote_sha1. If o->remote_ref looks like an
584                  * unborn ref, perform the merge using an empty notes tree.
585                  */
586                 if (!check_ref_format(o->remote_ref)) {
587                         hashclr(remote_sha1);
588                         remote = NULL;
589                 } else {
590                         die("Failed to resolve remote notes ref '%s'",
591                             o->remote_ref);
592                 }
593         } else if (!(remote = lookup_commit_reference(remote_sha1))) {
594                 die("Could not parse remote commit %s (%s)",
595                     sha1_to_hex(remote_sha1), o->remote_ref);
596         }
597         trace_printf("\tremote commit: %.7s\n", sha1_to_hex(remote_sha1));
599         if (!local && !remote)
600                 die("Cannot merge empty notes ref (%s) into empty notes ref "
601                     "(%s)", o->remote_ref, o->local_ref);
602         if (!local) {
603                 /* result == remote commit */
604                 hashcpy(result_sha1, remote_sha1);
605                 goto found_result;
606         }
607         if (!remote) {
608                 /* result == local commit */
609                 hashcpy(result_sha1, local_sha1);
610                 goto found_result;
611         }
612         assert(local && remote);
614         /* Find merge bases */
615         bases = get_merge_bases(local, remote, 1);
616         if (!bases) {
617                 base_sha1 = null_sha1;
618                 base_tree_sha1 = EMPTY_TREE_SHA1_BIN;
619                 OUTPUT(o, 4, "No merge base found; doing history-less merge");
620         } else if (!bases->next) {
621                 base_sha1 = bases->item->object.sha1;
622                 base_tree_sha1 = bases->item->tree->object.sha1;
623                 OUTPUT(o, 4, "One merge base found (%.7s)",
624                        sha1_to_hex(base_sha1));
625         } else {
626                 /* TODO: How to handle multiple merge-bases? */
627                 base_sha1 = bases->item->object.sha1;
628                 base_tree_sha1 = bases->item->tree->object.sha1;
629                 OUTPUT(o, 3, "Multiple merge bases found. Using the first "
630                        "(%.7s)", sha1_to_hex(base_sha1));
631         }
633         OUTPUT(o, 4, "Merging remote commit %.7s into local commit %.7s with "
634                "merge-base %.7s", sha1_to_hex(remote->object.sha1),
635                sha1_to_hex(local->object.sha1), sha1_to_hex(base_sha1));
637         if (!hashcmp(remote->object.sha1, base_sha1)) {
638                 /* Already merged; result == local commit */
639                 OUTPUT(o, 2, "Already up-to-date!");
640                 hashcpy(result_sha1, local->object.sha1);
641                 goto found_result;
642         }
643         if (!hashcmp(local->object.sha1, base_sha1)) {
644                 /* Fast-forward; result == remote commit */
645                 OUTPUT(o, 2, "Fast-forward");
646                 hashcpy(result_sha1, remote->object.sha1);
647                 goto found_result;
648         }
650         result = merge_from_diffs(o, base_tree_sha1, local->tree->object.sha1,
651                                   remote->tree->object.sha1, local_tree);
653         if (result != 0) { /* non-trivial merge (with or without conflicts) */
654                 /* Commit (partial) result */
655                 struct commit_list *parents = NULL;
656                 commit_list_insert(remote, &parents); /* LIFO order */
657                 commit_list_insert(local, &parents);
658                 create_notes_commit(local_tree, parents, o->commit_msg.buf,
659                                     result_sha1);
660         }
662 found_result:
663         free_commit_list(bases);
664         strbuf_release(&(o->commit_msg));
665         trace_printf("notes_merge(): result = %i, result_sha1 = %.7s\n",
666                result, sha1_to_hex(result_sha1));
667         return result;
670 int notes_merge_commit(struct notes_merge_options *o,
671                        struct notes_tree *partial_tree,
672                        struct commit *partial_commit,
673                        unsigned char *result_sha1)
675         /*
676          * Iterate through files in .git/NOTES_MERGE_WORKTREE and add all
677          * found notes to 'partial_tree'. Write the updates notes tree to
678          * the DB, and commit the resulting tree object while reusing the
679          * commit message and parents from 'partial_commit'.
680          * Finally store the new commit object SHA1 into 'result_sha1'.
681          */
682         struct dir_struct dir;
683         const char *path = git_path(NOTES_MERGE_WORKTREE "/");
684         int path_len = strlen(path), i;
685         const char *msg = strstr(partial_commit->buffer, "\n\n");
687         OUTPUT(o, 3, "Committing notes in notes merge worktree at %.*s",
688                path_len - 1, path);
690         if (!msg || msg[2] == '\0')
691                 die("partial notes commit has empty message");
692         msg += 2;
694         memset(&dir, 0, sizeof(dir));
695         read_directory(&dir, path, path_len, NULL);
696         for (i = 0; i < dir.nr; i++) {
697                 struct dir_entry *ent = dir.entries[i];
698                 struct stat st;
699                 const char *relpath = ent->name + path_len;
700                 unsigned char obj_sha1[20], blob_sha1[20];
702                 if (ent->len - path_len != 40 || get_sha1_hex(relpath, obj_sha1)) {
703                         OUTPUT(o, 3, "Skipping non-SHA1 entry '%s'", ent->name);
704                         continue;
705                 }
707                 /* write file as blob, and add to partial_tree */
708                 if (stat(ent->name, &st))
709                         die_errno("Failed to stat '%s'", ent->name);
710                 if (index_path(blob_sha1, ent->name, &st, HASH_WRITE_OBJECT))
711                         die("Failed to write blob object from '%s'", ent->name);
712                 if (add_note(partial_tree, obj_sha1, blob_sha1, NULL))
713                         die("Failed to add resolved note '%s' to notes tree",
714                             ent->name);
715                 OUTPUT(o, 4, "Added resolved note for object %s: %s",
716                        sha1_to_hex(obj_sha1), sha1_to_hex(blob_sha1));
717         }
719         create_notes_commit(partial_tree, partial_commit->parents, msg,
720                             result_sha1);
721         OUTPUT(o, 4, "Finalized notes merge commit: %s",
722                sha1_to_hex(result_sha1));
723         return 0;
726 int notes_merge_abort(struct notes_merge_options *o)
728         /* Remove .git/NOTES_MERGE_WORKTREE directory and all files within */
729         struct strbuf buf = STRBUF_INIT;
730         int ret;
732         strbuf_addstr(&buf, git_path(NOTES_MERGE_WORKTREE));
733         OUTPUT(o, 3, "Removing notes merge worktree at %s", buf.buf);
734         ret = remove_dir_recursively(&buf, 0);
735         strbuf_release(&buf);
736         return ret;