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