test-lib: add a GIT_TEST_PASSING_SANITIZE_LEAK=check mode
[git.git] / builtin / tag.c
blob75dece0e4f1c90c592f86a4881a01e6553d87613
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 "config.h"
11 #include "builtin.h"
12 #include "refs.h"
13 #include "object-store.h"
14 #include "tag.h"
15 #include "run-command.h"
16 #include "parse-options.h"
17 #include "diff.h"
18 #include "revision.h"
19 #include "gpg-interface.h"
20 #include "oid-array.h"
21 #include "column.h"
22 #include "ref-filter.h"
23 #include "date.h"
25 static const char * const git_tag_usage[] = {
26 N_("git tag [-a | -s | -u <key-id>] [-f] [-m <msg> | -F <file>]\n"
27 " <tagname> [<head>]"),
28 N_("git tag -d <tagname>..."),
29 N_("git tag -l [-n[<num>]] [--contains <commit>] [--no-contains <commit>] [--points-at <object>]\n"
30 " [--format=<format>] [--merged <commit>] [--no-merged <commit>] [<pattern>...]"),
31 N_("git tag -v [--format=<format>] <tagname>..."),
32 NULL
35 static unsigned int colopts;
36 static int force_sign_annotate;
37 static int config_sign_tag = -1; /* unspecified */
39 static int list_tags(struct ref_filter *filter, struct ref_sorting *sorting,
40 struct ref_format *format)
42 struct ref_array array;
43 struct strbuf output = STRBUF_INIT;
44 struct strbuf err = STRBUF_INIT;
45 char *to_free = NULL;
46 int i;
48 memset(&array, 0, sizeof(array));
50 if (filter->lines == -1)
51 filter->lines = 0;
53 if (!format->format) {
54 if (filter->lines) {
55 to_free = xstrfmt("%s %%(contents:lines=%d)",
56 "%(align:15)%(refname:lstrip=2)%(end)",
57 filter->lines);
58 format->format = to_free;
59 } else
60 format->format = "%(refname:lstrip=2)";
63 if (verify_ref_format(format))
64 die(_("unable to parse format string"));
65 filter->with_commit_tag_algo = 1;
66 filter_refs(&array, filter, FILTER_REFS_TAGS);
67 ref_array_sort(sorting, &array);
69 for (i = 0; i < array.nr; i++) {
70 strbuf_reset(&output);
71 strbuf_reset(&err);
72 if (format_ref_array_item(array.items[i], format, &output, &err))
73 die("%s", err.buf);
74 fwrite(output.buf, 1, output.len, stdout);
75 putchar('\n');
78 strbuf_release(&err);
79 strbuf_release(&output);
80 ref_array_clear(&array);
81 free(to_free);
83 return 0;
86 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
87 const struct object_id *oid, void *cb_data);
89 static int for_each_tag_name(const char **argv, each_tag_name_fn fn,
90 void *cb_data)
92 const char **p;
93 struct strbuf ref = STRBUF_INIT;
94 int had_error = 0;
95 struct object_id oid;
97 for (p = argv; *p; p++) {
98 strbuf_reset(&ref);
99 strbuf_addf(&ref, "refs/tags/%s", *p);
100 if (read_ref(ref.buf, &oid)) {
101 error(_("tag '%s' not found."), *p);
102 had_error = 1;
103 continue;
105 if (fn(*p, ref.buf, &oid, cb_data))
106 had_error = 1;
108 strbuf_release(&ref);
109 return had_error;
112 static int collect_tags(const char *name, const char *ref,
113 const struct object_id *oid, void *cb_data)
115 struct string_list *ref_list = cb_data;
117 string_list_append(ref_list, ref);
118 ref_list->items[ref_list->nr - 1].util = oiddup(oid);
119 return 0;
122 static int delete_tags(const char **argv)
124 int result;
125 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
126 struct string_list_item *item;
128 result = for_each_tag_name(argv, collect_tags, (void *)&refs_to_delete);
129 if (delete_refs(NULL, &refs_to_delete, REF_NO_DEREF))
130 result = 1;
132 for_each_string_list_item(item, &refs_to_delete) {
133 const char *name = item->string;
134 struct object_id *oid = item->util;
135 if (!ref_exists(name))
136 printf(_("Deleted tag '%s' (was %s)\n"),
137 item->string + 10,
138 find_unique_abbrev(oid, DEFAULT_ABBREV));
140 free(oid);
142 string_list_clear(&refs_to_delete, 0);
143 return result;
146 static int verify_tag(const char *name, const char *ref,
147 const struct object_id *oid, void *cb_data)
149 int flags;
150 struct ref_format *format = cb_data;
151 flags = GPG_VERIFY_VERBOSE;
153 if (format->format)
154 flags = GPG_VERIFY_OMIT_STATUS;
156 if (gpg_verify_tag(oid, name, flags))
157 return -1;
159 if (format->format)
160 pretty_print_ref(name, oid, format);
162 return 0;
165 static int do_sign(struct strbuf *buffer)
167 return sign_buffer(buffer, buffer, get_signing_key());
170 static const char tag_template[] =
171 N_("\nWrite a message for tag:\n %s\n"
172 "Lines starting with '%c' will be ignored.\n");
174 static const char tag_template_nocleanup[] =
175 N_("\nWrite a message for tag:\n %s\n"
176 "Lines starting with '%c' will be kept; you may remove them"
177 " yourself if you want to.\n");
179 static int git_tag_config(const char *var, const char *value, void *cb)
181 int status;
183 if (!strcmp(var, "tag.gpgsign")) {
184 config_sign_tag = git_config_bool(var, value);
185 return 0;
188 if (!strcmp(var, "tag.sort")) {
189 if (!value)
190 return config_error_nonbool(var);
191 string_list_append(cb, value);
192 return 0;
195 status = git_gpg_config(var, value, cb);
196 if (status)
197 return status;
198 if (!strcmp(var, "tag.forcesignannotated")) {
199 force_sign_annotate = git_config_bool(var, value);
200 return 0;
203 if (starts_with(var, "column."))
204 return git_column_config(var, value, "tag", &colopts);
205 return git_color_default_config(var, value, cb);
208 static void write_tag_body(int fd, const struct object_id *oid)
210 unsigned long size;
211 enum object_type type;
212 char *buf, *sp, *orig;
213 struct strbuf payload = STRBUF_INIT;
214 struct strbuf signature = STRBUF_INIT;
216 orig = buf = read_object_file(oid, &type, &size);
217 if (!buf)
218 return;
219 if (parse_signature(buf, size, &payload, &signature)) {
220 buf = payload.buf;
221 size = payload.len;
223 /* skip header */
224 sp = strstr(buf, "\n\n");
226 if (!sp || !size || type != OBJ_TAG) {
227 free(buf);
228 return;
230 sp += 2; /* skip the 2 LFs */
231 write_or_die(fd, sp, buf + size - sp);
233 free(orig);
234 strbuf_release(&payload);
235 strbuf_release(&signature);
238 static int build_tag_object(struct strbuf *buf, int sign, struct object_id *result)
240 if (sign && do_sign(buf) < 0)
241 return error(_("unable to sign the tag"));
242 if (write_object_file(buf->buf, buf->len, OBJ_TAG, result) < 0)
243 return error(_("unable to write tag file"));
244 return 0;
247 struct create_tag_options {
248 unsigned int message_given:1;
249 unsigned int use_editor:1;
250 unsigned int sign;
251 enum {
252 CLEANUP_NONE,
253 CLEANUP_SPACE,
254 CLEANUP_ALL
255 } cleanup_mode;
258 static const char message_advice_nested_tag[] =
259 N_("You have created a nested tag. The object referred to by your new tag is\n"
260 "already a tag. If you meant to tag the object that it points to, use:\n"
261 "\n"
262 "\tgit tag -f %s %s^{}");
264 static void create_tag(const struct object_id *object, const char *object_ref,
265 const char *tag,
266 struct strbuf *buf, struct create_tag_options *opt,
267 struct object_id *prev, struct object_id *result)
269 enum object_type type;
270 struct strbuf header = STRBUF_INIT;
271 char *path = NULL;
273 type = oid_object_info(the_repository, object, NULL);
274 if (type <= OBJ_NONE)
275 die(_("bad object type."));
277 if (type == OBJ_TAG)
278 advise_if_enabled(ADVICE_NESTED_TAG, _(message_advice_nested_tag),
279 tag, object_ref);
281 strbuf_addf(&header,
282 "object %s\n"
283 "type %s\n"
284 "tag %s\n"
285 "tagger %s\n\n",
286 oid_to_hex(object),
287 type_name(type),
288 tag,
289 git_committer_info(IDENT_STRICT));
291 if (!opt->message_given || opt->use_editor) {
292 int fd;
294 /* write the template message before editing: */
295 path = git_pathdup("TAG_EDITMSG");
296 fd = xopen(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
298 if (opt->message_given) {
299 write_or_die(fd, buf->buf, buf->len);
300 strbuf_reset(buf);
301 } else if (!is_null_oid(prev)) {
302 write_tag_body(fd, prev);
303 } else {
304 struct strbuf buf = STRBUF_INIT;
305 strbuf_addch(&buf, '\n');
306 if (opt->cleanup_mode == CLEANUP_ALL)
307 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
308 else
309 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
310 write_or_die(fd, buf.buf, buf.len);
311 strbuf_release(&buf);
313 close(fd);
315 if (launch_editor(path, buf, NULL)) {
316 fprintf(stderr,
317 _("Please supply the message using either -m or -F option.\n"));
318 exit(1);
322 if (opt->cleanup_mode != CLEANUP_NONE)
323 strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
325 if (!opt->message_given && !buf->len)
326 die(_("no tag message?"));
328 strbuf_insert(buf, 0, header.buf, header.len);
329 strbuf_release(&header);
331 if (build_tag_object(buf, opt->sign, result) < 0) {
332 if (path)
333 fprintf(stderr, _("The tag message has been left in %s\n"),
334 path);
335 exit(128);
337 if (path) {
338 unlink_or_warn(path);
339 free(path);
343 static void create_reflog_msg(const struct object_id *oid, struct strbuf *sb)
345 enum object_type type;
346 struct commit *c;
347 char *buf;
348 unsigned long size;
349 int subject_len = 0;
350 const char *subject_start;
352 char *rla = getenv("GIT_REFLOG_ACTION");
353 if (rla) {
354 strbuf_addstr(sb, rla);
355 } else {
356 strbuf_addstr(sb, "tag: tagging ");
357 strbuf_add_unique_abbrev(sb, oid, DEFAULT_ABBREV);
360 strbuf_addstr(sb, " (");
361 type = oid_object_info(the_repository, oid, NULL);
362 switch (type) {
363 default:
364 strbuf_addstr(sb, "object of unknown type");
365 break;
366 case OBJ_COMMIT:
367 if ((buf = read_object_file(oid, &type, &size))) {
368 subject_len = find_commit_subject(buf, &subject_start);
369 strbuf_insert(sb, sb->len, subject_start, subject_len);
370 } else {
371 strbuf_addstr(sb, "commit object");
373 free(buf);
375 if ((c = lookup_commit_reference(the_repository, oid)))
376 strbuf_addf(sb, ", %s", show_date(c->date, 0, DATE_MODE(SHORT)));
377 break;
378 case OBJ_TREE:
379 strbuf_addstr(sb, "tree object");
380 break;
381 case OBJ_BLOB:
382 strbuf_addstr(sb, "blob object");
383 break;
384 case OBJ_TAG:
385 strbuf_addstr(sb, "other tag object");
386 break;
388 strbuf_addch(sb, ')');
391 struct msg_arg {
392 int given;
393 struct strbuf buf;
396 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
398 struct msg_arg *msg = opt->value;
400 BUG_ON_OPT_NEG(unset);
402 if (!arg)
403 return -1;
404 if (msg->buf.len)
405 strbuf_addstr(&(msg->buf), "\n\n");
406 strbuf_addstr(&(msg->buf), arg);
407 msg->given = 1;
408 return 0;
411 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
413 if (name[0] == '-')
414 return -1;
416 strbuf_reset(sb);
417 strbuf_addf(sb, "refs/tags/%s", name);
419 return check_refname_format(sb->buf, 0);
422 int cmd_tag(int argc, const char **argv, const char *prefix)
424 struct strbuf buf = STRBUF_INIT;
425 struct strbuf ref = STRBUF_INIT;
426 struct strbuf reflog_msg = STRBUF_INIT;
427 struct object_id object, prev;
428 const char *object_ref, *tag;
429 struct create_tag_options opt;
430 char *cleanup_arg = NULL;
431 int create_reflog = 0;
432 int annotate = 0, force = 0;
433 int cmdmode = 0, create_tag_object = 0;
434 const char *msgfile = NULL, *keyid = NULL;
435 struct msg_arg msg = { .buf = STRBUF_INIT };
436 struct ref_transaction *transaction;
437 struct strbuf err = STRBUF_INIT;
438 struct ref_filter filter;
439 struct ref_sorting *sorting;
440 struct string_list sorting_options = STRING_LIST_INIT_DUP;
441 struct ref_format format = REF_FORMAT_INIT;
442 int icase = 0;
443 int edit_flag = 0;
444 struct option options[] = {
445 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
446 { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"),
447 N_("print <n> lines of each tag message"),
448 PARSE_OPT_OPTARG, NULL, 1 },
449 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
450 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
452 OPT_GROUP(N_("Tag creation options")),
453 OPT_BOOL('a', "annotate", &annotate,
454 N_("annotated tag, needs a message")),
455 OPT_CALLBACK_F('m', "message", &msg, N_("message"),
456 N_("tag message"), PARSE_OPT_NONEG, parse_msg_arg),
457 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
458 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of tag message")),
459 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
460 OPT_CLEANUP(&cleanup_arg),
461 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
462 N_("use another key to sign the tag")),
463 OPT__FORCE(&force, N_("replace the tag if exists"), 0),
464 OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")),
466 OPT_GROUP(N_("Tag listing options")),
467 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
468 OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")),
469 OPT_NO_CONTAINS(&filter.no_commit, N_("print only tags that don't contain the commit")),
470 OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")),
471 OPT_WITHOUT(&filter.no_commit, N_("print only tags that don't contain the commit")),
472 OPT_MERGED(&filter, N_("print only tags that are merged")),
473 OPT_NO_MERGED(&filter, N_("print only tags that are not merged")),
474 OPT_REF_SORT(&sorting_options),
476 OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"),
477 N_("print only tags of the object"), PARSE_OPT_LASTARG_DEFAULT,
478 parse_opt_object_name, (intptr_t) "HEAD"
480 OPT_STRING( 0 , "format", &format.format, N_("format"),
481 N_("format to use for the output")),
482 OPT__COLOR(&format.use_color, N_("respect format colors")),
483 OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
484 OPT_END()
486 int ret = 0;
487 const char *only_in_list = NULL;
489 setup_ref_filter_porcelain_msg();
491 git_config(git_tag_config, &sorting_options);
493 memset(&opt, 0, sizeof(opt));
494 memset(&filter, 0, sizeof(filter));
495 filter.lines = -1;
496 opt.sign = -1;
498 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
500 if (!cmdmode) {
501 if (argc == 0)
502 cmdmode = 'l';
503 else if (filter.with_commit || filter.no_commit ||
504 filter.reachable_from || filter.unreachable_from ||
505 filter.points_at.nr || filter.lines != -1)
506 cmdmode = 'l';
509 if (cmdmode == 'l')
510 setup_auto_pager("tag", 1);
512 if (opt.sign == -1)
513 opt.sign = cmdmode ? 0 : config_sign_tag > 0;
515 if (keyid) {
516 opt.sign = 1;
517 set_signing_key(keyid);
519 create_tag_object = (opt.sign || annotate || msg.given || msgfile);
521 if ((create_tag_object || force) && (cmdmode != 0))
522 usage_with_options(git_tag_usage, options);
524 finalize_colopts(&colopts, -1);
525 if (cmdmode == 'l' && filter.lines != -1) {
526 if (explicitly_enable_column(colopts))
527 die(_("options '%s' and '%s' cannot be used together"), "--column", "-n");
528 colopts = 0;
530 sorting = ref_sorting_options(&sorting_options);
531 ref_sorting_set_sort_flags_all(sorting, REF_SORTING_ICASE, icase);
532 filter.ignore_case = icase;
533 if (cmdmode == 'l') {
534 if (column_active(colopts)) {
535 struct column_options copts;
536 memset(&copts, 0, sizeof(copts));
537 copts.padding = 2;
538 run_column_filter(colopts, &copts);
540 filter.name_patterns = argv;
541 ret = list_tags(&filter, sorting, &format);
542 if (column_active(colopts))
543 stop_column_filter();
544 goto cleanup;
546 if (filter.lines != -1)
547 only_in_list = "-n";
548 else if (filter.with_commit)
549 only_in_list = "--contains";
550 else if (filter.no_commit)
551 only_in_list = "--no-contains";
552 else if (filter.points_at.nr)
553 only_in_list = "--points-at";
554 else if (filter.reachable_from)
555 only_in_list = "--merged";
556 else if (filter.unreachable_from)
557 only_in_list = "--no-merged";
558 if (only_in_list)
559 die(_("the '%s' option is only allowed in list mode"), only_in_list);
560 if (cmdmode == 'd') {
561 ret = delete_tags(argv);
562 goto cleanup;
564 if (cmdmode == 'v') {
565 if (format.format && verify_ref_format(&format))
566 usage_with_options(git_tag_usage, options);
567 ret = for_each_tag_name(argv, verify_tag, &format);
568 goto cleanup;
571 if (msg.given || msgfile) {
572 if (msg.given && msgfile)
573 die(_("options '%s' and '%s' cannot be used together"), "-F", "-m");
574 if (msg.given)
575 strbuf_addbuf(&buf, &(msg.buf));
576 else {
577 if (!strcmp(msgfile, "-")) {
578 if (strbuf_read(&buf, 0, 1024) < 0)
579 die_errno(_("cannot read '%s'"), msgfile);
580 } else {
581 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
582 die_errno(_("could not open or read '%s'"),
583 msgfile);
588 tag = argv[0];
590 object_ref = argc == 2 ? argv[1] : "HEAD";
591 if (argc > 2)
592 die(_("too many arguments"));
594 if (get_oid(object_ref, &object))
595 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
597 if (strbuf_check_tag_ref(&ref, tag))
598 die(_("'%s' is not a valid tag name."), tag);
600 if (read_ref(ref.buf, &prev))
601 oidclr(&prev);
602 else if (!force)
603 die(_("tag '%s' already exists"), tag);
605 opt.message_given = msg.given || msgfile;
606 opt.use_editor = edit_flag;
608 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
609 opt.cleanup_mode = CLEANUP_ALL;
610 else if (!strcmp(cleanup_arg, "verbatim"))
611 opt.cleanup_mode = CLEANUP_NONE;
612 else if (!strcmp(cleanup_arg, "whitespace"))
613 opt.cleanup_mode = CLEANUP_SPACE;
614 else
615 die(_("Invalid cleanup mode %s"), cleanup_arg);
617 create_reflog_msg(&object, &reflog_msg);
619 if (create_tag_object) {
620 if (force_sign_annotate && !annotate)
621 opt.sign = 1;
622 create_tag(&object, object_ref, tag, &buf, &opt, &prev, &object);
625 transaction = ref_transaction_begin(&err);
626 if (!transaction ||
627 ref_transaction_update(transaction, ref.buf, &object, &prev,
628 create_reflog ? REF_FORCE_CREATE_REFLOG : 0,
629 reflog_msg.buf, &err) ||
630 ref_transaction_commit(transaction, &err))
631 die("%s", err.buf);
632 ref_transaction_free(transaction);
633 if (force && !is_null_oid(&prev) && !oideq(&prev, &object))
634 printf(_("Updated tag '%s' (was %s)\n"), tag,
635 find_unique_abbrev(&prev, DEFAULT_ABBREV));
637 cleanup:
638 ref_sorting_release(sorting);
639 strbuf_release(&buf);
640 strbuf_release(&ref);
641 strbuf_release(&reflog_msg);
642 strbuf_release(&msg.buf);
643 strbuf_release(&err);
644 return ret;