ref-filter: implement '--contains' option
[git/git.git] / builtin / tag.c
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
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
28 };
29
30 #define STRCMP_SORT 0 /* must be zero */
31 #define VERCMP_SORT 1
32 #define SORT_MASK 0x7fff
33 #define REVERSE_SORT 0x8000
34
35 static int tag_sort;
36
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;
43 };
44
45 static struct sha1_array points_at;
46 static unsigned int colopts;
47
48 static int match_pattern(const char **patterns, const char *ref)
49 {
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;
57 }
58
59 /*
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.
62 */
63 static const unsigned char *match_points_at(const char *refname,
64 const unsigned char *sha1)
65 {
66 const unsigned char *tagged_sha1 = NULL;
67 struct object *obj;
68
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;
79 }
80
81 static int in_commit_list(const struct commit_list *want, struct commit *c)
82 {
83 for (; want; want = want->next)
84 if (!hashcmp(want->item->object.sha1, c->object.sha1))
85 return 1;
86 return 0;
87 }
88
89 /*
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.
93 */
94 enum contains_result {
95 CONTAINS_UNKNOWN = -1,
96 CONTAINS_NO = 0,
97 CONTAINS_YES = 1
98 };
99
100 /*
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.
103 */
104 static enum contains_result contains_test(struct commit *candidate,
105 const struct commit_list *want)
106 {
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;
117 }
118
119 if (parse_commit(candidate) < 0)
120 return 0;
121
122 return -1;
123 }
124
125 /*
126 * Mimicking the real stack, this stack lives on the heap, avoiding stack
127 * overflows.
128 *
129 * At each recursion step, the stack items points to the commits whose
130 * ancestors are to be inspected.
131 */
132 struct stack {
133 int nr, alloc;
134 struct stack_entry {
135 struct commit *commit;
136 struct commit_list *parents;
137 } *stack;
138 };
139
140 static void push_to_stack(struct commit *candidate, struct stack *stack)
141 {
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;
146 }
147
148 static enum contains_result contains(struct commit *candidate,
149 const struct commit_list *want)
150 {
151 struct stack stack = { 0, 0, NULL };
152 int result = contains_test(candidate, want);
153
154 if (result != CONTAINS_UNKNOWN)
155 return result;
156
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;
162
163 if (!parents) {
164 commit->object.flags |= UNINTERESTING;
165 stack.nr--;
166 }
167 /*
168 * If we just popped the stack, parents->item has been marked,
169 * therefore contains_test will return a meaningful 0 or 1.
170 */
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;
182 }
183 }
184 free(stack.stack);
185 return contains_test(candidate, want);
186 }
187
188 static void show_tag_lines(const struct object_id *oid, int lines)
189 {
190 int i;
191 unsigned long size;
192 enum object_type type;
193 char *buf, *sp, *eol;
194 size_t len;
195
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));
204
205 /* skip header */
206 sp = strstr(buf, "\n\n");
207 if (!sp)
208 goto free_return;
209
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;
222 }
223 free_return:
224 free(buf);
225 }
226
227 static int show_reference(const char *refname, const struct object_id *oid,
228 int flag, void *cb_data)
229 {
230 struct tag_filter *filter = cb_data;
231
232 if (match_pattern(filter->patterns, refname)) {
233 if (filter->with_commit) {
234 struct commit *commit;
235
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;
241 }
242
243 if (points_at.nr && !match_points_at(refname, oid->hash))
244 return 0;
245
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;
252 }
253 printf("%-15s ", refname);
254 show_tag_lines(oid, filter->lines);
255 putchar('\n');
256 }
257
258 return 0;
259 }
260
261 static int sort_by_version(const void *a_, const void *b_)
262 {
263 const struct string_list_item *a = a_;
264 const struct string_list_item *b = b_;
265 return versioncmp(a->string, b->string);
266 }
267
268 static int list_tags(const char **patterns, int lines,
269 struct commit_list *with_commit, int sort)
270 {
271 struct tag_filter filter;
272
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;
279
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);
293 }
294 return 0;
295 }
296
297 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
298 const unsigned char *sha1);
299
300 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
301 {
302 const char **p;
303 char ref[PATH_MAX];
304 int had_error = 0;
305 unsigned char sha1[20];
306
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;
313 }
314 if (read_ref(ref, sha1)) {
315 error(_("tag '%s' not found."), *p);
316 had_error = 1;
317 continue;
318 }
319 if (fn(*p, ref, sha1))
320 had_error = 1;
321 }
322 return had_error;
323 }
324
325 static int delete_tag(const char *name, const char *ref,
326 const unsigned char *sha1)
327 {
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;
332 }
333
334 static int verify_tag(const char *name, const char *ref,
335 const unsigned char *sha1)
336 {
337 const char *argv_verify_tag[] = {"verify-tag",
338 "-v", "SHA1_HEX", NULL};
339 argv_verify_tag[2] = sha1_to_hex(sha1);
340
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;
344 }
345
346 static int do_sign(struct strbuf *buffer)
347 {
348 return sign_buffer(buffer, buffer, get_signing_key());
349 }
350
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");
354
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");
359
360 /*
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.
365 */
366 static int parse_sort_string(const char *var, const char *arg, int *sort)
367 {
368 int type = 0, flags = 0;
369
370 if (skip_prefix(arg, "-", &arg))
371 flags |= REVERSE_SORT;
372
373 if (skip_prefix(arg, "version:", &arg) || skip_prefix(arg, "v:", &arg))
374 type = VERCMP_SORT;
375 else
376 type = STRCMP_SORT;
377
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;
385 }
386 }
387
388 *sort = (type | flags);
389
390 return 0;
391 }
392
393 static int git_tag_config(const char *var, const char *value, void *cb)
394 {
395 int status;
396
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;
402 }
403
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);
410 }
411
412 static void write_tag_body(int fd, const unsigned char *sha1)
413 {
414 unsigned long size;
415 enum object_type type;
416 char *buf, *sp;
417
418 buf = read_sha1_file(sha1, &type, &size);
419 if (!buf)
420 return;
421 /* skip header */
422 sp = strstr(buf, "\n\n");
423
424 if (!sp || !size || type != OBJ_TAG) {
425 free(buf);
426 return;
427 }
428 sp += 2; /* skip the 2 LFs */
429 write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
430
431 free(buf);
432 }
433
434 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
435 {
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;
441 }
442
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;
451 };
452
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)
456 {
457 enum object_type type;
458 char header_buf[1024];
459 int header_len;
460 char *path = NULL;
461
462 type = sha1_object_info(object, NULL);
463 if (type <= OBJ_NONE)
464 die(_("bad object type."));
465
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));
475
476 if (header_len > sizeof(header_buf) - 1)
477 die(_("tag header too big."));
478
479 if (!opt->message_given) {
480 int fd;
481
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);
487
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);
499 }
500 close(fd);
501
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);
506 }
507 }
508
509 if (opt->cleanup_mode != CLEANUP_NONE)
510 stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
511
512 if (!opt->message_given && !buf->len)
513 die(_("no tag message?"));
514
515 strbuf_insert(buf, 0, header_buf, header_len);
516
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);
522 }
523 if (path) {
524 unlink_or_warn(path);
525 free(path);
526 }
527 }
528
529 struct msg_arg {
530 int given;
531 struct strbuf buf;
532 };
533
534 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
535 {
536 struct msg_arg *msg = opt->value;
537
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;
545 }
546
547 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
548 {
549 if (name[0] == '-')
550 return -1;
551
552 strbuf_reset(sb);
553 strbuf_addf(sb, "refs/tags/%s", name);
554
555 return check_refname_format(sb->buf, 0);
556 }
557
558 static int parse_opt_sort(const struct option *opt, const char *arg, int unset)
559 {
560 int *sort = opt->value;
561
562 return parse_sort_string(NULL, arg, sort);
563 }
564
565 int cmd_tag(int argc, const char **argv, const char *prefix)
566 {
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'),
587
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")),
600
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")),
605 {
606 OPTION_CALLBACK, 0, "sort", &tag_sort, N_("type"), N_("sort tags"),
607 PARSE_OPT_NONEG, parse_opt_sort
608 },
609 {
610 OPTION_CALLBACK, 0, "points-at", &points_at, N_("object"),
611 N_("print only tags of the object"), 0, parse_opt_object_name
612 },
613 OPT_END()
614 };
615
616 git_config(git_tag_config, NULL);
617
618 memset(&opt, 0, sizeof(opt));
619
620 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
621
622 if (keyid) {
623 opt.sign = 1;
624 set_signing_key(keyid);
625 }
626 if (opt.sign)
627 annotate = 1;
628 if (argc == 0 && !cmdmode)
629 cmdmode = 'l';
630
631 if ((annotate || msg.given || msgfile || force) && (cmdmode != 0))
632 usage_with_options(git_tag_usage, options);
633
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;
639 }
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);
647 }
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;
654 }
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);
665
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);
680 }
681 }
682 }
683
684 tag = argv[0];
685
686 object_ref = argc == 2 ? argv[1] : "HEAD";
687 if (argc > 2)
688 die(_("too many params"));
689
690 if (get_sha1(object_ref, object))
691 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
692
693 if (strbuf_check_tag_ref(&ref, tag))
694 die(_("'%s' is not a valid tag name."), tag);
695
696 if (read_ref(ref.buf, prev))
697 hashclr(prev);
698 else if (!force)
699 die(_("tag '%s' already exists"), tag);
700
701 opt.message_given = msg.given || msgfile;
702
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);
711
712 if (annotate)
713 create_tag(object, tag, &buf, &opt, prev, object);
714
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));
724
725 strbuf_release(&err);
726 strbuf_release(&buf);
727 strbuf_release(&ref);
728 return 0;
729 }