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