Merge branch 'jl/submodule-add-relurl-wo-upstream' into next
[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
18 static const char * const git_tag_usage[] = {
19         "git tag [-a|-s|-u <key-id>] [-f] [-m <msg>|-F <file>] <tagname> [<head>]",
20         "git tag -d <tagname>...",
21         "git tag -l [-n[<num>]] [<pattern>...]",
22         "git tag -v <tagname>...",
23         NULL
24 };
25
26 static char signingkey[1000];
27
28 static int core_clock_skew = 86400;
29
30 struct tag_filter {
31         const char **patterns;
32         int lines;
33         struct commit_list *with_commit;
34 };
35
36 static int match_pattern(const char **patterns, const char *ref)
37 {
38         /* no pattern means match everything */
39         if (!*patterns)
40                 return 1;
41         for (; *patterns; patterns++)
42                 if (!fnmatch(*patterns, ref, 0))
43                         return 1;
44         return 0;
45 }
46
47 static int in_commit_list(const struct commit_list *want, struct commit *c)
48 {
49         for (; want; want = want->next)
50                 if (!hashcmp(want->item->object.sha1, c->object.sha1))
51                         return 1;
52         return 0;
53 }
54
55 static int contains_recurse(struct commit *candidate,
56                             const struct commit_list *want,
57                             unsigned long cutoff)
58 {
59         struct commit_list *p;
60
61         /* was it previously marked as containing a want commit? */
62         if (candidate->object.flags & TMP_MARK)
63                 return 1;
64         /* or marked as not possibly containing a want commit? */
65         if (candidate->object.flags & UNINTERESTING)
66                 return 0;
67         /* or are we it? */
68         if (in_commit_list(want, candidate))
69                 return 1;
70
71         if (parse_commit(candidate) < 0)
72                 return 0;
73
74         /* stop searching if we go too far back in time */
75         if (candidate->date < cutoff)
76                 return 0;
77
78         /* Otherwise recurse and mark ourselves for future traversals. */
79         for (p = candidate->parents; p; p = p->next) {
80                 if (contains_recurse(p->item, want, cutoff)) {
81                         candidate->object.flags |= TMP_MARK;
82                         return 1;
83                 }
84         }
85         candidate->object.flags |= UNINTERESTING;
86         return 0;
87 }
88
89 static int contains(struct commit *candidate, const struct commit_list *want)
90 {
91         unsigned long cutoff = 0;
92
93         if (core_clock_skew >= 0) {
94                 const struct commit_list *c;
95                 unsigned long min_date = ULONG_MAX;
96                 for (c = want; c; c = c->next) {
97                         if (parse_commit(c->item) < 0)
98                                 continue;
99                         if (c->item->date < min_date)
100                                 min_date = c->item->date;
101                 }
102                 if (min_date > core_clock_skew)
103                         cutoff = min_date - core_clock_skew;
104         }
105
106         return contains_recurse(candidate, want, cutoff);
107 }
108
109 static int show_reference(const char *refname, const unsigned char *sha1,
110                           int flag, void *cb_data)
111 {
112         struct tag_filter *filter = cb_data;
113
114         if (match_pattern(filter->patterns, refname)) {
115                 int i;
116                 unsigned long size;
117                 enum object_type type;
118                 char *buf, *sp, *eol;
119                 size_t len;
120
121                 if (filter->with_commit) {
122                         struct commit *commit;
123
124                         commit = lookup_commit_reference_gently(sha1, 1);
125                         if (!commit)
126                                 return 0;
127                         if (!contains(commit, filter->with_commit))
128                                 return 0;
129                 }
130
131                 if (!filter->lines) {
132                         printf("%s\n", refname);
133                         return 0;
134                 }
135                 printf("%-15s ", refname);
136
137                 buf = read_sha1_file(sha1, &type, &size);
138                 if (!buf || !size)
139                         return 0;
140
141                 /* skip header */
142                 sp = strstr(buf, "\n\n");
143                 if (!sp) {
144                         free(buf);
145                         return 0;
146                 }
147                 /* only take up to "lines" lines, and strip the signature */
148                 size = parse_signature(buf, size);
149                 for (i = 0, sp += 2;
150                                 i < filter->lines && sp < buf + size;
151                                 i++) {
152                         if (i)
153                                 printf("\n    ");
154                         eol = memchr(sp, '\n', size - (sp - buf));
155                         len = eol ? eol - sp : size - (sp - buf);
156                         fwrite(sp, len, 1, stdout);
157                         if (!eol)
158                                 break;
159                         sp = eol + 1;
160                 }
161                 putchar('\n');
162                 free(buf);
163         }
164
165         return 0;
166 }
167
168 static int list_tags(const char **patterns, int lines,
169                         struct commit_list *with_commit)
170 {
171         struct tag_filter filter;
172
173         filter.patterns = patterns;
174         filter.lines = lines;
175         filter.with_commit = with_commit;
176
177         for_each_tag_ref(show_reference, (void *) &filter);
178
179         return 0;
180 }
181
182 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
183                                 const unsigned char *sha1);
184
185 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
186 {
187         const char **p;
188         char ref[PATH_MAX];
189         int had_error = 0;
190         unsigned char sha1[20];
191
192         for (p = argv; *p; p++) {
193                 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
194                                         >= sizeof(ref)) {
195                         error(_("tag name too long: %.*s..."), 50, *p);
196                         had_error = 1;
197                         continue;
198                 }
199                 if (!resolve_ref(ref, sha1, 1, NULL)) {
200                         error(_("tag '%s' not found."), *p);
201                         had_error = 1;
202                         continue;
203                 }
204                 if (fn(*p, ref, sha1))
205                         had_error = 1;
206         }
207         return had_error;
208 }
209
210 static int delete_tag(const char *name, const char *ref,
211                                 const unsigned char *sha1)
212 {
213         if (delete_ref(ref, sha1, 0))
214                 return 1;
215         printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
216         return 0;
217 }
218
219 static int verify_tag(const char *name, const char *ref,
220                                 const unsigned char *sha1)
221 {
222         const char *argv_verify_tag[] = {"verify-tag",
223                                         "-v", "SHA1_HEX", NULL};
224         argv_verify_tag[2] = sha1_to_hex(sha1);
225
226         if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
227                 return error(_("could not verify the tag '%s'"), name);
228         return 0;
229 }
230
231 static int do_sign(struct strbuf *buffer)
232 {
233         struct child_process gpg;
234         const char *args[4];
235         char *bracket;
236         int len;
237         int i, j;
238
239         if (!*signingkey) {
240                 if (strlcpy(signingkey, git_committer_info(IDENT_ERROR_ON_NO_NAME),
241                                 sizeof(signingkey)) > sizeof(signingkey) - 1)
242                         return error(_("committer info too long."));
243                 bracket = strchr(signingkey, '>');
244                 if (bracket)
245                         bracket[1] = '\0';
246         }
247
248         /* When the username signingkey is bad, program could be terminated
249          * because gpg exits without reading and then write gets SIGPIPE. */
250         signal(SIGPIPE, SIG_IGN);
251
252         memset(&gpg, 0, sizeof(gpg));
253         gpg.argv = args;
254         gpg.in = -1;
255         gpg.out = -1;
256         args[0] = "gpg";
257         args[1] = "-bsau";
258         args[2] = signingkey;
259         args[3] = NULL;
260
261         if (start_command(&gpg))
262                 return error(_("could not run gpg."));
263
264         if (write_in_full(gpg.in, buffer->buf, buffer->len) != buffer->len) {
265                 close(gpg.in);
266                 close(gpg.out);
267                 finish_command(&gpg);
268                 return error(_("gpg did not accept the tag data"));
269         }
270         close(gpg.in);
271         len = strbuf_read(buffer, gpg.out, 1024);
272         close(gpg.out);
273
274         if (finish_command(&gpg) || !len || len < 0)
275                 return error(_("gpg failed to sign the tag"));
276
277         /* Strip CR from the line endings, in case we are on Windows. */
278         for (i = j = 0; i < buffer->len; i++)
279                 if (buffer->buf[i] != '\r') {
280                         if (i != j)
281                                 buffer->buf[j] = buffer->buf[i];
282                         j++;
283                 }
284         strbuf_setlen(buffer, j);
285
286         return 0;
287 }
288
289 static const char tag_template[] =
290         N_("\n"
291         "#\n"
292         "# Write a tag message\n"
293         "#\n");
294
295 static void set_signingkey(const char *value)
296 {
297         if (strlcpy(signingkey, value, sizeof(signingkey)) >= sizeof(signingkey))
298                 die(_("signing key value too long (%.10s...)"), value);
299 }
300
301 static int git_tag_config(const char *var, const char *value, void *cb)
302 {
303         if (!strcmp(var, "user.signingkey")) {
304                 if (!value)
305                         return config_error_nonbool(var);
306                 set_signingkey(value);
307                 return 0;
308         }
309
310         if (!strcmp(var, "core.clockskew")) {
311                 if (!value || !strcmp(value, "none"))
312                         core_clock_skew = -1;
313                 else
314                         core_clock_skew = git_config_int(var, value);
315                 return 0;
316         }
317
318         return git_default_config(var, value, cb);
319 }
320
321 static void write_tag_body(int fd, const unsigned char *sha1)
322 {
323         unsigned long size;
324         enum object_type type;
325         char *buf, *sp;
326
327         buf = read_sha1_file(sha1, &type, &size);
328         if (!buf)
329                 return;
330         /* skip header */
331         sp = strstr(buf, "\n\n");
332
333         if (!sp || !size || type != OBJ_TAG) {
334                 free(buf);
335                 return;
336         }
337         sp += 2; /* skip the 2 LFs */
338         write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
339
340         free(buf);
341 }
342
343 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
344 {
345         if (sign && do_sign(buf) < 0)
346                 return error(_("unable to sign the tag"));
347         if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
348                 return error(_("unable to write tag file"));
349         return 0;
350 }
351
352 static void create_tag(const unsigned char *object, const char *tag,
353                        struct strbuf *buf, int message, int sign,
354                        unsigned char *prev, unsigned char *result)
355 {
356         enum object_type type;
357         char header_buf[1024];
358         int header_len;
359         char *path = NULL;
360
361         type = sha1_object_info(object, NULL);
362         if (type <= OBJ_NONE)
363             die(_("bad object type."));
364
365         header_len = snprintf(header_buf, sizeof(header_buf),
366                           "object %s\n"
367                           "type %s\n"
368                           "tag %s\n"
369                           "tagger %s\n\n",
370                           sha1_to_hex(object),
371                           typename(type),
372                           tag,
373                           git_committer_info(IDENT_ERROR_ON_NO_NAME));
374
375         if (header_len > sizeof(header_buf) - 1)
376                 die(_("tag header too big."));
377
378         if (!message) {
379                 int fd;
380
381                 /* write the template message before editing: */
382                 path = git_pathdup("TAG_EDITMSG");
383                 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
384                 if (fd < 0)
385                         die_errno(_("could not create file '%s'"), path);
386
387                 if (!is_null_sha1(prev))
388                         write_tag_body(fd, prev);
389                 else
390                         write_or_die(fd, _(tag_template), strlen(_(tag_template)));
391                 close(fd);
392
393                 if (launch_editor(path, buf, NULL)) {
394                         fprintf(stderr,
395                         _("Please supply the message using either -m or -F option.\n"));
396                         exit(1);
397                 }
398         }
399
400         stripspace(buf, 1);
401
402         if (!message && !buf->len)
403                 die(_("no tag message?"));
404
405         strbuf_insert(buf, 0, header_buf, header_len);
406
407         if (build_tag_object(buf, sign, result) < 0) {
408                 if (path)
409                         fprintf(stderr, _("The tag message has been left in %s\n"),
410                                 path);
411                 exit(128);
412         }
413         if (path) {
414                 unlink_or_warn(path);
415                 free(path);
416         }
417 }
418
419 struct msg_arg {
420         int given;
421         struct strbuf buf;
422 };
423
424 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
425 {
426         struct msg_arg *msg = opt->value;
427
428         if (!arg)
429                 return -1;
430         if (msg->buf.len)
431                 strbuf_addstr(&(msg->buf), "\n\n");
432         strbuf_addstr(&(msg->buf), arg);
433         msg->given = 1;
434         return 0;
435 }
436
437 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
438 {
439         if (name[0] == '-')
440                 return CHECK_REF_FORMAT_ERROR;
441
442         strbuf_reset(sb);
443         strbuf_addf(sb, "refs/tags/%s", name);
444
445         return check_ref_format(sb->buf);
446 }
447
448 int cmd_tag(int argc, const char **argv, const char *prefix)
449 {
450         struct strbuf buf = STRBUF_INIT;
451         struct strbuf ref = STRBUF_INIT;
452         unsigned char object[20], prev[20];
453         const char *object_ref, *tag;
454         struct ref_lock *lock;
455
456         int annotate = 0, sign = 0, force = 0, lines = -1,
457                 list = 0, delete = 0, verify = 0;
458         const char *msgfile = NULL, *keyid = NULL;
459         struct msg_arg msg = { 0, STRBUF_INIT };
460         struct commit_list *with_commit = NULL;
461         struct option options[] = {
462                 OPT_BOOLEAN('l', NULL, &list, "list tag names"),
463                 { OPTION_INTEGER, 'n', NULL, &lines, "n",
464                                 "print <n> lines of each tag message",
465                                 PARSE_OPT_OPTARG, NULL, 1 },
466                 OPT_BOOLEAN('d', NULL, &delete, "delete tags"),
467                 OPT_BOOLEAN('v', NULL, &verify, "verify tags"),
468
469                 OPT_GROUP("Tag creation options"),
470                 OPT_BOOLEAN('a', NULL, &annotate,
471                                         "annotated tag, needs a message"),
472                 OPT_CALLBACK('m', NULL, &msg, "message",
473                              "tag message", parse_msg_arg),
474                 OPT_FILENAME('F', NULL, &msgfile, "read message from file"),
475                 OPT_BOOLEAN('s', NULL, &sign, "annotated and GPG-signed tag"),
476                 OPT_STRING('u', NULL, &keyid, "key-id",
477                                         "use another key to sign the tag"),
478                 OPT__FORCE(&force, "replace the tag if exists"),
479
480                 OPT_GROUP("Tag listing options"),
481                 {
482                         OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
483                         "print only tags that contain the commit",
484                         PARSE_OPT_LASTARG_DEFAULT,
485                         parse_opt_with_commit, (intptr_t)"HEAD",
486                 },
487                 OPT_END()
488         };
489
490         git_config(git_tag_config, NULL);
491
492         argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
493
494         if (keyid) {
495                 sign = 1;
496                 set_signingkey(keyid);
497         }
498         if (sign)
499                 annotate = 1;
500         if (argc == 0 && !(delete || verify))
501                 list = 1;
502
503         if ((annotate || msg.given || msgfile || force) &&
504             (list || delete || verify))
505                 usage_with_options(git_tag_usage, options);
506
507         if (list + delete + verify > 1)
508                 usage_with_options(git_tag_usage, options);
509         if (list)
510                 return list_tags(argv, lines == -1 ? 0 : lines,
511                                  with_commit);
512         if (lines != -1)
513                 die(_("-n option is only allowed with -l."));
514         if (with_commit)
515                 die(_("--contains option is only allowed with -l."));
516         if (delete)
517                 return for_each_tag_name(argv, delete_tag);
518         if (verify)
519                 return for_each_tag_name(argv, verify_tag);
520
521         if (msg.given || msgfile) {
522                 if (msg.given && msgfile)
523                         die(_("only one -F or -m option is allowed."));
524                 annotate = 1;
525                 if (msg.given)
526                         strbuf_addbuf(&buf, &(msg.buf));
527                 else {
528                         if (!strcmp(msgfile, "-")) {
529                                 if (strbuf_read(&buf, 0, 1024) < 0)
530                                         die_errno(_("cannot read '%s'"), msgfile);
531                         } else {
532                                 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
533                                         die_errno(_("could not open or read '%s'"),
534                                                 msgfile);
535                         }
536                 }
537         }
538
539         tag = argv[0];
540
541         object_ref = argc == 2 ? argv[1] : "HEAD";
542         if (argc > 2)
543                 die(_("too many params"));
544
545         if (get_sha1(object_ref, object))
546                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
547
548         if (strbuf_check_tag_ref(&ref, tag))
549                 die(_("'%s' is not a valid tag name."), tag);
550
551         if (!resolve_ref(ref.buf, prev, 1, NULL))
552                 hashclr(prev);
553         else if (!force)
554                 die(_("tag '%s' already exists"), tag);
555
556         if (annotate)
557                 create_tag(object, tag, &buf, msg.given || msgfile,
558                            sign, prev, object);
559
560         lock = lock_any_ref_for_update(ref.buf, prev, 0);
561         if (!lock)
562                 die(_("%s: cannot lock the ref"), ref.buf);
563         if (write_ref_sha1(lock, object, NULL) < 0)
564                 die(_("%s: cannot update the ref"), ref.buf);
565         if (force && hashcmp(prev, object))
566                 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
567
568         strbuf_release(&buf);
569         strbuf_release(&ref);
570         return 0;
571 }