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