Merge branch 'jc/rerere-multi'
[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 "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
22 static 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
31 static unsigned int colopts;
32 static int force_sign_annotate;
33
34 static 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
68 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
69                                 const unsigned char *sha1);
70
71 static 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
96 static 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
105 static int verify_tag(const char *name, const char *ref,
106                                 const unsigned char *sha1)
107 {
108         const char *argv_verify_tag[] = {"verify-tag",
109                                         "-v", "SHA1_HEX", NULL};
110         argv_verify_tag[2] = sha1_to_hex(sha1);
111
112         if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
113                 return error(_("could not verify the tag '%s'"), name);
114         return 0;
115 }
116
117 static int do_sign(struct strbuf *buffer)
118 {
119         return sign_buffer(buffer, buffer, get_signing_key());
120 }
121
122 static const char tag_template[] =
123         N_("\nWrite a message for tag:\n  %s\n"
124         "Lines starting with '%c' will be ignored.\n");
125
126 static const char tag_template_nocleanup[] =
127         N_("\nWrite a message for tag:\n  %s\n"
128         "Lines starting with '%c' will be kept; you may remove them"
129         " yourself if you want to.\n");
130
131 /* Parse arg given and add it the ref_sorting array */
132 static int parse_sorting_string(const char *arg, struct ref_sorting **sorting_tail)
133 {
134         struct ref_sorting *s;
135         int len;
136
137         s = xcalloc(1, sizeof(*s));
138         s->next = *sorting_tail;
139         *sorting_tail = s;
140
141         if (*arg == '-') {
142                 s->reverse = 1;
143                 arg++;
144         }
145         if (skip_prefix(arg, "version:", &arg) ||
146             skip_prefix(arg, "v:", &arg))
147                 s->version = 1;
148
149         len = strlen(arg);
150         s->atom = parse_ref_filter_atom(arg, arg+len);
151
152         return 0;
153 }
154
155 static int git_tag_config(const char *var, const char *value, void *cb)
156 {
157         int status;
158         struct ref_sorting **sorting_tail = (struct ref_sorting **)cb;
159
160         if (!strcmp(var, "tag.sort")) {
161                 if (!value)
162                         return config_error_nonbool(var);
163                 parse_sorting_string(value, sorting_tail);
164                 return 0;
165         }
166
167         status = git_gpg_config(var, value, cb);
168         if (status)
169                 return status;
170         if (!strcmp(var, "tag.forcesignannotated")) {
171                 force_sign_annotate = git_config_bool(var, value);
172                 return 0;
173         }
174
175         if (starts_with(var, "column."))
176                 return git_column_config(var, value, "tag", &colopts);
177         return git_default_config(var, value, cb);
178 }
179
180 static void write_tag_body(int fd, const unsigned char *sha1)
181 {
182         unsigned long size;
183         enum object_type type;
184         char *buf, *sp;
185
186         buf = read_sha1_file(sha1, &type, &size);
187         if (!buf)
188                 return;
189         /* skip header */
190         sp = strstr(buf, "\n\n");
191
192         if (!sp || !size || type != OBJ_TAG) {
193                 free(buf);
194                 return;
195         }
196         sp += 2; /* skip the 2 LFs */
197         write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
198
199         free(buf);
200 }
201
202 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
203 {
204         if (sign && do_sign(buf) < 0)
205                 return error(_("unable to sign the tag"));
206         if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
207                 return error(_("unable to write tag file"));
208         return 0;
209 }
210
211 struct create_tag_options {
212         unsigned int message_given:1;
213         unsigned int sign;
214         enum {
215                 CLEANUP_NONE,
216                 CLEANUP_SPACE,
217                 CLEANUP_ALL
218         } cleanup_mode;
219 };
220
221 static void create_tag(const unsigned char *object, const char *tag,
222                        struct strbuf *buf, struct create_tag_options *opt,
223                        unsigned char *prev, unsigned char *result)
224 {
225         enum object_type type;
226         char header_buf[1024];
227         int header_len;
228         char *path = NULL;
229
230         type = sha1_object_info(object, NULL);
231         if (type <= OBJ_NONE)
232             die(_("bad object type."));
233
234         header_len = snprintf(header_buf, sizeof(header_buf),
235                           "object %s\n"
236                           "type %s\n"
237                           "tag %s\n"
238                           "tagger %s\n\n",
239                           sha1_to_hex(object),
240                           typename(type),
241                           tag,
242                           git_committer_info(IDENT_STRICT));
243
244         if (header_len > sizeof(header_buf) - 1)
245                 die(_("tag header too big."));
246
247         if (!opt->message_given) {
248                 int fd;
249
250                 /* write the template message before editing: */
251                 path = git_pathdup("TAG_EDITMSG");
252                 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
253                 if (fd < 0)
254                         die_errno(_("could not create file '%s'"), path);
255
256                 if (!is_null_sha1(prev)) {
257                         write_tag_body(fd, prev);
258                 } else {
259                         struct strbuf buf = STRBUF_INIT;
260                         strbuf_addch(&buf, '\n');
261                         if (opt->cleanup_mode == CLEANUP_ALL)
262                                 strbuf_commented_addf(&buf, _(tag_template), tag, comment_line_char);
263                         else
264                                 strbuf_commented_addf(&buf, _(tag_template_nocleanup), tag, comment_line_char);
265                         write_or_die(fd, buf.buf, buf.len);
266                         strbuf_release(&buf);
267                 }
268                 close(fd);
269
270                 if (launch_editor(path, buf, NULL)) {
271                         fprintf(stderr,
272                         _("Please supply the message using either -m or -F option.\n"));
273                         exit(1);
274                 }
275         }
276
277         if (opt->cleanup_mode != CLEANUP_NONE)
278                 strbuf_stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
279
280         if (!opt->message_given && !buf->len)
281                 die(_("no tag message?"));
282
283         strbuf_insert(buf, 0, header_buf, header_len);
284
285         if (build_tag_object(buf, opt->sign, result) < 0) {
286                 if (path)
287                         fprintf(stderr, _("The tag message has been left in %s\n"),
288                                 path);
289                 exit(128);
290         }
291         if (path) {
292                 unlink_or_warn(path);
293                 free(path);
294         }
295 }
296
297 struct msg_arg {
298         int given;
299         struct strbuf buf;
300 };
301
302 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
303 {
304         struct msg_arg *msg = opt->value;
305
306         if (!arg)
307                 return -1;
308         if (msg->buf.len)
309                 strbuf_addstr(&(msg->buf), "\n\n");
310         strbuf_addstr(&(msg->buf), arg);
311         msg->given = 1;
312         return 0;
313 }
314
315 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
316 {
317         if (name[0] == '-')
318                 return -1;
319
320         strbuf_reset(sb);
321         strbuf_addf(sb, "refs/tags/%s", name);
322
323         return check_refname_format(sb->buf, 0);
324 }
325
326 int cmd_tag(int argc, const char **argv, const char *prefix)
327 {
328         struct strbuf buf = STRBUF_INIT;
329         struct strbuf ref = STRBUF_INIT;
330         unsigned char object[20], prev[20];
331         const char *object_ref, *tag;
332         struct create_tag_options opt;
333         char *cleanup_arg = NULL;
334         int create_reflog = 0;
335         int annotate = 0, force = 0;
336         int cmdmode = 0, create_tag_object = 0;
337         const char *msgfile = NULL, *keyid = NULL;
338         struct msg_arg msg = { 0, STRBUF_INIT };
339         struct ref_transaction *transaction;
340         struct strbuf err = STRBUF_INIT;
341         struct ref_filter filter;
342         static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
343         const char *format = NULL;
344         struct option options[] = {
345                 OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
346                 { OPTION_INTEGER, 'n', NULL, &filter.lines, N_("n"),
347                                 N_("print <n> lines of each tag message"),
348                                 PARSE_OPT_OPTARG, NULL, 1 },
349                 OPT_CMDMODE('d', "delete", &cmdmode, N_("delete tags"), 'd'),
350                 OPT_CMDMODE('v', "verify", &cmdmode, N_("verify tags"), 'v'),
351
352                 OPT_GROUP(N_("Tag creation options")),
353                 OPT_BOOL('a', "annotate", &annotate,
354                                         N_("annotated tag, needs a message")),
355                 OPT_CALLBACK('m', "message", &msg, N_("message"),
356                              N_("tag message"), parse_msg_arg),
357                 OPT_FILENAME('F', "file", &msgfile, N_("read message from file")),
358                 OPT_BOOL('s', "sign", &opt.sign, N_("annotated and GPG-signed tag")),
359                 OPT_STRING(0, "cleanup", &cleanup_arg, N_("mode"),
360                         N_("how to strip spaces and #comments from message")),
361                 OPT_STRING('u', "local-user", &keyid, N_("key-id"),
362                                         N_("use another key to sign the tag")),
363                 OPT__FORCE(&force, N_("replace the tag if exists")),
364                 OPT_BOOL(0, "create-reflog", &create_reflog, N_("create a reflog")),
365
366                 OPT_GROUP(N_("Tag listing options")),
367                 OPT_COLUMN(0, "column", &colopts, N_("show tag list in columns")),
368                 OPT_CONTAINS(&filter.with_commit, N_("print only tags that contain the commit")),
369                 OPT_WITH(&filter.with_commit, N_("print only tags that contain the commit")),
370                 OPT_MERGED(&filter, N_("print only tags that are merged")),
371                 OPT_NO_MERGED(&filter, N_("print only tags that are not merged")),
372                 OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
373                              N_("field name to sort on"), &parse_opt_ref_sorting),
374                 {
375                         OPTION_CALLBACK, 0, "points-at", &filter.points_at, N_("object"),
376                         N_("print only tags of the object"), 0, parse_opt_object_name
377                 },
378                 OPT_STRING(  0 , "format", &format, N_("format"), N_("format to use for the output")),
379                 OPT_END()
380         };
381
382         git_config(git_tag_config, sorting_tail);
383
384         memset(&opt, 0, sizeof(opt));
385         memset(&filter, 0, sizeof(filter));
386         filter.lines = -1;
387
388         argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
389
390         if (keyid) {
391                 opt.sign = 1;
392                 set_signing_key(keyid);
393         }
394         create_tag_object = (opt.sign || annotate || msg.given || msgfile);
395
396         if (argc == 0 && !cmdmode)
397                 cmdmode = 'l';
398
399         if ((create_tag_object || force) && (cmdmode != 0))
400                 usage_with_options(git_tag_usage, options);
401
402         finalize_colopts(&colopts, -1);
403         if (cmdmode == 'l' && filter.lines != -1) {
404                 if (explicitly_enable_column(colopts))
405                         die(_("--column and -n are incompatible"));
406                 colopts = 0;
407         }
408         if (!sorting)
409                 sorting = ref_default_sorting();
410         if (cmdmode == 'l') {
411                 int ret;
412                 if (column_active(colopts)) {
413                         struct column_options copts;
414                         memset(&copts, 0, sizeof(copts));
415                         copts.padding = 2;
416                         run_column_filter(colopts, &copts);
417                 }
418                 filter.name_patterns = argv;
419                 ret = list_tags(&filter, sorting, format);
420                 if (column_active(colopts))
421                         stop_column_filter();
422                 return ret;
423         }
424         if (filter.lines != -1)
425                 die(_("-n option is only allowed with -l."));
426         if (filter.with_commit)
427                 die(_("--contains option is only allowed with -l."));
428         if (filter.points_at.nr)
429                 die(_("--points-at option is only allowed with -l."));
430         if (filter.merge_commit)
431                 die(_("--merged and --no-merged option are only allowed with -l"));
432         if (cmdmode == 'd')
433                 return for_each_tag_name(argv, delete_tag);
434         if (cmdmode == 'v')
435                 return for_each_tag_name(argv, verify_tag);
436
437         if (msg.given || msgfile) {
438                 if (msg.given && msgfile)
439                         die(_("only one -F or -m option is allowed."));
440                 if (msg.given)
441                         strbuf_addbuf(&buf, &(msg.buf));
442                 else {
443                         if (!strcmp(msgfile, "-")) {
444                                 if (strbuf_read(&buf, 0, 1024) < 0)
445                                         die_errno(_("cannot read '%s'"), msgfile);
446                         } else {
447                                 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
448                                         die_errno(_("could not open or read '%s'"),
449                                                 msgfile);
450                         }
451                 }
452         }
453
454         tag = argv[0];
455
456         object_ref = argc == 2 ? argv[1] : "HEAD";
457         if (argc > 2)
458                 die(_("too many params"));
459
460         if (get_sha1(object_ref, object))
461                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
462
463         if (strbuf_check_tag_ref(&ref, tag))
464                 die(_("'%s' is not a valid tag name."), tag);
465
466         if (read_ref(ref.buf, prev))
467                 hashclr(prev);
468         else if (!force)
469                 die(_("tag '%s' already exists"), tag);
470
471         opt.message_given = msg.given || msgfile;
472
473         if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
474                 opt.cleanup_mode = CLEANUP_ALL;
475         else if (!strcmp(cleanup_arg, "verbatim"))
476                 opt.cleanup_mode = CLEANUP_NONE;
477         else if (!strcmp(cleanup_arg, "whitespace"))
478                 opt.cleanup_mode = CLEANUP_SPACE;
479         else
480                 die(_("Invalid cleanup mode %s"), cleanup_arg);
481
482         if (create_tag_object) {
483                 if (force_sign_annotate && !annotate)
484                         opt.sign = 1;
485                 create_tag(object, tag, &buf, &opt, prev, object);
486         }
487
488         transaction = ref_transaction_begin(&err);
489         if (!transaction ||
490             ref_transaction_update(transaction, ref.buf, object, prev,
491                                    create_reflog ? REF_FORCE_CREATE_REFLOG : 0,
492                                    NULL, &err) ||
493             ref_transaction_commit(transaction, &err))
494                 die("%s", err.buf);
495         ref_transaction_free(transaction);
496         if (force && !is_null_sha1(prev) && hashcmp(prev, object))
497                 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
498
499         strbuf_release(&err);
500         strbuf_release(&buf);
501         strbuf_release(&ref);
502         return 0;
503 }