builtin / tag.con commit Git 2.12.5 (9752ad0)
   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:strip=2)%(end)",
  49                                          filter->lines);
  50                        format = to_free;
  51                } else
  52                        format = "%(refname:strip=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        char ref[PATH_MAX];
  76        int had_error = 0;
  77        unsigned char sha1[20];
  78
  79        for (p = argv; *p; p++) {
  80                if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
  81                                        >= sizeof(ref)) {
  82                        error(_("tag name too long: %.*s..."), 50, *p);
  83                        had_error = 1;
  84                        continue;
  85                }
  86                if (read_ref(ref, sha1)) {
  87                        error(_("tag '%s' not found."), *p);
  88                        had_error = 1;
  89                        continue;
  90                }
  91                if (fn(*p, ref, sha1, cb_data))
  92                        had_error = 1;
  93        }
  94        return had_error;
  95}
  96
  97static int delete_tag(const char *name, const char *ref,
  98                      const unsigned char *sha1, const void *cb_data)
  99{
 100        if (delete_ref(ref, sha1, 0))
 101                return 1;
 102        printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
 103        return 0;
 104}
 105
 106static int verify_tag(const char *name, const char *ref,
 107                      const unsigned char *sha1, const void *cb_data)
 108{
 109        int flags;
 110        const char *fmt_pretty = cb_data;
 111        flags = GPG_VERIFY_VERBOSE;
 112
 113        if (fmt_pretty)
 114                flags = GPG_VERIFY_OMIT_STATUS;
 115
 116        if (gpg_verify_tag(sha1, name, flags))
 117                return -1;
 118
 119        if (fmt_pretty)
 120                pretty_print_ref(name, sha1, fmt_pretty);
 121
 122        return 0;
 123}
 124
 125static int do_sign(struct strbuf *buffer)
 126{
 127        return sign_buffer(buffer, buffer, get_signing_key());
 128}
 129
 130static const char tag_template[] =
 131        N_("\nWrite a message for tag:\n  %s\n"
 132        "Lines starting with '%c' will be ignored.\n");
 133
 134static const char tag_template_nocleanup[] =
 135        N_("\nWrite a message for tag:\n  %s\n"
 136        "Lines starting with '%c' will be kept; you may remove them"
 137        " yourself if you want to.\n");
 138
 139/* Parse arg given and add it the ref_sorting array */
 140static int parse_sorting_string(const char *arg, struct ref_sorting **sorting_tail)
 141{
 142        struct ref_sorting *s;
 143        int len;
 144
 145        s = xcalloc(1, sizeof(*s));
 146        s->next = *sorting_tail;
 147        *sorting_tail = s;
 148
 149        if (*arg == '-') {
 150                s->reverse = 1;
 151                arg++;
 152        }
 153        if (skip_prefix(arg, "version:", &arg) ||
 154            skip_prefix(arg, "v:", &arg))
 155                s->version = 1;
 156
 157        len = strlen(arg);
 158        s->atom = parse_ref_filter_atom(arg, arg+len);
 159
 160        return 0;
 161}
 162
 163static int git_tag_config(const char *var, const char *value, void *cb)
 164{
 165        int status;
 166        struct ref_sorting **sorting_tail = (struct ref_sorting **)cb;
 167
 168        if (!strcmp(var, "tag.sort")) {
 169                if (!value)
 170                        return config_error_nonbool(var);
 171                parse_sorting_string(value, sorting_tail);
 172                return 0;
 173        }
 174
 175        status = git_gpg_config(var, value, cb);
 176        if (status)
 177                return status;
 178        if (!strcmp(var, "tag.forcesignannotated")) {
 179                force_sign_annotate = git_config_bool(var, value);
 180                return 0;
 181        }
 182
 183        if (starts_with(var, "column."))
 184                return git_column_config(var, value, "tag", &colopts);
 185        return git_default_config(var, value, cb);
 186}
 187
 188static void write_tag_body(int fd, const unsigned char *sha1)
 189{
 190        unsigned long size;
 191        enum object_type type;
 192        char *buf, *sp;
 193
 194        buf = read_sha1_file(sha1, &type, &size);
 195        if (!buf)
 196                return;
 197        /* skip header */
 198        sp = strstr(buf, "\n\n");
 199
 200        if (!sp || !size || type != OBJ_TAG) {
 201                free(buf);
 202                return;
 203        }
 204        sp += 2; /* skip the 2 LFs */
 205        write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
 206
 207        free(buf);
 208}
 209
 210static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
 211{
 212        if (sign && do_sign(buf) < 0)
 213                return error(_("unable to sign the tag"));
 214        if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
 215                return error(_("unable to write tag file"));
 216        return 0;
 217}
 218
 219struct create_tag_options {
 220        unsigned int message_given:1;
 221        unsigned int sign;
 222        enum {
 223                CLEANUP_NONE,
 224                CLEANUP_SPACE,
 225                CLEANUP_ALL
 226        } cleanup_mode;
 227};
 228
 229static void create_tag(const unsigned char *object, const char *tag,
 230                       struct strbuf *buf, struct create_tag_options *opt,
 231                       unsigned char *prev, unsigned char *result)
 232{
 233        enum object_type type;
 234        char header_buf[1024];
 235        int header_len;
 236        char *path = NULL;
 237
 238        type = sha1_object_info(object, NULL);
 239        if (type <= OBJ_NONE)
 240            die(_("bad object type."));
 241
 242        header_len = snprintf(header_buf, sizeof(header_buf),
 243                          "object %s\n"
 244                          "type %s\n"
 245                          "tag %s\n"
 246                          "tagger %s\n\n",
 247                          sha1_to_hex(object),
 248                          typename(type),
 249                          tag,
 250                          git_committer_info(IDENT_STRICT));
 251
 252        if (header_len > sizeof(header_buf) - 1)
 253                die(_("tag header too big."));
 254
 255        if (!opt->message_given) {
 256                int fd;
 257
 258                /* write the template message before editing: */
 259                path = git_pathdup("TAG_EDITMSG");
 260                fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
 261                if (fd < 0)
 262                        die_errno(_("could not create file '%s'"), path);
 263
 264                if (!is_null_sha1(prev)) {
 265                        write_tag_body(fd, prev);
 266                } else {
 267                        struct strbuf buf = STRBUF_INIT;
 268                        strbuf_addch(&buf, '\n');
 269                        if (opt->cleanup_mode == CLEANUP_ALL)
 270                                strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
 271                        else
 272                                strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
 273                        write_or_die(fd, buf.buf, buf.len);
 274                        strbuf_release(&buf);
 275                }
 276                close(fd);
 277
 278                if (launch_editor(path, buf, NULL)) {
 279                        fprintf(stderr,
 280                        _("Please supply the message using either -m or -F option.\n"));
 281                        exit(1);
 282                }
 283        }
 284
 285        if (opt->cleanup_mode != CLEANUP_NONE)
 286                strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
 287
 288        if (!opt->message_given && !buf->len)
 289                die(_("no tag message?"));
 290
 291        strbuf_insert(buf, 0, header_buf, header_len);
 292
 293        if (build_tag_object(buf, opt->sign, result) < 0) {
 294                if (path)
 295                        fprintf(stderr, _("The tag message has been left in %s\n"),
 296                                path);
 297                exit(128);
 298        }
 299        if (path) {
 300                unlink_or_warn(path);
 301                free(path);
 302        }
 303}
 304
 305struct msg_arg {
 306        int given;
 307        struct strbuf buf;
 308};
 309
 310static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
 311{
 312        struct msg_arg *msg = opt->value;
 313
 314        if (!arg)
 315                return -1;
 316        if (msg->buf.len)
 317                strbuf_addstr(&(msg->buf), "\n\n");
 318        strbuf_addstr(&(msg->buf), arg);
 319        msg->given = 1;
 320        return 0;
 321}
 322
 323static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
 324{
 325        if (name[0] == '-')
 326                return -1;
 327
 328        strbuf_reset(sb);
 329        strbuf_addf(sb, "refs/tags/%s", name);
 330
 331        return check_refname_format(sb->buf, 0);
 332}
 333
 334int cmd_tag(int argc, const char **argv, const char *prefix)
 335{
 336        struct strbuf buf = STRBUF_INIT;
 337        struct strbuf ref = STRBUF_INIT;
 338        unsigned char object[20], prev[20];
 339        const char *object_ref, *tag;
 340        struct create_tag_options opt;
 341        char *cleanup_arg = NULL;
 342        int create_reflog = 0;
 343        int annotate = 0, force = 0;
 344        int cmdmode = 0, create_tag_object = 0;
 345        const char *msgfile = NULL, *keyid = NULL;
 346        struct msg_arg msg = { 0, STRBUF_INIT };
 347        struct ref_transaction *transaction;
 348        struct strbuf err = STRBUF_INIT;
 349        struct ref_filter filter;
 350        static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
 351        const char *format = NULL;
 352        int icase = 0;
 353        struct option options[] = {
 354                OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
 355                { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"),
 356                                N_("print <n> lines of each tag message"),
 357                                PARSE_OPT_OPTARG, NULL, 1 },
 358                OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
 359                OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
 360
 361                OPT_GROUP(N_("Tag creation options")),
 362                OPT_BOOL('a', "annotate", &annotate,
 363                                        N_("annotated tag, needs a message")),
 364                OPT_CALLBACK('m', "message", &msg, N_("message"),
 365                             N_("tag message"), parse_msg_arg),
 366                OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
 367                OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
 368                OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
 369                        N_("how to strip spaces and #comments from message")),
 370                OPT_STRING('u', "local-user", &keyid, N_("key-id"),
 371                                        N_("use another key to sign the tag")),
 372                OPT__FORCE(&force, N_("replace the tag if exists")),
 373                OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")),
 374
 375                OPT_GROUP(N_("Tag listing options")),
 376                OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
 377                OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")),
 378                OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")),
 379                OPT_MERGED(&filter, N_("print only tags that are merged")),
 380                OPT_NO_MERGED(&filter, N_("print only tags that are not merged")),
 381                OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
 382                             N_("field name to sort on"), &parse_opt_ref_sorting),
 383                {
 384                        OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"),
 385                        N_("print only tags of the object"), 0, parse_opt_object_name
 386                },
 387                OPT_STRING(  0 , "format", &format, N_("format"), N_("format to use for the output")),
 388                OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
 389                OPT_END()
 390        };
 391
 392        git_config(git_tag_config, sorting_tail);
 393
 394        memset(&opt, 0, sizeof(opt));
 395        memset(&filter, 0, sizeof(filter));
 396        filter.lines = -1;
 397
 398        argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
 399
 400        if (keyid) {
 401                opt.sign = 1;
 402                set_signing_key(keyid);
 403        }
 404        create_tag_object = (opt.sign || annotate || msg.given || msgfile);
 405
 406        if (argc == 0 && !cmdmode)
 407                cmdmode = 'l';
 408
 409        if ((create_tag_object || force) && (cmdmode != 0))
 410                usage_with_options(git_tag_usage, options);
 411
 412        finalize_colopts(&colopts, -1);
 413        if (cmdmode == 'l' && filter.lines != -1) {
 414                if (explicitly_enable_column(colopts))
 415                        die(_("--column and -n are incompatible"));
 416                colopts = 0;
 417        }
 418        if (!sorting)
 419                sorting = ref_default_sorting();
 420        sorting->ignore_case = icase;
 421        filter.ignore_case = icase;
 422        if (cmdmode == 'l') {
 423                int ret;
 424                if (column_active(colopts)) {
 425                        struct column_options copts;
 426                        memset(&copts, 0, sizeof(copts));
 427                        copts.padding = 2;
 428                        run_column_filter(colopts, &copts);
 429                }
 430                filter.name_patterns = argv;
 431                ret = list_tags(&filter, sorting, format);
 432                if (column_active(colopts))
 433                        stop_column_filter();
 434                return ret;
 435        }
 436        if (filter.lines != -1)
 437                die(_("-n option is only allowed with -l."));
 438        if (filter.with_commit)
 439                die(_("--contains option is only allowed with -l."));
 440        if (filter.points_at.nr)
 441                die(_("--points-at option is only allowed with -l."));
 442        if (filter.merge_commit)
 443                die(_("--merged and --no-merged option are only allowed with -l"));
 444        if (cmdmode == 'd')
 445                return for_each_tag_name(argv, delete_tag, NULL);
 446        if (cmdmode == 'v') {
 447                if (format)
 448                        verify_ref_format(format);
 449                return for_each_tag_name(argv, verify_tag, format);
 450        }
 451
 452        if (msg.given || msgfile) {
 453                if (msg.given && msgfile)
 454                        die(_("only one -F or -m option is allowed."));
 455                if (msg.given)
 456                        strbuf_addbuf(&buf, &(msg.buf));
 457                else {
 458                        if (!strcmp(msgfile, "-")) {
 459                                if (strbuf_read(&buf, 0, 1024) < 0)
 460                                        die_errno(_("cannot read '%s'"), msgfile);
 461                        } else {
 462                                if (strbuf_read_file(&buf, msgfile, 1024) < 0)
 463                                        die_errno(_("could not open or read '%s'"),
 464                                                msgfile);
 465                        }
 466                }
 467        }
 468
 469        tag = argv[0];
 470
 471        object_ref = argc == 2 ? argv[1] : "HEAD";
 472        if (argc > 2)
 473                die(_("too many params"));
 474
 475        if (get_sha1(object_ref, object))
 476                die(_("Failed to resolve '%s' as a valid ref."), object_ref);
 477
 478        if (strbuf_check_tag_ref(&ref, tag))
 479                die(_("'%s' is not a valid tag name."), tag);
 480
 481        if (read_ref(ref.buf, prev))
 482                hashclr(prev);
 483        else if (!force)
 484                die(_("tag '%s' already exists"), tag);
 485
 486        opt.message_given = msg.given || msgfile;
 487
 488        if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
 489                opt.cleanup_mode = CLEANUP_ALL;
 490        else if (!strcmp(cleanup_arg, "verbatim"))
 491                opt.cleanup_mode = CLEANUP_NONE;
 492        else if (!strcmp(cleanup_arg, "whitespace"))
 493                opt.cleanup_mode = CLEANUP_SPACE;
 494        else
 495                die(_("Invalid cleanup mode %s"), cleanup_arg);
 496
 497        if (create_tag_object) {
 498                if (force_sign_annotate && !annotate)
 499                        opt.sign = 1;
 500                create_tag(object, tag, &buf, &opt, prev, object);
 501        }
 502
 503        transaction = ref_transaction_begin(&err);
 504        if (!transaction ||
 505            ref_transaction_update(transaction, ref.buf, object, prev,
 506                                   create_reflog ? REF_FORCE_CREATE_REFLOG : 0,
 507                                   NULL, &err) ||
 508            ref_transaction_commit(transaction, &err))
 509                die("%s", err.buf);
 510        ref_transaction_free(transaction);
 511        if (force && !is_null_sha1(prev) && hashcmp(prev, object))
 512                printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
 513
 514        strbuf_release(&err);
 515        strbuf_release(&buf);
 516        strbuf_release(&ref);
 517        return 0;
 518}