fmt-merge-msg: plug small leak of commit buffer
[git] / builtin / fmt-merge-msg.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "commit.h"
4 #include "diff.h"
5 #include "revision.h"
6 #include "tag.h"
7 #include "string-list.h"
8 #include "branch.h"
9 #include "fmt-merge-msg.h"
10 #include "gpg-interface.h"
11
12 static const char * const fmt_merge_msg_usage[] = {
13         N_("git fmt-merge-msg [-m <message>] [--log[=<n>]|--no-log] [--file <file>]"),
14         NULL
15 };
16
17 static int use_branch_desc;
18
19 int fmt_merge_msg_config(const char *key, const char *value, void *cb)
20 {
21         if (!strcmp(key, "merge.log") || !strcmp(key, "merge.summary")) {
22                 int is_bool;
23                 merge_log_config = git_config_bool_or_int(key, value, &is_bool);
24                 if (!is_bool && merge_log_config < 0)
25                         return error("%s: negative length %s", key, value);
26                 if (is_bool && merge_log_config)
27                         merge_log_config = DEFAULT_MERGE_LOG_LEN;
28         } else if (!strcmp(key, "merge.branchdesc")) {
29                 use_branch_desc = git_config_bool(key, value);
30         } else {
31                 return git_default_config(key, value, cb);
32         }
33         return 0;
34 }
35
36 /* merge data per repository where the merged tips came from */
37 struct src_data {
38         struct string_list branch, tag, r_branch, generic;
39         int head_status;
40 };
41
42 struct origin_data {
43         unsigned char sha1[20];
44         unsigned is_local_branch:1;
45 };
46
47 static void init_src_data(struct src_data *data)
48 {
49         data->branch.strdup_strings = 1;
50         data->tag.strdup_strings = 1;
51         data->r_branch.strdup_strings = 1;
52         data->generic.strdup_strings = 1;
53 }
54
55 static struct string_list srcs = STRING_LIST_INIT_DUP;
56 static struct string_list origins = STRING_LIST_INIT_DUP;
57
58 struct merge_parents {
59         int alloc, nr;
60         struct merge_parent {
61                 unsigned char given[20];
62                 unsigned char commit[20];
63                 unsigned char used;
64         } *item;
65 };
66
67 /*
68  * I know, I know, this is inefficient, but you won't be pulling and merging
69  * hundreds of heads at a time anyway.
70  */
71 static struct merge_parent *find_merge_parent(struct merge_parents *table,
72                                               unsigned char *given,
73                                               unsigned char *commit)
74 {
75         int i;
76         for (i = 0; i < table->nr; i++) {
77                 if (given && hashcmp(table->item[i].given, given))
78                         continue;
79                 if (commit && hashcmp(table->item[i].commit, commit))
80                         continue;
81                 return &table->item[i];
82         }
83         return NULL;
84 }
85
86 static void add_merge_parent(struct merge_parents *table,
87                              unsigned char *given,
88                              unsigned char *commit)
89 {
90         if (table->nr && find_merge_parent(table, given, commit))
91                 return;
92         ALLOC_GROW(table->item, table->nr + 1, table->alloc);
93         hashcpy(table->item[table->nr].given, given);
94         hashcpy(table->item[table->nr].commit, commit);
95         table->item[table->nr].used = 0;
96         table->nr++;
97 }
98
99 static int handle_line(char *line, struct merge_parents *merge_parents)
100 {
101         int i, len = strlen(line);
102         struct origin_data *origin_data;
103         char *src, *origin;
104         struct src_data *src_data;
105         struct string_list_item *item;
106         int pulling_head = 0;
107         unsigned char sha1[20];
108
109         if (len < 43 || line[40] != '\t')
110                 return 1;
111
112         if (starts_with(line + 41, "not-for-merge"))
113                 return 0;
114
115         if (line[41] != '\t')
116                 return 2;
117
118         i = get_sha1_hex(line, sha1);
119         if (i)
120                 return 3;
121
122         if (!find_merge_parent(merge_parents, sha1, NULL))
123                 return 0; /* subsumed by other parents */
124
125         origin_data = xcalloc(1, sizeof(struct origin_data));
126         hashcpy(origin_data->sha1, sha1);
127
128         if (line[len - 1] == '\n')
129                 line[len - 1] = 0;
130         line += 42;
131
132         /*
133          * At this point, line points at the beginning of comment e.g.
134          * "branch 'frotz' of git://that/repository.git".
135          * Find the repository name and point it with src.
136          */
137         src = strstr(line, " of ");
138         if (src) {
139                 *src = 0;
140                 src += 4;
141                 pulling_head = 0;
142         } else {
143                 src = line;
144                 pulling_head = 1;
145         }
146
147         item = unsorted_string_list_lookup(&srcs, src);
148         if (!item) {
149                 item = string_list_append(&srcs, src);
150                 item->util = xcalloc(1, sizeof(struct src_data));
151                 init_src_data(item->util);
152         }
153         src_data = item->util;
154
155         if (pulling_head) {
156                 origin = src;
157                 src_data->head_status |= 1;
158         } else if (starts_with(line, "branch ")) {
159                 origin_data->is_local_branch = 1;
160                 origin = line + 7;
161                 string_list_append(&src_data->branch, origin);
162                 src_data->head_status |= 2;
163         } else if (starts_with(line, "tag ")) {
164                 origin = line;
165                 string_list_append(&src_data->tag, origin + 4);
166                 src_data->head_status |= 2;
167         } else if (starts_with(line, "remote-tracking branch ")) {
168                 origin = line + strlen("remote-tracking branch ");
169                 string_list_append(&src_data->r_branch, origin);
170                 src_data->head_status |= 2;
171         } else {
172                 origin = src;
173                 string_list_append(&src_data->generic, line);
174                 src_data->head_status |= 2;
175         }
176
177         if (!strcmp(".", src) || !strcmp(src, origin)) {
178                 int len = strlen(origin);
179                 if (origin[0] == '\'' && origin[len - 1] == '\'')
180                         origin = xmemdupz(origin + 1, len - 2);
181         } else {
182                 char *new_origin = xmalloc(strlen(origin) + strlen(src) + 5);
183                 sprintf(new_origin, "%s of %s", origin, src);
184                 origin = new_origin;
185         }
186         if (strcmp(".", src))
187                 origin_data->is_local_branch = 0;
188         string_list_append(&origins, origin)->util = origin_data;
189         return 0;
190 }
191
192 static void print_joined(const char *singular, const char *plural,
193                 struct string_list *list, struct strbuf *out)
194 {
195         if (list->nr == 0)
196                 return;
197         if (list->nr == 1) {
198                 strbuf_addf(out, "%s%s", singular, list->items[0].string);
199         } else {
200                 int i;
201                 strbuf_addstr(out, plural);
202                 for (i = 0; i < list->nr - 1; i++)
203                         strbuf_addf(out, "%s%s", i > 0 ? ", " : "",
204                                     list->items[i].string);
205                 strbuf_addf(out, " and %s", list->items[list->nr - 1].string);
206         }
207 }
208
209 static void add_branch_desc(struct strbuf *out, const char *name)
210 {
211         struct strbuf desc = STRBUF_INIT;
212
213         if (!read_branch_desc(&desc, name)) {
214                 const char *bp = desc.buf;
215                 while (*bp) {
216                         const char *ep = strchrnul(bp, '\n');
217                         if (*ep)
218                                 ep++;
219                         strbuf_addf(out, "  : %.*s", (int)(ep - bp), bp);
220                         bp = ep;
221                 }
222                 if (out->buf[out->len - 1] != '\n')
223                         strbuf_addch(out, '\n');
224         }
225         strbuf_release(&desc);
226 }
227
228 #define util_as_integral(elem) ((intptr_t)((elem)->util))
229
230 static void record_person_from_buf(int which, struct string_list *people,
231                                    const char *buffer)
232 {
233         char *name_buf, *name, *name_end;
234         struct string_list_item *elem;
235         const char *field;
236
237         field = (which == 'a') ? "\nauthor " : "\ncommitter ";
238         name = strstr(buffer, field);
239         if (!name)
240                 return;
241         name += strlen(field);
242         name_end = strchrnul(name, '<');
243         if (*name_end)
244                 name_end--;
245         while (isspace(*name_end) && name <= name_end)
246                 name_end--;
247         if (name_end < name)
248                 return;
249         name_buf = xmemdupz(name, name_end - name + 1);
250
251         elem = string_list_lookup(people, name_buf);
252         if (!elem) {
253                 elem = string_list_insert(people, name_buf);
254                 elem->util = (void *)0;
255         }
256         elem->util = (void*)(util_as_integral(elem) + 1);
257         free(name_buf);
258 }
259
260
261 static void record_person(int which, struct string_list *people,
262                           struct commit *commit)
263 {
264         const char *buffer = get_commit_buffer(commit);
265         record_person_from_buf(which, people, buffer);
266         unuse_commit_buffer(commit, buffer);
267 }
268
269 static int cmp_string_list_util_as_integral(const void *a_, const void *b_)
270 {
271         const struct string_list_item *a = a_, *b = b_;
272         return util_as_integral(b) - util_as_integral(a);
273 }
274
275 static void add_people_count(struct strbuf *out, struct string_list *people)
276 {
277         if (people->nr == 1)
278                 strbuf_addf(out, "%s", people->items[0].string);
279         else if (people->nr == 2)
280                 strbuf_addf(out, "%s (%d) and %s (%d)",
281                             people->items[0].string,
282                             (int)util_as_integral(&people->items[0]),
283                             people->items[1].string,
284                             (int)util_as_integral(&people->items[1]));
285         else if (people->nr)
286                 strbuf_addf(out, "%s (%d) and others",
287                             people->items[0].string,
288                             (int)util_as_integral(&people->items[0]));
289 }
290
291 static void credit_people(struct strbuf *out,
292                           struct string_list *them,
293                           int kind)
294 {
295         const char *label;
296         const char *me;
297
298         if (kind == 'a') {
299                 label = "By";
300                 me = git_author_info(IDENT_NO_DATE);
301         } else {
302                 label = "Via";
303                 me = git_committer_info(IDENT_NO_DATE);
304         }
305
306         if (!them->nr ||
307             (them->nr == 1 &&
308              me &&
309              (me = skip_prefix(me, them->items->string)) != NULL &&
310              skip_prefix(me, " <")))
311                 return;
312         strbuf_addf(out, "\n%c %s ", comment_line_char, label);
313         add_people_count(out, them);
314 }
315
316 static void add_people_info(struct strbuf *out,
317                             struct string_list *authors,
318                             struct string_list *committers)
319 {
320         if (authors->nr)
321                 qsort(authors->items,
322                       authors->nr, sizeof(authors->items[0]),
323                       cmp_string_list_util_as_integral);
324         if (committers->nr)
325                 qsort(committers->items,
326                       committers->nr, sizeof(committers->items[0]),
327                       cmp_string_list_util_as_integral);
328
329         credit_people(out, authors, 'a');
330         credit_people(out, committers, 'c');
331 }
332
333 static void shortlog(const char *name,
334                      struct origin_data *origin_data,
335                      struct commit *head,
336                      struct rev_info *rev,
337                      struct fmt_merge_msg_opts *opts,
338                      struct strbuf *out)
339 {
340         int i, count = 0;
341         struct commit *commit;
342         struct object *branch;
343         struct string_list subjects = STRING_LIST_INIT_DUP;
344         struct string_list authors = STRING_LIST_INIT_DUP;
345         struct string_list committers = STRING_LIST_INIT_DUP;
346         int flags = UNINTERESTING | TREESAME | SEEN | SHOWN | ADDED;
347         struct strbuf sb = STRBUF_INIT;
348         const unsigned char *sha1 = origin_data->sha1;
349         int limit = opts->shortlog_len;
350
351         branch = deref_tag(parse_object(sha1), sha1_to_hex(sha1), 40);
352         if (!branch || branch->type != OBJ_COMMIT)
353                 return;
354
355         setup_revisions(0, NULL, rev, NULL);
356         add_pending_object(rev, branch, name);
357         add_pending_object(rev, &head->object, "^HEAD");
358         head->object.flags |= UNINTERESTING;
359         if (prepare_revision_walk(rev))
360                 die("revision walk setup failed");
361         while ((commit = get_revision(rev)) != NULL) {
362                 struct pretty_print_context ctx = {0};
363
364                 if (commit->parents && commit->parents->next) {
365                         /* do not list a merge but count committer */
366                         if (opts->credit_people)
367                                 record_person('c', &committers, commit);
368                         continue;
369                 }
370                 if (!count && opts->credit_people)
371                         /* the 'tip' committer */
372                         record_person('c', &committers, commit);
373                 if (opts->credit_people)
374                         record_person('a', &authors, commit);
375                 count++;
376                 if (subjects.nr > limit)
377                         continue;
378
379                 format_commit_message(commit, "%s", &sb, &ctx);
380                 strbuf_ltrim(&sb);
381
382                 if (!sb.len)
383                         string_list_append(&subjects,
384                                            sha1_to_hex(commit->object.sha1));
385                 else
386                         string_list_append(&subjects, strbuf_detach(&sb, NULL));
387         }
388
389         if (opts->credit_people)
390                 add_people_info(out, &authors, &committers);
391         if (count > limit)
392                 strbuf_addf(out, "\n* %s: (%d commits)\n", name, count);
393         else
394                 strbuf_addf(out, "\n* %s:\n", name);
395
396         if (origin_data->is_local_branch && use_branch_desc)
397                 add_branch_desc(out, name);
398
399         for (i = 0; i < subjects.nr; i++)
400                 if (i >= limit)
401                         strbuf_addf(out, "  ...\n");
402                 else
403                         strbuf_addf(out, "  %s\n", subjects.items[i].string);
404
405         clear_commit_marks((struct commit *)branch, flags);
406         clear_commit_marks(head, flags);
407         free_commit_list(rev->commits);
408         rev->commits = NULL;
409         rev->pending.nr = 0;
410
411         string_list_clear(&authors, 0);
412         string_list_clear(&committers, 0);
413         string_list_clear(&subjects, 0);
414 }
415
416 static void fmt_merge_msg_title(struct strbuf *out,
417         const char *current_branch) {
418         int i = 0;
419         char *sep = "";
420
421         strbuf_addstr(out, "Merge ");
422         for (i = 0; i < srcs.nr; i++) {
423                 struct src_data *src_data = srcs.items[i].util;
424                 const char *subsep = "";
425
426                 strbuf_addstr(out, sep);
427                 sep = "; ";
428
429                 if (src_data->head_status == 1) {
430                         strbuf_addstr(out, srcs.items[i].string);
431                         continue;
432                 }
433                 if (src_data->head_status == 3) {
434                         subsep = ", ";
435                         strbuf_addstr(out, "HEAD");
436                 }
437                 if (src_data->branch.nr) {
438                         strbuf_addstr(out, subsep);
439                         subsep = ", ";
440                         print_joined("branch ", "branches ", &src_data->branch,
441                                         out);
442                 }
443                 if (src_data->r_branch.nr) {
444                         strbuf_addstr(out, subsep);
445                         subsep = ", ";
446                         print_joined("remote-tracking branch ", "remote-tracking branches ",
447                                         &src_data->r_branch, out);
448                 }
449                 if (src_data->tag.nr) {
450                         strbuf_addstr(out, subsep);
451                         subsep = ", ";
452                         print_joined("tag ", "tags ", &src_data->tag, out);
453                 }
454                 if (src_data->generic.nr) {
455                         strbuf_addstr(out, subsep);
456                         print_joined("commit ", "commits ", &src_data->generic,
457                                         out);
458                 }
459                 if (strcmp(".", srcs.items[i].string))
460                         strbuf_addf(out, " of %s", srcs.items[i].string);
461         }
462
463         if (!strcmp("master", current_branch))
464                 strbuf_addch(out, '\n');
465         else
466                 strbuf_addf(out, " into %s\n", current_branch);
467 }
468
469 static void fmt_tag_signature(struct strbuf *tagbuf,
470                               struct strbuf *sig,
471                               const char *buf,
472                               unsigned long len)
473 {
474         const char *tag_body = strstr(buf, "\n\n");
475         if (tag_body) {
476                 tag_body += 2;
477                 strbuf_add(tagbuf, tag_body, buf + len - tag_body);
478         }
479         strbuf_complete_line(tagbuf);
480         if (sig->len) {
481                 strbuf_addch(tagbuf, '\n');
482                 strbuf_add_commented_lines(tagbuf, sig->buf, sig->len);
483         }
484 }
485
486 static void fmt_merge_msg_sigs(struct strbuf *out)
487 {
488         int i, tag_number = 0, first_tag = 0;
489         struct strbuf tagbuf = STRBUF_INIT;
490
491         for (i = 0; i < origins.nr; i++) {
492                 unsigned char *sha1 = origins.items[i].util;
493                 enum object_type type;
494                 unsigned long size, len;
495                 char *buf = read_sha1_file(sha1, &type, &size);
496                 struct strbuf sig = STRBUF_INIT;
497
498                 if (!buf || type != OBJ_TAG)
499                         goto next;
500                 len = parse_signature(buf, size);
501
502                 if (size == len)
503                         ; /* merely annotated */
504                 else if (verify_signed_buffer(buf, len, buf + len, size - len, &sig, NULL)) {
505                         if (!sig.len)
506                                 strbuf_addstr(&sig, "gpg verification failed.\n");
507                 }
508
509                 if (!tag_number++) {
510                         fmt_tag_signature(&tagbuf, &sig, buf, len);
511                         first_tag = i;
512                 } else {
513                         if (tag_number == 2) {
514                                 struct strbuf tagline = STRBUF_INIT;
515                                 strbuf_addch(&tagline, '\n');
516                                 strbuf_add_commented_lines(&tagline,
517                                                 origins.items[first_tag].string,
518                                                 strlen(origins.items[first_tag].string));
519                                 strbuf_insert(&tagbuf, 0, tagline.buf,
520                                               tagline.len);
521                                 strbuf_release(&tagline);
522                         }
523                         strbuf_addch(&tagbuf, '\n');
524                         strbuf_add_commented_lines(&tagbuf,
525                                         origins.items[i].string,
526                                         strlen(origins.items[i].string));
527                         fmt_tag_signature(&tagbuf, &sig, buf, len);
528                 }
529                 strbuf_release(&sig);
530         next:
531                 free(buf);
532         }
533         if (tagbuf.len) {
534                 strbuf_addch(out, '\n');
535                 strbuf_addbuf(out, &tagbuf);
536         }
537         strbuf_release(&tagbuf);
538 }
539
540 static void find_merge_parents(struct merge_parents *result,
541                                struct strbuf *in, unsigned char *head)
542 {
543         struct commit_list *parents, *next;
544         struct commit *head_commit;
545         int pos = 0, i, j;
546
547         parents = NULL;
548         while (pos < in->len) {
549                 int len;
550                 char *p = in->buf + pos;
551                 char *newline = strchr(p, '\n');
552                 unsigned char sha1[20];
553                 struct commit *parent;
554                 struct object *obj;
555
556                 len = newline ? newline - p : strlen(p);
557                 pos += len + !!newline;
558
559                 if (len < 43 ||
560                     get_sha1_hex(p, sha1) ||
561                     p[40] != '\t' ||
562                     p[41] != '\t')
563                         continue; /* skip not-for-merge */
564                 /*
565                  * Do not use get_merge_parent() here; we do not have
566                  * "name" here and we do not want to contaminate its
567                  * util field yet.
568                  */
569                 obj = parse_object(sha1);
570                 parent = (struct commit *)peel_to_type(NULL, 0, obj, OBJ_COMMIT);
571                 if (!parent)
572                         continue;
573                 commit_list_insert(parent, &parents);
574                 add_merge_parent(result, obj->sha1, parent->object.sha1);
575         }
576         head_commit = lookup_commit(head);
577         if (head_commit)
578                 commit_list_insert(head_commit, &parents);
579         parents = reduce_heads(parents);
580
581         while (parents) {
582                 for (i = 0; i < result->nr; i++)
583                         if (!hashcmp(result->item[i].commit,
584                                      parents->item->object.sha1))
585                                 result->item[i].used = 1;
586                 next = parents->next;
587                 free(parents);
588                 parents = next;
589         }
590
591         for (i = j = 0; i < result->nr; i++) {
592                 if (result->item[i].used) {
593                         if (i != j)
594                                 result->item[j] = result->item[i];
595                         j++;
596                 }
597         }
598         result->nr = j;
599 }
600
601 int fmt_merge_msg(struct strbuf *in, struct strbuf *out,
602                   struct fmt_merge_msg_opts *opts)
603 {
604         int i = 0, pos = 0;
605         unsigned char head_sha1[20];
606         const char *current_branch;
607         void *current_branch_to_free;
608         struct merge_parents merge_parents;
609
610         memset(&merge_parents, 0, sizeof(merge_parents));
611
612         /* get current branch */
613         current_branch = current_branch_to_free =
614                 resolve_refdup("HEAD", head_sha1, 1, NULL);
615         if (!current_branch)
616                 die("No current branch");
617         if (starts_with(current_branch, "refs/heads/"))
618                 current_branch += 11;
619
620         find_merge_parents(&merge_parents, in, head_sha1);
621
622         /* get a line */
623         while (pos < in->len) {
624                 int len;
625                 char *newline, *p = in->buf + pos;
626
627                 newline = strchr(p, '\n');
628                 len = newline ? newline - p : strlen(p);
629                 pos += len + !!newline;
630                 i++;
631                 p[len] = 0;
632                 if (handle_line(p, &merge_parents))
633                         die ("Error in line %d: %.*s", i, len, p);
634         }
635
636         if (opts->add_title && srcs.nr)
637                 fmt_merge_msg_title(out, current_branch);
638
639         if (origins.nr)
640                 fmt_merge_msg_sigs(out);
641
642         if (opts->shortlog_len) {
643                 struct commit *head;
644                 struct rev_info rev;
645
646                 head = lookup_commit_or_die(head_sha1, "HEAD");
647                 init_revisions(&rev, NULL);
648                 rev.commit_format = CMIT_FMT_ONELINE;
649                 rev.ignore_merges = 1;
650                 rev.limited = 1;
651
652                 strbuf_complete_line(out);
653
654                 for (i = 0; i < origins.nr; i++)
655                         shortlog(origins.items[i].string,
656                                  origins.items[i].util,
657                                  head, &rev, opts, out);
658         }
659
660         strbuf_complete_line(out);
661         free(current_branch_to_free);
662         free(merge_parents.item);
663         return 0;
664 }
665
666 int cmd_fmt_merge_msg(int argc, const char **argv, const char *prefix)
667 {
668         const char *inpath = NULL;
669         const char *message = NULL;
670         int shortlog_len = -1;
671         struct option options[] = {
672                 { OPTION_INTEGER, 0, "log", &shortlog_len, N_("n"),
673                   N_("populate log with at most <n> entries from shortlog"),
674                   PARSE_OPT_OPTARG, NULL, DEFAULT_MERGE_LOG_LEN },
675                 { OPTION_INTEGER, 0, "summary", &shortlog_len, N_("n"),
676                   N_("alias for --log (deprecated)"),
677                   PARSE_OPT_OPTARG | PARSE_OPT_HIDDEN, NULL,
678                   DEFAULT_MERGE_LOG_LEN },
679                 OPT_STRING('m', "message", &message, N_("text"),
680                         N_("use <text> as start of message")),
681                 OPT_FILENAME('F', "file", &inpath, N_("file to read from")),
682                 OPT_END()
683         };
684
685         FILE *in = stdin;
686         struct strbuf input = STRBUF_INIT, output = STRBUF_INIT;
687         int ret;
688         struct fmt_merge_msg_opts opts;
689
690         git_config(fmt_merge_msg_config, NULL);
691         argc = parse_options(argc, argv, prefix, options, fmt_merge_msg_usage,
692                              0);
693         if (argc > 0)
694                 usage_with_options(fmt_merge_msg_usage, options);
695         if (shortlog_len < 0)
696                 shortlog_len = (merge_log_config > 0) ? merge_log_config : 0;
697
698         if (inpath && strcmp(inpath, "-")) {
699                 in = fopen(inpath, "r");
700                 if (!in)
701                         die_errno("cannot open '%s'", inpath);
702         }
703
704         if (strbuf_read(&input, fileno(in), 0) < 0)
705                 die_errno("could not read input file");
706
707         if (message)
708                 strbuf_addstr(&output, message);
709
710         memset(&opts, 0, sizeof(opts));
711         opts.add_title = !message;
712         opts.credit_people = 1;
713         opts.shortlog_len = shortlog_len;
714
715         ret = fmt_merge_msg(&input, &output, &opts);
716         if (ret)
717                 return ret;
718         write_in_full(STDOUT_FILENO, output.buf, output.len);
719         return 0;
720 }