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