help: respect aliases
[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
16 static const char * const git_tag_usage[] = {
17         "git-tag [-a|-s|-u <key-id>] [-f] [-m <msg>|-F <file>] <tagname> [<head>]",
18         "git-tag -d <tagname>...",
19         "git-tag -l [-n [<num>]] [<pattern>]",
20         "git-tag -v <tagname>...",
21         NULL
22 };
23
24 static char signingkey[1000];
25
26 void launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
27 {
28         const char *editor, *terminal;
29
30         editor = getenv("GIT_EDITOR");
31         if (!editor && editor_program)
32                 editor = editor_program;
33         if (!editor)
34                 editor = getenv("VISUAL");
35         if (!editor)
36                 editor = getenv("EDITOR");
37
38         terminal = getenv("TERM");
39         if (!editor && (!terminal || !strcmp(terminal, "dumb"))) {
40                 fprintf(stderr,
41                 "Terminal is dumb but no VISUAL nor EDITOR defined.\n"
42                 "Please supply the message using either -m or -F option.\n");
43                 exit(1);
44         }
45
46         if (!editor)
47                 editor = "vi";
48
49         if (strcmp(editor, ":")) {
50                 size_t len = strlen(editor);
51                 int i = 0;
52                 const char *args[6];
53
54                 if (strcspn(editor, "$ \t'") != len) {
55                         /* there are specials */
56                         args[i++] = "sh";
57                         args[i++] = "-c";
58                         args[i++] = "$0 \"$@\"";
59                 }
60                 args[i++] = editor;
61                 args[i++] = path;
62                 args[i] = NULL;
63
64                 if (run_command_v_opt_cd_env(args, 0, NULL, env))
65                         die("There was a problem with the editor %s.", editor);
66         }
67
68         if (!buffer)
69                 return;
70         if (strbuf_read_file(buffer, path, 0) < 0)
71                 die("could not read message file '%s': %s",
72                     path, strerror(errno));
73 }
74
75 struct tag_filter {
76         const char *pattern;
77         int lines;
78 };
79
80 #define PGP_SIGNATURE "-----BEGIN PGP SIGNATURE-----"
81
82 static int show_reference(const char *refname, const unsigned char *sha1,
83                           int flag, void *cb_data)
84 {
85         struct tag_filter *filter = cb_data;
86
87         if (!fnmatch(filter->pattern, refname, 0)) {
88                 int i;
89                 unsigned long size;
90                 enum object_type type;
91                 char *buf, *sp, *eol;
92                 size_t len;
93
94                 if (!filter->lines) {
95                         printf("%s\n", refname);
96                         return 0;
97                 }
98                 printf("%-15s ", refname);
99
100                 buf = read_sha1_file(sha1, &type, &size);
101                 if (!buf || !size)
102                         return 0;
103
104                 /* skip header */
105                 sp = strstr(buf, "\n\n");
106                 if (!sp) {
107                         free(buf);
108                         return 0;
109                 }
110                 /* only take up to "lines" lines, and strip the signature */
111                 for (i = 0, sp += 2;
112                                 i < filter->lines && sp < buf + size &&
113                                 prefixcmp(sp, PGP_SIGNATURE "\n");
114                                 i++) {
115                         if (i)
116                                 printf("\n    ");
117                         eol = memchr(sp, '\n', size - (sp - buf));
118                         len = eol ? eol - sp : size - (sp - buf);
119                         fwrite(sp, len, 1, stdout);
120                         if (!eol)
121                                 break;
122                         sp = eol + 1;
123                 }
124                 putchar('\n');
125                 free(buf);
126         }
127
128         return 0;
129 }
130
131 static int list_tags(const char *pattern, int lines)
132 {
133         struct tag_filter filter;
134
135         if (pattern == NULL)
136                 pattern = "*";
137
138         filter.pattern = pattern;
139         filter.lines = lines;
140
141         for_each_tag_ref(show_reference, (void *) &filter);
142
143         return 0;
144 }
145
146 typedef int (*each_tag_name_fn)(const char *name, const char *ref,
147                                 const unsigned char *sha1);
148
149 static int for_each_tag_name(const char **argv, each_tag_name_fn fn)
150 {
151         const char **p;
152         char ref[PATH_MAX];
153         int had_error = 0;
154         unsigned char sha1[20];
155
156         for (p = argv; *p; p++) {
157                 if (snprintf(ref, sizeof(ref), "refs/tags/%s", *p)
158                                         >= sizeof(ref)) {
159                         error("tag name too long: %.*s...", 50, *p);
160                         had_error = 1;
161                         continue;
162                 }
163                 if (!resolve_ref(ref, sha1, 1, NULL)) {
164                         error("tag '%s' not found.", *p);
165                         had_error = 1;
166                         continue;
167                 }
168                 if (fn(*p, ref, sha1))
169                         had_error = 1;
170         }
171         return had_error;
172 }
173
174 static int delete_tag(const char *name, const char *ref,
175                                 const unsigned char *sha1)
176 {
177         if (delete_ref(ref, sha1))
178                 return 1;
179         printf("Deleted tag '%s'\n", name);
180         return 0;
181 }
182
183 static int verify_tag(const char *name, const char *ref,
184                                 const unsigned char *sha1)
185 {
186         const char *argv_verify_tag[] = {"git-verify-tag",
187                                         "-v", "SHA1_HEX", NULL};
188         argv_verify_tag[2] = sha1_to_hex(sha1);
189
190         if (run_command_v_opt(argv_verify_tag, 0))
191                 return error("could not verify the tag '%s'", name);
192         return 0;
193 }
194
195 static int do_sign(struct strbuf *buffer)
196 {
197         struct child_process gpg;
198         const char *args[4];
199         char *bracket;
200         int len;
201
202         if (!*signingkey) {
203                 if (strlcpy(signingkey, git_committer_info(IDENT_ERROR_ON_NO_NAME),
204                                 sizeof(signingkey)) > sizeof(signingkey) - 1)
205                         return error("committer info too long.");
206                 bracket = strchr(signingkey, '>');
207                 if (bracket)
208                         bracket[1] = '\0';
209         }
210
211         /* When the username signingkey is bad, program could be terminated
212          * because gpg exits without reading and then write gets SIGPIPE. */
213         signal(SIGPIPE, SIG_IGN);
214
215         memset(&gpg, 0, sizeof(gpg));
216         gpg.argv = args;
217         gpg.in = -1;
218         gpg.out = -1;
219         args[0] = "gpg";
220         args[1] = "-bsau";
221         args[2] = signingkey;
222         args[3] = NULL;
223
224         if (start_command(&gpg))
225                 return error("could not run gpg.");
226
227         if (write_in_full(gpg.in, buffer->buf, buffer->len) != buffer->len) {
228                 close(gpg.in);
229                 finish_command(&gpg);
230                 return error("gpg did not accept the tag data");
231         }
232         close(gpg.in);
233         gpg.close_in = 0;
234         len = strbuf_read(buffer, gpg.out, 1024);
235
236         if (finish_command(&gpg) || !len || len < 0)
237                 return error("gpg failed to sign the tag");
238
239         return 0;
240 }
241
242 static const char tag_template[] =
243         "\n"
244         "#\n"
245         "# Write a tag message\n"
246         "#\n";
247
248 static void set_signingkey(const char *value)
249 {
250         if (strlcpy(signingkey, value, sizeof(signingkey)) >= sizeof(signingkey))
251                 die("signing key value too long (%.10s...)", value);
252 }
253
254 static int git_tag_config(const char *var, const char *value)
255 {
256         if (!strcmp(var, "user.signingkey")) {
257                 if (!value)
258                         return config_error_nonbool(value);
259                 set_signingkey(value);
260                 return 0;
261         }
262
263         return git_default_config(var, value);
264 }
265
266 static void write_tag_body(int fd, const unsigned char *sha1)
267 {
268         unsigned long size;
269         enum object_type type;
270         char *buf, *sp, *eob;
271         size_t len;
272
273         buf = read_sha1_file(sha1, &type, &size);
274         if (!buf)
275                 return;
276         /* skip header */
277         sp = strstr(buf, "\n\n");
278
279         if (!sp || !size || type != OBJ_TAG) {
280                 free(buf);
281                 return;
282         }
283         sp += 2; /* skip the 2 LFs */
284         eob = strstr(sp, "\n" PGP_SIGNATURE "\n");
285         if (eob)
286                 len = eob - sp;
287         else
288                 len = buf + size - sp;
289         write_or_die(fd, sp, len);
290
291         free(buf);
292 }
293
294 static void create_tag(const unsigned char *object, const char *tag,
295                        struct strbuf *buf, int message, int sign,
296                        unsigned char *prev, unsigned char *result)
297 {
298         enum object_type type;
299         char header_buf[1024];
300         int header_len;
301
302         type = sha1_object_info(object, NULL);
303         if (type <= OBJ_NONE)
304             die("bad object type.");
305
306         header_len = snprintf(header_buf, sizeof(header_buf),
307                           "object %s\n"
308                           "type %s\n"
309                           "tag %s\n"
310                           "tagger %s\n\n",
311                           sha1_to_hex(object),
312                           typename(type),
313                           tag,
314                           git_committer_info(IDENT_ERROR_ON_NO_NAME));
315
316         if (header_len > sizeof(header_buf) - 1)
317                 die("tag header too big.");
318
319         if (!message) {
320                 char *path;
321                 int fd;
322
323                 /* write the template message before editing: */
324                 path = xstrdup(git_path("TAG_EDITMSG"));
325                 fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
326                 if (fd < 0)
327                         die("could not create file '%s': %s",
328                                                 path, strerror(errno));
329
330                 if (!is_null_sha1(prev))
331                         write_tag_body(fd, prev);
332                 else
333                         write_or_die(fd, tag_template, strlen(tag_template));
334                 close(fd);
335
336                 launch_editor(path, buf, NULL);
337
338                 unlink(path);
339                 free(path);
340         }
341
342         stripspace(buf, 1);
343
344         if (!message && !buf->len)
345                 die("no tag message?");
346
347         strbuf_insert(buf, 0, header_buf, header_len);
348
349         if (sign && do_sign(buf) < 0)
350                 die("unable to sign the tag");
351         if (write_sha1_file(buf->buf, buf->len, tag_type, result) < 0)
352                 die("unable to write tag file");
353 }
354
355 struct msg_arg {
356         int given;
357         struct strbuf buf;
358 };
359
360 static int parse_msg_arg(const struct option *opt, const char *arg, int unset)
361 {
362         struct msg_arg *msg = opt->value;
363
364         if (!arg)
365                 return -1;
366         if (msg->buf.len)
367                 strbuf_addstr(&(msg->buf), "\n\n");
368         strbuf_addstr(&(msg->buf), arg);
369         msg->given = 1;
370         return 0;
371 }
372
373 int cmd_tag(int argc, const char **argv, const char *prefix)
374 {
375         struct strbuf buf;
376         unsigned char object[20], prev[20];
377         char ref[PATH_MAX];
378         const char *object_ref, *tag;
379         struct ref_lock *lock;
380
381         int annotate = 0, sign = 0, force = 0, lines = 0,
382                 list = 0, delete = 0, verify = 0;
383         char *msgfile = NULL, *keyid = NULL;
384         struct msg_arg msg = { 0, STRBUF_INIT };
385         struct option options[] = {
386                 OPT_BOOLEAN('l', NULL, &list, "list tag names"),
387                 { OPTION_INTEGER, 'n', NULL, &lines, NULL,
388                                 "print n lines of each tag message",
389                                 PARSE_OPT_OPTARG, NULL, 1 },
390                 OPT_BOOLEAN('d', NULL, &delete, "delete tags"),
391                 OPT_BOOLEAN('v', NULL, &verify, "verify tags"),
392
393                 OPT_GROUP("Tag creation options"),
394                 OPT_BOOLEAN('a', NULL, &annotate,
395                                         "annotated tag, needs a message"),
396                 OPT_CALLBACK('m', NULL, &msg, "msg",
397                              "message for the tag", parse_msg_arg),
398                 OPT_STRING('F', NULL, &msgfile, "file", "message in a file"),
399                 OPT_BOOLEAN('s', NULL, &sign, "annotated and GPG-signed tag"),
400                 OPT_STRING('u', NULL, &keyid, "key-id",
401                                         "use another key to sign the tag"),
402                 OPT_BOOLEAN('f', NULL, &force, "replace the tag if exists"),
403                 OPT_END()
404         };
405
406         git_config(git_tag_config);
407
408         argc = parse_options(argc, argv, options, git_tag_usage, 0);
409
410         if (keyid) {
411                 sign = 1;
412                 set_signingkey(keyid);
413         }
414         if (sign)
415                 annotate = 1;
416
417         if (list)
418                 return list_tags(argv[0], lines);
419         if (delete)
420                 return for_each_tag_name(argv, delete_tag);
421         if (verify)
422                 return for_each_tag_name(argv, verify_tag);
423
424         strbuf_init(&buf, 0);
425         if (msg.given || msgfile) {
426                 if (msg.given && msgfile)
427                         die("only one -F or -m option is allowed.");
428                 annotate = 1;
429                 if (msg.given)
430                         strbuf_addbuf(&buf, &(msg.buf));
431                 else {
432                         if (!strcmp(msgfile, "-")) {
433                                 if (strbuf_read(&buf, 0, 1024) < 0)
434                                         die("cannot read %s", msgfile);
435                         } else {
436                                 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
437                                         die("could not open or read '%s': %s",
438                                                 msgfile, strerror(errno));
439                         }
440                 }
441         }
442
443         if (argc == 0) {
444                 if (annotate)
445                         usage_with_options(git_tag_usage, options);
446                 return list_tags(NULL, lines);
447         }
448         tag = argv[0];
449
450         object_ref = argc == 2 ? argv[1] : "HEAD";
451         if (argc > 2)
452                 die("too many params");
453
454         if (get_sha1(object_ref, object))
455                 die("Failed to resolve '%s' as a valid ref.", object_ref);
456
457         if (snprintf(ref, sizeof(ref), "refs/tags/%s", tag) > sizeof(ref) - 1)
458                 die("tag name too long: %.*s...", 50, tag);
459         if (check_ref_format(ref))
460                 die("'%s' is not a valid tag name.", tag);
461
462         if (!resolve_ref(ref, prev, 1, NULL))
463                 hashclr(prev);
464         else if (!force)
465                 die("tag '%s' already exists", tag);
466
467         if (annotate)
468                 create_tag(object, tag, &buf, msg.given || msgfile,
469                            sign, prev, object);
470
471         lock = lock_any_ref_for_update(ref, prev, 0);
472         if (!lock)
473                 die("%s: cannot lock the ref", ref);
474         if (write_ref_sha1(lock, object, NULL) < 0)
475                 die("%s: cannot update the ref", ref);
476
477         strbuf_release(&buf);
478         return 0;
479 }