Merge branch 'jp/index-with-corrupt-stages'
[git/mjg.git] / builtin / tag.c
bloba81b9e4174c77fc10d9f0a37c547723505208c3c
1 /*
2 * Builtin "git tag"
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 */
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"
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>..."),
27 NULL
30 #define STRCMP_SORT 0 /* must be zero */
31 #define VERCMP_SORT 1
32 #define SORT_MASK 0x7fff
33 #define REVERSE_SORT 0x8000
35 static int tag_sort;
37 struct tag_filter {
38 const char **patterns;
39 int lines;
40 int sort;
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 */
51 if (!*patterns)
52 return 1;
53 for (; *patterns; patterns++)
54 if (!wildmatch(*patterns, ref, 0, NULL))
55 return 1;
56 return 0;
59 static const unsigned char *match_points_at(const char *refname,
60 const unsigned char *sha1)
62 const unsigned char *tagged_sha1 = NULL;
63 struct object *obj;
65 if (sha1_array_lookup(&points_at, sha1) >= 0)
66 return sha1;
67 obj = parse_object(sha1);
68 if (!obj)
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)
73 return tagged_sha1;
74 return NULL;
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))
81 return 1;
82 return 0;
85 enum contains_result {
86 CONTAINS_UNKNOWN = -1,
87 CONTAINS_NO = 0,
88 CONTAINS_YES = 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)
100 return 1;
101 /* or marked as not possibly containing a want commit? */
102 if (candidate->object.flags & UNINTERESTING)
103 return 0;
104 /* or are we it? */
105 if (in_commit_list(want, candidate)) {
106 candidate->object.flags |= TMP_MARK;
107 return 1;
110 if (parse_commit(candidate) < 0)
111 return 0;
113 return -1;
117 * Mimicking the real stack, this stack lives on the heap, avoiding stack
118 * overflows.
120 * At each recursion step, the stack items points to the commits whose
121 * ancestors are to be inspected.
123 struct stack {
124 int nr, alloc;
125 struct stack_entry {
126 struct commit *commit;
127 struct commit_list *parents;
128 } *stack;
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)
146 return result;
148 push_to_stack(candidate, &stack);
149 while (stack.nr) {
150 struct stack_entry *entry = &stack.stack[stack.nr - 1];
151 struct commit *commit = entry->commit;
152 struct commit_list *parents = entry->parents;
154 if (!parents) {
155 commit->object.flags |= UNINTERESTING;
156 stack.nr--;
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)) {
163 case CONTAINS_YES:
164 commit->object.flags |= TMP_MARK;
165 stack.nr--;
166 break;
167 case CONTAINS_NO:
168 entry->parents = parents->next;
169 break;
170 case CONTAINS_UNKNOWN:
171 push_to_stack(parents->item, &stack);
172 break;
175 free(stack.stack);
176 return contains_test(candidate, want);
179 static void show_tag_lines(const unsigned char *sha1, int lines)
181 int i;
182 unsigned long size;
183 enum object_type type;
184 char *buf, *sp, *eol;
185 size_t len;
187 buf = read_sha1_file(sha1, &type, &size);
188 if (!buf)
189 die_errno("unable to read object %s", sha1_to_hex(sha1));
190 if (type != OBJ_COMMIT && type != OBJ_TAG)
191 goto free_return;
192 if (!size)
193 die("an empty %s object %s?",
194 typename(type), sha1_to_hex(sha1));
196 /* skip header */
197 sp = strstr(buf, "\n\n");
198 if (!sp)
199 goto free_return;
201 /* only take up to "lines" lines, and strip the signature from a tag */
202 if (type == OBJ_TAG)
203 size = parse_signature(buf, size);
204 for (i = 0, sp += 2; i < lines && sp < buf + size; i++) {
205 if (i)
206 printf("\n ");
207 eol = memchr(sp, '\n', size - (sp - buf));
208 len = eol ? eol - sp : size - (sp - buf);
209 fwrite(sp, len, 1, stdout);
210 if (!eol)
211 break;
212 sp = eol + 1;
214 free_return:
215 free(buf);
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);
228 if (!commit)
229 return 0;
230 if (!contains(commit, filter->with_commit))
231 return 0;
234 if (points_at.nr && !match_points_at(refname, sha1))
235 return 0;
237 if (!filter->lines) {
238 if (filter->sort)
239 string_list_append(&filter->tags, refname);
240 else
241 printf("%s\n", refname);
242 return 0;
244 printf("%-15s ", refname);
245 show_tag_lines(sha1, filter->lines);
246 putchar('\n');
249 return 0;
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;
264 filter.patterns = patterns;
265 filter.lines = lines;
266 filter.sort = sort;
267 filter.with_commit = with_commit;
268 memset(&filter.tags, 0, sizeof(filter.tags));
269 filter.tags.strdup_strings = 1;
271 for_each_tag_ref(show_reference, (void *) &filter);
272 if (sort) {
273 int i;
274 if ((sort & SORT_MASK) == VERCMP_SORT)
275 qsort(filter.tags.items, filter.tags.nr,
276 sizeof(struct string_list_item), sort_by_version);
277 if (sort & REVERSE_SORT)
278 for (i = filter.tags.nr - 1; i >= 0; i--)
279 printf("%s\n", filter.tags.items[i].string);
280 else
281 for (i = 0; i < filter.tags.nr; i++)
282 printf("%s\n", filter.tags.items[i].string);
283 string_list_clear(&filter.tags, 0);
285 return 0;
288 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
289 const unsigned char *sha1);
291 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
293 const char **p;
294 char ref[PATH_MAX];
295 int had_error = 0;
296 unsigned char sha1[20];
298 for (p = argv; *p; p++) {
299 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
300 >= sizeof(ref)) {
301 error(_("tag name too long: %.*s..."), 50, *p);
302 had_error = 1;
303 continue;
305 if (read_ref(ref, sha1)) {
306 error(_("tag '%s' not found."), *p);
307 had_error = 1;
308 continue;
310 if (fn(*p, ref, sha1))
311 had_error = 1;
313 return had_error;
316 static int delete_tag(const char *name, const char *ref,
317 const unsigned char *sha1)
319 if (delete_ref(ref, sha1, 0))
320 return 1;
321 printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
322 return 0;
325 static int verify_tag(const char *name, const char *ref,
326 const unsigned char *sha1)
328 const char *argv_verify_tag[] = {"verify-tag",
329 "-v", "SHA1_HEX", NULL};
330 argv_verify_tag[2] = sha1_to_hex(sha1);
332 if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
333 return error(_("could not verify the tag '%s'"), name);
334 return 0;
337 static int do_sign(struct strbuf *buffer)
339 return sign_buffer(buffer, buffer, get_signing_key());
342 static const char tag_template[] =
343 N_("\nWrite a message for tag:\n %s\n"
344 "Lines starting with '%c' will be ignored.\n");
346 static const char tag_template_nocleanup[] =
347 N_("\nWrite a message for tag:\n %s\n"
348 "Lines starting with '%c' will be kept; you may remove them"
349 " yourself if you want to.\n");
352 * Parse a sort string, and return 0 if parsed successfully. Will return
353 * non-zero when the sort string does not parse into a known type. If var is
354 * given, the error message becomes a warning and includes information about
355 * the configuration value.
357 static int parse_sort_string(const char *var, const char *arg, int *sort)
359 int type = 0, flags = 0;
361 if (skip_prefix(arg, "-", &arg))
362 flags |= REVERSE_SORT;
364 if (skip_prefix(arg, "version:", &arg) || skip_prefix(arg, "v:", &arg))
365 type = VERCMP_SORT;
366 else
367 type = STRCMP_SORT;
369 if (strcmp(arg, "refname")) {
370 if (!var)
371 return error(_("unsupported sort specification '%s'"), arg);
372 else {
373 warning(_("unsupported sort specification '%s' in variable '%s'"),
374 var, arg);
375 return -1;
379 *sort = (type | flags);
381 return 0;
384 static int git_tag_config(const char *var, const char *value, void *cb)
386 int status;
388 if (!strcmp(var, "tag.sort")) {
389 if (!value)
390 return config_error_nonbool(var);
391 parse_sort_string(var, value, &tag_sort);
392 return 0;
395 status = git_gpg_config(var, value, cb);
396 if (status)
397 return status;
398 if (starts_with(var, "column."))
399 return git_column_config(var, value, "tag", &colopts);
400 return git_default_config(var, value, cb);
403 static void write_tag_body(int fd, const unsigned char *sha1)
405 unsigned long size;
406 enum object_type type;
407 char *buf, *sp;
409 buf = read_sha1_file(sha1, &type, &size);
410 if (!buf)
411 return;
412 /* skip header */
413 sp = strstr(buf, "\n\n");
415 if (!sp || !size || type != OBJ_TAG) {
416 free(buf);
417 return;
419 sp += 2; /* skip the 2 LFs */
420 write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
422 free(buf);
425 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
427 if (sign && do_sign(buf) < 0)
428 return error(_("unable to sign the tag"));
429 if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
430 return error(_("unable to write tag file"));
431 return 0;
434 struct create_tag_options {
435 unsigned int message_given:1;
436 unsigned int sign;
437 enum {
438 CLEANUP_NONE,
439 CLEANUP_SPACE,
440 CLEANUP_ALL
441 } cleanup_mode;
444 static void create_tag(const unsigned char *object, const char *tag,
445 struct strbuf *buf, struct create_tag_options *opt,
446 unsigned char *prev, unsigned char *result)
448 enum object_type type;
449 char header_buf[1024];
450 int header_len;
451 char *path = NULL;
453 type = sha1_object_info(object, NULL);
454 if (type <= OBJ_NONE)
455 die(_("bad object type."));
457 header_len = snprintf(header_buf, sizeof(header_buf),
458 "object %s\n"
459 "type %s\n"
460 "tag %s\n"
461 "tagger %s\n\n",
462 sha1_to_hex(object),
463 typename(type),
464 tag,
465 git_committer_info(IDENT_STRICT));
467 if (header_len > sizeof(header_buf) - 1)
468 die(_("tag header too big."));
470 if (!opt->message_given) {
471 int fd;
473 /* write the template message before editing: */
474 path = git_pathdup("TAG_EDITMSG");
475 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
476 if (fd < 0)
477 die_errno(_("could not create file '%s'"), path);
479 if (!is_null_sha1(prev)) {
480 write_tag_body(fd, prev);
481 } else {
482 struct strbuf buf = STRBUF_INIT;
483 strbuf_addch(&buf, '\n');
484 if (opt->cleanup_mode == CLEANUP_ALL)
485 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
486 else
487 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
488 write_or_die(fd, buf.buf, buf.len);
489 strbuf_release(&buf);
491 close(fd);
493 if (launch_editor(path, buf, NULL)) {
494 fprintf(stderr,
495 _("Please supply the message using either -m or -F option.\n"));
496 exit(1);
500 if (opt->cleanup_mode != CLEANUP_NONE)
501 stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
503 if (!opt->message_given && !buf->len)
504 die(_("no tag message?"));
506 strbuf_insert(buf, 0, header_buf, header_len);
508 if (build_tag_object(buf, opt->sign, result) < 0) {
509 if (path)
510 fprintf(stderr, _("The tag message has been left in %s\n"),
511 path);
512 exit(128);
514 if (path) {
515 unlink_or_warn(path);
516 free(path);
520 struct msg_arg {
521 int given;
522 struct strbuf buf;
525 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
527 struct msg_arg *msg = opt->value;
529 if (!arg)
530 return -1;
531 if (msg->buf.len)
532 strbuf_addstr(&(msg->buf), "\n\n");
533 strbuf_addstr(&(msg->buf), arg);
534 msg->given = 1;
535 return 0;
538 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
540 if (name[0] == '-')
541 return -1;
543 strbuf_reset(sb);
544 strbuf_addf(sb, "refs/tags/%s", name);
546 return check_refname_format(sb->buf, 0);
549 static int parse_opt_points_at(const struct option *opt __attribute__((unused)),
550 const char *arg, int unset)
552 unsigned char sha1[20];
554 if (unset) {
555 sha1_array_clear(&points_at);
556 return 0;
558 if (!arg)
559 return error(_("switch 'points-at' requires an object"));
560 if (get_sha1(arg, sha1))
561 return error(_("malformed object name '%s'"), arg);
562 sha1_array_append(&points_at, sha1);
563 return 0;
566 static int parse_opt_sort(const struct option *opt, const char *arg, int unset)
568 int *sort = opt->value;
570 return parse_sort_string(NULL, arg, sort);
573 int cmd_tag(int argc, const char **argv, const char *prefix)
575 struct strbuf buf = STRBUF_INIT;
576 struct strbuf ref = STRBUF_INIT;
577 unsigned char object[20], prev[20];
578 const char *object_ref, *tag;
579 struct create_tag_options opt;
580 char *cleanup_arg = NULL;
581 int annotate = 0, force = 0, lines = -1;
582 int cmdmode = 0;
583 const char *msgfile = NULL, *keyid = NULL;
584 struct msg_arg msg = { 0, STRBUF_INIT };
585 struct commit_list *with_commit = NULL;
586 struct ref_transaction *transaction;
587 struct strbuf err = STRBUF_INIT;
588 struct option options[] = {
589 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
590 { OPTION_INTEGER, 'n', NULL, &lines, N_("n"),
591 N_("print <n> lines of each tag message"),
592 PARSE_OPT_OPTARG, NULL, 1 },
593 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
594 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
596 OPT_GROUP(N_("Tag creation options")),
597 OPT_BOOL('a', "annotate", &annotate,
598 N_("annotated tag, needs a message")),
599 OPT_CALLBACK('m', "message", &msg, N_("message"),
600 N_("tag message"), parse_msg_arg),
601 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
602 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
603 OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
604 N_("how to strip spaces and #comments from message")),
605 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
606 N_("use another key to sign the tag")),
607 OPT__FORCE(&force, N_("replace the tag if exists")),
608 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
610 OPTION_CALLBACK, 0, "sort", &tag_sort, N_("type"), N_("sort tags"),
611 PARSE_OPT_NONEG, parse_opt_sort
614 OPT_GROUP(N_("Tag listing options")),
616 OPTION_CALLBACK, 0, "contains", &with_commit, N_("commit"),
617 N_("print only tags that contain the commit"),
618 PARSE_OPT_LASTARG_DEFAULT,
619 parse_opt_with_commit, (intptr_t)"HEAD",
622 OPTION_CALLBACK, 0, "with", &with_commit, N_("commit"),
623 N_("print only tags that contain the commit"),
624 PARSE_OPT_HIDDEN | PARSE_OPT_LASTARG_DEFAULT,
625 parse_opt_with_commit, (intptr_t)"HEAD",
628 OPTION_CALLBACK, 0, "points-at", NULL, N_("object"),
629 N_("print only tags of the object"), 0, parse_opt_points_at
631 OPT_END()
634 git_config(git_tag_config, NULL);
636 memset(&opt, 0, sizeof(opt));
638 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
640 if (keyid) {
641 opt.sign = 1;
642 set_signing_key(keyid);
644 if (opt.sign)
645 annotate = 1;
646 if (argc == 0 && !cmdmode)
647 cmdmode = 'l';
649 if ((annotate || msg.given || msgfile || force) && (cmdmode != 0))
650 usage_with_options(git_tag_usage, options);
652 finalize_colopts(&colopts, -1);
653 if (cmdmode == 'l' && lines != -1) {
654 if (explicitly_enable_column(colopts))
655 die(_("--column and -n are incompatible"));
656 colopts = 0;
658 if (cmdmode == 'l') {
659 int ret;
660 if (column_active(colopts)) {
661 struct column_options copts;
662 memset(&copts, 0, sizeof(copts));
663 copts.padding = 2;
664 run_column_filter(colopts, &copts);
666 if (lines != -1 && tag_sort)
667 die(_("--sort and -n are incompatible"));
668 ret = list_tags(argv, lines == -1 ? 0 : lines, with_commit, tag_sort);
669 if (column_active(colopts))
670 stop_column_filter();
671 return ret;
673 if (lines != -1)
674 die(_("-n option is only allowed with -l."));
675 if (with_commit)
676 die(_("--contains option is only allowed with -l."));
677 if (points_at.nr)
678 die(_("--points-at option is only allowed with -l."));
679 if (cmdmode == 'd')
680 return for_each_tag_name(argv, delete_tag);
681 if (cmdmode == 'v')
682 return for_each_tag_name(argv, verify_tag);
684 if (msg.given || msgfile) {
685 if (msg.given && msgfile)
686 die(_("only one -F or -m option is allowed."));
687 annotate = 1;
688 if (msg.given)
689 strbuf_addbuf(&buf, &(msg.buf));
690 else {
691 if (!strcmp(msgfile, "-")) {
692 if (strbuf_read(&buf, 0, 1024) < 0)
693 die_errno(_("cannot read '%s'"), msgfile);
694 } else {
695 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
696 die_errno(_("could not open or read '%s'"),
697 msgfile);
702 tag = argv[0];
704 object_ref = argc == 2 ? argv[1] : "HEAD";
705 if (argc > 2)
706 die(_("too many params"));
708 if (get_sha1(object_ref, object))
709 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
711 if (strbuf_check_tag_ref(&ref, tag))
712 die(_("'%s' is not a valid tag name."), tag);
714 if (read_ref(ref.buf, prev))
715 hashclr(prev);
716 else if (!force)
717 die(_("tag '%s' already exists"), tag);
719 opt.message_given = msg.given || msgfile;
721 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
722 opt.cleanup_mode = CLEANUP_ALL;
723 else if (!strcmp(cleanup_arg, "verbatim"))
724 opt.cleanup_mode = CLEANUP_NONE;
725 else if (!strcmp(cleanup_arg, "whitespace"))
726 opt.cleanup_mode = CLEANUP_SPACE;
727 else
728 die(_("Invalid cleanup mode %s"), cleanup_arg);
730 if (annotate)
731 create_tag(object, tag, &buf, &opt, prev, object);
733 transaction = ref_transaction_begin(&err);
734 if (!transaction ||
735 ref_transaction_update(transaction, ref.buf, object, prev,
736 0, 1, &err) ||
737 ref_transaction_commit(transaction, NULL, &err))
738 die("%s", err.buf);
739 ref_transaction_free(transaction);
740 if (force && !is_null_sha1(prev) && hashcmp(prev, object))
741 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
743 strbuf_release(&err);
744 strbuf_release(&buf);
745 strbuf_release(&ref);
746 return 0;