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.
13 #include "run-command.h"
14 #include "parse-options.h"
17 #include "gpg-interface.h"
18 #include "sha1-array.h"
21 static const char * const git_tag_usage[] = {
22 N_("git tag [-a | -s | -u <key-id>] [-f] [-m <msg> | -F <file>] <tagname> [<head>]"),
23 N_("git tag -d <tagname>..."),
24 N_("git tag -l [-n[<num>]] [--contains <commit>] [--points-at <object>]"
25 "\n\t\t[<pattern>...]"),
26 N_("git tag -v <tagname>..."),
30 #define STRCMP_SORT 0 /* must be zero */
32 #define SORT_MASK 0x7fff
33 #define REVERSE_SORT 0x8000
38 const char **patterns;
41 struct string_list tags;
42 struct commit_list *with_commit;
45 static struct sha1_array points_at;
46 static unsigned int colopts;
48 static int match_pattern(const char **patterns, const char *ref)
50 /* no pattern means match everything */
53 for (; *patterns; patterns++)
54 if (!wildmatch(*patterns, ref, 0, NULL))
59 static const unsigned char *match_points_at(const char *refname,
60 const unsigned char *sha1)
62 const unsigned char *tagged_sha1 = NULL;
65 if (sha1_array_lookup(&points_at, sha1) >= 0)
67 obj = parse_object(sha1);
69 die(_("malformed object at '%s'"), refname);
70 if (obj->type == OBJ_TAG)
71 tagged_sha1 = ((struct tag *)obj)->tagged->sha1;
72 if (tagged_sha1 && sha1_array_lookup(&points_at, tagged_sha1) >= 0)
77 static int in_commit_list(const struct commit_list *want, struct commit *c)
79 for (; want; want = want->next)
80 if (!hashcmp(want->item->object.sha1, c->object.sha1))
85 enum contains_result {
86 CONTAINS_UNKNOWN = -1,
92 * Test whether the candidate or one of its parents is contained in the list.
93 * Do not recurse to find out, though, but return -1 if inconclusive.
95 static enum contains_result contains_test(struct commit *candidate,
96 const struct commit_list *want)
98 /* was it previously marked as containing a want commit? */
99 if (candidate->object.flags & TMP_MARK)
101 /* or marked as not possibly containing a want commit? */
102 if (candidate->object.flags & UNINTERESTING)
105 if (in_commit_list(want, candidate)) {
106 candidate->object.flags |= TMP_MARK;
110 if (parse_commit(candidate) < 0)
117 * Mimicking the real stack, this stack lives on the heap, avoiding stack
120 * At each recursion step, the stack items points to the commits whose
121 * ancestors are to be inspected.
126 struct commit *commit;
127 struct commit_list *parents;
131 static void push_to_stack(struct commit *candidate, struct stack *stack)
133 int index = stack->nr++;
134 ALLOC_GROW(stack->stack, stack->nr, stack->alloc);
135 stack->stack[index].commit = candidate;
136 stack->stack[index].parents = candidate->parents;
139 static enum contains_result contains(struct commit *candidate,
140 const struct commit_list *want)
142 struct stack stack = { 0, 0, NULL };
143 int result = contains_test(candidate, want);
145 if (result != CONTAINS_UNKNOWN)
148 push_to_stack(candidate, &stack);
150 struct stack_entry *entry = &stack.stack[stack.nr - 1];
151 struct commit *commit = entry->commit;
152 struct commit_list *parents = entry->parents;
155 commit->object.flags |= UNINTERESTING;
159 * If we just popped the stack, parents->item has been marked,
160 * therefore contains_test will return a meaningful 0 or 1.
162 else switch (contains_test(parents->item, want)) {
164 commit->object.flags |= TMP_MARK;
168 entry->parents = parents->next;
170 case CONTAINS_UNKNOWN:
171 push_to_stack(parents->item, &stack);
176 return contains_test(candidate, want);
179 static void show_tag_lines(const unsigned char *sha1, int lines)
183 enum object_type type;
184 char *buf, *sp, *eol;
187 buf = read_sha1_file(sha1, &type, &size);
189 die_errno("unable to read object %s", sha1_to_hex(sha1));
190 if (type != OBJ_COMMIT && type != OBJ_TAG)
193 die("an empty %s object %s?",
194 typename(type), sha1_to_hex(sha1));
197 sp = strstr(buf, "\n\n");
201 /* only take up to "lines" lines, and strip the signature from a tag */
203 size = parse_signature(buf, size);
204 for (i = 0, sp += 2; i < lines && sp < buf + size; i++) {
207 eol = memchr(sp, '\n', size - (sp - buf));
208 len = eol ? eol - sp : size - (sp - buf);
209 fwrite(sp, len, 1, stdout);
218 static int show_reference(const char *refname, const unsigned char *sha1,
219 int flag, void *cb_data)
221 struct tag_filter *filter = cb_data;
223 if (match_pattern(filter->patterns, refname)) {
224 if (filter->with_commit) {
225 struct commit *commit;
227 commit = lookup_commit_reference_gently(sha1, 1);
230 if (!contains(commit, filter->with_commit))
234 if (points_at.nr && !match_points_at(refname, sha1))
237 if (!filter->lines) {
239 string_list_append(&filter->tags, refname);
241 printf("%s\n", refname);
244 printf("%-15s ", refname);
245 show_tag_lines(sha1, filter->lines);
252 static int sort_by_version(const void *a_, const void *b_)
254 const struct string_list_item *a = a_;
255 const struct string_list_item *b = b_;
256 return versioncmp(a->string, b->string);
259 static int list_tags(const char **patterns, int lines,
260 struct commit_list *with_commit, int sort)
262 struct tag_filter filter;
263 struct each_ref_fn_sha1_adapter wrapped_show_reference =
264 {show_reference, (void *)&filter};
266 filter.patterns = patterns;
267 filter.lines = lines;
269 filter.with_commit = with_commit;
270 memset(&filter.tags, 0, sizeof(filter.tags));
271 filter.tags.strdup_strings = 1;
273 for_each_tag_ref(each_ref_fn_adapter, &wrapped_show_reference);
276 if ((sort & SORT_MASK) == VERCMP_SORT)
277 qsort(filter.tags.items, filter.tags.nr,
278 sizeof(struct string_list_item), sort_by_version);
279 if (sort & REVERSE_SORT)
280 for (i = filter.tags.nr - 1; i >= 0; i--)
281 printf("%s\n", filter.tags.items[i].string);
283 for (i = 0; i < filter.tags.nr; i++)
284 printf("%s\n", filter.tags.items[i].string);
285 string_list_clear(&filter.tags, 0);
290 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
291 const unsigned char *sha1);
293 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
298 unsigned char sha1[20];
300 for (p = argv; *p; p++) {
301 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
303 error(_("tag name too long: %.*s..."), 50, *p);
307 if (read_ref(ref, sha1)) {
308 error(_("tag '%s' not found."), *p);
312 if (fn(*p, ref, sha1))
318 static int delete_tag(const char *name, const char *ref,
319 const unsigned char *sha1)
321 if (delete_ref(ref, sha1, 0))
323 printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
327 static int verify_tag(const char *name, const char *ref,
328 const unsigned char *sha1)
330 const char *argv_verify_tag[] = {"verify-tag",
331 "-v", "SHA1_HEX", NULL};
332 argv_verify_tag[2] = sha1_to_hex(sha1);
334 if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
335 return error(_("could not verify the tag '%s'"), name);
339 static int do_sign(struct strbuf *buffer)
341 return sign_buffer(buffer, buffer, get_signing_key());
344 static const char tag_template[] =
345 N_("\nWrite a message for tag:\n %s\n"
346 "Lines starting with '%c' will be ignored.\n");
348 static const char tag_template_nocleanup[] =
349 N_("\nWrite a message for tag:\n %s\n"
350 "Lines starting with '%c' will be kept; you may remove them"
351 " yourself if you want to.\n");
354 * Parse a sort string, and return 0 if parsed successfully. Will return
355 * non-zero when the sort string does not parse into a known type. If var is
356 * given, the error message becomes a warning and includes information about
357 * the configuration value.
359 static int parse_sort_string(const char *var, const char *arg, int *sort)
361 int type = 0, flags = 0;
363 if (skip_prefix(arg, "-", &arg))
364 flags |= REVERSE_SORT;
366 if (skip_prefix(arg, "version:", &arg) || skip_prefix(arg, "v:", &arg))
371 if (strcmp(arg, "refname")) {
373 return error(_("unsupported sort specification '%s'"), arg);
375 warning(_("unsupported sort specification '%s' in variable '%s'"),
381 *sort = (type | flags);
386 static int git_tag_config(const char *var, const char *value, void *cb)
390 if (!strcmp(var, "tag.sort")) {
392 return config_error_nonbool(var);
393 parse_sort_string(var, value, &tag_sort);
397 status = git_gpg_config(var, value, cb);
400 if (starts_with(var, "column."))
401 return git_column_config(var, value, "tag", &colopts);
402 return git_default_config(var, value, cb);
405 static void write_tag_body(int fd, const unsigned char *sha1)
408 enum object_type type;
411 buf = read_sha1_file(sha1, &type, &size);
415 sp = strstr(buf, "\n\n");
417 if (!sp || !size || type != OBJ_TAG) {
421 sp += 2; /* skip the 2 LFs */
422 write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
427 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
429 if (sign && do_sign(buf) < 0)
430 return error(_("unable to sign the tag"));
431 if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
432 return error(_("unable to write tag file"));
436 struct create_tag_options {
437 unsigned int message_given:1;
446 static void create_tag(const unsigned char *object, const char *tag,
447 struct strbuf *buf, struct create_tag_options *opt,
448 unsigned char *prev, unsigned char *result)
450 enum object_type type;
451 char header_buf[1024];
455 type = sha1_object_info(object, NULL);
456 if (type <= OBJ_NONE)
457 die(_("bad object type."));
459 header_len = snprintf(header_buf, sizeof(header_buf),
467 git_committer_info(IDENT_STRICT));
469 if (header_len > sizeof(header_buf) - 1)
470 die(_("tag header too big."));
472 if (!opt->message_given) {
475 /* write the template message before editing: */
476 path = git_pathdup("TAG_EDITMSG");
477 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
479 die_errno(_("could not create file '%s'"), path);
481 if (!is_null_sha1(prev)) {
482 write_tag_body(fd, prev);
484 struct strbuf buf = STRBUF_INIT;
485 strbuf_addch(&buf, '\n');
486 if (opt->cleanup_mode == CLEANUP_ALL)
487 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
489 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
490 write_or_die(fd, buf.buf, buf.len);
491 strbuf_release(&buf);
495 if (launch_editor(path, buf, NULL)) {
497 _("Please supply the message using either -m or -F option.\n"));
502 if (opt->cleanup_mode != CLEANUP_NONE)
503 stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
505 if (!opt->message_given && !buf->len)
506 die(_("no tag message?"));
508 strbuf_insert(buf, 0, header_buf, header_len);
510 if (build_tag_object(buf, opt->sign, result) < 0) {
512 fprintf(stderr, _("The tag message has been left in %s\n"),
517 unlink_or_warn(path);
527 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
529 struct msg_arg *msg = opt->value;
534 strbuf_addstr(&(msg->buf), "\n\n");
535 strbuf_addstr(&(msg->buf), arg);
540 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
546 strbuf_addf(sb, "refs/tags/%s", name);
548 return check_refname_format(sb->buf, 0);
551 static int parse_opt_points_at(const struct option *opt __attribute__((unused)),
552 const char *arg, int unset)
554 unsigned char sha1[20];
557 sha1_array_clear(&points_at);
561 return error(_("switch 'points-at' requires an object"));
562 if (get_sha1(arg, sha1))
563 return error(_("malformed object name '%s'"), arg);
564 sha1_array_append(&points_at, sha1);
568 static int parse_opt_sort(const struct option *opt, const char *arg, int unset)
570 int *sort = opt->value;
572 return parse_sort_string(NULL, arg, sort);
575 int cmd_tag(int argc, const char **argv, const char *prefix)
577 struct strbuf buf = STRBUF_INIT;
578 struct strbuf ref = STRBUF_INIT;
579 unsigned char object[20], prev[20];
580 const char *object_ref, *tag;
581 struct create_tag_options opt;
582 char *cleanup_arg = NULL;
583 int annotate = 0, force = 0, lines = -1;
585 const char *msgfile = NULL, *keyid = NULL;
586 struct msg_arg msg = { 0, STRBUF_INIT };
587 struct commit_list *with_commit = NULL;
588 struct ref_transaction *transaction;
589 struct strbuf err = STRBUF_INIT;
590 struct option options[] = {
591 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
592 { OPTION_INTEGER, 'n', NULL, &lines, N_("n"),
593 N_("print <n> lines of each tag message"),
594 PARSE_OPT_OPTARG, NULL, 1 },
595 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
596 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
598 OPT_GROUP(N_("Tag creation options")),
599 OPT_BOOL('a', "annotate", &annotate,
600 N_("annotated tag, needs a message")),
601 OPT_CALLBACK('m', "message", &msg, N_("message"),
602 N_("tag message"), parse_msg_arg),
603 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
604 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
605 OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
606 N_("how to strip spaces and #comments from message")),
607 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
608 N_("use another key to sign the tag")),
609 OPT__FORCE(&force, N_("replace the tag if exists")),
611 OPT_GROUP(N_("Tag listing options")),
612 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
614 OPTION_CALLBACK, 0, "sort", &tag_sort, N_("type"), N_("sort tags"),
615 PARSE_OPT_NONEG, parse_opt_sort
618 OPTION_CALLBACK, 0, "contains", &with_commit, N_("commit"),
619 N_("print only tags that contain the commit"),
620 PARSE_OPT_LASTARG_DEFAULT,
621 parse_opt_with_commit, (intptr_t)"HEAD",
624 OPTION_CALLBACK, 0, "with", &with_commit, N_("commit"),
625 N_("print only tags that contain the commit"),
626 PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
627 parse_opt_with_commit, (intptr_t)"HEAD",
630 OPTION_CALLBACK, 0, "points-at", NULL, N_("object"),
631 N_("print only tags of the object"), 0, parse_opt_points_at
636 git_config(git_tag_config, NULL);
638 memset(&opt, 0, sizeof(opt));
640 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
644 set_signing_key(keyid);
648 if (argc == 0 && !cmdmode)
651 if ((annotate || msg.given || msgfile || force) && (cmdmode != 0))
652 usage_with_options(git_tag_usage, options);
654 finalize_colopts(&colopts, -1);
655 if (cmdmode == 'l' && lines != -1) {
656 if (explicitly_enable_column(colopts))
657 die(_("--column and -n are incompatible"));
660 if (cmdmode == 'l') {
662 if (column_active(colopts)) {
663 struct column_options copts;
664 memset(&copts, 0, sizeof(copts));
666 run_column_filter(colopts, &copts);
668 if (lines != -1 && tag_sort)
669 die(_("--sort and -n are incompatible"));
670 ret = list_tags(argv, lines == -1 ? 0 : lines, with_commit, tag_sort);
671 if (column_active(colopts))
672 stop_column_filter();
676 die(_("-n option is only allowed with -l."));
678 die(_("--contains option is only allowed with -l."));
680 die(_("--points-at option is only allowed with -l."));
682 return for_each_tag_name(argv, delete_tag);
684 return for_each_tag_name(argv, verify_tag);
686 if (msg.given || msgfile) {
687 if (msg.given && msgfile)
688 die(_("only one -F or -m option is allowed."));
691 strbuf_addbuf(&buf, &(msg.buf));
693 if (!strcmp(msgfile, "-")) {
694 if (strbuf_read(&buf, 0, 1024) < 0)
695 die_errno(_("cannot read '%s'"), msgfile);
697 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
698 die_errno(_("could not open or read '%s'"),
706 object_ref = argc == 2 ? argv[1] : "HEAD";
708 die(_("too many params"));
710 if (get_sha1(object_ref, object))
711 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
713 if (strbuf_check_tag_ref(&ref, tag))
714 die(_("'%s' is not a valid tag name."), tag);
716 if (read_ref(ref.buf, prev))
719 die(_("tag '%s' already exists"), tag);
721 opt.message_given = msg.given || msgfile;
723 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
724 opt.cleanup_mode = CLEANUP_ALL;
725 else if (!strcmp(cleanup_arg, "verbatim"))
726 opt.cleanup_mode = CLEANUP_NONE;
727 else if (!strcmp(cleanup_arg, "whitespace"))
728 opt.cleanup_mode = CLEANUP_SPACE;
730 die(_("Invalid cleanup mode %s"), cleanup_arg);
733 create_tag(object, tag, &buf, &opt, prev, object);
735 transaction = ref_transaction_begin(&err);
737 ref_transaction_update(transaction, ref.buf, object, prev,
739 ref_transaction_commit(transaction, &err))
741 ref_transaction_free(transaction);
742 if (force && !is_null_sha1(prev) && hashcmp(prev, object))
743 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
745 strbuf_release(&err);
746 strbuf_release(&buf);
747 strbuf_release(&ref);