Simplify topo-sort logic
[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 #include "interpolate.h"
7 #include "diff.h"
8 #include "revision.h"
9
10 int save_commit_buffer = 1;
11
12 const char *commit_type = "commit";
13
14 static struct cmt_fmt_map {
15         const char *n;
16         size_t cmp_len;
17         enum cmit_fmt v;
18 } cmt_fmts[] = {
19         { "raw",        1,      CMIT_FMT_RAW },
20         { "medium",     1,      CMIT_FMT_MEDIUM },
21         { "short",      1,      CMIT_FMT_SHORT },
22         { "email",      1,      CMIT_FMT_EMAIL },
23         { "full",       5,      CMIT_FMT_FULL },
24         { "fuller",     5,      CMIT_FMT_FULLER },
25         { "oneline",    1,      CMIT_FMT_ONELINE },
26         { "format:",    7,      CMIT_FMT_USERFORMAT},
27 };
28
29 static char *user_format;
30
31 enum cmit_fmt get_commit_format(const char *arg)
32 {
33         int i;
34
35         if (!arg || !*arg)
36                 return CMIT_FMT_DEFAULT;
37         if (*arg == '=')
38                 arg++;
39         if (!prefixcmp(arg, "format:")) {
40                 if (user_format)
41                         free(user_format);
42                 user_format = xstrdup(arg + 7);
43                 return CMIT_FMT_USERFORMAT;
44         }
45         for (i = 0; i < ARRAY_SIZE(cmt_fmts); i++) {
46                 if (!strncmp(arg, cmt_fmts[i].n, cmt_fmts[i].cmp_len) &&
47                     !strncmp(arg, cmt_fmts[i].n, strlen(arg)))
48                         return cmt_fmts[i].v;
49         }
50
51         die("invalid --pretty format: %s", arg);
52 }
53
54 static struct commit *check_commit(struct object *obj,
55                                    const unsigned char *sha1,
56                                    int quiet)
57 {
58         if (obj->type != OBJ_COMMIT) {
59                 if (!quiet)
60                         error("Object %s is a %s, not a commit",
61                               sha1_to_hex(sha1), typename(obj->type));
62                 return NULL;
63         }
64         return (struct commit *) obj;
65 }
66
67 struct commit *lookup_commit_reference_gently(const unsigned char *sha1,
68                                               int quiet)
69 {
70         struct object *obj = deref_tag(parse_object(sha1), NULL, 0);
71
72         if (!obj)
73                 return NULL;
74         return check_commit(obj, sha1, quiet);
75 }
76
77 struct commit *lookup_commit_reference(const unsigned char *sha1)
78 {
79         return lookup_commit_reference_gently(sha1, 0);
80 }
81
82 struct commit *lookup_commit(const unsigned char *sha1)
83 {
84         struct object *obj = lookup_object(sha1);
85         if (!obj)
86                 return create_object(sha1, OBJ_COMMIT, alloc_commit_node());
87         if (!obj->type)
88                 obj->type = OBJ_COMMIT;
89         return check_commit(obj, sha1, 0);
90 }
91
92 static unsigned long parse_commit_date(const char *buf)
93 {
94         unsigned long date;
95
96         if (memcmp(buf, "author", 6))
97                 return 0;
98         while (*buf++ != '\n')
99                 /* nada */;
100         if (memcmp(buf, "committer", 9))
101                 return 0;
102         while (*buf++ != '>')
103                 /* nada */;
104         date = strtoul(buf, NULL, 10);
105         if (date == ULONG_MAX)
106                 date = 0;
107         return date;
108 }
109
110 static struct commit_graft **commit_graft;
111 static int commit_graft_alloc, commit_graft_nr;
112
113 static int commit_graft_pos(const unsigned char *sha1)
114 {
115         int lo, hi;
116         lo = 0;
117         hi = commit_graft_nr;
118         while (lo < hi) {
119                 int mi = (lo + hi) / 2;
120                 struct commit_graft *graft = commit_graft[mi];
121                 int cmp = hashcmp(sha1, graft->sha1);
122                 if (!cmp)
123                         return mi;
124                 if (cmp < 0)
125                         hi = mi;
126                 else
127                         lo = mi + 1;
128         }
129         return -lo - 1;
130 }
131
132 int register_commit_graft(struct commit_graft *graft, int ignore_dups)
133 {
134         int pos = commit_graft_pos(graft->sha1);
135
136         if (0 <= pos) {
137                 if (ignore_dups)
138                         free(graft);
139                 else {
140                         free(commit_graft[pos]);
141                         commit_graft[pos] = graft;
142                 }
143                 return 1;
144         }
145         pos = -pos - 1;
146         if (commit_graft_alloc <= ++commit_graft_nr) {
147                 commit_graft_alloc = alloc_nr(commit_graft_alloc);
148                 commit_graft = xrealloc(commit_graft,
149                                         sizeof(*commit_graft) *
150                                         commit_graft_alloc);
151         }
152         if (pos < commit_graft_nr)
153                 memmove(commit_graft + pos + 1,
154                         commit_graft + pos,
155                         (commit_graft_nr - pos - 1) *
156                         sizeof(*commit_graft));
157         commit_graft[pos] = graft;
158         return 0;
159 }
160
161 struct commit_graft *read_graft_line(char *buf, int len)
162 {
163         /* The format is just "Commit Parent1 Parent2 ...\n" */
164         int i;
165         struct commit_graft *graft = NULL;
166
167         if (buf[len-1] == '\n')
168                 buf[--len] = 0;
169         if (buf[0] == '#' || buf[0] == '\0')
170                 return NULL;
171         if ((len + 1) % 41) {
172         bad_graft_data:
173                 error("bad graft data: %s", buf);
174                 free(graft);
175                 return NULL;
176         }
177         i = (len + 1) / 41 - 1;
178         graft = xmalloc(sizeof(*graft) + 20 * i);
179         graft->nr_parent = i;
180         if (get_sha1_hex(buf, graft->sha1))
181                 goto bad_graft_data;
182         for (i = 40; i < len; i += 41) {
183                 if (buf[i] != ' ')
184                         goto bad_graft_data;
185                 if (get_sha1_hex(buf + i + 1, graft->parent[i/41]))
186                         goto bad_graft_data;
187         }
188         return graft;
189 }
190
191 int read_graft_file(const char *graft_file)
192 {
193         FILE *fp = fopen(graft_file, "r");
194         char buf[1024];
195         if (!fp)
196                 return -1;
197         while (fgets(buf, sizeof(buf), fp)) {
198                 /* The format is just "Commit Parent1 Parent2 ...\n" */
199                 int len = strlen(buf);
200                 struct commit_graft *graft = read_graft_line(buf, len);
201                 if (!graft)
202                         continue;
203                 if (register_commit_graft(graft, 1))
204                         error("duplicate graft data: %s", buf);
205         }
206         fclose(fp);
207         return 0;
208 }
209
210 static void prepare_commit_graft(void)
211 {
212         static int commit_graft_prepared;
213         char *graft_file;
214
215         if (commit_graft_prepared)
216                 return;
217         graft_file = get_graft_file();
218         read_graft_file(graft_file);
219         /* make sure shallows are read */
220         is_repository_shallow();
221         commit_graft_prepared = 1;
222 }
223
224 static struct commit_graft *lookup_commit_graft(const unsigned char *sha1)
225 {
226         int pos;
227         prepare_commit_graft();
228         pos = commit_graft_pos(sha1);
229         if (pos < 0)
230                 return NULL;
231         return commit_graft[pos];
232 }
233
234 int write_shallow_commits(int fd, int use_pack_protocol)
235 {
236         int i, count = 0;
237         for (i = 0; i < commit_graft_nr; i++)
238                 if (commit_graft[i]->nr_parent < 0) {
239                         const char *hex =
240                                 sha1_to_hex(commit_graft[i]->sha1);
241                         count++;
242                         if (use_pack_protocol)
243                                 packet_write(fd, "shallow %s", hex);
244                         else {
245                                 if (write_in_full(fd, hex,  40) != 40)
246                                         break;
247                                 if (write_in_full(fd, "\n", 1) != 1)
248                                         break;
249                         }
250                 }
251         return count;
252 }
253
254 int unregister_shallow(const unsigned char *sha1)
255 {
256         int pos = commit_graft_pos(sha1);
257         if (pos < 0)
258                 return -1;
259         if (pos + 1 < commit_graft_nr)
260                 memcpy(commit_graft + pos, commit_graft + pos + 1,
261                                 sizeof(struct commit_graft *)
262                                 * (commit_graft_nr - pos - 1));
263         commit_graft_nr--;
264         return 0;
265 }
266
267 int parse_commit_buffer(struct commit *item, void *buffer, unsigned long size)
268 {
269         char *tail = buffer;
270         char *bufptr = buffer;
271         unsigned char parent[20];
272         struct commit_list **pptr;
273         struct commit_graft *graft;
274         unsigned n_refs = 0;
275
276         if (item->object.parsed)
277                 return 0;
278         item->object.parsed = 1;
279         tail += size;
280         if (tail <= bufptr + 5 || memcmp(bufptr, "tree ", 5))
281                 return error("bogus commit object %s", sha1_to_hex(item->object.sha1));
282         if (tail <= bufptr + 45 || get_sha1_hex(bufptr + 5, parent) < 0)
283                 return error("bad tree pointer in commit %s",
284                              sha1_to_hex(item->object.sha1));
285         item->tree = lookup_tree(parent);
286         if (item->tree)
287                 n_refs++;
288         bufptr += 46; /* "tree " + "hex sha1" + "\n" */
289         pptr = &item->parents;
290
291         graft = lookup_commit_graft(item->object.sha1);
292         while (bufptr + 48 < tail && !memcmp(bufptr, "parent ", 7)) {
293                 struct commit *new_parent;
294
295                 if (tail <= bufptr + 48 ||
296                     get_sha1_hex(bufptr + 7, parent) ||
297                     bufptr[47] != '\n')
298                         return error("bad parents in commit %s", sha1_to_hex(item->object.sha1));
299                 bufptr += 48;
300                 if (graft)
301                         continue;
302                 new_parent = lookup_commit(parent);
303                 if (new_parent) {
304                         pptr = &commit_list_insert(new_parent, pptr)->next;
305                         n_refs++;
306                 }
307         }
308         if (graft) {
309                 int i;
310                 struct commit *new_parent;
311                 for (i = 0; i < graft->nr_parent; i++) {
312                         new_parent = lookup_commit(graft->parent[i]);
313                         if (!new_parent)
314                                 continue;
315                         pptr = &commit_list_insert(new_parent, pptr)->next;
316                         n_refs++;
317                 }
318         }
319         item->date = parse_commit_date(bufptr);
320
321         if (track_object_refs) {
322                 unsigned i = 0;
323                 struct commit_list *p;
324                 struct object_refs *refs = alloc_object_refs(n_refs);
325                 if (item->tree)
326                         refs->ref[i++] = &item->tree->object;
327                 for (p = item->parents; p; p = p->next)
328                         refs->ref[i++] = &p->item->object;
329                 set_object_refs(&item->object, refs);
330         }
331
332         return 0;
333 }
334
335 int parse_commit(struct commit *item)
336 {
337         enum object_type type;
338         void *buffer;
339         unsigned long size;
340         int ret;
341
342         if (item->object.parsed)
343                 return 0;
344         buffer = read_sha1_file(item->object.sha1, &type, &size);
345         if (!buffer)
346                 return error("Could not read %s",
347                              sha1_to_hex(item->object.sha1));
348         if (type != OBJ_COMMIT) {
349                 free(buffer);
350                 return error("Object %s not a commit",
351                              sha1_to_hex(item->object.sha1));
352         }
353         ret = parse_commit_buffer(item, buffer, size);
354         if (save_commit_buffer && !ret) {
355                 item->buffer = buffer;
356                 return 0;
357         }
358         free(buffer);
359         return ret;
360 }
361
362 struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
363 {
364         struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
365         new_list->item = item;
366         new_list->next = *list_p;
367         *list_p = new_list;
368         return new_list;
369 }
370
371 void free_commit_list(struct commit_list *list)
372 {
373         while (list) {
374                 struct commit_list *temp = list;
375                 list = temp->next;
376                 free(temp);
377         }
378 }
379
380 struct commit_list * insert_by_date(struct commit *item, struct commit_list **list)
381 {
382         struct commit_list **pp = list;
383         struct commit_list *p;
384         while ((p = *pp) != NULL) {
385                 if (p->item->date < item->date) {
386                         break;
387                 }
388                 pp = &p->next;
389         }
390         return commit_list_insert(item, pp);
391 }
392
393
394 void sort_by_date(struct commit_list **list)
395 {
396         struct commit_list *ret = NULL;
397         while (*list) {
398                 insert_by_date((*list)->item, &ret);
399                 *list = (*list)->next;
400         }
401         *list = ret;
402 }
403
404 struct commit *pop_most_recent_commit(struct commit_list **list,
405                                       unsigned int mark)
406 {
407         struct commit *ret = (*list)->item;
408         struct commit_list *parents = ret->parents;
409         struct commit_list *old = *list;
410
411         *list = (*list)->next;
412         free(old);
413
414         while (parents) {
415                 struct commit *commit = parents->item;
416                 parse_commit(commit);
417                 if (!(commit->object.flags & mark)) {
418                         commit->object.flags |= mark;
419                         insert_by_date(commit, list);
420                 }
421                 parents = parents->next;
422         }
423         return ret;
424 }
425
426 void clear_commit_marks(struct commit *commit, unsigned int mark)
427 {
428         while (commit) {
429                 struct commit_list *parents;
430
431                 if (!(mark & commit->object.flags))
432                         return;
433
434                 commit->object.flags &= ~mark;
435
436                 parents = commit->parents;
437                 if (!parents)
438                         return;
439
440                 while ((parents = parents->next))
441                         clear_commit_marks(parents->item, mark);
442
443                 commit = commit->parents->item;
444         }
445 }
446
447 /*
448  * Generic support for pretty-printing the header
449  */
450 static int get_one_line(const char *msg)
451 {
452         int ret = 0;
453
454         for (;;) {
455                 char c = *msg++;
456                 if (!c)
457                         break;
458                 ret++;
459                 if (c == '\n')
460                         break;
461         }
462         return ret;
463 }
464
465 /* High bit set, or ISO-2022-INT */
466 int non_ascii(int ch)
467 {
468         ch = (ch & 0xff);
469         return ((ch & 0x80) || (ch == 0x1b));
470 }
471
472 static int is_rfc2047_special(char ch)
473 {
474         return (non_ascii(ch) || (ch == '=') || (ch == '?') || (ch == '_'));
475 }
476
477 static void add_rfc2047(struct strbuf *sb, const char *line, int len,
478                        const char *encoding)
479 {
480         int i, last;
481
482         for (i = 0; i < len; i++) {
483                 int ch = line[i];
484                 if (non_ascii(ch))
485                         goto needquote;
486                 if ((i + 1 < len) && (ch == '=' && line[i+1] == '?'))
487                         goto needquote;
488         }
489         strbuf_add(sb, line, len);
490         return;
491
492 needquote:
493         strbuf_grow(sb, len * 3 + strlen(encoding) + 100);
494         strbuf_addf(sb, "=?%s?q?", encoding);
495         for (i = last = 0; i < len; i++) {
496                 unsigned ch = line[i] & 0xFF;
497                 /*
498                  * We encode ' ' using '=20' even though rfc2047
499                  * allows using '_' for readability.  Unfortunately,
500                  * many programs do not understand this and just
501                  * leave the underscore in place.
502                  */
503                 if (is_rfc2047_special(ch) || ch == ' ') {
504                         strbuf_add(sb, line + last, i - last);
505                         strbuf_addf(sb, "=%02X", ch);
506                         last = i + 1;
507                 }
508         }
509         strbuf_add(sb, line + last, len - last);
510         strbuf_addstr(sb, "?=");
511 }
512
513 static void add_user_info(const char *what, enum cmit_fmt fmt, struct strbuf *sb,
514                          const char *line, enum date_mode dmode,
515                          const char *encoding)
516 {
517         char *date;
518         int namelen;
519         unsigned long time;
520         int tz;
521         const char *filler = "    ";
522
523         if (fmt == CMIT_FMT_ONELINE)
524                 return;
525         date = strchr(line, '>');
526         if (!date)
527                 return;
528         namelen = ++date - line;
529         time = strtoul(date, &date, 10);
530         tz = strtol(date, NULL, 10);
531
532         if (fmt == CMIT_FMT_EMAIL) {
533                 char *name_tail = strchr(line, '<');
534                 int display_name_length;
535                 if (!name_tail)
536                         return;
537                 while (line < name_tail && isspace(name_tail[-1]))
538                         name_tail--;
539                 display_name_length = name_tail - line;
540                 filler = "";
541                 strbuf_addstr(sb, "From: ");
542                 add_rfc2047(sb, line, display_name_length, encoding);
543                 strbuf_add(sb, name_tail, namelen - display_name_length);
544                 strbuf_addch(sb, '\n');
545         } else {
546                 strbuf_addf(sb, "%s: %.*s%.*s\n", what,
547                               (fmt == CMIT_FMT_FULLER) ? 4 : 0,
548                               filler, namelen, line);
549         }
550         switch (fmt) {
551         case CMIT_FMT_MEDIUM:
552                 strbuf_addf(sb, "Date:   %s\n", show_date(time, tz, dmode));
553                 break;
554         case CMIT_FMT_EMAIL:
555                 strbuf_addf(sb, "Date: %s\n", show_date(time, tz, DATE_RFC2822));
556                 break;
557         case CMIT_FMT_FULLER:
558                 strbuf_addf(sb, "%sDate: %s\n", what, show_date(time, tz, dmode));
559                 break;
560         default:
561                 /* notin' */
562                 break;
563         }
564 }
565
566 static int is_empty_line(const char *line, int *len_p)
567 {
568         int len = *len_p;
569         while (len && isspace(line[len-1]))
570                 len--;
571         *len_p = len;
572         return !len;
573 }
574
575 static void add_merge_info(enum cmit_fmt fmt, struct strbuf *sb,
576                         const struct commit *commit, int abbrev)
577 {
578         struct commit_list *parent = commit->parents;
579
580         if ((fmt == CMIT_FMT_ONELINE) || (fmt == CMIT_FMT_EMAIL) ||
581             !parent || !parent->next)
582                 return;
583
584         strbuf_addstr(sb, "Merge:");
585
586         while (parent) {
587                 struct commit *p = parent->item;
588                 const char *hex = NULL;
589                 const char *dots;
590                 if (abbrev)
591                         hex = find_unique_abbrev(p->object.sha1, abbrev);
592                 if (!hex)
593                         hex = sha1_to_hex(p->object.sha1);
594                 dots = (abbrev && strlen(hex) != 40) ?  "..." : "";
595                 parent = parent->next;
596
597                 strbuf_addf(sb, " %s%s", hex, dots);
598         }
599         strbuf_addch(sb, '\n');
600 }
601
602 static char *get_header(const struct commit *commit, const char *key)
603 {
604         int key_len = strlen(key);
605         const char *line = commit->buffer;
606
607         for (;;) {
608                 const char *eol = strchr(line, '\n'), *next;
609
610                 if (line == eol)
611                         return NULL;
612                 if (!eol) {
613                         eol = line + strlen(line);
614                         next = NULL;
615                 } else
616                         next = eol + 1;
617                 if (eol - line > key_len &&
618                     !strncmp(line, key, key_len) &&
619                     line[key_len] == ' ') {
620                         return xmemdupz(line + key_len + 1, eol - line - key_len - 1);
621                 }
622                 line = next;
623         }
624 }
625
626 static char *replace_encoding_header(char *buf, const char *encoding)
627 {
628         struct strbuf tmp;
629         size_t start, len;
630         char *cp = buf;
631
632         /* guess if there is an encoding header before a \n\n */
633         while (strncmp(cp, "encoding ", strlen("encoding "))) {
634                 cp = strchr(cp, '\n');
635                 if (!cp || *++cp == '\n')
636                         return buf;
637         }
638         start = cp - buf;
639         cp = strchr(cp, '\n');
640         if (!cp)
641                 return buf; /* should not happen but be defensive */
642         len = cp + 1 - (buf + start);
643
644         strbuf_init(&tmp, 0);
645         strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1);
646         if (is_encoding_utf8(encoding)) {
647                 /* we have re-coded to UTF-8; drop the header */
648                 strbuf_remove(&tmp, start, len);
649         } else {
650                 /* just replaces XXXX in 'encoding XXXX\n' */
651                 strbuf_splice(&tmp, start + strlen("encoding "),
652                                           len - strlen("encoding \n"),
653                                           encoding, strlen(encoding));
654         }
655         return strbuf_detach(&tmp, NULL);
656 }
657
658 static char *logmsg_reencode(const struct commit *commit,
659                              const char *output_encoding)
660 {
661         static const char *utf8 = "utf-8";
662         const char *use_encoding;
663         char *encoding;
664         char *out;
665
666         if (!*output_encoding)
667                 return NULL;
668         encoding = get_header(commit, "encoding");
669         use_encoding = encoding ? encoding : utf8;
670         if (!strcmp(use_encoding, output_encoding))
671                 if (encoding) /* we'll strip encoding header later */
672                         out = xstrdup(commit->buffer);
673                 else
674                         return NULL; /* nothing to do */
675         else
676                 out = reencode_string(commit->buffer,
677                                       output_encoding, use_encoding);
678         if (out)
679                 out = replace_encoding_header(out, output_encoding);
680
681         free(encoding);
682         return out;
683 }
684
685 static void fill_person(struct interp *table, const char *msg, int len)
686 {
687         int start, end, tz = 0;
688         unsigned long date;
689         char *ep;
690
691         /* parse name */
692         for (end = 0; end < len && msg[end] != '<'; end++)
693                 ; /* do nothing */
694         start = end + 1;
695         while (end > 0 && isspace(msg[end - 1]))
696                 end--;
697         table[0].value = xmemdupz(msg, end);
698
699         if (start >= len)
700                 return;
701
702         /* parse email */
703         for (end = start + 1; end < len && msg[end] != '>'; end++)
704                 ; /* do nothing */
705
706         if (end >= len)
707                 return;
708
709         table[1].value = xmemdupz(msg + start, end - start);
710
711         /* parse date */
712         for (start = end + 1; start < len && isspace(msg[start]); start++)
713                 ; /* do nothing */
714         if (start >= len)
715                 return;
716         date = strtoul(msg + start, &ep, 10);
717         if (msg + start == ep)
718                 return;
719
720         table[5].value = xmemdupz(msg + start, ep - (msg + start));
721
722         /* parse tz */
723         for (start = ep - msg + 1; start < len && isspace(msg[start]); start++)
724                 ; /* do nothing */
725         if (start + 1 < len) {
726                 tz = strtoul(msg + start + 1, NULL, 10);
727                 if (msg[start] == '-')
728                         tz = -tz;
729         }
730
731         interp_set_entry(table, 2, show_date(date, tz, DATE_NORMAL));
732         interp_set_entry(table, 3, show_date(date, tz, DATE_RFC2822));
733         interp_set_entry(table, 4, show_date(date, tz, DATE_RELATIVE));
734         interp_set_entry(table, 6, show_date(date, tz, DATE_ISO8601));
735 }
736
737 void format_commit_message(const struct commit *commit,
738                            const void *format, struct strbuf *sb)
739 {
740         struct interp table[] = {
741                 { "%H" },       /* commit hash */
742                 { "%h" },       /* abbreviated commit hash */
743                 { "%T" },       /* tree hash */
744                 { "%t" },       /* abbreviated tree hash */
745                 { "%P" },       /* parent hashes */
746                 { "%p" },       /* abbreviated parent hashes */
747                 { "%an" },      /* author name */
748                 { "%ae" },      /* author email */
749                 { "%ad" },      /* author date */
750                 { "%aD" },      /* author date, RFC2822 style */
751                 { "%ar" },      /* author date, relative */
752                 { "%at" },      /* author date, UNIX timestamp */
753                 { "%ai" },      /* author date, ISO 8601 */
754                 { "%cn" },      /* committer name */
755                 { "%ce" },      /* committer email */
756                 { "%cd" },      /* committer date */
757                 { "%cD" },      /* committer date, RFC2822 style */
758                 { "%cr" },      /* committer date, relative */
759                 { "%ct" },      /* committer date, UNIX timestamp */
760                 { "%ci" },      /* committer date, ISO 8601 */
761                 { "%e" },       /* encoding */
762                 { "%s" },       /* subject */
763                 { "%b" },       /* body */
764                 { "%Cred" },    /* red */
765                 { "%Cgreen" },  /* green */
766                 { "%Cblue" },   /* blue */
767                 { "%Creset" },  /* reset color */
768                 { "%n" },       /* newline */
769                 { "%m" },       /* left/right/bottom */
770         };
771         enum interp_index {
772                 IHASH = 0, IHASH_ABBREV,
773                 ITREE, ITREE_ABBREV,
774                 IPARENTS, IPARENTS_ABBREV,
775                 IAUTHOR_NAME, IAUTHOR_EMAIL,
776                 IAUTHOR_DATE, IAUTHOR_DATE_RFC2822, IAUTHOR_DATE_RELATIVE,
777                 IAUTHOR_TIMESTAMP, IAUTHOR_ISO8601,
778                 ICOMMITTER_NAME, ICOMMITTER_EMAIL,
779                 ICOMMITTER_DATE, ICOMMITTER_DATE_RFC2822,
780                 ICOMMITTER_DATE_RELATIVE, ICOMMITTER_TIMESTAMP,
781                 ICOMMITTER_ISO8601,
782                 IENCODING,
783                 ISUBJECT,
784                 IBODY,
785                 IRED, IGREEN, IBLUE, IRESET_COLOR,
786                 INEWLINE,
787                 ILEFT_RIGHT,
788         };
789         struct commit_list *p;
790         char parents[1024];
791         unsigned long len;
792         int i;
793         enum { HEADER, SUBJECT, BODY } state;
794         const char *msg = commit->buffer;
795
796         if (ILEFT_RIGHT + 1 != ARRAY_SIZE(table))
797                 die("invalid interp table!");
798
799         /* these are independent of the commit */
800         interp_set_entry(table, IRED, "\033[31m");
801         interp_set_entry(table, IGREEN, "\033[32m");
802         interp_set_entry(table, IBLUE, "\033[34m");
803         interp_set_entry(table, IRESET_COLOR, "\033[m");
804         interp_set_entry(table, INEWLINE, "\n");
805
806         /* these depend on the commit */
807         if (!commit->object.parsed)
808                 parse_object(commit->object.sha1);
809         interp_set_entry(table, IHASH, sha1_to_hex(commit->object.sha1));
810         interp_set_entry(table, IHASH_ABBREV,
811                         find_unique_abbrev(commit->object.sha1,
812                                 DEFAULT_ABBREV));
813         interp_set_entry(table, ITREE, sha1_to_hex(commit->tree->object.sha1));
814         interp_set_entry(table, ITREE_ABBREV,
815                         find_unique_abbrev(commit->tree->object.sha1,
816                                 DEFAULT_ABBREV));
817         interp_set_entry(table, ILEFT_RIGHT,
818                          (commit->object.flags & BOUNDARY)
819                          ? "-"
820                          : (commit->object.flags & SYMMETRIC_LEFT)
821                          ? "<"
822                          : ">");
823
824         parents[1] = 0;
825         for (i = 0, p = commit->parents;
826                         p && i < sizeof(parents) - 1;
827                         p = p->next)
828                 i += snprintf(parents + i, sizeof(parents) - i - 1, " %s",
829                         sha1_to_hex(p->item->object.sha1));
830         interp_set_entry(table, IPARENTS, parents + 1);
831
832         parents[1] = 0;
833         for (i = 0, p = commit->parents;
834                         p && i < sizeof(parents) - 1;
835                         p = p->next)
836                 i += snprintf(parents + i, sizeof(parents) - i - 1, " %s",
837                         find_unique_abbrev(p->item->object.sha1,
838                                 DEFAULT_ABBREV));
839         interp_set_entry(table, IPARENTS_ABBREV, parents + 1);
840
841         for (i = 0, state = HEADER; msg[i] && state < BODY; i++) {
842                 int eol;
843                 for (eol = i; msg[eol] && msg[eol] != '\n'; eol++)
844                         ; /* do nothing */
845
846                 if (state == SUBJECT) {
847                         table[ISUBJECT].value = xmemdupz(msg + i, eol - i);
848                         i = eol;
849                 }
850                 if (i == eol) {
851                         state++;
852                         /* strip empty lines */
853                         while (msg[eol + 1] == '\n')
854                                 eol++;
855                 } else if (!prefixcmp(msg + i, "author "))
856                         fill_person(table + IAUTHOR_NAME,
857                                         msg + i + 7, eol - i - 7);
858                 else if (!prefixcmp(msg + i, "committer "))
859                         fill_person(table + ICOMMITTER_NAME,
860                                         msg + i + 10, eol - i - 10);
861                 else if (!prefixcmp(msg + i, "encoding "))
862                         table[IENCODING].value =
863                                 xmemdupz(msg + i + 9, eol - i - 9);
864                 i = eol;
865         }
866         if (msg[i])
867                 table[IBODY].value = xstrdup(msg + i);
868
869         len = interpolate(sb->buf + sb->len, strbuf_avail(sb),
870                                 format, table, ARRAY_SIZE(table));
871         if (len > strbuf_avail(sb)) {
872                 strbuf_grow(sb, len);
873                 interpolate(sb->buf + sb->len, strbuf_avail(sb) + 1,
874                                         format, table, ARRAY_SIZE(table));
875         }
876         strbuf_setlen(sb, sb->len + len);
877         interp_clear_table(table, ARRAY_SIZE(table));
878 }
879
880 static void pp_header(enum cmit_fmt fmt,
881                       int abbrev,
882                       enum date_mode dmode,
883                       const char *encoding,
884                       const struct commit *commit,
885                       const char **msg_p,
886                       struct strbuf *sb)
887 {
888         int parents_shown = 0;
889
890         for (;;) {
891                 const char *line = *msg_p;
892                 int linelen = get_one_line(*msg_p);
893
894                 if (!linelen)
895                         return;
896                 *msg_p += linelen;
897
898                 if (linelen == 1)
899                         /* End of header */
900                         return;
901
902                 if (fmt == CMIT_FMT_RAW) {
903                         strbuf_add(sb, line, linelen);
904                         continue;
905                 }
906
907                 if (!memcmp(line, "parent ", 7)) {
908                         if (linelen != 48)
909                                 die("bad parent line in commit");
910                         continue;
911                 }
912
913                 if (!parents_shown) {
914                         struct commit_list *parent;
915                         int num;
916                         for (parent = commit->parents, num = 0;
917                              parent;
918                              parent = parent->next, num++)
919                                 ;
920                         /* with enough slop */
921                         strbuf_grow(sb, num * 50 + 20);
922                         add_merge_info(fmt, sb, commit, abbrev);
923                         parents_shown = 1;
924                 }
925
926                 /*
927                  * MEDIUM == DEFAULT shows only author with dates.
928                  * FULL shows both authors but not dates.
929                  * FULLER shows both authors and dates.
930                  */
931                 if (!memcmp(line, "author ", 7)) {
932                         strbuf_grow(sb, linelen + 80);
933                         add_user_info("Author", fmt, sb, line + 7, dmode, encoding);
934                 }
935                 if (!memcmp(line, "committer ", 10) &&
936                     (fmt == CMIT_FMT_FULL || fmt == CMIT_FMT_FULLER)) {
937                         strbuf_grow(sb, linelen + 80);
938                         add_user_info("Commit", fmt, sb, line + 10, dmode, encoding);
939                 }
940         }
941 }
942
943 static void pp_title_line(enum cmit_fmt fmt,
944                           const char **msg_p,
945                           struct strbuf *sb,
946                           const char *subject,
947                           const char *after_subject,
948                           const char *encoding,
949                           int plain_non_ascii)
950 {
951         struct strbuf title;
952
953         strbuf_init(&title, 80);
954
955         for (;;) {
956                 const char *line = *msg_p;
957                 int linelen = get_one_line(line);
958
959                 *msg_p += linelen;
960                 if (!linelen || is_empty_line(line, &linelen))
961                         break;
962
963                 strbuf_grow(&title, linelen + 2);
964                 if (title.len) {
965                         if (fmt == CMIT_FMT_EMAIL) {
966                                 strbuf_addch(&title, '\n');
967                         }
968                         strbuf_addch(&title, ' ');
969                 }
970                 strbuf_add(&title, line, linelen);
971         }
972
973         strbuf_grow(sb, title.len + 1024);
974         if (subject) {
975                 strbuf_addstr(sb, subject);
976                 add_rfc2047(sb, title.buf, title.len, encoding);
977         } else {
978                 strbuf_addbuf(sb, &title);
979         }
980         strbuf_addch(sb, '\n');
981
982         if (plain_non_ascii) {
983                 const char *header_fmt =
984                         "MIME-Version: 1.0\n"
985                         "Content-Type: text/plain; charset=%s\n"
986                         "Content-Transfer-Encoding: 8bit\n";
987                 strbuf_addf(sb, header_fmt, encoding);
988         }
989         if (after_subject) {
990                 strbuf_addstr(sb, after_subject);
991         }
992         if (fmt == CMIT_FMT_EMAIL) {
993                 strbuf_addch(sb, '\n');
994         }
995         strbuf_release(&title);
996 }
997
998 static void pp_remainder(enum cmit_fmt fmt,
999                          const char **msg_p,
1000                          struct strbuf *sb,
1001                          int indent)
1002 {
1003         int first = 1;
1004         for (;;) {
1005                 const char *line = *msg_p;
1006                 int linelen = get_one_line(line);
1007                 *msg_p += linelen;
1008
1009                 if (!linelen)
1010                         break;
1011
1012                 if (is_empty_line(line, &linelen)) {
1013                         if (first)
1014                                 continue;
1015                         if (fmt == CMIT_FMT_SHORT)
1016                                 break;
1017                 }
1018                 first = 0;
1019
1020                 strbuf_grow(sb, linelen + indent + 20);
1021                 if (indent) {
1022                         memset(sb->buf + sb->len, ' ', indent);
1023                         strbuf_setlen(sb, sb->len + indent);
1024                 }
1025                 strbuf_add(sb, line, linelen);
1026                 strbuf_addch(sb, '\n');
1027         }
1028 }
1029
1030 void pretty_print_commit(enum cmit_fmt fmt, const struct commit *commit,
1031                                   struct strbuf *sb, int abbrev,
1032                                   const char *subject, const char *after_subject,
1033                                   enum date_mode dmode, int plain_non_ascii)
1034 {
1035         unsigned long beginning_of_body;
1036         int indent = 4;
1037         const char *msg = commit->buffer;
1038         char *reencoded;
1039         const char *encoding;
1040
1041         if (fmt == CMIT_FMT_USERFORMAT) {
1042                 format_commit_message(commit, user_format, sb);
1043                 return;
1044         }
1045
1046         encoding = (git_log_output_encoding
1047                     ? git_log_output_encoding
1048                     : git_commit_encoding);
1049         if (!encoding)
1050                 encoding = "utf-8";
1051         reencoded = logmsg_reencode(commit, encoding);
1052         if (reencoded) {
1053                 msg = reencoded;
1054         }
1055
1056         if (fmt == CMIT_FMT_ONELINE || fmt == CMIT_FMT_EMAIL)
1057                 indent = 0;
1058
1059         /* After-subject is used to pass in Content-Type: multipart
1060          * MIME header; in that case we do not have to do the
1061          * plaintext content type even if the commit message has
1062          * non 7-bit ASCII character.  Otherwise, check if we need
1063          * to say this is not a 7-bit ASCII.
1064          */
1065         if (fmt == CMIT_FMT_EMAIL && !after_subject) {
1066                 int i, ch, in_body;
1067
1068                 for (in_body = i = 0; (ch = msg[i]); i++) {
1069                         if (!in_body) {
1070                                 /* author could be non 7-bit ASCII but
1071                                  * the log may be so; skip over the
1072                                  * header part first.
1073                                  */
1074                                 if (ch == '\n' && msg[i+1] == '\n')
1075                                         in_body = 1;
1076                         }
1077                         else if (non_ascii(ch)) {
1078                                 plain_non_ascii = 1;
1079                                 break;
1080                         }
1081                 }
1082         }
1083
1084         pp_header(fmt, abbrev, dmode, encoding, commit, &msg, sb);
1085         if (fmt != CMIT_FMT_ONELINE && !subject) {
1086                 strbuf_addch(sb, '\n');
1087         }
1088
1089         /* Skip excess blank lines at the beginning of body, if any... */
1090         for (;;) {
1091                 int linelen = get_one_line(msg);
1092                 int ll = linelen;
1093                 if (!linelen)
1094                         break;
1095                 if (!is_empty_line(msg, &ll))
1096                         break;
1097                 msg += linelen;
1098         }
1099
1100         /* These formats treat the title line specially. */
1101         if (fmt == CMIT_FMT_ONELINE || fmt == CMIT_FMT_EMAIL)
1102                 pp_title_line(fmt, &msg, sb, subject,
1103                               after_subject, encoding, plain_non_ascii);
1104
1105         beginning_of_body = sb->len;
1106         if (fmt != CMIT_FMT_ONELINE)
1107                 pp_remainder(fmt, &msg, sb, indent);
1108         strbuf_rtrim(sb);
1109
1110         /* Make sure there is an EOLN for the non-oneline case */
1111         if (fmt != CMIT_FMT_ONELINE)
1112                 strbuf_addch(sb, '\n');
1113
1114         /*
1115          * The caller may append additional body text in e-mail
1116          * format.  Make sure we did not strip the blank line
1117          * between the header and the body.
1118          */
1119         if (fmt == CMIT_FMT_EMAIL && sb->len <= beginning_of_body)
1120                 strbuf_addch(sb, '\n');
1121         free(reencoded);
1122 }
1123
1124 struct commit *pop_commit(struct commit_list **stack)
1125 {
1126         struct commit_list *top = *stack;
1127         struct commit *item = top ? top->item : NULL;
1128
1129         if (top) {
1130                 *stack = top->next;
1131                 free(top);
1132         }
1133         return item;
1134 }
1135
1136 /*
1137  * Performs an in-place topological sort on the list supplied.
1138  */
1139 void sort_in_topological_order(struct commit_list ** list, int lifo)
1140 {
1141         struct commit_list *next, *orig = *list;
1142         struct commit_list *work, **insert;
1143         struct commit_list **pptr;
1144
1145         if (!orig)
1146                 return;
1147         *list = NULL;
1148
1149         /* Mark them and clear the indegree */
1150         for (next = orig; next; next = next->next) {
1151                 struct commit *commit = next->item;
1152                 commit->object.flags |= TOPOSORT;
1153                 commit->indegree = 0;
1154         }
1155
1156         /* update the indegree */
1157         for (next = orig; next; next = next->next) {
1158                 struct commit_list * parents = next->item->parents;
1159                 while (parents) {
1160                         struct commit *parent = parents->item;
1161
1162                         if (parent->object.flags & TOPOSORT)
1163                                 parent->indegree++;
1164                         parents = parents->next;
1165                 }
1166         }
1167
1168         /*
1169          * find the tips
1170          *
1171          * tips are nodes not reachable from any other node in the list
1172          *
1173          * the tips serve as a starting set for the work queue.
1174          */
1175         work = NULL;
1176         insert = &work;
1177         for (next = orig; next; next = next->next) {
1178                 struct commit *commit = next->item;
1179
1180                 if (!commit->indegree)
1181                         insert = &commit_list_insert(commit, insert)->next;
1182         }
1183
1184         /* process the list in topological order */
1185         if (!lifo)
1186                 sort_by_date(&work);
1187
1188         pptr = list;
1189         *list = NULL;
1190         while (work) {
1191                 struct commit *commit;
1192                 struct commit_list *parents, *work_item;
1193
1194                 work_item = work;
1195                 work = work_item->next;
1196                 work_item->next = NULL;
1197
1198                 commit = work_item->item;
1199                 for (parents = commit->parents; parents ; parents = parents->next) {
1200                         struct commit *parent=parents->item;
1201
1202                         if (!(parent->object.flags & TOPOSORT))
1203                                 continue;
1204
1205                         /*
1206                          * parents are only enqueued for emission
1207                          * when all their children have been emitted thereby
1208                          * guaranteeing topological order.
1209                          */
1210                         if (!--parent->indegree) {
1211                                 if (!lifo)
1212                                         insert_by_date(parent, &work);
1213                                 else
1214                                         commit_list_insert(parent, &work);
1215                         }
1216                 }
1217                 /*
1218                  * work_item is a commit all of whose children
1219                  * have already been emitted. we can emit it now.
1220                  */
1221                 commit->object.flags &= ~TOPOSORT;
1222                 *pptr = work_item;
1223                 pptr = &work_item->next;
1224         }
1225 }
1226
1227 /* merge-base stuff */
1228
1229 /* bits #0..15 in revision.h */
1230 #define PARENT1         (1u<<16)
1231 #define PARENT2         (1u<<17)
1232 #define STALE           (1u<<18)
1233 #define RESULT          (1u<<19)
1234
1235 static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);
1236
1237 static struct commit *interesting(struct commit_list *list)
1238 {
1239         while (list) {
1240                 struct commit *commit = list->item;
1241                 list = list->next;
1242                 if (commit->object.flags & STALE)
1243                         continue;
1244                 return commit;
1245         }
1246         return NULL;
1247 }
1248
1249 static struct commit_list *merge_bases(struct commit *one, struct commit *two)
1250 {
1251         struct commit_list *list = NULL;
1252         struct commit_list *result = NULL;
1253
1254         if (one == two)
1255                 /* We do not mark this even with RESULT so we do not
1256                  * have to clean it up.
1257                  */
1258                 return commit_list_insert(one, &result);
1259
1260         parse_commit(one);
1261         parse_commit(two);
1262
1263         one->object.flags |= PARENT1;
1264         two->object.flags |= PARENT2;
1265         insert_by_date(one, &list);
1266         insert_by_date(two, &list);
1267
1268         while (interesting(list)) {
1269                 struct commit *commit;
1270                 struct commit_list *parents;
1271                 struct commit_list *n;
1272                 int flags;
1273
1274                 commit = list->item;
1275                 n = list->next;
1276                 free(list);
1277                 list = n;
1278
1279                 flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
1280                 if (flags == (PARENT1 | PARENT2)) {
1281                         if (!(commit->object.flags & RESULT)) {
1282                                 commit->object.flags |= RESULT;
1283                                 insert_by_date(commit, &result);
1284                         }
1285                         /* Mark parents of a found merge stale */
1286                         flags |= STALE;
1287                 }
1288                 parents = commit->parents;
1289                 while (parents) {
1290                         struct commit *p = parents->item;
1291                         parents = parents->next;
1292                         if ((p->object.flags & flags) == flags)
1293                                 continue;
1294                         parse_commit(p);
1295                         p->object.flags |= flags;
1296                         insert_by_date(p, &list);
1297                 }
1298         }
1299
1300         /* Clean up the result to remove stale ones */
1301         free_commit_list(list);
1302         list = result; result = NULL;
1303         while (list) {
1304                 struct commit_list *n = list->next;
1305                 if (!(list->item->object.flags & STALE))
1306                         insert_by_date(list->item, &result);
1307                 free(list);
1308                 list = n;
1309         }
1310         return result;
1311 }
1312
1313 struct commit_list *get_merge_bases(struct commit *one,
1314                                         struct commit *two, int cleanup)
1315 {
1316         struct commit_list *list;
1317         struct commit **rslt;
1318         struct commit_list *result;
1319         int cnt, i, j;
1320
1321         result = merge_bases(one, two);
1322         if (one == two)
1323                 return result;
1324         if (!result || !result->next) {
1325                 if (cleanup) {
1326                         clear_commit_marks(one, all_flags);
1327                         clear_commit_marks(two, all_flags);
1328                 }
1329                 return result;
1330         }
1331
1332         /* There are more than one */
1333         cnt = 0;
1334         list = result;
1335         while (list) {
1336                 list = list->next;
1337                 cnt++;
1338         }
1339         rslt = xcalloc(cnt, sizeof(*rslt));
1340         for (list = result, i = 0; list; list = list->next)
1341                 rslt[i++] = list->item;
1342         free_commit_list(result);
1343
1344         clear_commit_marks(one, all_flags);
1345         clear_commit_marks(two, all_flags);
1346         for (i = 0; i < cnt - 1; i++) {
1347                 for (j = i+1; j < cnt; j++) {
1348                         if (!rslt[i] || !rslt[j])
1349                                 continue;
1350                         result = merge_bases(rslt[i], rslt[j]);
1351                         clear_commit_marks(rslt[i], all_flags);
1352                         clear_commit_marks(rslt[j], all_flags);
1353                         for (list = result; list; list = list->next) {
1354                                 if (rslt[i] == list->item)
1355                                         rslt[i] = NULL;
1356                                 if (rslt[j] == list->item)
1357                                         rslt[j] = NULL;
1358                         }
1359                 }
1360         }
1361
1362         /* Surviving ones in rslt[] are the independent results */
1363         result = NULL;
1364         for (i = 0; i < cnt; i++) {
1365                 if (rslt[i])
1366                         insert_by_date(rslt[i], &result);
1367         }
1368         free(rslt);
1369         return result;
1370 }
1371
1372 int in_merge_bases(struct commit *commit, struct commit **reference, int num)
1373 {
1374         struct commit_list *bases, *b;
1375         int ret = 0;
1376
1377         if (num == 1)
1378                 bases = get_merge_bases(commit, *reference, 1);
1379         else
1380                 die("not yet");
1381         for (b = bases; b; b = b->next) {
1382                 if (!hashcmp(commit->object.sha1, b->item->object.sha1)) {
1383                         ret = 1;
1384                         break;
1385                 }
1386         }
1387
1388         free_commit_list(bases);
1389         return ret;
1390 }