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 void create_tag(const struct object_id *object, const char *tag,
210 struct strbuf *buf, struct create_tag_options *opt,
211 struct object_id *prev, struct object_id *result)
212{
213 enum object_type type;
214 struct strbuf header = STRBUF_INIT;
215 char *path = NULL;
216
217 type = oid_object_info(the_repository, object, NULL);
218 if (type <= OBJ_NONE)
219 die(_("bad object type."));
220
221 strbuf_addf(&header,
222 "object %s\n"
223 "type %s\n"
224 "tag %s\n"
225 "tagger %s\n\n",
226 oid_to_hex(object),
227 type_name(type),
228 tag,
229 git_committer_info(IDENT_STRICT));
230
231 if (!opt->message_given || opt->use_editor) {
232 int fd;
233
234 /* write the template message before editing: */
235 path = git_pathdup("TAG_EDITMSG");
236 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
237 if (fd < 0)
238 die_errno(_("could not create file '%s'"), path);
239
240 if (opt->message_given) {
241 write_or_die(fd, buf->buf, buf->len);
242 strbuf_reset(buf);
243 } else if (!is_null_oid(prev)) {
244 write_tag_body(fd, prev);
245 } else {
246 struct strbuf buf = STRBUF_INIT;
247 strbuf_addch(&buf, '\n');
248 if (opt->cleanup_mode == CLEANUP_ALL)
249 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
250 else
251 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
252 write_or_die(fd, buf.buf, buf.len);
253 strbuf_release(&buf);
254 }
255 close(fd);
256
257 if (launch_editor(path, buf, NULL)) {
258 fprintf(stderr,
259 _("Please supply the message using either -m or -F option.\n"));
260 exit(1);
261 }
262 }
263
264 if (opt->cleanup_mode != CLEANUP_NONE)
265 strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
266
267 if (!opt->message_given && !buf->len)
268 die(_("no tag message?"));
269
270 strbuf_insert(buf, 0, header.buf, header.len);
271 strbuf_release(&header);
272
273 if (build_tag_object(buf, opt->sign, result) < 0) {
274 if (path)
275 fprintf(stderr, _("The tag message has been left in %s\n"),
276 path);
277 exit(128);
278 }
279 if (path) {
280 unlink_or_warn(path);
281 free(path);
282 }
283}
284
285static void create_reflog_msg(const struct object_id *oid, struct strbuf *sb)
286{
287 enum object_type type;
288 struct commit *c;
289 char *buf;
290 unsigned long size;
291 int subject_len = 0;
292 const char *subject_start;
293
294 char *rla = getenv("GIT_REFLOG_ACTION");
295 if (rla) {
296 strbuf_addstr(sb, rla);
297 } else {
298 strbuf_addstr(sb, "tag: tagging ");
299 strbuf_add_unique_abbrev(sb, oid, DEFAULT_ABBREV);
300 }
301
302 strbuf_addstr(sb, " (");
303 type = oid_object_info(the_repository, oid, NULL);
304 switch (type) {
305 default:
306 strbuf_addstr(sb, "object of unknown type");
307 break;
308 case OBJ_COMMIT:
309 if ((buf = read_object_file(oid, &type, &size)) != NULL) {
310 subject_len = find_commit_subject(buf, &subject_start);
311 strbuf_insert(sb, sb->len, subject_start, subject_len);
312 } else {
313 strbuf_addstr(sb, "commit object");
314 }
315 free(buf);
316
317 if ((c = lookup_commit_reference(the_repository, oid)) != NULL)
318 strbuf_addf(sb, ", %s", show_date(c->date, 0, DATE_MODE(SHORT)));
319 break;
320 case OBJ_TREE:
321 strbuf_addstr(sb, "tree object");
322 break;
323 case OBJ_BLOB:
324 strbuf_addstr(sb, "blob object");
325 break;
326 case OBJ_TAG:
327 strbuf_addstr(sb, "other tag object");
328 break;
329 }
330 strbuf_addch(sb, ')');
331}
332
333struct msg_arg {
334 int given;
335 struct strbuf buf;
336};
337
338static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
339{
340 struct msg_arg *msg = opt->value;
341
342 BUG_ON_OPT_NEG(unset);
343
344 if (!arg)
345 return -1;
346 if (msg->buf.len)
347 strbuf_addstr(&(msg->buf), "\n\n");
348 strbuf_addstr(&(msg->buf), arg);
349 msg->given = 1;
350 return 0;
351}
352
353static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
354{
355 if (name[0] == '-')
356 return -1;
357
358 strbuf_reset(sb);
359 strbuf_addf(sb, "refs/tags/%s", name);
360
361 return check_refname_format(sb->buf, 0);
362}
363
364int cmd_tag(int argc, const char **argv, const char *prefix)
365{
366 struct strbuf buf = STRBUF_INIT;
367 struct strbuf ref = STRBUF_INIT;
368 struct strbuf reflog_msg = STRBUF_INIT;
369 struct object_id object, prev;
370 const char *object_ref, *tag;
371 struct create_tag_options opt;
372 char *cleanup_arg = NULL;
373 int create_reflog = 0;
374 int annotate = 0, force = 0;
375 int cmdmode = 0, create_tag_object = 0;
376 const char *msgfile = NULL, *keyid = NULL;
377 struct msg_arg msg = { 0, STRBUF_INIT };
378 struct ref_transaction *transaction;
379 struct strbuf err = STRBUF_INIT;
380 struct ref_filter filter;
381 static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
382 struct ref_format format = REF_FORMAT_INIT;
383 int icase = 0;
384 int edit_flag = 0;
385 struct option options[] = {
386 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
387 { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"),
388 N_("print <n> lines of each tag message"),
389 PARSE_OPT_OPTARG, NULL, 1 },
390 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
391 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
392
393 OPT_GROUP(N_("Tag creation options")),
394 OPT_BOOL('a', "annotate", &annotate,
395 N_("annotated tag, needs a message")),
396 { OPTION_CALLBACK, 'm', "message", &msg, N_("message"),
397 N_("tag message"), PARSE_OPT_NONEG, parse_msg_arg },
398 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
399 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of tag message")),
400 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
401 OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
402 N_("how to strip spaces and #comments from message")),
403 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
404 N_("use another key to sign the tag")),
405 OPT__FORCE(&force, N_("replace the tag if exists"), 0),
406 OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")),
407
408 OPT_GROUP(N_("Tag listing options")),
409 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
410 OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")),
411 OPT_NO_CONTAINS(&filter.no_commit, N_("print only tags that don't contain the commit")),
412 OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")),
413 OPT_WITHOUT(&filter.no_commit, N_("print only tags that don't contain the commit")),
414 OPT_MERGED(&filter, N_("print only tags that are merged")),
415 OPT_NO_MERGED(&filter, N_("print only tags that are not merged")),
416 OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
417 N_("field name to sort on"), &parse_opt_ref_sorting),
418 {
419 OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"),
420 N_("print only tags of the object"), PARSE_OPT_LASTARG_DEFAULT,
421 parse_opt_object_name, (intptr_t) "HEAD"
422 },
423 OPT_STRING( 0 , "format", &format.format, N_("format"),
424 N_("format to use for the output")),
425 OPT__COLOR(&format.use_color, N_("respect format colors")),
426 OPT_BOOL('i', "ignore-case", &icase, N_("sorting and filtering are case insensitive")),
427 OPT_END()
428 };
429
430 setup_ref_filter_porcelain_msg();
431
432 git_config(git_tag_config, sorting_tail);
433
434 memset(&opt, 0, sizeof(opt));
435 memset(&filter, 0, sizeof(filter));
436 filter.lines = -1;
437
438 argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
439
440 if (keyid) {
441 opt.sign = 1;
442 set_signing_key(keyid);
443 }
444 create_tag_object = (opt.sign || annotate || msg.given || msgfile);
445
446 if (!cmdmode) {
447 if (argc == 0)
448 cmdmode = 'l';
449 else if (filter.with_commit || filter.no_commit ||
450 filter.points_at.nr || filter.merge_commit ||
451 filter.lines != -1)
452 cmdmode = 'l';
453 }
454
455 if (cmdmode == 'l')
456 setup_auto_pager("tag", 1);
457
458 if ((create_tag_object || force) && (cmdmode != 0))
459 usage_with_options(git_tag_usage, options);
460
461 finalize_colopts(&colopts, -1);
462 if (cmdmode == 'l' && filter.lines != -1) {
463 if (explicitly_enable_column(colopts))
464 die(_("--column and -n are incompatible"));
465 colopts = 0;
466 }
467 if (!sorting)
468 sorting = ref_default_sorting();
469 sorting->ignore_case = icase;
470 filter.ignore_case = icase;
471 if (cmdmode == 'l') {
472 int ret;
473 if (column_active(colopts)) {
474 struct column_options copts;
475 memset(&copts, 0, sizeof(copts));
476 copts.padding = 2;
477 run_column_filter(colopts, &copts);
478 }
479 filter.name_patterns = argv;
480 ret = list_tags(&filter, sorting, &format);
481 if (column_active(colopts))
482 stop_column_filter();
483 return ret;
484 }
485 if (filter.lines != -1)
486 die(_("-n option is only allowed in list mode"));
487 if (filter.with_commit)
488 die(_("--contains option is only allowed in list mode"));
489 if (filter.no_commit)
490 die(_("--no-contains option is only allowed in list mode"));
491 if (filter.points_at.nr)
492 die(_("--points-at option is only allowed in list mode"));
493 if (filter.merge_commit)
494 die(_("--merged and --no-merged options are only allowed in list mode"));
495 if (cmdmode == 'd')
496 return for_each_tag_name(argv, delete_tag, NULL);
497 if (cmdmode == 'v') {
498 if (format.format && verify_ref_format(&format))
499 usage_with_options(git_tag_usage, options);
500 return for_each_tag_name(argv, verify_tag, &format);
501 }
502
503 if (msg.given || msgfile) {
504 if (msg.given && msgfile)
505 die(_("only one -F or -m option is allowed."));
506 if (msg.given)
507 strbuf_addbuf(&buf, &(msg.buf));
508 else {
509 if (!strcmp(msgfile, "-")) {
510 if (strbuf_read(&buf, 0, 1024) < 0)
511 die_errno(_("cannot read '%s'"), msgfile);
512 } else {
513 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
514 die_errno(_("could not open or read '%s'"),
515 msgfile);
516 }
517 }
518 }
519
520 tag = argv[0];
521
522 object_ref = argc == 2 ? argv[1] : "HEAD";
523 if (argc > 2)
524 die(_("too many params"));
525
526 if (get_oid(object_ref, &object))
527 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
528
529 if (strbuf_check_tag_ref(&ref, tag))
530 die(_("'%s' is not a valid tag name."), tag);
531
532 if (read_ref(ref.buf, &prev))
533 oidclr(&prev);
534 else if (!force)
535 die(_("tag '%s' already exists"), tag);
536
537 opt.message_given = msg.given || msgfile;
538 opt.use_editor = edit_flag;
539
540 if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
541 opt.cleanup_mode = CLEANUP_ALL;
542 else if (!strcmp(cleanup_arg, "verbatim"))
543 opt.cleanup_mode = CLEANUP_NONE;
544 else if (!strcmp(cleanup_arg, "whitespace"))
545 opt.cleanup_mode = CLEANUP_SPACE;
546 else
547 die(_("Invalid cleanup mode %s"), cleanup_arg);
548
549 create_reflog_msg(&object, &reflog_msg);
550
551 if (create_tag_object) {
552 if (force_sign_annotate && !annotate)
553 opt.sign = 1;
554 create_tag(&object, tag, &buf, &opt, &prev, &object);
555 }
556
557 transaction = ref_transaction_begin(&err);
558 if (!transaction ||
559 ref_transaction_update(transaction, ref.buf, &object, &prev,
560 create_reflog ? REF_FORCE_CREATE_REFLOG : 0,
561 reflog_msg.buf, &err) ||
562 ref_transaction_commit(transaction, &err))
563 die("%s", err.buf);
564 ref_transaction_free(transaction);
565 if (force && !is_null_oid(&prev) && !oideq(&prev, &object))
566 printf(_("Updated tag '%s' (was %s)\n"), tag,
567 find_unique_abbrev(&prev, DEFAULT_ABBREV));
568
569 UNLEAK(buf);
570 UNLEAK(ref);
571 UNLEAK(reflog_msg);
572 UNLEAK(msg);
573 UNLEAK(err);
574 return 0;
575}