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