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