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