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