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