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