Code

tag: add --points-at list option
[git.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  */
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"
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 };
29 struct tag_filter {
30         const char **patterns;
31         int lines;
32         struct commit_list *with_commit;
33 };
35 static struct sha1_array points_at;
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 }
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;
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 }
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 }
74 static int contains_recurse(struct commit *candidate,
75                             const struct commit_list *want)
76 {
77         struct commit_list *p;
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;
89         if (parse_commit(candidate) < 0)
90                 return 0;
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;
103 static int contains(struct commit *candidate, const struct commit_list *want)
105         return contains_recurse(candidate, want);
108 static int show_reference(const char *refname, const unsigned char *sha1,
109                           int flag, void *cb_data)
111         struct tag_filter *filter = cb_data;
113         if (match_pattern(filter->patterns, refname)) {
114                 int i;
115                 unsigned long size;
116                 enum object_type type;
117                 char *buf, *sp, *eol;
118                 size_t len;
120                 if (filter->with_commit) {
121                         struct commit *commit;
123                         commit = lookup_commit_reference_gently(sha1, 1);
124                         if (!commit)
125                                 return 0;
126                         if (!contains(commit, filter->with_commit))
127                                 return 0;
128                 }
130                 if (points_at.nr && !match_points_at(refname, sha1))
131                         return 0;
133                 if (!filter->lines) {
134                         printf("%s\n", refname);
135                         return 0;
136                 }
137                 printf("%-15s ", refname);
139                 buf = read_sha1_file(sha1, &type, &size);
140                 if (!buf || !size)
141                         return 0;
143                 /* skip header */
144                 sp = strstr(buf, "\n\n");
145                 if (!sp) {
146                         free(buf);
147                         return 0;
148                 }
149                 /* only take up to "lines" lines, and strip the signature */
150                 size = parse_signature(buf, size);
151                 for (i = 0, sp += 2;
152                                 i < filter->lines && sp < buf + size;
153                                 i++) {
154                         if (i)
155                                 printf("\n    ");
156                         eol = memchr(sp, '\n', size - (sp - buf));
157                         len = eol ? eol - sp : size - (sp - buf);
158                         fwrite(sp, len, 1, stdout);
159                         if (!eol)
160                                 break;
161                         sp = eol + 1;
162                 }
163                 putchar('\n');
164                 free(buf);
165         }
167         return 0;
170 static int list_tags(const char **patterns, int lines,
171                         struct commit_list *with_commit)
173         struct tag_filter filter;
175         filter.patterns = patterns;
176         filter.lines = lines;
177         filter.with_commit = with_commit;
179         for_each_tag_ref(show_reference, (void *) &filter);
181         return 0;
184 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
185                                 const unsigned char *sha1);
187 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
189         const char **p;
190         char ref[PATH_MAX];
191         int had_error = 0;
192         unsigned char sha1[20];
194         for (p = argv; *p; p++) {
195                 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
196                                         >= sizeof(ref)) {
197                         error(_("tag name too long: %.*s..."), 50, *p);
198                         had_error = 1;
199                         continue;
200                 }
201                 if (read_ref(ref, sha1)) {
202                         error(_("tag '%s' not found."), *p);
203                         had_error = 1;
204                         continue;
205                 }
206                 if (fn(*p, ref, sha1))
207                         had_error = 1;
208         }
209         return had_error;
212 static int delete_tag(const char *name, const char *ref,
213                                 const unsigned char *sha1)
215         if (delete_ref(ref, sha1, 0))
216                 return 1;
217         printf(_("Deleted tag '%s' (was %s)\n"), name, find_unique_abbrev(sha1, DEFAULT_ABBREV));
218         return 0;
221 static int verify_tag(const char *name, const char *ref,
222                                 const unsigned char *sha1)
224         const char *argv_verify_tag[] = {"verify-tag",
225                                         "-v", "SHA1_HEX", NULL};
226         argv_verify_tag[2] = sha1_to_hex(sha1);
228         if (run_command_v_opt(argv_verify_tag, RUN_GIT_CMD))
229                 return error(_("could not verify the tag '%s'"), name);
230         return 0;
233 static int do_sign(struct strbuf *buffer)
235         return sign_buffer(buffer, buffer, get_signing_key());
238 static const char tag_template[] =
239         N_("\n"
240         "#\n"
241         "# Write a tag message\n"
242         "# Lines starting with '#' will be ignored.\n"
243         "#\n");
245 static const char tag_template_nocleanup[] =
246         N_("\n"
247         "#\n"
248         "# Write a tag message\n"
249         "# Lines starting with '#' will be kept; you may remove them"
250         " yourself if you want to.\n"
251         "#\n");
253 static int git_tag_config(const char *var, const char *value, void *cb)
255         int status = git_gpg_config(var, value, cb);
256         if (status)
257                 return status;
258         return git_default_config(var, value, cb);
261 static void write_tag_body(int fd, const unsigned char *sha1)
263         unsigned long size;
264         enum object_type type;
265         char *buf, *sp;
267         buf = read_sha1_file(sha1, &type, &size);
268         if (!buf)
269                 return;
270         /* skip header */
271         sp = strstr(buf, "\n\n");
273         if (!sp || !size || type != OBJ_TAG) {
274                 free(buf);
275                 return;
276         }
277         sp += 2; /* skip the 2 LFs */
278         write_or_die(fd, sp, parse_signature(sp, buf + size - sp));
280         free(buf);
283 static int build_tag_object(struct strbuf *buf, int sign, unsigned char *result)
285         if (sign && do_sign(buf) < 0)
286                 return error(_("unable to sign the tag"));
287         if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
288                 return error(_("unable to write tag file"));
289         return 0;
292 struct create_tag_options {
293         unsigned int message_given:1;
294         unsigned int sign;
295         enum {
296                 CLEANUP_NONE,
297                 CLEANUP_SPACE,
298                 CLEANUP_ALL
299         } cleanup_mode;
300 };
302 static void create_tag(const unsigned char *object, const char *tag,
303                        struct strbuf *buf, struct create_tag_options *opt,
304                        unsigned char *prev, unsigned char *result)
306         enum object_type type;
307         char header_buf[1024];
308         int header_len;
309         char *path = NULL;
311         type = sha1_object_info(object, NULL);
312         if (type <= OBJ_NONE)
313             die(_("bad object type."));
315         header_len = snprintf(header_buf, sizeof(header_buf),
316                           "object %s\n"
317                           "type %s\n"
318                           "tag %s\n"
319                           "tagger %s\n\n",
320                           sha1_to_hex(object),
321                           typename(type),
322                           tag,
323                           git_committer_info(IDENT_ERROR_ON_NO_NAME));
325         if (header_len > sizeof(header_buf) - 1)
326                 die(_("tag header too big."));
328         if (!opt->message_given) {
329                 int fd;
331                 /* write the template message before editing: */
332                 path = git_pathdup("TAG_EDITMSG");
333                 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
334                 if (fd < 0)
335                         die_errno(_("could not create file '%s'"), path);
337                 if (!is_null_sha1(prev))
338                         write_tag_body(fd, prev);
339                 else if (opt->cleanup_mode == CLEANUP_ALL)
340                         write_or_die(fd, _(tag_template),
341                                         strlen(_(tag_template)));
342                 else
343                         write_or_die(fd, _(tag_template_nocleanup),
344                                         strlen(_(tag_template_nocleanup)));
345                 close(fd);
347                 if (launch_editor(path, buf, NULL)) {
348                         fprintf(stderr,
349                         _("Please supply the message using either -m or -F option.\n"));
350                         exit(1);
351                 }
352         }
354         if (opt->cleanup_mode != CLEANUP_NONE)
355                 stripspace(buf, opt->cleanup_mode == CLEANUP_ALL);
357         if (!opt->message_given && !buf->len)
358                 die(_("no tag message?"));
360         strbuf_insert(buf, 0, header_buf, header_len);
362         if (build_tag_object(buf, opt->sign, result) < 0) {
363                 if (path)
364                         fprintf(stderr, _("The tag message has been left in %s\n"),
365                                 path);
366                 exit(128);
367         }
368         if (path) {
369                 unlink_or_warn(path);
370                 free(path);
371         }
374 struct msg_arg {
375         int given;
376         struct strbuf buf;
377 };
379 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
381         struct msg_arg *msg = opt->value;
383         if (!arg)
384                 return -1;
385         if (msg->buf.len)
386                 strbuf_addstr(&(msg->buf), "\n\n");
387         strbuf_addstr(&(msg->buf), arg);
388         msg->given = 1;
389         return 0;
392 static int strbuf_check_tag_ref(struct strbuf *sb, const char *name)
394         if (name[0] == '-')
395                 return -1;
397         strbuf_reset(sb);
398         strbuf_addf(sb, "refs/tags/%s", name);
400         return check_refname_format(sb->buf, 0);
403 int parse_opt_points_at(const struct option *opt __attribute__ ((unused)),
404                         const char *arg, int unset)
406         unsigned char sha1[20];
408         if (unset) {
409                 sha1_array_clear(&points_at);
410                 return 0;
411         }
412         if (!arg)
413                 return error(_("switch 'points-at' requires an object"));
414         if (get_sha1(arg, sha1))
415                 return error(_("malformed object name '%s'"), arg);
416         sha1_array_append(&points_at, sha1);
417         return 0;
420 int cmd_tag(int argc, const char **argv, const char *prefix)
422         struct strbuf buf = STRBUF_INIT;
423         struct strbuf ref = STRBUF_INIT;
424         unsigned char object[20], prev[20];
425         const char *object_ref, *tag;
426         struct ref_lock *lock;
427         struct create_tag_options opt;
428         char *cleanup_arg = NULL;
429         int annotate = 0, force = 0, lines = -1, list = 0,
430                 delete = 0, verify = 0;
431         const char *msgfile = NULL, *keyid = NULL;
432         struct msg_arg msg = { 0, STRBUF_INIT };
433         struct commit_list *with_commit = NULL;
434         struct option options[] = {
435                 OPT_BOOLEAN('l', "list", &list, "list tag names"),
436                 { OPTION_INTEGER, 'n', NULL, &lines, "n",
437                                 "print <n> lines of each tag message",
438                                 PARSE_OPT_OPTARG, NULL, 1 },
439                 OPT_BOOLEAN('d', "delete", &delete, "delete tags"),
440                 OPT_BOOLEAN('v', "verify", &verify, "verify tags"),
442                 OPT_GROUP("Tag creation options"),
443                 OPT_BOOLEAN('a', "annotate", &annotate,
444                                         "annotated tag, needs a message"),
445                 OPT_CALLBACK('m', "message", &msg, "message",
446                              "tag message", parse_msg_arg),
447                 OPT_FILENAME('F', "file", &msgfile, "read message from file"),
448                 OPT_BOOLEAN('s', "sign", &opt.sign, "annotated and GPG-signed tag"),
449                 OPT_STRING(0, "cleanup", &cleanup_arg, "mode",
450                         "how to strip spaces and #comments from message"),
451                 OPT_STRING('u', "local-user", &keyid, "key-id",
452                                         "use another key to sign the tag"),
453                 OPT__FORCE(&force, "replace the tag if exists"),
455                 OPT_GROUP("Tag listing options"),
456                 {
457                         OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
458                         "print only tags that contain the commit",
459                         PARSE_OPT_LASTARG_DEFAULT,
460                         parse_opt_with_commit, (intptr_t)"HEAD",
461                 },
462                 {
463                         OPTION_CALLBACK, 0, "points-at", NULL, "object",
464                         "print only tags of the object", 0, parse_opt_points_at
465                 },
466                 OPT_END()
467         };
469         git_config(git_tag_config, NULL);
471         memset(&opt, 0, sizeof(opt));
473         argc = parse_options(argc, argv, prefix, options, git_tag_usage, 0);
475         if (keyid) {
476                 opt.sign = 1;
477                 set_signing_key(keyid);
478         }
479         if (opt.sign)
480                 annotate = 1;
481         if (argc == 0 && !(delete || verify))
482                 list = 1;
484         if ((annotate || msg.given || msgfile || force) &&
485             (list || delete || verify))
486                 usage_with_options(git_tag_usage, options);
488         if (list + delete + verify > 1)
489                 usage_with_options(git_tag_usage, options);
490         if (list)
491                 return list_tags(argv, lines == -1 ? 0 : lines,
492                                  with_commit);
493         if (lines != -1)
494                 die(_("-n option is only allowed with -l."));
495         if (with_commit)
496                 die(_("--contains option is only allowed with -l."));
497         if (points_at.nr)
498                 die(_("--points-at option is only allowed with -l."));
499         if (delete)
500                 return for_each_tag_name(argv, delete_tag);
501         if (verify)
502                 return for_each_tag_name(argv, verify_tag);
504         if (msg.given || msgfile) {
505                 if (msg.given && msgfile)
506                         die(_("only one -F or -m option is allowed."));
507                 annotate = 1;
508                 if (msg.given)
509                         strbuf_addbuf(&buf, &(msg.buf));
510                 else {
511                         if (!strcmp(msgfile, "-")) {
512                                 if (strbuf_read(&buf, 0, 1024) < 0)
513                                         die_errno(_("cannot read '%s'"), msgfile);
514                         } else {
515                                 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
516                                         die_errno(_("could not open or read '%s'"),
517                                                 msgfile);
518                         }
519                 }
520         }
522         tag = argv[0];
524         object_ref = argc == 2 ? argv[1] : "HEAD";
525         if (argc > 2)
526                 die(_("too many params"));
528         if (get_sha1(object_ref, object))
529                 die(_("Failed to resolve '%s' as a valid ref."), object_ref);
531         if (strbuf_check_tag_ref(&ref, tag))
532                 die(_("'%s' is not a valid tag name."), tag);
534         if (read_ref(ref.buf, prev))
535                 hashclr(prev);
536         else if (!force)
537                 die(_("tag '%s' already exists"), tag);
539         opt.message_given = msg.given || msgfile;
541         if (!cleanup_arg || !strcmp(cleanup_arg, "strip"))
542                 opt.cleanup_mode = CLEANUP_ALL;
543         else if (!strcmp(cleanup_arg, "verbatim"))
544                 opt.cleanup_mode = CLEANUP_NONE;
545         else if (!strcmp(cleanup_arg, "whitespace"))
546                 opt.cleanup_mode = CLEANUP_SPACE;
547         else
548                 die(_("Invalid cleanup mode %s"), cleanup_arg);
550         if (annotate)
551                 create_tag(object, tag, &buf, &opt, prev, object);
553         lock = lock_any_ref_for_update(ref.buf, prev, 0);
554         if (!lock)
555                 die(_("%s: cannot lock the ref"), ref.buf);
556         if (write_ref_sha1(lock, object, NULL) < 0)
557                 die(_("%s: cannot update the ref"), ref.buf);
558         if (force && hashcmp(prev, object))
559                 printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
561         strbuf_release(&buf);
562         strbuf_release(&ref);
563         return 0;