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