builtin / tag.con commit tag: add --column (d96e3c1)
   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
  21static const char * const git_tag_usage[] = {
  22        "git tag [-a|-s|-u <key-id>] [-f] [-m <msg>|-F <file>] <tagname> [<head>]",
  23        "git tag -d <tagname>...",
  24        "git tag -l [-n[<num>]] [--contains <commit>] [--points-at <object>] "
  25                "\n\t\t[<pattern>...]",
  26        "git tag -v <tagname>...",
  27        NULL
  28};
  29
  30struct tag_filter {
  31        const char **patterns;
  32        int lines;
  33        struct commit_list *with_commit;
  34};
  35
  36static struct sha1_array points_at;
  37static unsigned int colopts;
  38
  39static int match_pattern(const char **patterns, const char *ref)
  40{
  41        /* no pattern means match everything */
  42        if (!*patterns)
  43                return 1;
  44        for (; *patterns; patterns++)
  45                if (!fnmatch(*patterns, ref, 0))
  46                        return 1;
  47        return 0;
  48}
  49
  50static const unsigned char *match_points_at(const char *refname,
  51                                            const unsigned char *sha1)
  52{
  53        const unsigned char *tagged_sha1 = NULL;
  54        struct object *obj;
  55
  56        if (sha1_array_lookup(&points_at, sha1) >= 0)
  57                return sha1;
  58        obj = parse_object(sha1);
  59        if (!obj)
  60                die(_("malformed object at '%s'"), refname);
  61        if (obj->type == OBJ_TAG)
  62                tagged_sha1 = ((struct tag *)obj)->tagged->sha1;
  63        if (tagged_sha1 && sha1_array_lookup(&points_at, tagged_sha1) >= 0)
  64                return tagged_sha1;
  65        return NULL;
  66}
  67
  68static int in_commit_list(const struct commit_list *want, struct commit *c)
  69{
  70        for (; want; want = want->next)
  71                if (!hashcmp(want->item->object.sha1, c->object.sha1))
  72                        return 1;
  73        return 0;
  74}
  75
  76static int contains_recurse(struct commit *candidate,
  77                            const struct commit_list *want)
  78{
  79        struct commit_list *p;
  80
  81        /* was it previously marked as containing a want commit? */
  82        if (candidate->object.flags & TMP_MARK)
  83                return 1;
  84        /* or marked as not possibly containing a want commit? */
  85        if (candidate->object.flags & UNINTERESTING)
  86                return 0;
  87        /* or are we it? */
  88        if (in_commit_list(want, candidate))
  89                return 1;
  90
  91        if (parse_commit(candidate) < 0)
  92                return 0;
  93
  94        /* Otherwise recurse and mark ourselves for future traversals. */
  95        for (p = candidate->parents; p; p = p->next) {
  96                if (contains_recurse(p->item, want)) {
  97                        candidate->object.flags |= TMP_MARK;
  98                        return 1;
  99                }
 100        }
 101        candidate->object.flags |= UNINTERESTING;
 102        return 0;
 103}
 104
 105static int contains(struct commit *candidate, const struct commit_list *want)
 106{
 107        return contains_recurse(candidate, want);
 108}
 109
 110static void show_tag_lines(const unsigned char *sha1, int lines)
 111{
 112        int i;
 113        unsigned long size;
 114        enum object_type type;
 115        char *buf, *sp, *eol;
 116        size_t len;
 117
 118        buf = read_sha1_file(sha1, &type, &size);
 119        if (!buf)
 120                die_errno("unable to read object %s", sha1_to_hex(sha1));
 121        if (type != OBJ_COMMIT && type != OBJ_TAG)
 122                goto free_return;
 123        if (!size)
 124                die("an empty %s object %s?",
 125                    typename(type), sha1_to_hex(sha1));
 126
 127        /* skip header */
 128        sp = strstr(buf, "\n\n");
 129        if (!sp)
 130                goto free_return;
 131
 132        /* only take up to "lines" lines, and strip the signature from a tag */
 133        if (type == OBJ_TAG)
 134                size = parse_signature(buf, size);
 135        for (i = 0, sp += 2; i < lines && sp < buf + size; i++) {
 136                if (i)
 137                        printf("\n    ");
 138                eol = memchr(sp, '\n', size - (sp - buf));
 139                len = eol ? eol - sp : size - (sp - buf);
 140                fwrite(sp, len, 1, stdout);
 141                if (!eol)
 142                        break;
 143                sp = eol + 1;
 144        }
 145free_return:
 146        free(buf);
 147}
 148
 149static int show_reference(const char *refname, const unsigned char *sha1,
 150                          int flag, void *cb_data)
 151{
 152        struct tag_filter *filter = cb_data;
 153
 154        if (match_pattern(filter->patterns, refname)) {
 155                if (filter->with_commit) {
 156                        struct commit *commit;
 157
 158                        commit = lookup_commit_reference_gently(sha1, 1);
 159                        if (!commit)
 160                                return 0;
 161                        if (!contains(commit, filter->with_commit))
 162                                return 0;
 163                }
 164
 165                if (points_at.nr && !match_points_at(refname, sha1))
 166                        return 0;
 167
 168                if (!filter->lines) {
 169                        printf("%s\n", refname);
 170                        return 0;
 171                }
 172                printf("%-15s ", refname);
 173                show_tag_lines(sha1, filter->lines);
 174                putchar('\n');
 175        }
 176
 177        return 0;
 178}
 179
 180static int list_tags(const char **patterns, int lines,
 181                        struct commit_list *with_commit)
 182{
 183        struct tag_filter filter;
 184
 185        filter.patterns = patterns;
 186        filter.lines = lines;
 187        filter.with_commit = with_commit;
 188
 189        for_each_tag_ref(show_reference, (void *) &filter);
 190
 191        return 0;
 192}
 193
 194typedef int (*each_tag_name_fn)(const char *name, const char *ref,
 195                                const unsigned char *sha1);
 196
 197static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
 198{
 199        const char **p;
 200        char ref[PATH_MAX];
 201        int had_error = 0;
 202        unsigned char sha1[20];
 203
 204        for (p = argv; *p; p++) {
 205                if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
 206                                        >= sizeof(ref)) {
 207                        error(_("tag name too long: %.*s..."), 50, *p);
 208                        had_error = 1;
 209                        continue;
 210                }
 211                if (read_ref(ref, sha1)) {
 212                        error(_("tag '%s' not found."), *p);
 213                        had_error = 1;
 214                        continue;
 215                }
 216                if (fn(*p, ref, sha1))
 217                        had_error = 1;
 218        }
 219        return had_error;
 220}
 221
 222static int delete_tag(const char *name, const char *ref,
 223                                const unsigned char *sha1)
 224{
 225        if (delete_ref(ref, sha1, 0))
 226                return 1;
 227        printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
 228        return 0;
 229}
 230
 231static int verify_tag(const char *name, const char *ref,
 232                                const unsigned char *sha1)
 233{
 234        const char *argv_verify_tag[] = {"verify-tag",
 235                                        "-v", "SHA1_HEX", NULL};
 236        argv_verify_tag[2] = sha1_to_hex(sha1);
 237
 238        if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
 239                return error(_("could not verify the tag '%s'"), name);
 240        return 0;
 241}
 242
 243static int do_sign(struct strbuf *buffer)
 244{
 245        return sign_buffer(buffer, buffer, get_signing_key());
 246}
 247
 248static const char tag_template[] =
 249        N_("\n"
 250        "#\n"
 251        "# Write a tag message\n"
 252        "# Lines starting with '#' will be ignored.\n"
 253        "#\n");
 254
 255static const char tag_template_nocleanup[] =
 256        N_("\n"
 257        "#\n"
 258        "# Write a tag message\n"
 259        "# Lines starting with '#' will be kept; you may remove them"
 260        " yourself if you want to.\n"
 261        "#\n");
 262
 263static int git_tag_config(const char *var, const char *value, void *cb)
 264{
 265        int status = git_gpg_config(var, value, cb);
 266        if (status)
 267                return status;
 268        if (!prefixcmp(var, "column."))
 269                return git_column_config(var, value, "tag", &colopts);
 270        return git_default_config(var, value, cb);
 271}
 272
 273static void write_tag_body(int fd, const unsigned char *sha1)
 274{
 275        unsigned long size;
 276        enum object_type type;
 277        char *buf, *sp;
 278
 279        buf = read_sha1_file(sha1, &type, &size);
 280        if (!buf)
 281                return;
 282        /* skip header */
 283        sp = strstr(buf, "\n\n");
 284
 285        if (!sp || !size || type != OBJ_TAG) {
 286                free(buf);
 287                return;
 288        }
 289        sp += 2; /* skip the 2 LFs */
 290        write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
 291
 292        free(buf);
 293}
 294
 295static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
 296{
 297        if (sign && do_sign(buf) < 0)
 298                return error(_("unable to sign the tag"));
 299        if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
 300                return error(_("unable to write tag file"));
 301        return 0;
 302}
 303
 304struct create_tag_options {
 305        unsigned int message_given:1;
 306        unsigned int sign;
 307        enum {
 308                CLEANUP_NONE,
 309                CLEANUP_SPACE,
 310                CLEANUP_ALL
 311        } cleanup_mode;
 312};
 313
 314static void create_tag(const unsigned char *object, const char *tag,
 315                       struct strbuf *buf, struct create_tag_options *opt,
 316                       unsigned char *prev, unsigned char *result)
 317{
 318        enum object_type type;
 319        char header_buf[1024];
 320        int header_len;
 321        char *path = NULL;
 322
 323        type = sha1_object_info(object, NULL);
 324        if (type <= OBJ_NONE)
 325            die(_("bad object type."));
 326
 327        header_len = snprintf(header_buf, sizeof(header_buf),
 328                          "object %s\n"
 329                          "type %s\n"
 330                          "tag %s\n"
 331                          "tagger %s\n\n",
 332                          sha1_to_hex(object),
 333                          typename(type),
 334                          tag,
 335                          git_committer_info(IDENT_ERROR_ON_NO_NAME));
 336
 337        if (header_len > sizeof(header_buf) - 1)
 338                die(_("tag header too big."));
 339
 340        if (!opt->message_given) {
 341                int fd;
 342
 343                /* write the template message before editing: */
 344                path = git_pathdup("TAG_EDITMSG");
 345                fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
 346                if (fd < 0)
 347                        die_errno(_("could not create file '%s'"), path);
 348
 349                if (!is_null_sha1(prev))
 350                        write_tag_body(fd, prev);
 351                else if (opt->cleanup_mode == CLEANUP_ALL)
 352                        write_or_die(fd, _(tag_template),
 353                                        strlen(_(tag_template)));
 354                else
 355                        write_or_die(fd, _(tag_template_nocleanup),
 356                                        strlen(_(tag_template_nocleanup)));
 357                close(fd);
 358
 359                if (launch_editor(path, buf, NULL)) {
 360                        fprintf(stderr,
 361                        _("Please supply the message using either -m or -F option.\n"));
 362                        exit(1);
 363                }
 364        }
 365
 366        if (opt->cleanup_mode != CLEANUP_NONE)
 367                stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
 368
 369        if (!opt->message_given && !buf->len)
 370                die(_("no tag message?"));
 371
 372        strbuf_insert(buf, 0, header_buf, header_len);
 373
 374        if (build_tag_object(buf, opt->sign, result) < 0) {
 375                if (path)
 376                        fprintf(stderr, _("The tag message has been left in %s\n"),
 377                                path);
 378                exit(128);
 379        }
 380        if (path) {
 381                unlink_or_warn(path);
 382                free(path);
 383        }
 384}
 385
 386struct msg_arg {
 387        int given;
 388        struct strbuf buf;
 389};
 390
 391static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
 392{
 393        struct msg_arg *msg = opt->value;
 394
 395        if (!arg)
 396                return -1;
 397        if (msg->buf.len)
 398                strbuf_addstr(&(msg->buf), "\n\n");
 399        strbuf_addstr(&(msg->buf), arg);
 400        msg->given = 1;
 401        return 0;
 402}
 403
 404static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
 405{
 406        if (name[0] == '-')
 407                return -1;
 408
 409        strbuf_reset(sb);
 410        strbuf_addf(sb, "refs/tags/%s", name);
 411
 412        return check_refname_format(sb->buf, 0);
 413}
 414
 415static int parse_opt_points_at(const struct option *opt __attribute__((unused)),
 416                        const char *arg, int unset)
 417{
 418        unsigned char sha1[20];
 419
 420        if (unset) {
 421                sha1_array_clear(&points_at);
 422                return 0;
 423        }
 424        if (!arg)
 425                return error(_("switch 'points-at' requires an object"));
 426        if (get_sha1(arg, sha1))
 427                return error(_("malformed object name '%s'"), arg);
 428        sha1_array_append(&points_at, sha1);
 429        return 0;
 430}
 431
 432int cmd_tag(int argc, const char **argv, const char *prefix)
 433{
 434        struct strbuf buf = STRBUF_INIT;
 435        struct strbuf ref = STRBUF_INIT;
 436        unsigned char object[20], prev[20];
 437        const char *object_ref, *tag;
 438        struct ref_lock *lock;
 439        struct create_tag_options opt;
 440        char *cleanup_arg = NULL;
 441        int annotate = 0, force = 0, lines = -1, list = 0,
 442                delete = 0, verify = 0;
 443        const char *msgfile = NULL, *keyid = NULL;
 444        struct msg_arg msg = { 0, STRBUF_INIT };
 445        struct commit_list *with_commit = NULL;
 446        struct option options[] = {
 447                OPT_BOOLEAN('l', "list", &list, "list tag names"),
 448                { OPTION_INTEGER, 'n', NULL, &lines, "n",
 449                                "print <n> lines of each tag message",
 450                                PARSE_OPT_OPTARG, NULL, 1 },
 451                OPT_BOOLEAN('d', "delete", &delete, "delete tags"),
 452                OPT_BOOLEAN('v', "verify", &verify, "verify tags"),
 453
 454                OPT_GROUP("Tag creation options"),
 455                OPT_BOOLEAN('a', "annotate", &annotate,
 456                                        "annotated tag, needs a message"),
 457                OPT_CALLBACK('m', "message", &msg, "message",
 458                             "tag message", parse_msg_arg),
 459                OPT_FILENAME('F', "file", &msgfile, "read message from file"),
 460                OPT_BOOLEAN('s', "sign", &opt.sign, "annotated and GPG-signed tag"),
 461                OPT_STRING(0, "cleanup", &cleanup_arg, "mode",
 462                        "how to strip spaces and #comments from message"),
 463                OPT_STRING('u', "local-user", &keyid, "key-id",
 464                                        "use another key to sign the tag"),
 465                OPT__FORCE(&force, "replace the tag if exists"),
 466                OPT_COLUMN(0, "column", &colopts, "show tag list in columns"),
 467
 468                OPT_GROUP("Tag listing options"),
 469                {
 470                        OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
 471                        "print only tags that contain the commit",
 472                        PARSE_OPT_LASTARG_DEFAULT,
 473                        parse_opt_with_commit, (intptr_t)"HEAD",
 474                },
 475                {
 476                        OPTION_CALLBACK, 0, "points-at", NULL, "object",
 477                        "print only tags of the object", 0, parse_opt_points_at
 478                },
 479                OPT_END()
 480        };
 481
 482        git_config(git_tag_config, NULL);
 483
 484        memset(&opt, 0, sizeof(opt));
 485
 486        argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
 487
 488        if (keyid) {
 489                opt.sign = 1;
 490                set_signing_key(keyid);
 491        }
 492        if (opt.sign)
 493                annotate = 1;
 494        if (argc == 0 && !(delete || verify))
 495                list = 1;
 496
 497        if ((annotate || msg.given || msgfile || force) &&
 498            (list || delete || verify))
 499                usage_with_options(git_tag_usage, options);
 500
 501        if (list + delete + verify > 1)
 502                usage_with_options(git_tag_usage, options);
 503        finalize_colopts(&colopts, -1);
 504        if (list && lines != -1) {
 505                if (explicitly_enable_column(colopts))
 506                        die(_("--column and -n are incompatible"));
 507                colopts = 0;
 508        }
 509        if (list) {
 510                int ret;
 511                if (column_active(colopts)) {
 512                        struct column_options copts;
 513                        memset(&copts, 0, sizeof(copts));
 514                        copts.padding = 2;
 515                        run_column_filter(colopts, &copts);
 516                }
 517                ret = list_tags(argv, lines == -1 ? 0 : lines, with_commit);
 518                if (column_active(colopts))
 519                        stop_column_filter();
 520                return ret;
 521        }
 522        if (lines != -1)
 523                die(_("-n option is only allowed with -l."));
 524        if (with_commit)
 525                die(_("--contains option is only allowed with -l."));
 526        if (points_at.nr)
 527                die(_("--points-at option is only allowed with -l."));
 528        if (delete)
 529                return for_each_tag_name(argv, delete_tag);
 530        if (verify)
 531                return for_each_tag_name(argv, verify_tag);
 532
 533        if (msg.given || msgfile) {
 534                if (msg.given && msgfile)
 535                        die(_("only one -F or -m option is allowed."));
 536                annotate = 1;
 537                if (msg.given)
 538                        strbuf_addbuf(&buf, &(msg.buf));
 539                else {
 540                        if (!strcmp(msgfile, "-")) {
 541                                if (strbuf_read(&buf, 0, 1024) < 0)
 542                                        die_errno(_("cannot read '%s'"), msgfile);
 543                        } else {
 544                                if (strbuf_read_file(&buf, msgfile, 1024) < 0)
 545                                        die_errno(_("could not open or read '%s'"),
 546                                                msgfile);
 547                        }
 548                }
 549        }
 550
 551        tag = argv[0];
 552
 553        object_ref = argc == 2 ? argv[1] : "HEAD";
 554        if (argc > 2)
 555                die(_("too many params"));
 556
 557        if (get_sha1(object_ref, object))
 558                die(_("Failed to resolve '%s' as a valid ref."), object_ref);
 559
 560        if (strbuf_check_tag_ref(&ref, tag))
 561                die(_("'%s' is not a valid tag name."), tag);
 562
 563        if (read_ref(ref.buf, prev))
 564                hashclr(prev);
 565        else if (!force)
 566                die(_("tag '%s' already exists"), tag);
 567
 568        opt.message_given = msg.given || msgfile;
 569
 570        if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
 571                opt.cleanup_mode = CLEANUP_ALL;
 572        else if (!strcmp(cleanup_arg, "verbatim"))
 573                opt.cleanup_mode = CLEANUP_NONE;
 574        else if (!strcmp(cleanup_arg, "whitespace"))
 575                opt.cleanup_mode = CLEANUP_SPACE;
 576        else
 577                die(_("Invalid cleanup mode %s"), cleanup_arg);
 578
 579        if (annotate)
 580                create_tag(object, tag, &buf, &opt, prev, object);
 581
 582        lock = lock_any_ref_for_update(ref.buf, prev, 0);
 583        if (!lock)
 584                die(_("%s: cannot lock the ref"), ref.buf);
 585        if (write_ref_sha1(lock, object, NULL) < 0)
 586                die(_("%s: cannot update the ref"), ref.buf);
 587        if (force && hashcmp(prev, object))
 588                printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
 589
 590        strbuf_release(&buf);
 591        strbuf_release(&ref);
 592        return 0;
 593}