commit: fix pretty-printing of messages with "\nencoding "
[git] / commit.c
1 #include "cache.h"
2 #include "tag.h"
3 #include "commit.h"
4 #include "pkt-line.h"
5 #include "utf8.h"
6
7 int save_commit_buffer = 1;
8
9 struct sort_node
10 {
11         /*
12          * the number of children of the associated commit
13          * that also occur in the list being sorted.
14          */
15         unsigned int indegree;
16
17         /*
18          * reference to original list item that we will re-use
19          * on output.
20          */
21         struct commit_list * list_item;
22
23 };
24
25 const char *commit_type = "commit";
26
27 struct cmt_fmt_map {
28         const char *n;
29         size_t cmp_len;
30         enum cmit_fmt v;
31 } cmt_fmts[] = {
32         { "raw",        1,      CMIT_FMT_RAW },
33         { "medium",     1,      CMIT_FMT_MEDIUM },
34         { "short",      1,      CMIT_FMT_SHORT },
35         { "email",      1,      CMIT_FMT_EMAIL },
36         { "full",       5,      CMIT_FMT_FULL },
37         { "fuller",     5,      CMIT_FMT_FULLER },
38         { "oneline",    1,      CMIT_FMT_ONELINE },
39 };
40
41 enum cmit_fmt get_commit_format(const char *arg)
42 {
43         int i;
44
45         if (!arg || !*arg)
46                 return CMIT_FMT_DEFAULT;
47         if (*arg == '=')
48                 arg++;
49         for (i = 0; i < ARRAY_SIZE(cmt_fmts); i++) {
50                 if (!strncmp(arg, cmt_fmts[i].n, cmt_fmts[i].cmp_len) &&
51                     !strncmp(arg, cmt_fmts[i].n, strlen(arg)))
52                         return cmt_fmts[i].v;
53         }
54
55         die("invalid --pretty format: %s", arg);
56 }
57
58 static struct commit *check_commit(struct object *obj,
59                                    const unsigned char *sha1,
60                                    int quiet)
61 {
62         if (obj->type != OBJ_COMMIT) {
63                 if (!quiet)
64                         error("Object %s is a %s, not a commit",
65                               sha1_to_hex(sha1), typename(obj->type));
66                 return NULL;
67         }
68         return (struct commit *) obj;
69 }
70
71 struct commit *lookup_commit_reference_gently(const unsigned char *sha1,
72                                               int quiet)
73 {
74         struct object *obj = deref_tag(parse_object(sha1), NULL, 0);
75
76         if (!obj)
77                 return NULL;
78         return check_commit(obj, sha1, quiet);
79 }
80
81 struct commit *lookup_commit_reference(const unsigned char *sha1)
82 {
83         return lookup_commit_reference_gently(sha1, 0);
84 }
85
86 struct commit *lookup_commit(const unsigned char *sha1)
87 {
88         struct object *obj = lookup_object(sha1);
89         if (!obj) {
90                 struct commit *ret = alloc_commit_node();
91                 created_object(sha1, &ret->object);
92                 ret->object.type = OBJ_COMMIT;
93                 return ret;
94         }
95         if (!obj->type)
96                 obj->type = OBJ_COMMIT;
97         return check_commit(obj, sha1, 0);
98 }
99
100 static unsigned long parse_commit_date(const char *buf)
101 {
102         unsigned long date;
103
104         if (memcmp(buf, "author", 6))
105                 return 0;
106         while (*buf++ != '\n')
107                 /* nada */;
108         if (memcmp(buf, "committer", 9))
109                 return 0;
110         while (*buf++ != '>')
111                 /* nada */;
112         date = strtoul(buf, NULL, 10);
113         if (date == ULONG_MAX)
114                 date = 0;
115         return date;
116 }
117
118 static struct commit_graft **commit_graft;
119 static int commit_graft_alloc, commit_graft_nr;
120
121 static int commit_graft_pos(const unsigned char *sha1)
122 {
123         int lo, hi;
124         lo = 0;
125         hi = commit_graft_nr;
126         while (lo < hi) {
127                 int mi = (lo + hi) / 2;
128                 struct commit_graft *graft = commit_graft[mi];
129                 int cmp = hashcmp(sha1, graft->sha1);
130                 if (!cmp)
131                         return mi;
132                 if (cmp < 0)
133                         hi = mi;
134                 else
135                         lo = mi + 1;
136         }
137         return -lo - 1;
138 }
139
140 int register_commit_graft(struct commit_graft *graft, int ignore_dups)
141 {
142         int pos = commit_graft_pos(graft->sha1);
143         
144         if (0 <= pos) {
145                 if (ignore_dups)
146                         free(graft);
147                 else {
148                         free(commit_graft[pos]);
149                         commit_graft[pos] = graft;
150                 }
151                 return 1;
152         }
153         pos = -pos - 1;
154         if (commit_graft_alloc <= ++commit_graft_nr) {
155                 commit_graft_alloc = alloc_nr(commit_graft_alloc);
156                 commit_graft = xrealloc(commit_graft,
157                                         sizeof(*commit_graft) *
158                                         commit_graft_alloc);
159         }
160         if (pos < commit_graft_nr)
161                 memmove(commit_graft + pos + 1,
162                         commit_graft + pos,
163                         (commit_graft_nr - pos - 1) *
164                         sizeof(*commit_graft));
165         commit_graft[pos] = graft;
166         return 0;
167 }
168
169 struct commit_graft *read_graft_line(char *buf, int len)
170 {
171         /* The format is just "Commit Parent1 Parent2 ...\n" */
172         int i;
173         struct commit_graft *graft = NULL;
174
175         if (buf[len-1] == '\n')
176                 buf[--len] = 0;
177         if (buf[0] == '#' || buf[0] == '\0')
178                 return NULL;
179         if ((len + 1) % 41) {
180         bad_graft_data:
181                 error("bad graft data: %s", buf);
182                 free(graft);
183                 return NULL;
184         }
185         i = (len + 1) / 41 - 1;
186         graft = xmalloc(sizeof(*graft) + 20 * i);
187         graft->nr_parent = i;
188         if (get_sha1_hex(buf, graft->sha1))
189                 goto bad_graft_data;
190         for (i = 40; i < len; i += 41) {
191                 if (buf[i] != ' ')
192                         goto bad_graft_data;
193                 if (get_sha1_hex(buf + i + 1, graft->parent[i/41]))
194                         goto bad_graft_data;
195         }
196         return graft;
197 }
198
199 int read_graft_file(const char *graft_file)
200 {
201         FILE *fp = fopen(graft_file, "r");
202         char buf[1024];
203         if (!fp)
204                 return -1;
205         while (fgets(buf, sizeof(buf), fp)) {
206                 /* The format is just "Commit Parent1 Parent2 ...\n" */
207                 int len = strlen(buf);
208                 struct commit_graft *graft = read_graft_line(buf, len);
209                 if (!graft)
210                         continue;
211                 if (register_commit_graft(graft, 1))
212                         error("duplicate graft data: %s", buf);
213         }
214         fclose(fp);
215         return 0;
216 }
217
218 static void prepare_commit_graft(void)
219 {
220         static int commit_graft_prepared;
221         char *graft_file;
222
223         if (commit_graft_prepared)
224                 return;
225         graft_file = get_graft_file();
226         read_graft_file(graft_file);
227         /* make sure shallows are read */
228         is_repository_shallow();
229         commit_graft_prepared = 1;
230 }
231
232 static struct commit_graft *lookup_commit_graft(const unsigned char *sha1)
233 {
234         int pos;
235         prepare_commit_graft();
236         pos = commit_graft_pos(sha1);
237         if (pos < 0)
238                 return NULL;
239         return commit_graft[pos];
240 }
241
242 int write_shallow_commits(int fd, int use_pack_protocol)
243 {
244         int i, count = 0;
245         for (i = 0; i < commit_graft_nr; i++)
246                 if (commit_graft[i]->nr_parent < 0) {
247                         const char *hex =
248                                 sha1_to_hex(commit_graft[i]->sha1);
249                         count++;
250                         if (use_pack_protocol)
251                                 packet_write(fd, "shallow %s", hex);
252                         else {
253                                 if (write_in_full(fd, hex,  40) != 40)
254                                         break;
255                                 if (write_in_full(fd, "\n", 1) != 1)
256                                         break;
257                         }
258                 }
259         return count;
260 }
261
262 int unregister_shallow(const unsigned char *sha1)
263 {
264         int pos = commit_graft_pos(sha1);
265         if (pos < 0)
266                 return -1;
267         if (pos + 1 < commit_graft_nr)
268                 memcpy(commit_graft + pos, commit_graft + pos + 1,
269                                 sizeof(struct commit_graft *)
270                                 * (commit_graft_nr - pos - 1));
271         commit_graft_nr--;
272         return 0;
273 }
274
275 int parse_commit_buffer(struct commit *item, void *buffer, unsigned long size)
276 {
277         char *tail = buffer;
278         char *bufptr = buffer;
279         unsigned char parent[20];
280         struct commit_list **pptr;
281         struct commit_graft *graft;
282         unsigned n_refs = 0;
283
284         if (item->object.parsed)
285                 return 0;
286         item->object.parsed = 1;
287         tail += size;
288         if (tail <= bufptr + 5 || memcmp(bufptr, "tree ", 5))
289                 return error("bogus commit object %s", sha1_to_hex(item->object.sha1));
290         if (tail <= bufptr + 45 || get_sha1_hex(bufptr + 5, parent) < 0)
291                 return error("bad tree pointer in commit %s",
292                              sha1_to_hex(item->object.sha1));
293         item->tree = lookup_tree(parent);
294         if (item->tree)
295                 n_refs++;
296         bufptr += 46; /* "tree " + "hex sha1" + "\n" */
297         pptr = &item->parents;
298
299         graft = lookup_commit_graft(item->object.sha1);
300         while (bufptr + 48 < tail && !memcmp(bufptr, "parent ", 7)) {
301                 struct commit *new_parent;
302
303                 if (tail <= bufptr + 48 ||
304                     get_sha1_hex(bufptr + 7, parent) ||
305                     bufptr[47] != '\n')
306                         return error("bad parents in commit %s", sha1_to_hex(item->object.sha1));
307                 bufptr += 48;
308                 if (graft)
309                         continue;
310                 new_parent = lookup_commit(parent);
311                 if (new_parent) {
312                         pptr = &commit_list_insert(new_parent, pptr)->next;
313                         n_refs++;
314                 }
315         }
316         if (graft) {
317                 int i;
318                 struct commit *new_parent;
319                 for (i = 0; i < graft->nr_parent; i++) {
320                         new_parent = lookup_commit(graft->parent[i]);
321                         if (!new_parent)
322                                 continue;
323                         pptr = &commit_list_insert(new_parent, pptr)->next;
324                         n_refs++;
325                 }
326         }
327         item->date = parse_commit_date(bufptr);
328
329         if (track_object_refs) {
330                 unsigned i = 0;
331                 struct commit_list *p;
332                 struct object_refs *refs = alloc_object_refs(n_refs);
333                 if (item->tree)
334                         refs->ref[i++] = &item->tree->object;
335                 for (p = item->parents; p; p = p->next)
336                         refs->ref[i++] = &p->item->object;
337                 set_object_refs(&item->object, refs);
338         }
339
340         return 0;
341 }
342
343 int parse_commit(struct commit *item)
344 {
345         char type[20];
346         void *buffer;
347         unsigned long size;
348         int ret;
349
350         if (item->object.parsed)
351                 return 0;
352         buffer = read_sha1_file(item->object.sha1, type, &size);
353         if (!buffer)
354                 return error("Could not read %s",
355                              sha1_to_hex(item->object.sha1));
356         if (strcmp(type, commit_type)) {
357                 free(buffer);
358                 return error("Object %s not a commit",
359                              sha1_to_hex(item->object.sha1));
360         }
361         ret = parse_commit_buffer(item, buffer, size);
362         if (save_commit_buffer && !ret) {
363                 item->buffer = buffer;
364                 return 0;
365         }
366         free(buffer);
367         return ret;
368 }
369
370 struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
371 {
372         struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
373         new_list->item = item;
374         new_list->next = *list_p;
375         *list_p = new_list;
376         return new_list;
377 }
378
379 void free_commit_list(struct commit_list *list)
380 {
381         while (list) {
382                 struct commit_list *temp = list;
383                 list = temp->next;
384                 free(temp);
385         }
386 }
387
388 struct commit_list * insert_by_date(struct commit *item, struct commit_list **list)
389 {
390         struct commit_list **pp = list;
391         struct commit_list *p;
392         while ((p = *pp) != NULL) {
393                 if (p->item->date < item->date) {
394                         break;
395                 }
396                 pp = &p->next;
397         }
398         return commit_list_insert(item, pp);
399 }
400
401         
402 void sort_by_date(struct commit_list **list)
403 {
404         struct commit_list *ret = NULL;
405         while (*list) {
406                 insert_by_date((*list)->item, &ret);
407                 *list = (*list)->next;
408         }
409         *list = ret;
410 }
411
412 struct commit *pop_most_recent_commit(struct commit_list **list,
413                                       unsigned int mark)
414 {
415         struct commit *ret = (*list)->item;
416         struct commit_list *parents = ret->parents;
417         struct commit_list *old = *list;
418
419         *list = (*list)->next;
420         free(old);
421
422         while (parents) {
423                 struct commit *commit = parents->item;
424                 parse_commit(commit);
425                 if (!(commit->object.flags & mark)) {
426                         commit->object.flags |= mark;
427                         insert_by_date(commit, list);
428                 }
429                 parents = parents->next;
430         }
431         return ret;
432 }
433
434 void clear_commit_marks(struct commit *commit, unsigned int mark)
435 {
436         struct commit_list *parents;
437
438         commit->object.flags &= ~mark;
439         parents = commit->parents;
440         while (parents) {
441                 struct commit *parent = parents->item;
442
443                 /* Have we already cleared this? */
444                 if (mark & parent->object.flags)
445                         clear_commit_marks(parent, mark);
446                 parents = parents->next;
447         }
448 }
449
450 /*
451  * Generic support for pretty-printing the header
452  */
453 static int get_one_line(const char *msg, unsigned long len)
454 {
455         int ret = 0;
456
457         while (len--) {
458                 char c = *msg++;
459                 if (!c)
460                         break;
461                 ret++;
462                 if (c == '\n')
463                         break;
464         }
465         return ret;
466 }
467
468 /* High bit set, or ISO-2022-INT */
469 static int non_ascii(int ch)
470 {
471         ch = (ch & 0xff);
472         return ((ch & 0x80) || (ch == 0x1b));
473 }
474
475 static int is_rfc2047_special(char ch)
476 {
477         return (non_ascii(ch) || (ch == '=') || (ch == '?') || (ch == '_'));
478 }
479
480 static int add_rfc2047(char *buf, const char *line, int len,
481                        const char *encoding)
482 {
483         char *bp = buf;
484         int i, needquote;
485         char q_encoding[128];
486         const char *q_encoding_fmt = "=?%s?q?";
487
488         for (i = needquote = 0; !needquote && i < len; i++) {
489                 int ch = line[i];
490                 if (non_ascii(ch))
491                         needquote++;
492                 if ((i + 1 < len) &&
493                     (ch == '=' && line[i+1] == '?'))
494                         needquote++;
495         }
496         if (!needquote)
497                 return sprintf(buf, "%.*s", len, line);
498
499         i = snprintf(q_encoding, sizeof(q_encoding), q_encoding_fmt, encoding);
500         if (sizeof(q_encoding) < i)
501                 die("Insanely long encoding name %s", encoding);
502         memcpy(bp, q_encoding, i);
503         bp += i;
504         for (i = 0; i < len; i++) {
505                 unsigned ch = line[i] & 0xFF;
506                 if (is_rfc2047_special(ch)) {
507                         sprintf(bp, "=%02X", ch);
508                         bp += 3;
509                 }
510                 else if (ch == ' ')
511                         *bp++ = '_';
512                 else
513                         *bp++ = ch;
514         }
515         memcpy(bp, "?=", 2);
516         bp += 2;
517         return bp - buf;
518 }
519
520 static int add_user_info(const char *what, enum cmit_fmt fmt, char *buf,
521                          const char *line, int relative_date,
522                          const char *encoding)
523 {
524         char *date;
525         int namelen;
526         unsigned long time;
527         int tz, ret;
528         const char *filler = "    ";
529
530         if (fmt == CMIT_FMT_ONELINE)
531                 return 0;
532         date = strchr(line, '>');
533         if (!date)
534                 return 0;
535         namelen = ++date - line;
536         time = strtoul(date, &date, 10);
537         tz = strtol(date, NULL, 10);
538
539         if (fmt == CMIT_FMT_EMAIL) {
540                 char *name_tail = strchr(line, '<');
541                 int display_name_length;
542                 if (!name_tail)
543                         return 0;
544                 while (line < name_tail && isspace(name_tail[-1]))
545                         name_tail--;
546                 display_name_length = name_tail - line;
547                 filler = "";
548                 strcpy(buf, "From: ");
549                 ret = strlen(buf);
550                 ret += add_rfc2047(buf + ret, line, display_name_length,
551                                    encoding);
552                 memcpy(buf + ret, name_tail, namelen - display_name_length);
553                 ret += namelen - display_name_length;
554                 buf[ret++] = '\n';
555         }
556         else {
557                 ret = sprintf(buf, "%s: %.*s%.*s\n", what,
558                               (fmt == CMIT_FMT_FULLER) ? 4 : 0,
559                               filler, namelen, line);
560         }
561         switch (fmt) {
562         case CMIT_FMT_MEDIUM:
563                 ret += sprintf(buf + ret, "Date:   %s\n",
564                                show_date(time, tz, relative_date));
565                 break;
566         case CMIT_FMT_EMAIL:
567                 ret += sprintf(buf + ret, "Date: %s\n",
568                                show_rfc2822_date(time, tz));
569                 break;
570         case CMIT_FMT_FULLER:
571                 ret += sprintf(buf + ret, "%sDate: %s\n", what,
572                                show_date(time, tz, relative_date));
573                 break;
574         default:
575                 /* notin' */
576                 break;
577         }
578         return ret;
579 }
580
581 static int is_empty_line(const char *line, int *len_p)
582 {
583         int len = *len_p;
584         while (len && isspace(line[len-1]))
585                 len--;
586         *len_p = len;
587         return !len;
588 }
589
590 static int add_merge_info(enum cmit_fmt fmt, char *buf, const struct commit *commit, int abbrev)
591 {
592         struct commit_list *parent = commit->parents;
593         int offset;
594
595         if ((fmt == CMIT_FMT_ONELINE) || (fmt == CMIT_FMT_EMAIL) ||
596             !parent || !parent->next)
597                 return 0;
598
599         offset = sprintf(buf, "Merge:");
600
601         while (parent) {
602                 struct commit *p = parent->item;
603                 const char *hex = NULL;
604                 const char *dots;
605                 if (abbrev)
606                         hex = find_unique_abbrev(p->object.sha1, abbrev);
607                 if (!hex)
608                         hex = sha1_to_hex(p->object.sha1);
609                 dots = (abbrev && strlen(hex) != 40) ?  "..." : "";
610                 parent = parent->next;
611
612                 offset += sprintf(buf + offset, " %s%s", hex, dots);
613         }
614         buf[offset++] = '\n';
615         return offset;
616 }
617
618 static char *get_header(const struct commit *commit, const char *key)
619 {
620         int key_len = strlen(key);
621         const char *line = commit->buffer;
622
623         for (;;) {
624                 const char *eol = strchr(line, '\n'), *next;
625
626                 if (line == eol)
627                         return NULL;
628                 if (!eol) {
629                         eol = line + strlen(line);
630                         next = NULL;
631                 } else
632                         next = eol + 1;
633                 if (!strncmp(line, key, key_len) && line[key_len] == ' ') {
634                         int len = eol - line - key_len;
635                         char *ret = xmalloc(len);
636                         memcpy(ret, line + key_len + 1, len - 1);
637                         ret[len - 1] = '\0';
638                         return ret;
639                 }
640                 line = next;
641         }
642 }
643
644 static char *replace_encoding_header(char *buf, char *encoding)
645 {
646         char *encoding_header = strstr(buf, "\nencoding ");
647         char *header_end = strstr(buf, "\n\n");
648         char *end_of_encoding_header;
649         int encoding_header_pos;
650         int encoding_header_len;
651         int new_len;
652         int need_len;
653         int buflen = strlen(buf) + 1;
654
655         if (!header_end)
656                 header_end = buf + buflen;
657         if (!encoding_header || encoding_header >= header_end)
658                 return buf;
659         encoding_header++;
660         end_of_encoding_header = strchr(encoding_header, '\n');
661         if (!end_of_encoding_header)
662                 return buf; /* should not happen but be defensive */
663         end_of_encoding_header++;
664
665         encoding_header_len = end_of_encoding_header - encoding_header;
666         encoding_header_pos = encoding_header - buf;
667
668         if (is_encoding_utf8(encoding)) {
669                 /* we have re-coded to UTF-8; drop the header */
670                 memmove(encoding_header, end_of_encoding_header,
671                         buflen - (encoding_header_pos + encoding_header_len));
672                 return buf;
673         }
674         new_len = strlen(encoding);
675         need_len = new_len + strlen("encoding \n");
676         if (encoding_header_len < need_len) {
677                 buf = xrealloc(buf, buflen + (need_len - encoding_header_len));
678                 encoding_header = buf + encoding_header_pos;
679                 end_of_encoding_header = encoding_header + encoding_header_len;
680         }
681         memmove(end_of_encoding_header + (need_len - encoding_header_len),
682                 end_of_encoding_header,
683                 buflen - (encoding_header_pos + encoding_header_len));
684         memcpy(encoding_header + 9, encoding, strlen(encoding));
685         encoding_header[9 + new_len] = '\n';
686         return buf;
687 }
688
689 static char *logmsg_reencode(const struct commit *commit,
690                              char *output_encoding)
691 {
692         char *encoding;
693         char *out;
694         char *utf8 = "utf-8";
695
696         if (!*output_encoding)
697                 return NULL;
698         encoding = get_header(commit, "encoding");
699         if (!encoding)
700                 encoding = utf8;
701         if (!strcmp(encoding, output_encoding))
702                 out = strdup(commit->buffer);
703         else
704                 out = reencode_string(commit->buffer,
705                                       output_encoding, encoding);
706         if (out)
707                 out = replace_encoding_header(out, output_encoding);
708
709         if (encoding != utf8)
710                 free(encoding);
711         if (!out)
712                 return NULL;
713         return out;
714 }
715
716 unsigned long pretty_print_commit(enum cmit_fmt fmt,
717                                   const struct commit *commit,
718                                   unsigned long len,
719                                   char *buf, unsigned long space,
720                                   int abbrev, const char *subject,
721                                   const char *after_subject,
722                                   int relative_date)
723 {
724         int hdr = 1, body = 0, seen_title = 0;
725         unsigned long offset = 0;
726         int indent = 4;
727         int parents_shown = 0;
728         const char *msg = commit->buffer;
729         int plain_non_ascii = 0;
730         char *reencoded;
731         char *encoding;
732
733         encoding = (git_log_output_encoding
734                     ? git_log_output_encoding
735                     : git_commit_encoding);
736         if (!encoding)
737                 encoding = "utf-8";
738         reencoded = logmsg_reencode(commit, encoding);
739         if (reencoded)
740                 msg = reencoded;
741
742         if (fmt == CMIT_FMT_ONELINE || fmt == CMIT_FMT_EMAIL)
743                 indent = 0;
744
745         /* After-subject is used to pass in Content-Type: multipart
746          * MIME header; in that case we do not have to do the
747          * plaintext content type even if the commit message has
748          * non 7-bit ASCII character.  Otherwise, check if we need
749          * to say this is not a 7-bit ASCII.
750          */
751         if (fmt == CMIT_FMT_EMAIL && !after_subject) {
752                 int i, ch, in_body;
753
754                 for (in_body = i = 0; (ch = msg[i]) && i < len; i++) {
755                         if (!in_body) {
756                                 /* author could be non 7-bit ASCII but
757                                  * the log may be so; skip over the
758                                  * header part first.
759                                  */
760                                 if (ch == '\n' &&
761                                     i + 1 < len && msg[i+1] == '\n')
762                                         in_body = 1;
763                         }
764                         else if (non_ascii(ch)) {
765                                 plain_non_ascii = 1;
766                                 break;
767                         }
768                 }
769         }
770
771         for (;;) {
772                 const char *line = msg;
773                 int linelen = get_one_line(msg, len);
774
775                 if (!linelen)
776                         break;
777
778                 /*
779                  * We want some slop for indentation and a possible
780                  * final "...". Thus the "+ 20".
781                  */
782                 if (offset + linelen + 20 > space) {
783                         memcpy(buf + offset, "    ...\n", 8);
784                         offset += 8;
785                         break;
786                 }
787
788                 msg += linelen;
789                 len -= linelen;
790                 if (hdr) {
791                         if (linelen == 1) {
792                                 hdr = 0;
793                                 if ((fmt != CMIT_FMT_ONELINE) && !subject)
794                                         buf[offset++] = '\n';
795                                 continue;
796                         }
797                         if (fmt == CMIT_FMT_RAW) {
798                                 memcpy(buf + offset, line, linelen);
799                                 offset += linelen;
800                                 continue;
801                         }
802                         if (!memcmp(line, "parent ", 7)) {
803                                 if (linelen != 48)
804                                         die("bad parent line in commit");
805                                 continue;
806                         }
807
808                         if (!parents_shown) {
809                                 offset += add_merge_info(fmt, buf + offset,
810                                                          commit, abbrev);
811                                 parents_shown = 1;
812                                 continue;
813                         }
814                         /*
815                          * MEDIUM == DEFAULT shows only author with dates.
816                          * FULL shows both authors but not dates.
817                          * FULLER shows both authors and dates.
818                          */
819                         if (!memcmp(line, "author ", 7))
820                                 offset += add_user_info("Author", fmt,
821                                                         buf + offset,
822                                                         line + 7,
823                                                         relative_date,
824                                                         encoding);
825                         if (!memcmp(line, "committer ", 10) &&
826                             (fmt == CMIT_FMT_FULL || fmt == CMIT_FMT_FULLER))
827                                 offset += add_user_info("Commit", fmt,
828                                                         buf + offset,
829                                                         line + 10,
830                                                         relative_date,
831                                                         encoding);
832                         continue;
833                 }
834
835                 if (!subject)
836                         body = 1;
837
838                 if (is_empty_line(line, &linelen)) {
839                         if (!seen_title)
840                                 continue;
841                         if (!body)
842                                 continue;
843                         if (subject)
844                                 continue;
845                         if (fmt == CMIT_FMT_SHORT)
846                                 break;
847                 }
848
849                 seen_title = 1;
850                 if (subject) {
851                         int slen = strlen(subject);
852                         memcpy(buf + offset, subject, slen);
853                         offset += slen;
854                         offset += add_rfc2047(buf + offset, line, linelen,
855                                               encoding);
856                 }
857                 else {
858                         memset(buf + offset, ' ', indent);
859                         memcpy(buf + offset + indent, line, linelen);
860                         offset += linelen + indent;
861                 }
862                 buf[offset++] = '\n';
863                 if (fmt == CMIT_FMT_ONELINE)
864                         break;
865                 if (subject && plain_non_ascii) {
866                         int sz;
867                         char header[512];
868                         const char *header_fmt =
869                                 "Content-Type: text/plain; charset=%s\n"
870                                 "Content-Transfer-Encoding: 8bit\n";
871                         sz = snprintf(header, sizeof(header), header_fmt,
872                                       encoding);
873                         if (sizeof(header) < sz)
874                                 die("Encoding name %s too long", encoding);
875                         memcpy(buf + offset, header, sz);
876                         offset += sz;
877                 }
878                 if (after_subject) {
879                         int slen = strlen(after_subject);
880                         if (slen > space - offset - 1)
881                                 slen = space - offset - 1;
882                         memcpy(buf + offset, after_subject, slen);
883                         offset += slen;
884                         after_subject = NULL;
885                 }
886                 subject = NULL;
887         }
888         while (offset && isspace(buf[offset-1]))
889                 offset--;
890         /* Make sure there is an EOLN for the non-oneline case */
891         if (fmt != CMIT_FMT_ONELINE)
892                 buf[offset++] = '\n';
893         /*
894          * make sure there is another EOLN to separate the headers from whatever
895          * body the caller appends if we haven't already written a body
896          */
897         if (fmt == CMIT_FMT_EMAIL && !body)
898                 buf[offset++] = '\n';
899         buf[offset] = '\0';
900
901         free(reencoded);
902         return offset;
903 }
904
905 struct commit *pop_commit(struct commit_list **stack)
906 {
907         struct commit_list *top = *stack;
908         struct commit *item = top ? top->item : NULL;
909
910         if (top) {
911                 *stack = top->next;
912                 free(top);
913         }
914         return item;
915 }
916
917 int count_parents(struct commit * commit)
918 {
919         int count;
920         struct commit_list * parents = commit->parents;
921         for (count = 0; parents; parents = parents->next,count++)
922                 ;
923         return count;
924 }
925
926 void topo_sort_default_setter(struct commit *c, void *data)
927 {
928         c->util = data;
929 }
930
931 void *topo_sort_default_getter(struct commit *c)
932 {
933         return c->util;
934 }
935
936 /*
937  * Performs an in-place topological sort on the list supplied.
938  */
939 void sort_in_topological_order(struct commit_list ** list, int lifo)
940 {
941         sort_in_topological_order_fn(list, lifo, topo_sort_default_setter,
942                                      topo_sort_default_getter);
943 }
944
945 void sort_in_topological_order_fn(struct commit_list ** list, int lifo,
946                                   topo_sort_set_fn_t setter,
947                                   topo_sort_get_fn_t getter)
948 {
949         struct commit_list * next = *list;
950         struct commit_list * work = NULL, **insert;
951         struct commit_list ** pptr = list;
952         struct sort_node * nodes;
953         struct sort_node * next_nodes;
954         int count = 0;
955
956         /* determine the size of the list */
957         while (next) {
958                 next = next->next;
959                 count++;
960         }
961         
962         if (!count)
963                 return;
964         /* allocate an array to help sort the list */
965         nodes = xcalloc(count, sizeof(*nodes));
966         /* link the list to the array */
967         next_nodes = nodes;
968         next=*list;
969         while (next) {
970                 next_nodes->list_item = next;
971                 setter(next->item, next_nodes);
972                 next_nodes++;
973                 next = next->next;
974         }
975         /* update the indegree */
976         next=*list;
977         while (next) {
978                 struct commit_list * parents = next->item->parents;
979                 while (parents) {
980                         struct commit * parent=parents->item;
981                         struct sort_node * pn = (struct sort_node *) getter(parent);
982
983                         if (pn)
984                                 pn->indegree++;
985                         parents=parents->next;
986                 }
987                 next=next->next;
988         }
989         /* 
990          * find the tips
991          *
992          * tips are nodes not reachable from any other node in the list 
993          * 
994          * the tips serve as a starting set for the work queue.
995          */
996         next=*list;
997         insert = &work;
998         while (next) {
999                 struct sort_node * node = (struct sort_node *) getter(next->item);
1000
1001                 if (node->indegree == 0) {
1002                         insert = &commit_list_insert(next->item, insert)->next;
1003                 }
1004                 next=next->next;
1005         }
1006
1007         /* process the list in topological order */
1008         if (!lifo)
1009                 sort_by_date(&work);
1010         while (work) {
1011                 struct commit * work_item = pop_commit(&work);
1012                 struct sort_node * work_node = (struct sort_node *) getter(work_item);
1013                 struct commit_list * parents = work_item->parents;
1014
1015                 while (parents) {
1016                         struct commit * parent=parents->item;
1017                         struct sort_node * pn = (struct sort_node *) getter(parent);
1018
1019                         if (pn) {
1020                                 /*
1021                                  * parents are only enqueued for emission 
1022                                  * when all their children have been emitted thereby
1023                                  * guaranteeing topological order.
1024                                  */
1025                                 pn->indegree--;
1026                                 if (!pn->indegree) {
1027                                         if (!lifo)
1028                                                 insert_by_date(parent, &work);
1029                                         else
1030                                                 commit_list_insert(parent, &work);
1031                                 }
1032                         }
1033                         parents=parents->next;
1034                 }
1035                 /*
1036                  * work_item is a commit all of whose children
1037                  * have already been emitted. we can emit it now.
1038                  */
1039                 *pptr = work_node->list_item;
1040                 pptr = &(*pptr)->next;
1041                 *pptr = NULL;
1042                 setter(work_item, NULL);
1043         }
1044         free(nodes);
1045 }
1046
1047 /* merge-base stuff */
1048
1049 /* bits #0..15 in revision.h */
1050 #define PARENT1         (1u<<16)
1051 #define PARENT2         (1u<<17)
1052 #define STALE           (1u<<18)
1053 #define RESULT          (1u<<19)
1054
1055 static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);
1056
1057 static struct commit *interesting(struct commit_list *list)
1058 {
1059         while (list) {
1060                 struct commit *commit = list->item;
1061                 list = list->next;
1062                 if (commit->object.flags & STALE)
1063                         continue;
1064                 return commit;
1065         }
1066         return NULL;
1067 }
1068
1069 static struct commit_list *merge_bases(struct commit *one, struct commit *two)
1070 {
1071         struct commit_list *list = NULL;
1072         struct commit_list *result = NULL;
1073
1074         if (one == two)
1075                 /* We do not mark this even with RESULT so we do not
1076                  * have to clean it up.
1077                  */
1078                 return commit_list_insert(one, &result);
1079
1080         parse_commit(one);
1081         parse_commit(two);
1082
1083         one->object.flags |= PARENT1;
1084         two->object.flags |= PARENT2;
1085         insert_by_date(one, &list);
1086         insert_by_date(two, &list);
1087
1088         while (interesting(list)) {
1089                 struct commit *commit;
1090                 struct commit_list *parents;
1091                 struct commit_list *n;
1092                 int flags;
1093
1094                 commit = list->item;
1095                 n = list->next;
1096                 free(list);
1097                 list = n;
1098
1099                 flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
1100                 if (flags == (PARENT1 | PARENT2)) {
1101                         if (!(commit->object.flags & RESULT)) {
1102                                 commit->object.flags |= RESULT;
1103                                 insert_by_date(commit, &result);
1104                         }
1105                         /* Mark parents of a found merge stale */
1106                         flags |= STALE;
1107                 }
1108                 parents = commit->parents;
1109                 while (parents) {
1110                         struct commit *p = parents->item;
1111                         parents = parents->next;
1112                         if ((p->object.flags & flags) == flags)
1113                                 continue;
1114                         parse_commit(p);
1115                         p->object.flags |= flags;
1116                         insert_by_date(p, &list);
1117                 }
1118         }
1119
1120         /* Clean up the result to remove stale ones */
1121         free_commit_list(list);
1122         list = result; result = NULL;
1123         while (list) {
1124                 struct commit_list *n = list->next;
1125                 if (!(list->item->object.flags & STALE))
1126                         insert_by_date(list->item, &result);
1127                 free(list);
1128                 list = n;
1129         }
1130         return result;
1131 }
1132
1133 struct commit_list *get_merge_bases(struct commit *one,
1134                                     struct commit *two,
1135                                     int cleanup)
1136 {
1137         struct commit_list *list;
1138         struct commit **rslt;
1139         struct commit_list *result;
1140         int cnt, i, j;
1141
1142         result = merge_bases(one, two);
1143         if (one == two)
1144                 return result;
1145         if (!result || !result->next) {
1146                 if (cleanup) {
1147                         clear_commit_marks(one, all_flags);
1148                         clear_commit_marks(two, all_flags);
1149                 }
1150                 return result;
1151         }
1152
1153         /* There are more than one */
1154         cnt = 0;
1155         list = result;
1156         while (list) {
1157                 list = list->next;
1158                 cnt++;
1159         }
1160         rslt = xcalloc(cnt, sizeof(*rslt));
1161         for (list = result, i = 0; list; list = list->next)
1162                 rslt[i++] = list->item;
1163         free_commit_list(result);
1164
1165         clear_commit_marks(one, all_flags);
1166         clear_commit_marks(two, all_flags);
1167         for (i = 0; i < cnt - 1; i++) {
1168                 for (j = i+1; j < cnt; j++) {
1169                         if (!rslt[i] || !rslt[j])
1170                                 continue;
1171                         result = merge_bases(rslt[i], rslt[j]);
1172                         clear_commit_marks(rslt[i], all_flags);
1173                         clear_commit_marks(rslt[j], all_flags);
1174                         for (list = result; list; list = list->next) {
1175                                 if (rslt[i] == list->item)
1176                                         rslt[i] = NULL;
1177                                 if (rslt[j] == list->item)
1178                                         rslt[j] = NULL;
1179                         }
1180                 }
1181         }
1182
1183         /* Surviving ones in rslt[] are the independent results */
1184         result = NULL;
1185         for (i = 0; i < cnt; i++) {
1186                 if (rslt[i])
1187                         insert_by_date(rslt[i], &result);
1188         }
1189         free(rslt);
1190         return result;
1191 }
1192
1193 int in_merge_bases(struct commit *rev1, struct commit *rev2)
1194 {
1195         struct commit_list *bases, *b;
1196         int ret = 0;
1197
1198         bases = get_merge_bases(rev1, rev2, 1);
1199         for (b = bases; b; b = b->next) {
1200                 if (!hashcmp(rev1->object.sha1, b->item->object.sha1)) {
1201                         ret = 1;
1202                         break;
1203                 }
1204         }
1205
1206         free_commit_list(bases);
1207         return ret;
1208 }