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