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