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