Touch up the comments in the 'tag-contains' branch
[git/mingw/4msysgit.git] / builtin / tag.c
blob79c8c28616a41d9d7189d821e6b0ce4d9ab3d3ae
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 struct tag_filter {
31 const char **patterns;
32 int lines;
33 struct commit_list *with_commit;
36 static struct sha1_array points_at;
37 static unsigned int colopts;
39 static int match_pattern(const char **patterns, const char *ref)
41 /* no pattern means match everything */
42 if (!*patterns)
43 return 1;
44 for (; *patterns; patterns++)
45 if (!fnmatch(*patterns, ref, 0))
46 return 1;
47 return 0;
50 static const unsigned char *match_points_at(const char *refname,
51 const unsigned char *sha1)
53 const unsigned char *tagged_sha1 = NULL;
54 struct object *obj;
56 if (sha1_array_lookup(&points_at, sha1) >= 0)
57 return sha1;
58 obj = parse_object(sha1);
59 if (!obj)
60 die(_("malformed object at '%s'"), refname);
61 if (obj->type == OBJ_TAG)
62 tagged_sha1 = ((struct tag *)obj)->tagged->sha1;
63 if (tagged_sha1 && sha1_array_lookup(&points_at, tagged_sha1) >= 0)
64 return tagged_sha1;
65 return NULL;
68 static int in_commit_list(const struct commit_list *want, struct commit *c)
70 for (; want; want = want->next)
71 if (!hashcmp(want->item->object.sha1, c->object.sha1))
72 return 1;
73 return 0;
77 * Test whether the candidate or one of its parents is contained in the list.
78 * Do not recurse to find out, though, but return -1 if inconclusive.
80 static int contains_test(struct commit *candidate,
81 const struct commit_list *want)
83 /* was it previously marked as containing a want commit? */
84 if (candidate->object.flags & TMP_MARK)
85 return 1;
86 /* or marked as not possibly containing a want commit? */
87 if (candidate->object.flags & UNINTERESTING)
88 return 0;
89 /* or are we it? */
90 if (in_commit_list(want, candidate)) {
91 candidate->object.flags |= TMP_MARK;
92 return 1;
95 if (parse_commit(candidate) < 0)
96 return 0;
98 return -1;
102 * Mimicking the real stack, this stack lives on the heap, avoiding stack
103 * overflows.
105 * At each recursion step, the stack items points to the commits whose
106 * ancestors are to be inspected.
108 struct stack {
109 int nr, alloc;
110 struct stack_entry {
111 struct commit *commit;
112 struct commit_list *parents;
113 } *stack;
116 static void push_to_stack(struct commit *candidate, struct stack *stack)
118 int index = stack->nr++;
119 ALLOC_GROW(stack->stack, stack->nr, stack->alloc);
120 stack->stack[index].commit = candidate;
121 stack->stack[index].parents = candidate->parents;
124 static int contains(struct commit *candidate, const struct commit_list *want)
126 struct stack stack = { 0, 0, NULL };
127 int result = contains_test(candidate, want);
129 if (result >= 0)
130 return result;
132 push_to_stack(candidate, &stack);
133 while (stack.nr) {
134 struct stack_entry *entry = &stack.stack[stack.nr - 1];
135 struct commit *commit = entry->commit;
136 struct commit_list *parents = entry->parents;
138 if (!parents) {
139 commit->object.flags = UNINTERESTING;
140 stack.nr--;
143 * If we just popped the stack, parents->item has been marked,
144 * therefore contains_test will return a meaningful 0 or 1.
146 else switch (contains_test(parents->item, want)) {
147 case 1:
148 commit->object.flags |= TMP_MARK;
149 stack.nr--;
150 break;
151 case 0:
152 entry->parents = parents->next;
153 break;
154 default:
155 push_to_stack(parents->item, &stack);
156 break;
159 free(stack.stack);
160 return contains_test(candidate, want);
163 static void show_tag_lines(const unsigned char *sha1, int lines)
165 int i;
166 unsigned long size;
167 enum object_type type;
168 char *buf, *sp, *eol;
169 size_t len;
171 buf = read_sha1_file(sha1, &type, &size);
172 if (!buf)
173 die_errno("unable to read object %s", sha1_to_hex(sha1));
174 if (type != OBJ_COMMIT && type != OBJ_TAG)
175 goto free_return;
176 if (!size)
177 die("an empty %s object %s?",
178 typename(type), sha1_to_hex(sha1));
180 /* skip header */
181 sp = strstr(buf, "\n\n");
182 if (!sp)
183 goto free_return;
185 /* only take up to "lines" lines, and strip the signature from a tag */
186 if (type == OBJ_TAG)
187 size = parse_signature(buf, size);
188 for (i = 0, sp += 2; i < lines && sp < buf + size; i++) {
189 if (i)
190 printf("\n ");
191 eol = memchr(sp, '\n', size - (sp - buf));
192 len = eol ? eol - sp : size - (sp - buf);
193 fwrite(sp, len, 1, stdout);
194 if (!eol)
195 break;
196 sp = eol + 1;
198 free_return:
199 free(buf);
202 static int show_reference(const char *refname, const unsigned char *sha1,
203 int flag, void *cb_data)
205 struct tag_filter *filter = cb_data;
207 if (match_pattern(filter->patterns, refname)) {
208 if (filter->with_commit) {
209 struct commit *commit;
211 commit = lookup_commit_reference_gently(sha1, 1);
212 if (!commit)
213 return 0;
214 if (!contains(commit, filter->with_commit))
215 return 0;
218 if (points_at.nr && !match_points_at(refname, sha1))
219 return 0;
221 if (!filter->lines) {
222 printf("%s\n", refname);
223 return 0;
225 printf("%-15s ", refname);
226 show_tag_lines(sha1, filter->lines);
227 putchar('\n');
230 return 0;
233 static int list_tags(const char **patterns, int lines,
234 struct commit_list *with_commit)
236 struct tag_filter filter;
238 filter.patterns = patterns;
239 filter.lines = lines;
240 filter.with_commit = with_commit;
242 for_each_tag_ref(show_reference, (void *) &filter);
244 return 0;
247 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
248 const unsigned char *sha1);
250 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
252 const char **p;
253 char ref[PATH_MAX];
254 int had_error = 0;
255 unsigned char sha1[20];
257 for (p = argv; *p; p++) {
258 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
259 >= sizeof(ref)) {
260 error(_("tag name too long: %.*s..."), 50, *p);
261 had_error = 1;
262 continue;
264 if (read_ref(ref, sha1)) {
265 error(_("tag '%s' not found."), *p);
266 had_error = 1;
267 continue;
269 if (fn(*p, ref, sha1))
270 had_error = 1;
272 return had_error;
275 static int delete_tag(const char *name, const char *ref,
276 const unsigned char *sha1)
278 if (delete_ref(ref, sha1, 0))
279 return 1;
280 printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
281 return 0;
284 static int verify_tag(const char *name, const char *ref,
285 const unsigned char *sha1)
287 const char *argv_verify_tag[] = {"verify-tag",
288 "-v", "SHA1_HEX", NULL};
289 argv_verify_tag[2] = sha1_to_hex(sha1);
291 if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
292 return error(_("could not verify the tag '%s'"), name);
293 return 0;
296 static int do_sign(struct strbuf *buffer)
298 return sign_buffer(buffer, buffer, get_signing_key());
301 static const char tag_template[] =
302 N_("\nWrite a tag message\n"
303 "Lines starting with '%c' will be ignored.\n");
305 static const char tag_template_nocleanup[] =
306 N_("\nWrite a tag message\n"
307 "Lines starting with '%c' will be kept; you may remove them"
308 " yourself if you want to.\n");
310 static int git_tag_config(const char *var, const char *value, void *cb)
312 int status = git_gpg_config(var, value, cb);
313 if (status)
314 return status;
315 if (starts_with(var, "column."))
316 return git_column_config(var, value, "tag", &colopts);
317 return git_default_config(var, value, cb);
320 static void write_tag_body(int fd, const unsigned char *sha1)
322 unsigned long size;
323 enum object_type type;
324 char *buf, *sp;
326 buf = read_sha1_file(sha1, &type, &size);
327 if (!buf)
328 return;
329 /* skip header */
330 sp = strstr(buf, "\n\n");
332 if (!sp || !size || type != OBJ_TAG) {
333 free(buf);
334 return;
336 sp += 2; /* skip the 2 LFs */
337 write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
339 free(buf);
342 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
344 if (sign && do_sign(buf) < 0)
345 return error(_("unable to sign the tag"));
346 if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
347 return error(_("unable to write tag file"));
348 return 0;
351 struct create_tag_options {
352 unsigned int message_given:1;
353 unsigned int sign;
354 enum {
355 CLEANUP_NONE,
356 CLEANUP_SPACE,
357 CLEANUP_ALL
358 } cleanup_mode;
361 static void create_tag(const unsigned char *object, const char *tag,
362 struct strbuf *buf, struct create_tag_options *opt,
363 unsigned char *prev, unsigned char *result)
365 enum object_type type;
366 char header_buf[1024];
367 int header_len;
368 char *path = NULL;
370 type = sha1_object_info(object, NULL);
371 if (type <= OBJ_NONE)
372 die(_("bad object type."));
374 header_len = snprintf(header_buf, sizeof(header_buf),
375 "object %s\n"
376 "type %s\n"
377 "tag %s\n"
378 "tagger %s\n\n",
379 sha1_to_hex(object),
380 typename(type),
381 tag,
382 git_committer_info(IDENT_STRICT));
384 if (header_len > sizeof(header_buf) - 1)
385 die(_("tag header too big."));
387 if (!opt->message_given) {
388 int fd;
390 /* write the template message before editing: */
391 path = git_pathdup("TAG_EDITMSG");
392 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
393 if (fd < 0)
394 die_errno(_("could not create file '%s'"), path);
396 if (!is_null_sha1(prev)) {
397 write_tag_body(fd, prev);
398 } else {
399 struct strbuf buf = STRBUF_INIT;
400 strbuf_addch(&buf, '\n');
401 if (opt->cleanup_mode == CLEANUP_ALL)
402 strbuf_commented_addf(&buf, _(tag_template), comment_line_char);
403 else
404 strbuf_commented_addf(&buf, _(tag_template_nocleanup), comment_line_char);
405 write_or_die(fd, buf.buf, buf.len);
406 strbuf_release(&buf);
408 close(fd);
410 if (launch_editor(path, buf, NULL)) {
411 fprintf(stderr,
412 _("Please supply the message using either -m or -F option.\n"));
413 exit(1);
417 if (opt->cleanup_mode != CLEANUP_NONE)
418 stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
420 if (!opt->message_given && !buf->len)
421 die(_("no tag message?"));
423 strbuf_insert(buf, 0, header_buf, header_len);
425 if (build_tag_object(buf, opt->sign, result) < 0) {
426 if (path)
427 fprintf(stderr, _("The tag message has been left in %s\n"),
428 path);
429 exit(128);
431 if (path) {
432 unlink_or_warn(path);
433 free(path);
437 struct msg_arg {
438 int given;
439 struct strbuf buf;
442 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
444 struct msg_arg *msg = opt->value;
446 if (!arg)
447 return -1;
448 if (msg->buf.len)
449 strbuf_addstr(&(msg->buf), "\n\n");
450 strbuf_addstr(&(msg->buf), arg);
451 msg->given = 1;
452 return 0;
455 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
457 if (name[0] == '-')
458 return -1;
460 strbuf_reset(sb);
461 strbuf_addf(sb, "refs/tags/%s", name);
463 return check_refname_format(sb->buf, 0);
466 static int parse_opt_points_at(const struct option *opt __attribute__((unused)),
467 const char *arg, int unset)
469 unsigned char sha1[20];
471 if (unset) {
472 sha1_array_clear(&points_at);
473 return 0;
475 if (!arg)
476 return error(_("switch 'points-at' requires an object"));
477 if (get_sha1(arg, sha1))
478 return error(_("malformed object name '%s'"), arg);
479 sha1_array_append(&points_at, sha1);
480 return 0;
483 int cmd_tag(int argc, const char **argv, const char *prefix)
485 struct strbuf buf = STRBUF_INIT;
486 struct strbuf ref = STRBUF_INIT;
487 unsigned char object[20], prev[20];
488 const char *object_ref, *tag;
489 struct ref_lock *lock;
490 struct create_tag_options opt;
491 char *cleanup_arg = NULL;
492 int annotate = 0, force = 0, lines = -1;
493 int cmdmode = 0;
494 const char *msgfile = NULL, *keyid = NULL;
495 struct msg_arg msg = { 0, STRBUF_INIT };
496 struct commit_list *with_commit = NULL;
497 struct option options[] = {
498 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
499 { OPTION_INTEGER, 'n', NULL, &lines, N_("n"),
500 N_("print <n> lines of each tag message"),
501 PARSE_OPT_OPTARG, NULL, 1 },
502 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
503 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
505 OPT_GROUP(N_("Tag creation options")),
506 OPT_BOOL('a', "annotate", &annotate,
507 N_("annotated tag, needs a message")),
508 OPT_CALLBACK('m', "message", &msg, N_("message"),
509 N_("tag message"), parse_msg_arg),
510 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
511 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
512 OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
513 N_("how to strip spaces and #comments from message")),
514 OPT_STRING('u', "local-user", &keyid, N_("key id"),
515 N_("use another key to sign the tag")),
516 OPT__FORCE(&force, N_("replace the tag if exists")),
517 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
519 OPT_GROUP(N_("Tag listing options")),
521 OPTION_CALLBACK, 0, "contains", &with_commit, N_("commit"),
522 N_("print only tags that contain the commit"),
523 PARSE_OPT_LASTARG_DEFAULT,
524 parse_opt_with_commit, (intptr_t)"HEAD",
527 OPTION_CALLBACK, 0, "points-at", NULL, N_("object"),
528 N_("print only tags of the object"), 0, parse_opt_points_at
530 OPT_END()
533 git_config(git_tag_config, NULL);
535 memset(&opt, 0, sizeof(opt));
537 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
539 if (keyid) {
540 opt.sign = 1;
541 set_signing_key(keyid);
543 if (opt.sign)
544 annotate = 1;
545 if (argc == 0 && !cmdmode)
546 cmdmode = 'l';
548 if ((annotate || msg.given || msgfile || force) && (cmdmode != 0))
549 usage_with_options(git_tag_usage, options);
551 finalize_colopts(&colopts, -1);
552 if (cmdmode == 'l' && lines != -1) {
553 if (explicitly_enable_column(colopts))
554 die(_("--column and -n are incompatible"));
555 colopts = 0;
557 if (cmdmode == 'l') {
558 int ret;
559 if (column_active(colopts)) {
560 struct column_options copts;
561 memset(&copts, 0, sizeof(copts));
562 copts.padding = 2;
563 run_column_filter(colopts, &copts);
565 ret = list_tags(argv, lines == -1 ? 0 : lines, with_commit);
566 if (column_active(colopts))
567 stop_column_filter();
568 return ret;
570 if (lines != -1)
571 die(_("-n option is only allowed with -l."));
572 if (with_commit)
573 die(_("--contains option is only allowed with -l."));
574 if (points_at.nr)
575 die(_("--points-at option is only allowed with -l."));
576 if (cmdmode == 'd')
577 return for_each_tag_name(argv, delete_tag);
578 if (cmdmode == 'v')
579 return for_each_tag_name(argv, verify_tag);
581 if (msg.given || msgfile) {
582 if (msg.given && msgfile)
583 die(_("only one -F or -m option is allowed."));
584 annotate = 1;
585 if (msg.given)
586 strbuf_addbuf(&buf, &(msg.buf));
587 else {
588 if (!strcmp(msgfile, "-")) {
589 if (strbuf_read(&buf, 0, 1024) < 0)
590 die_errno(_("cannot read '%s'"), msgfile);
591 } else {
592 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
593 die_errno(_("could not open or read '%s'"),
594 msgfile);
599 tag = argv[0];
601 object_ref = argc == 2 ? argv[1] : "HEAD";
602 if (argc > 2)
603 die(_("too many params"));
605 if (get_sha1(object_ref, object))
606 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
608 if (strbuf_check_tag_ref(&ref, tag))
609 die(_("'%s' is not a valid tag name."), tag);
611 if (read_ref(ref.buf, prev))
612 hashclr(prev);
613 else if (!force)
614 die(_("tag '%s' already exists"), tag);
616 opt.message_given = msg.given || msgfile;
618 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
619 opt.cleanup_mode = CLEANUP_ALL;
620 else if (!strcmp(cleanup_arg, "verbatim"))
621 opt.cleanup_mode = CLEANUP_NONE;
622 else if (!strcmp(cleanup_arg, "whitespace"))
623 opt.cleanup_mode = CLEANUP_SPACE;
624 else
625 die(_("Invalid cleanup mode %s"), cleanup_arg);
627 if (annotate)
628 create_tag(object, tag, &buf, &opt, prev, object);
630 lock = lock_any_ref_for_update(ref.buf, prev, 0, NULL);
631 if (!lock)
632 die(_("%s: cannot lock the ref"), ref.buf);
633 if (write_ref_sha1(lock, object, NULL) < 0)
634 die(_("%s: cannot update the ref"), ref.buf);
635 if (force && !is_null_sha1(prev) && hashcmp(prev, object))
636 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
638 strbuf_release(&buf);
639 strbuf_release(&ref);
640 return 0;