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