builtin / tag.con commit create_branch: move msg setup closer to point of use (3818b25)
   1/*
   2 * Builtin "git tag"
   3 *
   4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>,
   5 *                    Carlos Rica <jasampler@gmail.com>
   6 * Based on git-tag.sh and mktag.c by Linus Torvalds.
   7 */
   8
   9#include "cache.h"
  10#include "builtin.h"
  11#include "refs.h"
  12#include "tag.h"
  13#include "run-command.h"
  14#include "parse-options.h"
  15#include "diff.h"
  16#include "revision.h"
  17#include "gpg-interface.h"
  18#include "sha1-array.h"
  19#include "column.h"
  20#include "ref-filter.h"
  21
  22static const char * const git_tag_usage[] = {
  23        N_("git tag [-a | -s | -u <key-id>] [-f] [-m <msg> | -F <file>] <tagname> [<head>]"),
  24        N_("git tag -d <tagname>..."),
  25        N_("git tag -l [-n[<num>]] [--contains <commit>] [--points-at <object>]"
  26                "\n\t\t[--format=<format>] [--[no-]merged [<commit>]] [<pattern>...]"),
  27        N_("git tag -v [--format=<format>] <tagname>..."),
  28        NULL
  29};
  30
  31static unsigned int colopts;
  32static int force_sign_annotate;
  33
  34static int list_tags(struct ref_filter *filter, struct ref_sorting *sorting, const char *format)
  35{
  36        struct ref_array array;
  37        char *to_free = NULL;
  38        int i;
  39
  40        memset(&array, 0, sizeof(array));
  41
  42        if (filter->lines == -1)
  43                filter->lines = 0;
  44
  45        if (!format) {
  46                if (filter->lines) {
  47                        to_free = xstrfmt("%s %%(contents:lines=%d)",
  48                                          "%(align:15)%(refname:lstrip=2)%(end)",
  49                                          filter->lines);
  50                        format = to_free;
  51                } else
  52                        format = "%(refname:lstrip=2)";
  53        }
  54
  55        verify_ref_format(format);
  56        filter->with_commit_tag_algo = 1;
  57        filter_refs(&array, filter, FILTER_REFS_TAGS);
  58        ref_array_sort(sorting, &array);
  59
  60        for (i = 0; i < array.nr; i++)
  61                show_ref_array_item(array.items[i], format, 0);
  62        ref_array_clear(&array);
  63        free(to_free);
  64
  65        return 0;
  66}
  67
  68typedef int (*each_tag_name_fn)(const char *name, const char *ref,
  69                                const unsigned char *sha1, const void *cb_data);
  70
  71static int for_each_tag_name(const char **argv, each_tag_name_fn fn,
  72                             const void *cb_data)
  73{
  74        const char **p;
  75        struct strbuf ref = STRBUF_INIT;
  76        int had_error = 0;
  77        unsigned char sha1[20];
  78
  79        for (p = argv; *p; p++) {
  80                strbuf_reset(&ref);
  81                strbuf_addf(&ref, "refs/tags/%s", *p);
  82                if (read_ref(ref.buf, sha1)) {
  83                        error(_("tag '%s' not found."), *p);
  84                        had_error = 1;
  85                        continue;
  86                }
  87                if (fn(*p, ref.buf, sha1, cb_data))
  88                        had_error = 1;
  89        }
  90        strbuf_release(&ref);
  91        return had_error;
  92}
  93
  94static int delete_tag(const char *name, const char *ref,
  95                      const unsigned char *sha1, const void *cb_data)
  96{
  97        if (delete_ref(NULL, ref, sha1, 0))
  98                return 1;
  99        printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
 100        return 0;
 101}
 102
 103static int verify_tag(const char *name, const char *ref,
 104                      const unsigned char *sha1, const void *cb_data)
 105{
 106        int flags;
 107        const char *fmt_pretty = cb_data;
 108        flags = GPG_VERIFY_VERBOSE;
 109
 110        if (fmt_pretty)
 111                flags = GPG_VERIFY_OMIT_STATUS;
 112
 113        if (gpg_verify_tag(sha1, name, flags))
 114                return -1;
 115
 116        if (fmt_pretty)
 117                pretty_print_ref(name, sha1, fmt_pretty);
 118
 119        return 0;
 120}
 121
 122static int do_sign(struct strbuf *buffer)
 123{
 124        return sign_buffer(buffer, buffer, get_signing_key());
 125}
 126
 127static const char tag_template[] =
 128        N_("\nWrite a message for tag:\n  %s\n"
 129        "Lines starting with '%c' will be ignored.\n");
 130
 131static const char tag_template_nocleanup[] =
 132        N_("\nWrite a message for tag:\n  %s\n"
 133        "Lines starting with '%c' will be kept; you may remove them"
 134        " yourself if you want to.\n");
 135
 136/* Parse arg given and add it the ref_sorting array */
 137static int parse_sorting_string(const char *arg, struct ref_sorting **sorting_tail)
 138{
 139        struct ref_sorting *s;
 140        int len;
 141
 142        s = xcalloc(1, sizeof(*s));
 143        s->next = *sorting_tail;
 144        *sorting_tail = s;
 145
 146        if (*arg == '-') {
 147                s->reverse = 1;
 148                arg++;
 149        }
 150        if (skip_prefix(arg, "version:", &arg) ||
 151            skip_prefix(arg, "v:", &arg))
 152                s->version = 1;
 153
 154        len = strlen(arg);
 155        s->atom = parse_ref_filter_atom(arg, arg+len);
 156
 157        return 0;
 158}
 159
 160static int git_tag_config(const char *var, const char *value, void *cb)
 161{
 162        int status;
 163        struct ref_sorting **sorting_tail = (struct ref_sorting **)cb;
 164
 165        if (!strcmp(var, "tag.sort")) {
 166                if (!value)
 167                        return config_error_nonbool(var);
 168                parse_sorting_string(value, sorting_tail);
 169                return 0;
 170        }
 171
 172        status = git_gpg_config(var, value, cb);
 173        if (status)
 174                return status;
 175        if (!strcmp(var, "tag.forcesignannotated")) {
 176                force_sign_annotate = git_config_bool(var, value);
 177                return 0;
 178        }
 179
 180        if (starts_with(var, "column."))
 181                return git_column_config(var, value, "tag", &colopts);
 182        return git_default_config(var, value, cb);
 183}
 184
 185static void write_tag_body(int fd, const unsigned char *sha1)
 186{
 187        unsigned long size;
 188        enum object_type type;
 189        char *buf, *sp;
 190
 191        buf = read_sha1_file(sha1, &type, &size);
 192        if (!buf)
 193                return;
 194        /* skip header */
 195        sp = strstr(buf, "\n\n");
 196
 197        if (!sp || !size || type != OBJ_TAG) {
 198                free(buf);
 199                return;
 200        }
 201        sp += 2; /* skip the 2 LFs */
 202        write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
 203
 204        free(buf);
 205}
 206
 207static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
 208{
 209        if (sign && do_sign(buf) < 0)
 210                return error(_("unable to sign the tag"));
 211        if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
 212                return error(_("unable to write tag file"));
 213        return 0;
 214}
 215
 216struct create_tag_options {
 217        unsigned int message_given:1;
 218        unsigned int sign;
 219        enum {
 220                CLEANUP_NONE,
 221                CLEANUP_SPACE,
 222                CLEANUP_ALL
 223        } cleanup_mode;
 224};
 225
 226static void create_tag(const unsigned char *object, const char *tag,
 227                       struct strbuf *buf, struct create_tag_options *opt,
 228                       unsigned char *prev, unsigned char *result)
 229{
 230        enum object_type type;
 231        struct strbuf header = STRBUF_INIT;
 232        char *path = NULL;
 233
 234        type = sha1_object_info(object, NULL);
 235        if (type <= OBJ_NONE)
 236            die(_("bad object type."));
 237
 238        strbuf_addf(&header,
 239                    "object %s\n"
 240                    "type %s\n"
 241                    "tag %s\n"
 242                    "tagger %s\n\n",
 243                    sha1_to_hex(object),
 244                    typename(type),
 245                    tag,
 246                    git_committer_info(IDENT_STRICT));
 247
 248        if (!opt->message_given) {
 249                int fd;
 250
 251                /* write the template message before editing: */
 252                path = git_pathdup("TAG_EDITMSG");
 253                fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
 254                if (fd < 0)
 255                        die_errno(_("could not create file '%s'"), path);
 256
 257                if (!is_null_sha1(prev)) {
 258                        write_tag_body(fd, prev);
 259                } else {
 260                        struct strbuf buf = STRBUF_INIT;
 261                        strbuf_addch(&buf, '\n');
 262                        if (opt->cleanup_mode == CLEANUP_ALL)
 263                                strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
 264                        else
 265                                strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
 266                        write_or_die(fd, buf.buf, buf.len);
 267                        strbuf_release(&buf);
 268                }
 269                close(fd);
 270
 271                if (launch_editor(path, buf, NULL)) {
 272                        fprintf(stderr,
 273                        _("Please supply the message using either -m or -F option.\n"));
 274                        exit(1);
 275                }
 276        }
 277
 278        if (opt->cleanup_mode != CLEANUP_NONE)
 279                strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
 280
 281        if (!opt->message_given && !buf->len)
 282                die(_("no tag message?"));
 283
 284        strbuf_insert(buf, 0, header.buf, header.len);
 285        strbuf_release(&header);
 286
 287        if (build_tag_object(buf, opt->sign, result) < 0) {
 288                if (path)
 289                        fprintf(stderr, _("The tag message has been left in %s\n"),
 290                                path);
 291                exit(128);
 292        }
 293        if (path) {
 294                unlink_or_warn(path);
 295                free(path);
 296        }
 297}
 298
 299static void create_reflog_msg(const unsigned char *sha1, struct strbuf *sb)
 300{
 301        enum object_type type;
 302        struct commit *c;
 303        char *buf;
 304        unsigned long size;
 305        int subject_len = 0;
 306        const char *subject_start;
 307
 308        char *rla = getenv("GIT_REFLOG_ACTION");
 309        if (rla) {
 310                strbuf_addstr(sb, rla);
 311        } else {
 312                strbuf_addstr(sb, _("tag: tagging "));
 313                strbuf_add_unique_abbrev(sb, sha1, DEFAULT_ABBREV);
 314        }
 315
 316        strbuf_addstr(sb, " (");
 317        type = sha1_object_info(sha1, NULL);
 318        switch (type) {
 319        default:
 320                strbuf_addstr(sb, _("object of unknown type"));
 321                break;
 322        case OBJ_COMMIT:
 323                if ((buf = read_sha1_file(sha1, &type, &size)) != NULL) {
 324                        subject_len = find_commit_subject(buf, &subject_start);
 325                        strbuf_insert(sb, sb->len, subject_start, subject_len);
 326                } else {
 327                        strbuf_addstr(sb, _("commit object"));
 328                }
 329                free(buf);
 330
 331                if ((c = lookup_commit_reference(sha1)) != NULL)
 332                        strbuf_addf(sb, ", %s", show_date(c->date, 0, DATE_MODE(SHORT)));
 333                break;
 334        case OBJ_TREE:
 335                strbuf_addstr(sb, _("tree object"));
 336                break;
 337        case OBJ_BLOB:
 338                strbuf_addstr(sb, _("blob object"));
 339                break;
 340        case OBJ_TAG:
 341                strbuf_addstr(sb, _("other tag object"));
 342                break;
 343        }
 344        strbuf_addch(sb, ')');
 345}
 346
 347struct msg_arg {
 348        int given;
 349        struct strbuf buf;
 350};
 351
 352static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
 353{
 354        struct msg_arg *msg = opt->value;
 355
 356        if (!arg)
 357                return -1;
 358        if (msg->buf.len)
 359                strbuf_addstr(&(msg->buf), "\n\n");
 360        strbuf_addstr(&(msg->buf), arg);
 361        msg->given = 1;
 362        return 0;
 363}
 364
 365static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
 366{
 367        if (name[0] == '-')
 368                return -1;
 369
 370        strbuf_reset(sb);
 371        strbuf_addf(sb, "refs/tags/%s", name);
 372
 373        return check_refname_format(sb->buf, 0);
 374}
 375
 376int cmd_tag(int argc, const char **argv, const char *prefix)
 377{
 378        struct strbuf buf = STRBUF_INIT;
 379        struct strbuf ref = STRBUF_INIT;
 380        struct strbuf reflog_msg = STRBUF_INIT;
 381        unsigned char object[20], prev[20];
 382        const char *object_ref, *tag;
 383        struct create_tag_options opt;
 384        char *cleanup_arg = NULL;
 385        int create_reflog = 0;
 386        int annotate = 0, force = 0;
 387        int cmdmode = 0, create_tag_object = 0;
 388        const char *msgfile = NULL, *keyid = NULL;
 389        struct msg_arg msg = { 0, STRBUF_INIT };
 390        struct ref_transaction *transaction;
 391        struct strbuf err = STRBUF_INIT;
 392        struct ref_filter filter;
 393        static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
 394        const char *format = NULL;
 395        int icase = 0;
 396        struct option options[] = {
 397                OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
 398                { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"),
 399                                N_("print <n> lines of each tag message"),
 400                                PARSE_OPT_OPTARG, NULL, 1 },
 401                OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
 402                OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
 403
 404                OPT_GROUP(N_("Tag creation options")),
 405                OPT_BOOL('a', "annotate", &annotate,
 406                                        N_("annotated tag, needs a message")),
 407                OPT_CALLBACK('m', "message", &msg, N_("message"),
 408                             N_("tag message"), parse_msg_arg),
 409                OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
 410                OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
 411                OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
 412                        N_("how to strip spaces and #comments from message")),
 413                OPT_STRING('u', "local-user", &keyid, N_("key-id"),
 414                                        N_("use another key to sign the tag")),
 415                OPT__FORCE(&force, N_("replace the tag if exists")),
 416                OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")),
 417
 418                OPT_GROUP(N_("Tag listing options")),
 419                OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
 420                OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")),
 421                OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")),
 422                OPT_MERGED(&filter, N_("print only tags that are merged")),
 423                OPT_NO_MERGED(&filter, N_("print only tags that are not merged")),
 424                OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
 425                             N_("field name to sort on"), &parse_opt_ref_sorting),
 426                {
 427                        OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"),
 428                        N_("print only tags of the object"), 0, parse_opt_object_name
 429                },
 430                OPT_STRING(  0 , "format", &format, N_("format"), N_("format to use for the output")),
 431                OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
 432                OPT_END()
 433        };
 434
 435        setup_ref_filter_porcelain_msg();
 436
 437        git_config(git_tag_config, sorting_tail);
 438
 439        memset(&opt, 0, sizeof(opt));
 440        memset(&filter, 0, sizeof(filter));
 441        filter.lines = -1;
 442
 443        argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
 444
 445        if (keyid) {
 446                opt.sign = 1;
 447                set_signing_key(keyid);
 448        }
 449        create_tag_object = (opt.sign || annotate || msg.given || msgfile);
 450
 451        if (argc == 0 && !cmdmode)
 452                cmdmode = 'l';
 453
 454        if ((create_tag_object || force) && (cmdmode != 0))
 455                usage_with_options(git_tag_usage, options);
 456
 457        finalize_colopts(&colopts, -1);
 458        if (cmdmode == 'l' && filter.lines != -1) {
 459                if (explicitly_enable_column(colopts))
 460                        die(_("--column and -n are incompatible"));
 461                colopts = 0;
 462        }
 463        if (!sorting)
 464                sorting = ref_default_sorting();
 465        sorting->ignore_case = icase;
 466        filter.ignore_case = icase;
 467        if (cmdmode == 'l') {
 468                int ret;
 469                if (column_active(colopts)) {
 470                        struct column_options copts;
 471                        memset(&copts, 0, sizeof(copts));
 472                        copts.padding = 2;
 473                        run_column_filter(colopts, &copts);
 474                }
 475                filter.name_patterns = argv;
 476                ret = list_tags(&filter, sorting, format);
 477                if (column_active(colopts))
 478                        stop_column_filter();
 479                return ret;
 480        }
 481        if (filter.lines != -1)
 482                die(_("-n option is only allowed with -l."));
 483        if (filter.with_commit)
 484                die(_("--contains option is only allowed with -l."));
 485        if (filter.points_at.nr)
 486                die(_("--points-at option is only allowed with -l."));
 487        if (filter.merge_commit)
 488                die(_("--merged and --no-merged option are only allowed with -l"));
 489        if (cmdmode == 'd')
 490                return for_each_tag_name(argv, delete_tag, NULL);
 491        if (cmdmode == 'v') {
 492                if (format)
 493                        verify_ref_format(format);
 494                return for_each_tag_name(argv, verify_tag, format);
 495        }
 496
 497        if (msg.given || msgfile) {
 498                if (msg.given && msgfile)
 499                        die(_("only one -F or -m option is allowed."));
 500                if (msg.given)
 501                        strbuf_addbuf(&buf, &(msg.buf));
 502                else {
 503                        if (!strcmp(msgfile, "-")) {
 504                                if (strbuf_read(&buf, 0, 1024) < 0)
 505                                        die_errno(_("cannot read '%s'"), msgfile);
 506                        } else {
 507                                if (strbuf_read_file(&buf, msgfile, 1024) < 0)
 508                                        die_errno(_("could not open or read '%s'"),
 509                                                msgfile);
 510                        }
 511                }
 512        }
 513
 514        tag = argv[0];
 515
 516        object_ref = argc == 2 ? argv[1] : "HEAD";
 517        if (argc > 2)
 518                die(_("too many params"));
 519
 520        if (get_sha1(object_ref, object))
 521                die(_("Failed to resolve '%s' as a valid ref."), object_ref);
 522
 523        if (strbuf_check_tag_ref(&ref, tag))
 524                die(_("'%s' is not a valid tag name."), tag);
 525
 526        if (read_ref(ref.buf, prev))
 527                hashclr(prev);
 528        else if (!force)
 529                die(_("tag '%s' already exists"), tag);
 530
 531        opt.message_given = msg.given || msgfile;
 532
 533        if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
 534                opt.cleanup_mode = CLEANUP_ALL;
 535        else if (!strcmp(cleanup_arg, "verbatim"))
 536                opt.cleanup_mode = CLEANUP_NONE;
 537        else if (!strcmp(cleanup_arg, "whitespace"))
 538                opt.cleanup_mode = CLEANUP_SPACE;
 539        else
 540                die(_("Invalid cleanup mode %s"), cleanup_arg);
 541
 542        create_reflog_msg(object, &reflog_msg);
 543
 544        if (create_tag_object) {
 545                if (force_sign_annotate && !annotate)
 546                        opt.sign = 1;
 547                create_tag(object, tag, &buf, &opt, prev, object);
 548        }
 549
 550        transaction = ref_transaction_begin(&err);
 551        if (!transaction ||
 552            ref_transaction_update(transaction, ref.buf, object, prev,
 553                                   create_reflog ? REF_FORCE_CREATE_REFLOG : 0,
 554                                   reflog_msg.buf, &err) ||
 555            ref_transaction_commit(transaction, &err))
 556                die("%s", err.buf);
 557        ref_transaction_free(transaction);
 558        if (force && !is_null_sha1(prev) && hashcmp(prev, object))
 559                printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
 560
 561        strbuf_release(&err);
 562        strbuf_release(&buf);
 563        strbuf_release(&ref);
 564        strbuf_release(&reflog_msg);
 565        return 0;
 566}