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