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