gpg-interface: improve interface for parsing tags
[git/gitster.git] / builtin / tag.c
blob7162f4ccc587162325795f899bc3e5982a0b5918
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"
24 static const char * const git_tag_usage[] = {
25 N_("git tag [-a | -s | -u <key-id>] [-f] [-m <msg> | -F <file>]\n"
26 "\t\t<tagname> [<head>]"),
27 N_("git tag -d <tagname>..."),
28 N_("git tag -l [-n[<num>]] [--contains <commit>] [--no-contains <commit>] [--points-at <object>]\n"
29 "\t\t[--format=<format>] [--merged <commit>] [--no-merged <commit>] [<pattern>...]"),
30 N_("git tag -v [--format=<format>] <tagname>..."),
31 NULL
34 static unsigned int colopts;
35 static int force_sign_annotate;
36 static int config_sign_tag = -1; /* unspecified */
38 static int list_tags(struct ref_filter *filter, struct ref_sorting *sorting,
39 struct ref_format *format)
41 struct ref_array array;
42 char *to_free = NULL;
43 int i;
45 memset(&array, 0, sizeof(array));
47 if (filter->lines == -1)
48 filter->lines = 0;
50 if (!format->format) {
51 if (filter->lines) {
52 to_free = xstrfmt("%s %%(contents:lines=%d)",
53 "%(align:15)%(refname:lstrip=2)%(end)",
54 filter->lines);
55 format->format = to_free;
56 } else
57 format->format = "%(refname:lstrip=2)";
60 if (verify_ref_format(format))
61 die(_("unable to parse format string"));
62 filter->with_commit_tag_algo = 1;
63 filter_refs(&array, filter, FILTER_REFS_TAGS);
64 ref_array_sort(sorting, &array);
66 for (i = 0; i < array.nr; i++)
67 show_ref_array_item(array.items[i], format);
68 ref_array_clear(&array);
69 free(to_free);
71 return 0;
74 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
75 const struct object_id *oid, const void *cb_data);
77 static int for_each_tag_name(const char **argv, each_tag_name_fn fn,
78 const void *cb_data)
80 const char **p;
81 struct strbuf ref = STRBUF_INIT;
82 int had_error = 0;
83 struct object_id oid;
85 for (p = argv; *p; p++) {
86 strbuf_reset(&ref);
87 strbuf_addf(&ref, "refs/tags/%s", *p);
88 if (read_ref(ref.buf, &oid)) {
89 error(_("tag '%s' not found."), *p);
90 had_error = 1;
91 continue;
93 if (fn(*p, ref.buf, &oid, cb_data))
94 had_error = 1;
96 strbuf_release(&ref);
97 return had_error;
100 static int delete_tag(const char *name, const char *ref,
101 const struct object_id *oid, const void *cb_data)
103 if (delete_ref(NULL, ref, oid, 0))
104 return 1;
105 printf(_("Deleted tag '%s' (was %s)\n"), name,
106 find_unique_abbrev(oid, DEFAULT_ABBREV));
107 return 0;
110 static int verify_tag(const char *name, const char *ref,
111 const struct object_id *oid, const void *cb_data)
113 int flags;
114 const struct ref_format *format = cb_data;
115 flags = GPG_VERIFY_VERBOSE;
117 if (format->format)
118 flags = GPG_VERIFY_OMIT_STATUS;
120 if (gpg_verify_tag(oid, name, flags))
121 return -1;
123 if (format->format)
124 pretty_print_ref(name, oid, format);
126 return 0;
129 static int do_sign(struct strbuf *buffer)
131 return sign_buffer(buffer, buffer, get_signing_key());
134 static const char tag_template[] =
135 N_("\nWrite a message for tag:\n %s\n"
136 "Lines starting with '%c' will be ignored.\n");
138 static const char tag_template_nocleanup[] =
139 N_("\nWrite a message for tag:\n %s\n"
140 "Lines starting with '%c' will be kept; you may remove them"
141 " yourself if you want to.\n");
143 static int git_tag_config(const char *var, const char *value, void *cb)
145 int status;
146 struct ref_sorting **sorting_tail = (struct ref_sorting **)cb;
148 if (!strcmp(var, "tag.gpgsign")) {
149 config_sign_tag = git_config_bool(var, value);
150 return 0;
153 if (!strcmp(var, "tag.sort")) {
154 if (!value)
155 return config_error_nonbool(var);
156 parse_ref_sorting(sorting_tail, value);
157 return 0;
160 status = git_gpg_config(var, value, cb);
161 if (status)
162 return status;
163 if (!strcmp(var, "tag.forcesignannotated")) {
164 force_sign_annotate = git_config_bool(var, value);
165 return 0;
168 if (starts_with(var, "column."))
169 return git_column_config(var, value, "tag", &colopts);
170 return git_color_default_config(var, value, cb);
173 static void write_tag_body(int fd, const struct object_id *oid)
175 unsigned long size;
176 enum object_type type;
177 char *buf, *sp, *orig;
178 struct strbuf payload = STRBUF_INIT;
179 struct strbuf signature = STRBUF_INIT;
181 orig = buf = read_object_file(oid, &type, &size);
182 if (!buf)
183 return;
184 if (parse_signature(buf, size, &payload, &signature)) {
185 buf = payload.buf;
186 size = payload.len;
188 /* skip header */
189 sp = strstr(buf, "\n\n");
191 if (!sp || !size || type != OBJ_TAG) {
192 free(buf);
193 return;
195 sp += 2; /* skip the 2 LFs */
196 write_or_die(fd, sp, buf + size - sp);
198 free(orig);
199 strbuf_release(&payload);
200 strbuf_release(&signature);
203 static int build_tag_object(struct strbuf *buf, int sign, struct object_id *result)
205 if (sign && do_sign(buf) < 0)
206 return error(_("unable to sign the tag"));
207 if (write_object_file(buf->buf, buf->len, tag_type, result) < 0)
208 return error(_("unable to write tag file"));
209 return 0;
212 struct create_tag_options {
213 unsigned int message_given:1;
214 unsigned int use_editor:1;
215 unsigned int sign;
216 enum {
217 CLEANUP_NONE,
218 CLEANUP_SPACE,
219 CLEANUP_ALL
220 } cleanup_mode;
223 static const char message_advice_nested_tag[] =
224 N_("You have created a nested tag. The object referred to by your new tag is\n"
225 "already a tag. If you meant to tag the object that it points to, use:\n"
226 "\n"
227 "\tgit tag -f %s %s^{}");
229 static void create_tag(const struct object_id *object, const char *object_ref,
230 const char *tag,
231 struct strbuf *buf, struct create_tag_options *opt,
232 struct object_id *prev, struct object_id *result)
234 enum object_type type;
235 struct strbuf header = STRBUF_INIT;
236 char *path = NULL;
238 type = oid_object_info(the_repository, object, NULL);
239 if (type <= OBJ_NONE)
240 die(_("bad object type."));
242 if (type == OBJ_TAG)
243 advise_if_enabled(ADVICE_NESTED_TAG, _(message_advice_nested_tag),
244 tag, object_ref);
246 strbuf_addf(&header,
247 "object %s\n"
248 "type %s\n"
249 "tag %s\n"
250 "tagger %s\n\n",
251 oid_to_hex(object),
252 type_name(type),
253 tag,
254 git_committer_info(IDENT_STRICT));
256 if (!opt->message_given || opt->use_editor) {
257 int fd;
259 /* write the template message before editing: */
260 path = git_pathdup("TAG_EDITMSG");
261 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
262 if (fd < 0)
263 die_errno(_("could not create file '%s'"), path);
265 if (opt->message_given) {
266 write_or_die(fd, buf->buf, buf->len);
267 strbuf_reset(buf);
268 } else if (!is_null_oid(prev)) {
269 write_tag_body(fd, prev);
270 } else {
271 struct strbuf buf = STRBUF_INIT;
272 strbuf_addch(&buf, '\n');
273 if (opt->cleanup_mode == CLEANUP_ALL)
274 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
275 else
276 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
277 write_or_die(fd, buf.buf, buf.len);
278 strbuf_release(&buf);
280 close(fd);
282 if (launch_editor(path, buf, NULL)) {
283 fprintf(stderr,
284 _("Please supply the message using either -m or -F option.\n"));
285 exit(1);
289 if (opt->cleanup_mode != CLEANUP_NONE)
290 strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
292 if (!opt->message_given && !buf->len)
293 die(_("no tag message?"));
295 strbuf_insert(buf, 0, header.buf, header.len);
296 strbuf_release(&header);
298 if (build_tag_object(buf, opt->sign, result) < 0) {
299 if (path)
300 fprintf(stderr, _("The tag message has been left in %s\n"),
301 path);
302 exit(128);
304 if (path) {
305 unlink_or_warn(path);
306 free(path);
310 static void create_reflog_msg(const struct object_id *oid, struct strbuf *sb)
312 enum object_type type;
313 struct commit *c;
314 char *buf;
315 unsigned long size;
316 int subject_len = 0;
317 const char *subject_start;
319 char *rla = getenv("GIT_REFLOG_ACTION");
320 if (rla) {
321 strbuf_addstr(sb, rla);
322 } else {
323 strbuf_addstr(sb, "tag: tagging ");
324 strbuf_add_unique_abbrev(sb, oid, DEFAULT_ABBREV);
327 strbuf_addstr(sb, " (");
328 type = oid_object_info(the_repository, oid, NULL);
329 switch (type) {
330 default:
331 strbuf_addstr(sb, "object of unknown type");
332 break;
333 case OBJ_COMMIT:
334 if ((buf = read_object_file(oid, &type, &size)) != NULL) {
335 subject_len = find_commit_subject(buf, &subject_start);
336 strbuf_insert(sb, sb->len, subject_start, subject_len);
337 } else {
338 strbuf_addstr(sb, "commit object");
340 free(buf);
342 if ((c = lookup_commit_reference(the_repository, oid)) != NULL)
343 strbuf_addf(sb, ", %s", show_date(c->date, 0, DATE_MODE(SHORT)));
344 break;
345 case OBJ_TREE:
346 strbuf_addstr(sb, "tree object");
347 break;
348 case OBJ_BLOB:
349 strbuf_addstr(sb, "blob object");
350 break;
351 case OBJ_TAG:
352 strbuf_addstr(sb, "other tag object");
353 break;
355 strbuf_addch(sb, ')');
358 struct msg_arg {
359 int given;
360 struct strbuf buf;
363 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
365 struct msg_arg *msg = opt->value;
367 BUG_ON_OPT_NEG(unset);
369 if (!arg)
370 return -1;
371 if (msg->buf.len)
372 strbuf_addstr(&(msg->buf), "\n\n");
373 strbuf_addstr(&(msg->buf), arg);
374 msg->given = 1;
375 return 0;
378 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
380 if (name[0] == '-')
381 return -1;
383 strbuf_reset(sb);
384 strbuf_addf(sb, "refs/tags/%s", name);
386 return check_refname_format(sb->buf, 0);
389 int cmd_tag(int argc, const char **argv, const char *prefix)
391 struct strbuf buf = STRBUF_INIT;
392 struct strbuf ref = STRBUF_INIT;
393 struct strbuf reflog_msg = STRBUF_INIT;
394 struct object_id object, prev;
395 const char *object_ref, *tag;
396 struct create_tag_options opt;
397 char *cleanup_arg = NULL;
398 int create_reflog = 0;
399 int annotate = 0, force = 0;
400 int cmdmode = 0, create_tag_object = 0;
401 const char *msgfile = NULL, *keyid = NULL;
402 struct msg_arg msg = { 0, STRBUF_INIT };
403 struct ref_transaction *transaction;
404 struct strbuf err = STRBUF_INIT;
405 struct ref_filter filter;
406 static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
407 struct ref_format format = REF_FORMAT_INIT;
408 int icase = 0;
409 int edit_flag = 0;
410 struct option options[] = {
411 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
412 { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"),
413 N_("print <n> lines of each tag message"),
414 PARSE_OPT_OPTARG, NULL, 1 },
415 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
416 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
418 OPT_GROUP(N_("Tag creation options")),
419 OPT_BOOL('a', "annotate", &annotate,
420 N_("annotated tag, needs a message")),
421 OPT_CALLBACK_F('m', "message", &msg, N_("message"),
422 N_("tag message"), PARSE_OPT_NONEG, parse_msg_arg),
423 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
424 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of tag message")),
425 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
426 OPT_CLEANUP(&cleanup_arg),
427 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
428 N_("use another key to sign the tag")),
429 OPT__FORCE(&force, N_("replace the tag if exists"), 0),
430 OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")),
432 OPT_GROUP(N_("Tag listing options")),
433 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
434 OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")),
435 OPT_NO_CONTAINS(&filter.no_commit, N_("print only tags that don't contain the commit")),
436 OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")),
437 OPT_WITHOUT(&filter.no_commit, N_("print only tags that don't contain the commit")),
438 OPT_MERGED(&filter, N_("print only tags that are merged")),
439 OPT_NO_MERGED(&filter, N_("print only tags that are not merged")),
440 OPT_REF_SORT(sorting_tail),
442 OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"),
443 N_("print only tags of the object"), PARSE_OPT_LASTARG_DEFAULT,
444 parse_opt_object_name, (intptr_t) "HEAD"
446 OPT_STRING( 0 , "format", &format.format, N_("format"),
447 N_("format to use for the output")),
448 OPT__COLOR(&format.use_color, N_("respect format colors")),
449 OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
450 OPT_END()
453 setup_ref_filter_porcelain_msg();
455 git_config(git_tag_config, sorting_tail);
457 memset(&opt, 0, sizeof(opt));
458 memset(&filter, 0, sizeof(filter));
459 filter.lines = -1;
460 opt.sign = -1;
462 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
464 if (!cmdmode) {
465 if (argc == 0)
466 cmdmode = 'l';
467 else if (filter.with_commit || filter.no_commit ||
468 filter.reachable_from || filter.unreachable_from ||
469 filter.points_at.nr || filter.lines != -1)
470 cmdmode = 'l';
473 if (cmdmode == 'l')
474 setup_auto_pager("tag", 1);
476 if (opt.sign == -1)
477 opt.sign = cmdmode ? 0 : config_sign_tag > 0;
479 if (keyid) {
480 opt.sign = 1;
481 set_signing_key(keyid);
483 create_tag_object = (opt.sign || annotate || msg.given || msgfile);
485 if ((create_tag_object || force) && (cmdmode != 0))
486 usage_with_options(git_tag_usage, options);
488 finalize_colopts(&colopts, -1);
489 if (cmdmode == 'l' && filter.lines != -1) {
490 if (explicitly_enable_column(colopts))
491 die(_("--column and -n are incompatible"));
492 colopts = 0;
494 if (!sorting)
495 sorting = ref_default_sorting();
496 ref_sorting_icase_all(sorting, icase);
497 filter.ignore_case = icase;
498 if (cmdmode == 'l') {
499 int ret;
500 if (column_active(colopts)) {
501 struct column_options copts;
502 memset(&copts, 0, sizeof(copts));
503 copts.padding = 2;
504 run_column_filter(colopts, &copts);
506 filter.name_patterns = argv;
507 ret = list_tags(&filter, sorting, &format);
508 if (column_active(colopts))
509 stop_column_filter();
510 return ret;
512 if (filter.lines != -1)
513 die(_("-n option is only allowed in list mode"));
514 if (filter.with_commit)
515 die(_("--contains option is only allowed in list mode"));
516 if (filter.no_commit)
517 die(_("--no-contains option is only allowed in list mode"));
518 if (filter.points_at.nr)
519 die(_("--points-at option is only allowed in list mode"));
520 if (filter.reachable_from || filter.unreachable_from)
521 die(_("--merged and --no-merged options are only allowed in list mode"));
522 if (cmdmode == 'd')
523 return for_each_tag_name(argv, delete_tag, NULL);
524 if (cmdmode == 'v') {
525 if (format.format && verify_ref_format(&format))
526 usage_with_options(git_tag_usage, options);
527 return for_each_tag_name(argv, verify_tag, &format);
530 if (msg.given || msgfile) {
531 if (msg.given && msgfile)
532 die(_("only one -F or -m option is allowed."));
533 if (msg.given)
534 strbuf_addbuf(&buf, &(msg.buf));
535 else {
536 if (!strcmp(msgfile, "-")) {
537 if (strbuf_read(&buf, 0, 1024) < 0)
538 die_errno(_("cannot read '%s'"), msgfile);
539 } else {
540 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
541 die_errno(_("could not open or read '%s'"),
542 msgfile);
547 tag = argv[0];
549 object_ref = argc == 2 ? argv[1] : "HEAD";
550 if (argc > 2)
551 die(_("too many params"));
553 if (get_oid(object_ref, &object))
554 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
556 if (strbuf_check_tag_ref(&ref, tag))
557 die(_("'%s' is not a valid tag name."), tag);
559 if (read_ref(ref.buf, &prev))
560 oidclr(&prev);
561 else if (!force)
562 die(_("tag '%s' already exists"), tag);
564 opt.message_given = msg.given || msgfile;
565 opt.use_editor = edit_flag;
567 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
568 opt.cleanup_mode = CLEANUP_ALL;
569 else if (!strcmp(cleanup_arg, "verbatim"))
570 opt.cleanup_mode = CLEANUP_NONE;
571 else if (!strcmp(cleanup_arg, "whitespace"))
572 opt.cleanup_mode = CLEANUP_SPACE;
573 else
574 die(_("Invalid cleanup mode %s"), cleanup_arg);
576 create_reflog_msg(&object, &reflog_msg);
578 if (create_tag_object) {
579 if (force_sign_annotate && !annotate)
580 opt.sign = 1;
581 create_tag(&object, object_ref, tag, &buf, &opt, &prev, &object);
584 transaction = ref_transaction_begin(&err);
585 if (!transaction ||
586 ref_transaction_update(transaction, ref.buf, &object, &prev,
587 create_reflog ? REF_FORCE_CREATE_REFLOG : 0,
588 reflog_msg.buf, &err) ||
589 ref_transaction_commit(transaction, &err))
590 die("%s", err.buf);
591 ref_transaction_free(transaction);
592 if (force && !is_null_oid(&prev) && !oideq(&prev, &object))
593 printf(_("Updated tag '%s' (was %s)\n"), tag,
594 find_unique_abbrev(&prev, DEFAULT_ABBREV));
596 UNLEAK(buf);
597 UNLEAK(ref);
598 UNLEAK(reflog_msg);
599 UNLEAK(msg);
600 UNLEAK(err);
601 return 0;