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