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