for-each-ref: add '--contains' option
[git/debian.git] / builtin / tag.c
blob071d001655c754b502ddcdf6f1625a053e32fa46
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;
60 * This is currently duplicated in ref-filter.c, and will eventually be
61 * removed as we port tag.c to use the ref-filter APIs.
63 static const unsigned char *match_points_at(const char *refname,
64 const unsigned char *sha1)
66 const unsigned char *tagged_sha1 = NULL;
67 struct object *obj;
69 if (sha1_array_lookup(&points_at, sha1) >= 0)
70 return sha1;
71 obj = parse_object(sha1);
72 if (!obj)
73 die(_("malformed object at '%s'"), refname);
74 if (obj->type == OBJ_TAG)
75 tagged_sha1 = ((struct tag *)obj)->tagged->sha1;
76 if (tagged_sha1 && sha1_array_lookup(&points_at, tagged_sha1) >= 0)
77 return tagged_sha1;
78 return NULL;
81 static int in_commit_list(const struct commit_list *want, struct commit *c)
83 for (; want; want = want->next)
84 if (!hashcmp(want->item->object.sha1, c->object.sha1))
85 return 1;
86 return 0;
90 * The entire code segment for supporting the --contains option has been
91 * copied over to ref-filter.{c,h}. This will be deleted evetually when
92 * we port tag.c to use ref-filter APIs.
94 enum contains_result {
95 CONTAINS_UNKNOWN = -1,
96 CONTAINS_NO = 0,
97 CONTAINS_YES = 1
101 * Test whether the candidate or one of its parents is contained in the list.
102 * Do not recurse to find out, though, but return -1 if inconclusive.
104 static enum contains_result contains_test(struct commit *candidate,
105 const struct commit_list *want)
107 /* was it previously marked as containing a want commit? */
108 if (candidate->object.flags & TMP_MARK)
109 return 1;
110 /* or marked as not possibly containing a want commit? */
111 if (candidate->object.flags & UNINTERESTING)
112 return 0;
113 /* or are we it? */
114 if (in_commit_list(want, candidate)) {
115 candidate->object.flags |= TMP_MARK;
116 return 1;
119 if (parse_commit(candidate) < 0)
120 return 0;
122 return -1;
126 * Mimicking the real stack, this stack lives on the heap, avoiding stack
127 * overflows.
129 * At each recursion step, the stack items points to the commits whose
130 * ancestors are to be inspected.
132 struct stack {
133 int nr, alloc;
134 struct stack_entry {
135 struct commit *commit;
136 struct commit_list *parents;
137 } *stack;
140 static void push_to_stack(struct commit *candidate, struct stack *stack)
142 int index = stack->nr++;
143 ALLOC_GROW(stack->stack, stack->nr, stack->alloc);
144 stack->stack[index].commit = candidate;
145 stack->stack[index].parents = candidate->parents;
148 static enum contains_result contains(struct commit *candidate,
149 const struct commit_list *want)
151 struct stack stack = { 0, 0, NULL };
152 int result = contains_test(candidate, want);
154 if (result != CONTAINS_UNKNOWN)
155 return result;
157 push_to_stack(candidate, &stack);
158 while (stack.nr) {
159 struct stack_entry *entry = &stack.stack[stack.nr - 1];
160 struct commit *commit = entry->commit;
161 struct commit_list *parents = entry->parents;
163 if (!parents) {
164 commit->object.flags |= UNINTERESTING;
165 stack.nr--;
168 * If we just popped the stack, parents->item has been marked,
169 * therefore contains_test will return a meaningful 0 or 1.
171 else switch (contains_test(parents->item, want)) {
172 case CONTAINS_YES:
173 commit->object.flags |= TMP_MARK;
174 stack.nr--;
175 break;
176 case CONTAINS_NO:
177 entry->parents = parents->next;
178 break;
179 case CONTAINS_UNKNOWN:
180 push_to_stack(parents->item, &stack);
181 break;
184 free(stack.stack);
185 return contains_test(candidate, want);
188 static void show_tag_lines(const struct object_id *oid, int lines)
190 int i;
191 unsigned long size;
192 enum object_type type;
193 char *buf, *sp, *eol;
194 size_t len;
196 buf = read_sha1_file(oid->hash, &type, &size);
197 if (!buf)
198 die_errno("unable to read object %s", oid_to_hex(oid));
199 if (type != OBJ_COMMIT && type != OBJ_TAG)
200 goto free_return;
201 if (!size)
202 die("an empty %s object %s?",
203 typename(type), oid_to_hex(oid));
205 /* skip header */
206 sp = strstr(buf, "\n\n");
207 if (!sp)
208 goto free_return;
210 /* only take up to "lines" lines, and strip the signature from a tag */
211 if (type == OBJ_TAG)
212 size = parse_signature(buf, size);
213 for (i = 0, sp += 2; i < lines && sp < buf + size; i++) {
214 if (i)
215 printf("\n ");
216 eol = memchr(sp, '\n', size - (sp - buf));
217 len = eol ? eol - sp : size - (sp - buf);
218 fwrite(sp, len, 1, stdout);
219 if (!eol)
220 break;
221 sp = eol + 1;
223 free_return:
224 free(buf);
227 static int show_reference(const char *refname, const struct object_id *oid,
228 int flag, void *cb_data)
230 struct tag_filter *filter = cb_data;
232 if (match_pattern(filter->patterns, refname)) {
233 if (filter->with_commit) {
234 struct commit *commit;
236 commit = lookup_commit_reference_gently(oid->hash, 1);
237 if (!commit)
238 return 0;
239 if (!contains(commit, filter->with_commit))
240 return 0;
243 if (points_at.nr && !match_points_at(refname, oid->hash))
244 return 0;
246 if (!filter->lines) {
247 if (filter->sort)
248 string_list_append(&filter->tags, refname);
249 else
250 printf("%s\n", refname);
251 return 0;
253 printf("%-15s ", refname);
254 show_tag_lines(oid, filter->lines);
255 putchar('\n');
258 return 0;
261 static int sort_by_version(const void *a_, const void *b_)
263 const struct string_list_item *a = a_;
264 const struct string_list_item *b = b_;
265 return versioncmp(a->string, b->string);
268 static int list_tags(const char **patterns, int lines,
269 struct commit_list *with_commit, int sort)
271 struct tag_filter filter;
273 filter.patterns = patterns;
274 filter.lines = lines;
275 filter.sort = sort;
276 filter.with_commit = with_commit;
277 memset(&filter.tags, 0, sizeof(filter.tags));
278 filter.tags.strdup_strings = 1;
280 for_each_tag_ref(show_reference, (void *)&filter);
281 if (sort) {
282 int i;
283 if ((sort & SORT_MASK) == VERCMP_SORT)
284 qsort(filter.tags.items, filter.tags.nr,
285 sizeof(struct string_list_item), sort_by_version);
286 if (sort & REVERSE_SORT)
287 for (i = filter.tags.nr - 1; i >= 0; i--)
288 printf("%s\n", filter.tags.items[i].string);
289 else
290 for (i = 0; i < filter.tags.nr; i++)
291 printf("%s\n", filter.tags.items[i].string);
292 string_list_clear(&filter.tags, 0);
294 return 0;
297 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
298 const unsigned char *sha1);
300 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
302 const char **p;
303 char ref[PATH_MAX];
304 int had_error = 0;
305 unsigned char sha1[20];
307 for (p = argv; *p; p++) {
308 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
309 >= sizeof(ref)) {
310 error(_("tag name too long: %.*s..."), 50, *p);
311 had_error = 1;
312 continue;
314 if (read_ref(ref, sha1)) {
315 error(_("tag '%s' not found."), *p);
316 had_error = 1;
317 continue;
319 if (fn(*p, ref, sha1))
320 had_error = 1;
322 return had_error;
325 static int delete_tag(const char *name, const char *ref,
326 const unsigned char *sha1)
328 if (delete_ref(ref, sha1, 0))
329 return 1;
330 printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
331 return 0;
334 static int verify_tag(const char *name, const char *ref,
335 const unsigned char *sha1)
337 const char *argv_verify_tag[] = {"verify-tag",
338 "-v", "SHA1_HEX", NULL};
339 argv_verify_tag[2] = sha1_to_hex(sha1);
341 if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
342 return error(_("could not verify the tag '%s'"), name);
343 return 0;
346 static int do_sign(struct strbuf *buffer)
348 return sign_buffer(buffer, buffer, get_signing_key());
351 static const char tag_template[] =
352 N_("\nWrite a message for tag:\n %s\n"
353 "Lines starting with '%c' will be ignored.\n");
355 static const char tag_template_nocleanup[] =
356 N_("\nWrite a message for tag:\n %s\n"
357 "Lines starting with '%c' will be kept; you may remove them"
358 " yourself if you want to.\n");
361 * Parse a sort string, and return 0 if parsed successfully. Will return
362 * non-zero when the sort string does not parse into a known type. If var is
363 * given, the error message becomes a warning and includes information about
364 * the configuration value.
366 static int parse_sort_string(const char *var, const char *arg, int *sort)
368 int type = 0, flags = 0;
370 if (skip_prefix(arg, "-", &arg))
371 flags |= REVERSE_SORT;
373 if (skip_prefix(arg, "version:", &arg) || skip_prefix(arg, "v:", &arg))
374 type = VERCMP_SORT;
375 else
376 type = STRCMP_SORT;
378 if (strcmp(arg, "refname")) {
379 if (!var)
380 return error(_("unsupported sort specification '%s'"), arg);
381 else {
382 warning(_("unsupported sort specification '%s' in variable '%s'"),
383 var, arg);
384 return -1;
388 *sort = (type | flags);
390 return 0;
393 static int git_tag_config(const char *var, const char *value, void *cb)
395 int status;
397 if (!strcmp(var, "tag.sort")) {
398 if (!value)
399 return config_error_nonbool(var);
400 parse_sort_string(var, value, &tag_sort);
401 return 0;
404 status = git_gpg_config(var, value, cb);
405 if (status)
406 return status;
407 if (starts_with(var, "column."))
408 return git_column_config(var, value, "tag", &colopts);
409 return git_default_config(var, value, cb);
412 static void write_tag_body(int fd, const unsigned char *sha1)
414 unsigned long size;
415 enum object_type type;
416 char *buf, *sp;
418 buf = read_sha1_file(sha1, &type, &size);
419 if (!buf)
420 return;
421 /* skip header */
422 sp = strstr(buf, "\n\n");
424 if (!sp || !size || type != OBJ_TAG) {
425 free(buf);
426 return;
428 sp += 2; /* skip the 2 LFs */
429 write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
431 free(buf);
434 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
436 if (sign && do_sign(buf) < 0)
437 return error(_("unable to sign the tag"));
438 if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
439 return error(_("unable to write tag file"));
440 return 0;
443 struct create_tag_options {
444 unsigned int message_given:1;
445 unsigned int sign;
446 enum {
447 CLEANUP_NONE,
448 CLEANUP_SPACE,
449 CLEANUP_ALL
450 } cleanup_mode;
453 static void create_tag(const unsigned char *object, const char *tag,
454 struct strbuf *buf, struct create_tag_options *opt,
455 unsigned char *prev, unsigned char *result)
457 enum object_type type;
458 char header_buf[1024];
459 int header_len;
460 char *path = NULL;
462 type = sha1_object_info(object, NULL);
463 if (type <= OBJ_NONE)
464 die(_("bad object type."));
466 header_len = snprintf(header_buf, sizeof(header_buf),
467 "object %s\n"
468 "type %s\n"
469 "tag %s\n"
470 "tagger %s\n\n",
471 sha1_to_hex(object),
472 typename(type),
473 tag,
474 git_committer_info(IDENT_STRICT));
476 if (header_len > sizeof(header_buf) - 1)
477 die(_("tag header too big."));
479 if (!opt->message_given) {
480 int fd;
482 /* write the template message before editing: */
483 path = git_pathdup("TAG_EDITMSG");
484 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
485 if (fd < 0)
486 die_errno(_("could not create file '%s'"), path);
488 if (!is_null_sha1(prev)) {
489 write_tag_body(fd, prev);
490 } else {
491 struct strbuf buf = STRBUF_INIT;
492 strbuf_addch(&buf, '\n');
493 if (opt->cleanup_mode == CLEANUP_ALL)
494 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
495 else
496 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
497 write_or_die(fd, buf.buf, buf.len);
498 strbuf_release(&buf);
500 close(fd);
502 if (launch_editor(path, buf, NULL)) {
503 fprintf(stderr,
504 _("Please supply the message using either -m or -F option.\n"));
505 exit(1);
509 if (opt->cleanup_mode != CLEANUP_NONE)
510 stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
512 if (!opt->message_given && !buf->len)
513 die(_("no tag message?"));
515 strbuf_insert(buf, 0, header_buf, header_len);
517 if (build_tag_object(buf, opt->sign, result) < 0) {
518 if (path)
519 fprintf(stderr, _("The tag message has been left in %s\n"),
520 path);
521 exit(128);
523 if (path) {
524 unlink_or_warn(path);
525 free(path);
529 struct msg_arg {
530 int given;
531 struct strbuf buf;
534 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
536 struct msg_arg *msg = opt->value;
538 if (!arg)
539 return -1;
540 if (msg->buf.len)
541 strbuf_addstr(&(msg->buf), "\n\n");
542 strbuf_addstr(&(msg->buf), arg);
543 msg->given = 1;
544 return 0;
547 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
549 if (name[0] == '-')
550 return -1;
552 strbuf_reset(sb);
553 strbuf_addf(sb, "refs/tags/%s", name);
555 return check_refname_format(sb->buf, 0);
558 static int parse_opt_sort(const struct option *opt, const char *arg, int unset)
560 int *sort = opt->value;
562 return parse_sort_string(NULL, arg, sort);
565 int cmd_tag(int argc, const char **argv, const char *prefix)
567 struct strbuf buf = STRBUF_INIT;
568 struct strbuf ref = STRBUF_INIT;
569 unsigned char object[20], prev[20];
570 const char *object_ref, *tag;
571 struct create_tag_options opt;
572 char *cleanup_arg = NULL;
573 int annotate = 0, force = 0, lines = -1;
574 int cmdmode = 0;
575 const char *msgfile = NULL, *keyid = NULL;
576 struct msg_arg msg = { 0, STRBUF_INIT };
577 struct commit_list *with_commit = NULL;
578 struct ref_transaction *transaction;
579 struct strbuf err = STRBUF_INIT;
580 struct option options[] = {
581 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
582 { OPTION_INTEGER, 'n', NULL, &lines, N_("n"),
583 N_("print <n> lines of each tag message"),
584 PARSE_OPT_OPTARG, NULL, 1 },
585 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
586 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
588 OPT_GROUP(N_("Tag creation options")),
589 OPT_BOOL('a', "annotate", &annotate,
590 N_("annotated tag, needs a message")),
591 OPT_CALLBACK('m', "message", &msg, N_("message"),
592 N_("tag message"), parse_msg_arg),
593 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
594 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
595 OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
596 N_("how to strip spaces and #comments from message")),
597 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
598 N_("use another key to sign the tag")),
599 OPT__FORCE(&force, N_("replace the tag if exists")),
601 OPT_GROUP(N_("Tag listing options")),
602 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
603 OPT_CONTAINS(&with_commit, N_("print only tags that contain the commit")),
604 OPT_WITH(&with_commit, N_("print only tags that contain the commit")),
606 OPTION_CALLBACK, 0, "sort", &tag_sort, N_("type"), N_("sort tags"),
607 PARSE_OPT_NONEG, parse_opt_sort
610 OPTION_CALLBACK, 0, "points-at", &points_at, N_("object"),
611 N_("print only tags of the object"), 0, parse_opt_object_name
613 OPT_END()
616 git_config(git_tag_config, NULL);
618 memset(&opt, 0, sizeof(opt));
620 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
622 if (keyid) {
623 opt.sign = 1;
624 set_signing_key(keyid);
626 if (opt.sign)
627 annotate = 1;
628 if (argc == 0 && !cmdmode)
629 cmdmode = 'l';
631 if ((annotate || msg.given || msgfile || force) && (cmdmode != 0))
632 usage_with_options(git_tag_usage, options);
634 finalize_colopts(&colopts, -1);
635 if (cmdmode == 'l' && lines != -1) {
636 if (explicitly_enable_column(colopts))
637 die(_("--column and -n are incompatible"));
638 colopts = 0;
640 if (cmdmode == 'l') {
641 int ret;
642 if (column_active(colopts)) {
643 struct column_options copts;
644 memset(&copts, 0, sizeof(copts));
645 copts.padding = 2;
646 run_column_filter(colopts, &copts);
648 if (lines != -1 && tag_sort)
649 die(_("--sort and -n are incompatible"));
650 ret = list_tags(argv, lines == -1 ? 0 : lines, with_commit, tag_sort);
651 if (column_active(colopts))
652 stop_column_filter();
653 return ret;
655 if (lines != -1)
656 die(_("-n option is only allowed with -l."));
657 if (with_commit)
658 die(_("--contains option is only allowed with -l."));
659 if (points_at.nr)
660 die(_("--points-at option is only allowed with -l."));
661 if (cmdmode == 'd')
662 return for_each_tag_name(argv, delete_tag);
663 if (cmdmode == 'v')
664 return for_each_tag_name(argv, verify_tag);
666 if (msg.given || msgfile) {
667 if (msg.given && msgfile)
668 die(_("only one -F or -m option is allowed."));
669 annotate = 1;
670 if (msg.given)
671 strbuf_addbuf(&buf, &(msg.buf));
672 else {
673 if (!strcmp(msgfile, "-")) {
674 if (strbuf_read(&buf, 0, 1024) < 0)
675 die_errno(_("cannot read '%s'"), msgfile);
676 } else {
677 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
678 die_errno(_("could not open or read '%s'"),
679 msgfile);
684 tag = argv[0];
686 object_ref = argc == 2 ? argv[1] : "HEAD";
687 if (argc > 2)
688 die(_("too many params"));
690 if (get_sha1(object_ref, object))
691 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
693 if (strbuf_check_tag_ref(&ref, tag))
694 die(_("'%s' is not a valid tag name."), tag);
696 if (read_ref(ref.buf, prev))
697 hashclr(prev);
698 else if (!force)
699 die(_("tag '%s' already exists"), tag);
701 opt.message_given = msg.given || msgfile;
703 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
704 opt.cleanup_mode = CLEANUP_ALL;
705 else if (!strcmp(cleanup_arg, "verbatim"))
706 opt.cleanup_mode = CLEANUP_NONE;
707 else if (!strcmp(cleanup_arg, "whitespace"))
708 opt.cleanup_mode = CLEANUP_SPACE;
709 else
710 die(_("Invalid cleanup mode %s"), cleanup_arg);
712 if (annotate)
713 create_tag(object, tag, &buf, &opt, prev, object);
715 transaction = ref_transaction_begin(&err);
716 if (!transaction ||
717 ref_transaction_update(transaction, ref.buf, object, prev,
718 0, NULL, &err) ||
719 ref_transaction_commit(transaction, &err))
720 die("%s", err.buf);
721 ref_transaction_free(transaction);
722 if (force && !is_null_sha1(prev) && hashcmp(prev, object))
723 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
725 strbuf_release(&err);
726 strbuf_release(&buf);
727 strbuf_release(&ref);
728 return 0;