builtin/notes: split create_note() to clarify add vs. remove logic
[git] / builtin / notes.c
1 /*
2  * Builtin "git notes"
3  *
4  * Copyright (c) 2010 Johan Herland <johan@herland.net>
5  *
6  * Based on git-notes.sh by Johannes Schindelin,
7  * and builtin/tag.c by Kristian Høgsberg and Carlos Rica.
8  */
9
10 #include "cache.h"
11 #include "builtin.h"
12 #include "notes.h"
13 #include "blob.h"
14 #include "commit.h"
15 #include "refs.h"
16 #include "exec_cmd.h"
17 #include "run-command.h"
18 #include "parse-options.h"
19 #include "string-list.h"
20 #include "notes-merge.h"
21 #include "notes-utils.h"
22
23 static const char * const git_notes_usage[] = {
24         N_("git notes [--ref <notes_ref>] [list [<object>]]"),
25         N_("git notes [--ref <notes_ref>] add [-f] [-m <msg> | -F <file> | (-c | -C) <object>] [<object>]"),
26         N_("git notes [--ref <notes_ref>] copy [-f] <from-object> <to-object>"),
27         N_("git notes [--ref <notes_ref>] append [-m <msg> | -F <file> | (-c | -C) <object>] [<object>]"),
28         N_("git notes [--ref <notes_ref>] edit [<object>]"),
29         N_("git notes [--ref <notes_ref>] show [<object>]"),
30         N_("git notes [--ref <notes_ref>] merge [-v | -q] [-s <strategy> ] <notes_ref>"),
31         N_("git notes merge --commit [-v | -q]"),
32         N_("git notes merge --abort [-v | -q]"),
33         N_("git notes [--ref <notes_ref>] remove [<object>...]"),
34         N_("git notes [--ref <notes_ref>] prune [-n | -v]"),
35         N_("git notes [--ref <notes_ref>] get-ref"),
36         NULL
37 };
38
39 static const char * const git_notes_list_usage[] = {
40         N_("git notes [list [<object>]]"),
41         NULL
42 };
43
44 static const char * const git_notes_add_usage[] = {
45         N_("git notes add [<options>] [<object>]"),
46         NULL
47 };
48
49 static const char * const git_notes_copy_usage[] = {
50         N_("git notes copy [<options>] <from-object> <to-object>"),
51         N_("git notes copy --stdin [<from-object> <to-object>]..."),
52         NULL
53 };
54
55 static const char * const git_notes_append_usage[] = {
56         N_("git notes append [<options>] [<object>]"),
57         NULL
58 };
59
60 static const char * const git_notes_edit_usage[] = {
61         N_("git notes edit [<object>]"),
62         NULL
63 };
64
65 static const char * const git_notes_show_usage[] = {
66         N_("git notes show [<object>]"),
67         NULL
68 };
69
70 static const char * const git_notes_merge_usage[] = {
71         N_("git notes merge [<options>] <notes_ref>"),
72         N_("git notes merge --commit [<options>]"),
73         N_("git notes merge --abort [<options>]"),
74         NULL
75 };
76
77 static const char * const git_notes_remove_usage[] = {
78         N_("git notes remove [<object>]"),
79         NULL
80 };
81
82 static const char * const git_notes_prune_usage[] = {
83         N_("git notes prune [<options>]"),
84         NULL
85 };
86
87 static const char * const git_notes_get_ref_usage[] = {
88         N_("git notes get-ref"),
89         NULL
90 };
91
92 static const char note_template[] =
93         "\nWrite/edit the notes for the following object:\n";
94
95 struct note_data {
96         int given;
97         int use_editor;
98         char *edit_path;
99         struct strbuf buf;
100 };
101
102 static void free_note_data(struct note_data *d)
103 {
104         if (d->edit_path) {
105                 unlink_or_warn(d->edit_path);
106                 free(d->edit_path);
107         }
108         strbuf_release(&d->buf);
109 }
110
111 static int list_each_note(const unsigned char *object_sha1,
112                 const unsigned char *note_sha1, char *note_path,
113                 void *cb_data)
114 {
115         printf("%s %s\n", sha1_to_hex(note_sha1), sha1_to_hex(object_sha1));
116         return 0;
117 }
118
119 static void copy_obj_to_fd(int fd, const unsigned char *sha1)
120 {
121         unsigned long size;
122         enum object_type type;
123         char *buf = read_sha1_file(sha1, &type, &size);
124         if (buf) {
125                 if (size)
126                         write_or_die(fd, buf, size);
127                 free(buf);
128         }
129 }
130
131 static void write_commented_object(int fd, const unsigned char *object)
132 {
133         const char *show_args[5] =
134                 {"show", "--stat", "--no-notes", sha1_to_hex(object), NULL};
135         struct child_process show = CHILD_PROCESS_INIT;
136         struct strbuf buf = STRBUF_INIT;
137         struct strbuf cbuf = STRBUF_INIT;
138
139         /* Invoke "git show --stat --no-notes $object" */
140         show.argv = show_args;
141         show.no_stdin = 1;
142         show.out = -1;
143         show.err = 0;
144         show.git_cmd = 1;
145         if (start_command(&show))
146                 die(_("unable to start 'show' for object '%s'"),
147                     sha1_to_hex(object));
148
149         if (strbuf_read(&buf, show.out, 0) < 0)
150                 die_errno(_("could not read 'show' output"));
151         strbuf_add_commented_lines(&cbuf, buf.buf, buf.len);
152         write_or_die(fd, cbuf.buf, cbuf.len);
153
154         strbuf_release(&cbuf);
155         strbuf_release(&buf);
156
157         if (finish_command(&show))
158                 die(_("failed to finish 'show' for object '%s'"),
159                     sha1_to_hex(object));
160 }
161
162 static void prepare_note_data(const unsigned char *object, struct note_data *d,
163                 const unsigned char *old_note)
164 {
165         if (d->use_editor || !d->given) {
166                 int fd;
167                 struct strbuf buf = STRBUF_INIT;
168
169                 /* write the template message before editing: */
170                 d->edit_path = git_pathdup("NOTES_EDITMSG");
171                 fd = open(d->edit_path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
172                 if (fd < 0)
173                         die_errno(_("could not create file '%s'"), d->edit_path);
174
175                 if (d->given)
176                         write_or_die(fd, d->buf.buf, d->buf.len);
177                 else if (old_note)
178                         copy_obj_to_fd(fd, old_note);
179
180                 strbuf_addch(&buf, '\n');
181                 strbuf_add_commented_lines(&buf, note_template, strlen(note_template));
182                 strbuf_addch(&buf, '\n');
183                 write_or_die(fd, buf.buf, buf.len);
184
185                 write_commented_object(fd, object);
186
187                 close(fd);
188                 strbuf_release(&buf);
189                 strbuf_reset(&d->buf);
190
191                 if (launch_editor(d->edit_path, &d->buf, NULL)) {
192                         die(_("Please supply the note contents using either -m or -F option"));
193                 }
194                 stripspace(&d->buf, 1);
195         }
196 }
197
198 static void write_note_data(struct note_data *d, unsigned char *sha1)
199 {
200         if (write_sha1_file(d->buf.buf, d->buf.len, blob_type, sha1)) {
201                 error(_("unable to write note object"));
202                 if (d->edit_path)
203                         error(_("The note contents have been left in %s"),
204                                 d->edit_path);
205                 exit(128);
206         }
207 }
208
209 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
210 {
211         struct note_data *d = opt->value;
212
213         strbuf_grow(&d->buf, strlen(arg) + 2);
214         if (d->buf.len)
215                 strbuf_addch(&d->buf, '\n');
216         strbuf_addstr(&d->buf, arg);
217         stripspace(&d->buf, 0);
218
219         d->given = 1;
220         return 0;
221 }
222
223 static int parse_file_arg(const struct option *opt, const char *arg, int unset)
224 {
225         struct note_data *d = opt->value;
226
227         if (d->buf.len)
228                 strbuf_addch(&d->buf, '\n');
229         if (!strcmp(arg, "-")) {
230                 if (strbuf_read(&d->buf, 0, 1024) < 0)
231                         die_errno(_("cannot read '%s'"), arg);
232         } else if (strbuf_read_file(&d->buf, arg, 1024) < 0)
233                 die_errno(_("could not open or read '%s'"), arg);
234         stripspace(&d->buf, 0);
235
236         d->given = 1;
237         return 0;
238 }
239
240 static int parse_reuse_arg(const struct option *opt, const char *arg, int unset)
241 {
242         struct note_data *d = opt->value;
243         char *buf;
244         unsigned char object[20];
245         enum object_type type;
246         unsigned long len;
247
248         if (d->buf.len)
249                 strbuf_addch(&d->buf, '\n');
250
251         if (get_sha1(arg, object))
252                 die(_("Failed to resolve '%s' as a valid ref."), arg);
253         if (!(buf = read_sha1_file(object, &type, &len))) {
254                 free(buf);
255                 die(_("Failed to read object '%s'."), arg);
256         }
257         if (type != OBJ_BLOB) {
258                 free(buf);
259                 die(_("Cannot read note data from non-blob object '%s'."), arg);
260         }
261         strbuf_add(&d->buf, buf, len);
262         free(buf);
263
264         d->given = 1;
265         return 0;
266 }
267
268 static int parse_reedit_arg(const struct option *opt, const char *arg, int unset)
269 {
270         struct note_data *d = opt->value;
271         d->use_editor = 1;
272         return parse_reuse_arg(opt, arg, unset);
273 }
274
275 static int notes_copy_from_stdin(int force, const char *rewrite_cmd)
276 {
277         struct strbuf buf = STRBUF_INIT;
278         struct notes_rewrite_cfg *c = NULL;
279         struct notes_tree *t = NULL;
280         int ret = 0;
281         const char *msg = "Notes added by 'git notes copy'";
282
283         if (rewrite_cmd) {
284                 c = init_copy_notes_for_rewrite(rewrite_cmd);
285                 if (!c)
286                         return 0;
287         } else {
288                 init_notes(NULL, NULL, NULL, 0);
289                 t = &default_notes_tree;
290         }
291
292         while (strbuf_getline(&buf, stdin, '\n') != EOF) {
293                 unsigned char from_obj[20], to_obj[20];
294                 struct strbuf **split;
295                 int err;
296
297                 split = strbuf_split(&buf, ' ');
298                 if (!split[0] || !split[1])
299                         die(_("Malformed input line: '%s'."), buf.buf);
300                 strbuf_rtrim(split[0]);
301                 strbuf_rtrim(split[1]);
302                 if (get_sha1(split[0]->buf, from_obj))
303                         die(_("Failed to resolve '%s' as a valid ref."), split[0]->buf);
304                 if (get_sha1(split[1]->buf, to_obj))
305                         die(_("Failed to resolve '%s' as a valid ref."), split[1]->buf);
306
307                 if (rewrite_cmd)
308                         err = copy_note_for_rewrite(c, from_obj, to_obj);
309                 else
310                         err = copy_note(t, from_obj, to_obj, force,
311                                         combine_notes_overwrite);
312
313                 if (err) {
314                         error(_("Failed to copy notes from '%s' to '%s'"),
315                               split[0]->buf, split[1]->buf);
316                         ret = 1;
317                 }
318
319                 strbuf_list_free(split);
320         }
321
322         if (!rewrite_cmd) {
323                 commit_notes(t, msg);
324                 free_notes(t);
325         } else {
326                 finish_copy_notes_for_rewrite(c, msg);
327         }
328         return ret;
329 }
330
331 static struct notes_tree *init_notes_check(const char *subcommand)
332 {
333         struct notes_tree *t;
334         init_notes(NULL, NULL, NULL, 0);
335         t = &default_notes_tree;
336
337         if (!starts_with(t->ref, "refs/notes/"))
338                 die("Refusing to %s notes in %s (outside of refs/notes/)",
339                     subcommand, t->ref);
340         return t;
341 }
342
343 static int list(int argc, const char **argv, const char *prefix)
344 {
345         struct notes_tree *t;
346         unsigned char object[20];
347         const unsigned char *note;
348         int retval = -1;
349         struct option options[] = {
350                 OPT_END()
351         };
352
353         if (argc)
354                 argc = parse_options(argc, argv, prefix, options,
355                                      git_notes_list_usage, 0);
356
357         if (1 < argc) {
358                 error(_("too many parameters"));
359                 usage_with_options(git_notes_list_usage, options);
360         }
361
362         t = init_notes_check("list");
363         if (argc) {
364                 if (get_sha1(argv[0], object))
365                         die(_("Failed to resolve '%s' as a valid ref."), argv[0]);
366                 note = get_note(t, object);
367                 if (note) {
368                         puts(sha1_to_hex(note));
369                         retval = 0;
370                 } else
371                         retval = error(_("No note found for object %s."),
372                                        sha1_to_hex(object));
373         } else
374                 retval = for_each_note(t, 0, list_each_note, NULL);
375
376         free_notes(t);
377         return retval;
378 }
379
380 static int append_edit(int argc, const char **argv, const char *prefix);
381
382 static int add(int argc, const char **argv, const char *prefix)
383 {
384         int force = 0;
385         const char *object_ref;
386         struct notes_tree *t;
387         unsigned char object[20], new_note[20];
388         const unsigned char *note;
389         struct note_data d = { 0, 0, NULL, STRBUF_INIT };
390         struct option options[] = {
391                 { OPTION_CALLBACK, 'm', "message", &d, N_("message"),
392                         N_("note contents as a string"), PARSE_OPT_NONEG,
393                         parse_msg_arg},
394                 { OPTION_CALLBACK, 'F', "file", &d, N_("file"),
395                         N_("note contents in a file"), PARSE_OPT_NONEG,
396                         parse_file_arg},
397                 { OPTION_CALLBACK, 'c', "reedit-message", &d, N_("object"),
398                         N_("reuse and edit specified note object"), PARSE_OPT_NONEG,
399                         parse_reedit_arg},
400                 { OPTION_CALLBACK, 'C', "reuse-message", &d, N_("object"),
401                         N_("reuse specified note object"), PARSE_OPT_NONEG,
402                         parse_reuse_arg},
403                 OPT__FORCE(&force, N_("replace existing notes")),
404                 OPT_END()
405         };
406
407         argc = parse_options(argc, argv, prefix, options, git_notes_add_usage,
408                              PARSE_OPT_KEEP_ARGV0);
409
410         if (2 < argc) {
411                 error(_("too many parameters"));
412                 usage_with_options(git_notes_add_usage, options);
413         }
414
415         object_ref = argc > 1 ? argv[1] : "HEAD";
416
417         if (get_sha1(object_ref, object))
418                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
419
420         t = init_notes_check("add");
421         note = get_note(t, object);
422
423         if (note) {
424                 if (!force) {
425                         free_notes(t);
426                         if (d.given) {
427                                 free_note_data(&d);
428                                 return error(_("Cannot add notes. "
429                                         "Found existing notes for object %s. "
430                                         "Use '-f' to overwrite existing notes"),
431                                         sha1_to_hex(object));
432                         }
433                         /*
434                          * Redirect to "edit" subcommand.
435                          *
436                          * We only end up here if none of -m/-F/-c/-C or -f are
437                          * given. The original args are therefore still in
438                          * argv[0-1].
439                          */
440                         argv[0] = "edit";
441                         return append_edit(argc, argv, prefix);
442                 }
443                 fprintf(stderr, _("Overwriting existing notes for object %s\n"),
444                         sha1_to_hex(object));
445         }
446
447         prepare_note_data(object, &d, note);
448         if (d.buf.len) {
449                 write_note_data(&d, new_note);
450                 if (add_note(t, object, new_note, combine_notes_overwrite))
451                         die("BUG: combine_notes_overwrite failed");
452                 commit_notes(t, "Notes added by 'git notes add'");
453         } else {
454                 fprintf(stderr, _("Removing note for object %s\n"),
455                         sha1_to_hex(object));
456                 remove_note(t, object);
457                 commit_notes(t, "Notes removed by 'git notes add'");
458         }
459
460         free_note_data(&d);
461         free_notes(t);
462         return 0;
463 }
464
465 static int copy(int argc, const char **argv, const char *prefix)
466 {
467         int retval = 0, force = 0, from_stdin = 0;
468         const unsigned char *from_note, *note;
469         const char *object_ref;
470         unsigned char object[20], from_obj[20];
471         struct notes_tree *t;
472         const char *rewrite_cmd = NULL;
473         struct option options[] = {
474                 OPT__FORCE(&force, N_("replace existing notes")),
475                 OPT_BOOL(0, "stdin", &from_stdin, N_("read objects from stdin")),
476                 OPT_STRING(0, "for-rewrite", &rewrite_cmd, N_("command"),
477                            N_("load rewriting config for <command> (implies "
478                               "--stdin)")),
479                 OPT_END()
480         };
481
482         argc = parse_options(argc, argv, prefix, options, git_notes_copy_usage,
483                              0);
484
485         if (from_stdin || rewrite_cmd) {
486                 if (argc) {
487                         error(_("too many parameters"));
488                         usage_with_options(git_notes_copy_usage, options);
489                 } else {
490                         return notes_copy_from_stdin(force, rewrite_cmd);
491                 }
492         }
493
494         if (argc < 2) {
495                 error(_("too few parameters"));
496                 usage_with_options(git_notes_copy_usage, options);
497         }
498         if (2 < argc) {
499                 error(_("too many parameters"));
500                 usage_with_options(git_notes_copy_usage, options);
501         }
502
503         if (get_sha1(argv[0], from_obj))
504                 die(_("Failed to resolve '%s' as a valid ref."), argv[0]);
505
506         object_ref = 1 < argc ? argv[1] : "HEAD";
507
508         if (get_sha1(object_ref, object))
509                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
510
511         t = init_notes_check("copy");
512         note = get_note(t, object);
513
514         if (note) {
515                 if (!force) {
516                         retval = error(_("Cannot copy notes. Found existing "
517                                        "notes for object %s. Use '-f' to "
518                                        "overwrite existing notes"),
519                                        sha1_to_hex(object));
520                         goto out;
521                 }
522                 fprintf(stderr, _("Overwriting existing notes for object %s\n"),
523                         sha1_to_hex(object));
524         }
525
526         from_note = get_note(t, from_obj);
527         if (!from_note) {
528                 retval = error(_("Missing notes on source object %s. Cannot "
529                                "copy."), sha1_to_hex(from_obj));
530                 goto out;
531         }
532
533         if (add_note(t, object, from_note, combine_notes_overwrite))
534                 die("BUG: combine_notes_overwrite failed");
535         commit_notes(t, "Notes added by 'git notes copy'");
536 out:
537         free_notes(t);
538         return retval;
539 }
540
541 static int append_edit(int argc, const char **argv, const char *prefix)
542 {
543         const char *object_ref;
544         struct notes_tree *t;
545         unsigned char object[20], new_note[20];
546         const unsigned char *note;
547         char logmsg[100];
548         const char * const *usage;
549         struct note_data d = { 0, 0, NULL, STRBUF_INIT };
550         struct option options[] = {
551                 { OPTION_CALLBACK, 'm', "message", &d, N_("message"),
552                         N_("note contents as a string"), PARSE_OPT_NONEG,
553                         parse_msg_arg},
554                 { OPTION_CALLBACK, 'F', "file", &d, N_("file"),
555                         N_("note contents in a file"), PARSE_OPT_NONEG,
556                         parse_file_arg},
557                 { OPTION_CALLBACK, 'c', "reedit-message", &d, N_("object"),
558                         N_("reuse and edit specified note object"), PARSE_OPT_NONEG,
559                         parse_reedit_arg},
560                 { OPTION_CALLBACK, 'C', "reuse-message", &d, N_("object"),
561                         N_("reuse specified note object"), PARSE_OPT_NONEG,
562                         parse_reuse_arg},
563                 OPT_END()
564         };
565         int edit = !strcmp(argv[0], "edit");
566
567         usage = edit ? git_notes_edit_usage : git_notes_append_usage;
568         argc = parse_options(argc, argv, prefix, options, usage,
569                              PARSE_OPT_KEEP_ARGV0);
570
571         if (2 < argc) {
572                 error(_("too many parameters"));
573                 usage_with_options(usage, options);
574         }
575
576         if (d.given && edit)
577                 fprintf(stderr, _("The -m/-F/-c/-C options have been deprecated "
578                         "for the 'edit' subcommand.\n"
579                         "Please use 'git notes add -f -m/-F/-c/-C' instead.\n"));
580
581         object_ref = 1 < argc ? argv[1] : "HEAD";
582
583         if (get_sha1(object_ref, object))
584                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
585
586         t = init_notes_check(argv[0]);
587         note = get_note(t, object);
588
589         prepare_note_data(object, &d, edit ? note : NULL);
590
591         if (note && !edit) {
592                 /* Append buf to previous note contents */
593                 unsigned long size;
594                 enum object_type type;
595                 char *prev_buf = read_sha1_file(note, &type, &size);
596
597                 strbuf_grow(&d.buf, size + 1);
598                 if (d.buf.len && prev_buf && size)
599                         strbuf_insert(&d.buf, 0, "\n", 1);
600                 if (prev_buf && size)
601                         strbuf_insert(&d.buf, 0, prev_buf, size);
602                 free(prev_buf);
603         }
604
605         if (d.buf.len) {
606                 write_note_data(&d, new_note);
607                 if (add_note(t, object, new_note, combine_notes_overwrite))
608                         die("BUG: combine_notes_overwrite failed");
609                 snprintf(logmsg, sizeof(logmsg), "Notes added by 'git notes %s'",
610                         argv[0]);
611         } else {
612                 fprintf(stderr, _("Removing note for object %s\n"),
613                         sha1_to_hex(object));
614                 remove_note(t, object);
615                 snprintf(logmsg, sizeof(logmsg), "Notes removed by 'git notes %s'",
616                         argv[0]);
617         }
618         commit_notes(t, logmsg);
619
620         free_note_data(&d);
621         free_notes(t);
622         return 0;
623 }
624
625 static int show(int argc, const char **argv, const char *prefix)
626 {
627         const char *object_ref;
628         struct notes_tree *t;
629         unsigned char object[20];
630         const unsigned char *note;
631         int retval;
632         struct option options[] = {
633                 OPT_END()
634         };
635
636         argc = parse_options(argc, argv, prefix, options, git_notes_show_usage,
637                              0);
638
639         if (1 < argc) {
640                 error(_("too many parameters"));
641                 usage_with_options(git_notes_show_usage, options);
642         }
643
644         object_ref = argc ? argv[0] : "HEAD";
645
646         if (get_sha1(object_ref, object))
647                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
648
649         t = init_notes_check("show");
650         note = get_note(t, object);
651
652         if (!note)
653                 retval = error(_("No note found for object %s."),
654                                sha1_to_hex(object));
655         else {
656                 const char *show_args[3] = {"show", sha1_to_hex(note), NULL};
657                 retval = execv_git_cmd(show_args);
658         }
659         free_notes(t);
660         return retval;
661 }
662
663 static int merge_abort(struct notes_merge_options *o)
664 {
665         int ret = 0;
666
667         /*
668          * Remove .git/NOTES_MERGE_PARTIAL and .git/NOTES_MERGE_REF, and call
669          * notes_merge_abort() to remove .git/NOTES_MERGE_WORKTREE.
670          */
671
672         if (delete_ref("NOTES_MERGE_PARTIAL", NULL, 0))
673                 ret += error("Failed to delete ref NOTES_MERGE_PARTIAL");
674         if (delete_ref("NOTES_MERGE_REF", NULL, REF_NODEREF))
675                 ret += error("Failed to delete ref NOTES_MERGE_REF");
676         if (notes_merge_abort(o))
677                 ret += error("Failed to remove 'git notes merge' worktree");
678         return ret;
679 }
680
681 static int merge_commit(struct notes_merge_options *o)
682 {
683         struct strbuf msg = STRBUF_INIT;
684         unsigned char sha1[20], parent_sha1[20];
685         struct notes_tree *t;
686         struct commit *partial;
687         struct pretty_print_context pretty_ctx;
688         void *local_ref_to_free;
689         int ret;
690
691         /*
692          * Read partial merge result from .git/NOTES_MERGE_PARTIAL,
693          * and target notes ref from .git/NOTES_MERGE_REF.
694          */
695
696         if (get_sha1("NOTES_MERGE_PARTIAL", sha1))
697                 die("Failed to read ref NOTES_MERGE_PARTIAL");
698         else if (!(partial = lookup_commit_reference(sha1)))
699                 die("Could not find commit from NOTES_MERGE_PARTIAL.");
700         else if (parse_commit(partial))
701                 die("Could not parse commit from NOTES_MERGE_PARTIAL.");
702
703         if (partial->parents)
704                 hashcpy(parent_sha1, partial->parents->item->object.sha1);
705         else
706                 hashclr(parent_sha1);
707
708         t = xcalloc(1, sizeof(struct notes_tree));
709         init_notes(t, "NOTES_MERGE_PARTIAL", combine_notes_overwrite, 0);
710
711         o->local_ref = local_ref_to_free =
712                 resolve_refdup("NOTES_MERGE_REF", 0, sha1, NULL);
713         if (!o->local_ref)
714                 die("Failed to resolve NOTES_MERGE_REF");
715
716         if (notes_merge_commit(o, t, partial, sha1))
717                 die("Failed to finalize notes merge");
718
719         /* Reuse existing commit message in reflog message */
720         memset(&pretty_ctx, 0, sizeof(pretty_ctx));
721         format_commit_message(partial, "%s", &msg, &pretty_ctx);
722         strbuf_trim(&msg);
723         strbuf_insert(&msg, 0, "notes: ", 7);
724         update_ref(msg.buf, o->local_ref, sha1,
725                    is_null_sha1(parent_sha1) ? NULL : parent_sha1,
726                    0, UPDATE_REFS_DIE_ON_ERR);
727
728         free_notes(t);
729         strbuf_release(&msg);
730         ret = merge_abort(o);
731         free(local_ref_to_free);
732         return ret;
733 }
734
735 static int merge(int argc, const char **argv, const char *prefix)
736 {
737         struct strbuf remote_ref = STRBUF_INIT, msg = STRBUF_INIT;
738         unsigned char result_sha1[20];
739         struct notes_tree *t;
740         struct notes_merge_options o;
741         int do_merge = 0, do_commit = 0, do_abort = 0;
742         int verbosity = 0, result;
743         const char *strategy = NULL;
744         struct option options[] = {
745                 OPT_GROUP(N_("General options")),
746                 OPT__VERBOSITY(&verbosity),
747                 OPT_GROUP(N_("Merge options")),
748                 OPT_STRING('s', "strategy", &strategy, N_("strategy"),
749                            N_("resolve notes conflicts using the given strategy "
750                               "(manual/ours/theirs/union/cat_sort_uniq)")),
751                 OPT_GROUP(N_("Committing unmerged notes")),
752                 { OPTION_SET_INT, 0, "commit", &do_commit, NULL,
753                         N_("finalize notes merge by committing unmerged notes"),
754                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
755                 OPT_GROUP(N_("Aborting notes merge resolution")),
756                 { OPTION_SET_INT, 0, "abort", &do_abort, NULL,
757                         N_("abort notes merge"),
758                         PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
759                 OPT_END()
760         };
761
762         argc = parse_options(argc, argv, prefix, options,
763                              git_notes_merge_usage, 0);
764
765         if (strategy || do_commit + do_abort == 0)
766                 do_merge = 1;
767         if (do_merge + do_commit + do_abort != 1) {
768                 error("cannot mix --commit, --abort or -s/--strategy");
769                 usage_with_options(git_notes_merge_usage, options);
770         }
771
772         if (do_merge && argc != 1) {
773                 error("Must specify a notes ref to merge");
774                 usage_with_options(git_notes_merge_usage, options);
775         } else if (!do_merge && argc) {
776                 error("too many parameters");
777                 usage_with_options(git_notes_merge_usage, options);
778         }
779
780         init_notes_merge_options(&o);
781         o.verbosity = verbosity + NOTES_MERGE_VERBOSITY_DEFAULT;
782
783         if (do_abort)
784                 return merge_abort(&o);
785         if (do_commit)
786                 return merge_commit(&o);
787
788         o.local_ref = default_notes_ref();
789         strbuf_addstr(&remote_ref, argv[0]);
790         expand_notes_ref(&remote_ref);
791         o.remote_ref = remote_ref.buf;
792
793         if (strategy) {
794                 if (!strcmp(strategy, "manual"))
795                         o.strategy = NOTES_MERGE_RESOLVE_MANUAL;
796                 else if (!strcmp(strategy, "ours"))
797                         o.strategy = NOTES_MERGE_RESOLVE_OURS;
798                 else if (!strcmp(strategy, "theirs"))
799                         o.strategy = NOTES_MERGE_RESOLVE_THEIRS;
800                 else if (!strcmp(strategy, "union"))
801                         o.strategy = NOTES_MERGE_RESOLVE_UNION;
802                 else if (!strcmp(strategy, "cat_sort_uniq"))
803                         o.strategy = NOTES_MERGE_RESOLVE_CAT_SORT_UNIQ;
804                 else {
805                         error("Unknown -s/--strategy: %s", strategy);
806                         usage_with_options(git_notes_merge_usage, options);
807                 }
808         }
809
810         t = init_notes_check("merge");
811
812         strbuf_addf(&msg, "notes: Merged notes from %s into %s",
813                     remote_ref.buf, default_notes_ref());
814         strbuf_add(&(o.commit_msg), msg.buf + 7, msg.len - 7); /* skip "notes: " */
815
816         result = notes_merge(&o, t, result_sha1);
817
818         if (result >= 0) /* Merge resulted (trivially) in result_sha1 */
819                 /* Update default notes ref with new commit */
820                 update_ref(msg.buf, default_notes_ref(), result_sha1, NULL,
821                            0, UPDATE_REFS_DIE_ON_ERR);
822         else { /* Merge has unresolved conflicts */
823                 /* Update .git/NOTES_MERGE_PARTIAL with partial merge result */
824                 update_ref(msg.buf, "NOTES_MERGE_PARTIAL", result_sha1, NULL,
825                            0, UPDATE_REFS_DIE_ON_ERR);
826                 /* Store ref-to-be-updated into .git/NOTES_MERGE_REF */
827                 if (create_symref("NOTES_MERGE_REF", default_notes_ref(), NULL))
828                         die("Failed to store link to current notes ref (%s)",
829                             default_notes_ref());
830                 printf("Automatic notes merge failed. Fix conflicts in %s and "
831                        "commit the result with 'git notes merge --commit', or "
832                        "abort the merge with 'git notes merge --abort'.\n",
833                        git_path(NOTES_MERGE_WORKTREE));
834         }
835
836         free_notes(t);
837         strbuf_release(&remote_ref);
838         strbuf_release(&msg);
839         return result < 0; /* return non-zero on conflicts */
840 }
841
842 #define IGNORE_MISSING 1
843
844 static int remove_one_note(struct notes_tree *t, const char *name, unsigned flag)
845 {
846         int status;
847         unsigned char sha1[20];
848         if (get_sha1(name, sha1))
849                 return error(_("Failed to resolve '%s' as a valid ref."), name);
850         status = remove_note(t, sha1);
851         if (status)
852                 fprintf(stderr, _("Object %s has no note\n"), name);
853         else
854                 fprintf(stderr, _("Removing note for object %s\n"), name);
855         return (flag & IGNORE_MISSING) ? 0 : status;
856 }
857
858 static int remove_cmd(int argc, const char **argv, const char *prefix)
859 {
860         unsigned flag = 0;
861         int from_stdin = 0;
862         struct option options[] = {
863                 OPT_BIT(0, "ignore-missing", &flag,
864                         N_("attempt to remove non-existent note is not an error"),
865                         IGNORE_MISSING),
866                 OPT_BOOL(0, "stdin", &from_stdin,
867                             N_("read object names from the standard input")),
868                 OPT_END()
869         };
870         struct notes_tree *t;
871         int retval = 0;
872
873         argc = parse_options(argc, argv, prefix, options,
874                              git_notes_remove_usage, 0);
875
876         t = init_notes_check("remove");
877
878         if (!argc && !from_stdin) {
879                 retval = remove_one_note(t, "HEAD", flag);
880         } else {
881                 while (*argv) {
882                         retval |= remove_one_note(t, *argv, flag);
883                         argv++;
884                 }
885         }
886         if (from_stdin) {
887                 struct strbuf sb = STRBUF_INIT;
888                 while (strbuf_getwholeline(&sb, stdin, '\n') != EOF) {
889                         strbuf_rtrim(&sb);
890                         retval |= remove_one_note(t, sb.buf, flag);
891                 }
892                 strbuf_release(&sb);
893         }
894         if (!retval)
895                 commit_notes(t, "Notes removed by 'git notes remove'");
896         free_notes(t);
897         return retval;
898 }
899
900 static int prune(int argc, const char **argv, const char *prefix)
901 {
902         struct notes_tree *t;
903         int show_only = 0, verbose = 0;
904         struct option options[] = {
905                 OPT__DRY_RUN(&show_only, "do not remove, show only"),
906                 OPT__VERBOSE(&verbose, "report pruned notes"),
907                 OPT_END()
908         };
909
910         argc = parse_options(argc, argv, prefix, options, git_notes_prune_usage,
911                              0);
912
913         if (argc) {
914                 error(_("too many parameters"));
915                 usage_with_options(git_notes_prune_usage, options);
916         }
917
918         t = init_notes_check("prune");
919
920         prune_notes(t, (verbose ? NOTES_PRUNE_VERBOSE : 0) |
921                 (show_only ? NOTES_PRUNE_VERBOSE|NOTES_PRUNE_DRYRUN : 0) );
922         if (!show_only)
923                 commit_notes(t, "Notes removed by 'git notes prune'");
924         free_notes(t);
925         return 0;
926 }
927
928 static int get_ref(int argc, const char **argv, const char *prefix)
929 {
930         struct option options[] = { OPT_END() };
931         argc = parse_options(argc, argv, prefix, options,
932                              git_notes_get_ref_usage, 0);
933
934         if (argc) {
935                 error("too many parameters");
936                 usage_with_options(git_notes_get_ref_usage, options);
937         }
938
939         puts(default_notes_ref());
940         return 0;
941 }
942
943 int cmd_notes(int argc, const char **argv, const char *prefix)
944 {
945         int result;
946         const char *override_notes_ref = NULL;
947         struct option options[] = {
948                 OPT_STRING(0, "ref", &override_notes_ref, N_("notes-ref"),
949                            N_("use notes from <notes_ref>")),
950                 OPT_END()
951         };
952
953         git_config(git_default_config, NULL);
954         argc = parse_options(argc, argv, prefix, options, git_notes_usage,
955                              PARSE_OPT_STOP_AT_NON_OPTION);
956
957         if (override_notes_ref) {
958                 struct strbuf sb = STRBUF_INIT;
959                 strbuf_addstr(&sb, override_notes_ref);
960                 expand_notes_ref(&sb);
961                 setenv("GIT_NOTES_REF", sb.buf, 1);
962                 strbuf_release(&sb);
963         }
964
965         if (argc < 1 || !strcmp(argv[0], "list"))
966                 result = list(argc, argv, prefix);
967         else if (!strcmp(argv[0], "add"))
968                 result = add(argc, argv, prefix);
969         else if (!strcmp(argv[0], "copy"))
970                 result = copy(argc, argv, prefix);
971         else if (!strcmp(argv[0], "append") || !strcmp(argv[0], "edit"))
972                 result = append_edit(argc, argv, prefix);
973         else if (!strcmp(argv[0], "show"))
974                 result = show(argc, argv, prefix);
975         else if (!strcmp(argv[0], "merge"))
976                 result = merge(argc, argv, prefix);
977         else if (!strcmp(argv[0], "remove"))
978                 result = remove_cmd(argc, argv, prefix);
979         else if (!strcmp(argv[0], "prune"))
980                 result = prune(argc, argv, prefix);
981         else if (!strcmp(argv[0], "get-ref"))
982                 result = get_ref(argc, argv, prefix);
983         else {
984                 result = error(_("Unknown subcommand: %s"), argv[0]);
985                 usage_with_options(git_notes_usage, options);
986         }
987
988         return result ? 1 : 0;
989 }