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