commit: convert commit->buffer to a slab
[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 "diff.h"
7 #include "revision.h"
8 #include "notes.h"
9 #include "gpg-interface.h"
10 #include "mergesort.h"
11 #include "commit-slab.h"
12 #include "prio-queue.h"
13 #include "sha1-lookup.h"
14
15 static struct commit_extra_header *read_commit_extra_header_lines(const char *buf, size_t len, const char **);
16
17 int save_commit_buffer = 1;
18
19 const char *commit_type = "commit";
20
21 static struct commit *check_commit(struct object *obj,
22                                    const unsigned char *sha1,
23                                    int quiet)
24 {
25         if (obj->type != OBJ_COMMIT) {
26                 if (!quiet)
27                         error("Object %s is a %s, not a commit",
28                               sha1_to_hex(sha1), typename(obj->type));
29                 return NULL;
30         }
31         return (struct commit *) obj;
32 }
33
34 struct commit *lookup_commit_reference_gently(const unsigned char *sha1,
35                                               int quiet)
36 {
37         struct object *obj = deref_tag(parse_object(sha1), NULL, 0);
38
39         if (!obj)
40                 return NULL;
41         return check_commit(obj, sha1, quiet);
42 }
43
44 struct commit *lookup_commit_reference(const unsigned char *sha1)
45 {
46         return lookup_commit_reference_gently(sha1, 0);
47 }
48
49 struct commit *lookup_commit_or_die(const unsigned char *sha1, const char *ref_name)
50 {
51         struct commit *c = lookup_commit_reference(sha1);
52         if (!c)
53                 die(_("could not parse %s"), ref_name);
54         if (hashcmp(sha1, c->object.sha1)) {
55                 warning(_("%s %s is not a commit!"),
56                         ref_name, sha1_to_hex(sha1));
57         }
58         return c;
59 }
60
61 struct commit *lookup_commit(const unsigned char *sha1)
62 {
63         struct object *obj = lookup_object(sha1);
64         if (!obj) {
65                 struct commit *c = alloc_commit_node();
66                 return create_object(sha1, OBJ_COMMIT, c);
67         }
68         if (!obj->type)
69                 obj->type = OBJ_COMMIT;
70         return check_commit(obj, sha1, 0);
71 }
72
73 struct commit *lookup_commit_reference_by_name(const char *name)
74 {
75         unsigned char sha1[20];
76         struct commit *commit;
77
78         if (get_sha1_committish(name, sha1))
79                 return NULL;
80         commit = lookup_commit_reference(sha1);
81         if (parse_commit(commit))
82                 return NULL;
83         return commit;
84 }
85
86 static unsigned long parse_commit_date(const char *buf, const char *tail)
87 {
88         const char *dateptr;
89
90         if (buf + 6 >= tail)
91                 return 0;
92         if (memcmp(buf, "author", 6))
93                 return 0;
94         while (buf < tail && *buf++ != '\n')
95                 /* nada */;
96         if (buf + 9 >= tail)
97                 return 0;
98         if (memcmp(buf, "committer", 9))
99                 return 0;
100         while (buf < tail && *buf++ != '>')
101                 /* nada */;
102         if (buf >= tail)
103                 return 0;
104         dateptr = buf;
105         while (buf < tail && *buf++ != '\n')
106                 /* nada */;
107         if (buf >= tail)
108                 return 0;
109         /* dateptr < buf && buf[-1] == '\n', so strtoul will stop at buf-1 */
110         return strtoul(dateptr, NULL, 10);
111 }
112
113 static struct commit_graft **commit_graft;
114 static int commit_graft_alloc, commit_graft_nr;
115
116 static const unsigned char *commit_graft_sha1_access(size_t index, void *table)
117 {
118         struct commit_graft **commit_graft_table = table;
119         return commit_graft_table[index]->sha1;
120 }
121
122 static int commit_graft_pos(const unsigned char *sha1)
123 {
124         return sha1_pos(sha1, commit_graft, commit_graft_nr,
125                         commit_graft_sha1_access);
126 }
127
128 int register_commit_graft(struct commit_graft *graft, int ignore_dups)
129 {
130         int pos = commit_graft_pos(graft->sha1);
131
132         if (0 <= pos) {
133                 if (ignore_dups)
134                         free(graft);
135                 else {
136                         free(commit_graft[pos]);
137                         commit_graft[pos] = graft;
138                 }
139                 return 1;
140         }
141         pos = -pos - 1;
142         ALLOC_GROW(commit_graft, commit_graft_nr + 1, commit_graft_alloc);
143         commit_graft_nr++;
144         if (pos < commit_graft_nr)
145                 memmove(commit_graft + pos + 1,
146                         commit_graft + pos,
147                         (commit_graft_nr - pos - 1) *
148                         sizeof(*commit_graft));
149         commit_graft[pos] = graft;
150         return 0;
151 }
152
153 struct commit_graft *read_graft_line(char *buf, int len)
154 {
155         /* The format is just "Commit Parent1 Parent2 ...\n" */
156         int i;
157         struct commit_graft *graft = NULL;
158
159         while (len && isspace(buf[len-1]))
160                 buf[--len] = '\0';
161         if (buf[0] == '#' || buf[0] == '\0')
162                 return NULL;
163         if ((len + 1) % 41)
164                 goto bad_graft_data;
165         i = (len + 1) / 41 - 1;
166         graft = xmalloc(sizeof(*graft) + 20 * i);
167         graft->nr_parent = i;
168         if (get_sha1_hex(buf, graft->sha1))
169                 goto bad_graft_data;
170         for (i = 40; i < len; i += 41) {
171                 if (buf[i] != ' ')
172                         goto bad_graft_data;
173                 if (get_sha1_hex(buf + i + 1, graft->parent[i/41]))
174                         goto bad_graft_data;
175         }
176         return graft;
177
178 bad_graft_data:
179         error("bad graft data: %s", buf);
180         free(graft);
181         return NULL;
182 }
183
184 static int read_graft_file(const char *graft_file)
185 {
186         FILE *fp = fopen(graft_file, "r");
187         struct strbuf buf = STRBUF_INIT;
188         if (!fp)
189                 return -1;
190         while (!strbuf_getwholeline(&buf, fp, '\n')) {
191                 /* The format is just "Commit Parent1 Parent2 ...\n" */
192                 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);
193                 if (!graft)
194                         continue;
195                 if (register_commit_graft(graft, 1))
196                         error("duplicate graft data: %s", buf.buf);
197         }
198         fclose(fp);
199         strbuf_release(&buf);
200         return 0;
201 }
202
203 static void prepare_commit_graft(void)
204 {
205         static int commit_graft_prepared;
206         char *graft_file;
207
208         if (commit_graft_prepared)
209                 return;
210         graft_file = get_graft_file();
211         read_graft_file(graft_file);
212         /* make sure shallows are read */
213         is_repository_shallow();
214         commit_graft_prepared = 1;
215 }
216
217 struct commit_graft *lookup_commit_graft(const unsigned char *sha1)
218 {
219         int pos;
220         prepare_commit_graft();
221         pos = commit_graft_pos(sha1);
222         if (pos < 0)
223                 return NULL;
224         return commit_graft[pos];
225 }
226
227 int for_each_commit_graft(each_commit_graft_fn fn, void *cb_data)
228 {
229         int i, ret;
230         for (i = ret = 0; i < commit_graft_nr && !ret; i++)
231                 ret = fn(commit_graft[i], cb_data);
232         return ret;
233 }
234
235 int unregister_shallow(const unsigned char *sha1)
236 {
237         int pos = commit_graft_pos(sha1);
238         if (pos < 0)
239                 return -1;
240         if (pos + 1 < commit_graft_nr)
241                 memmove(commit_graft + pos, commit_graft + pos + 1,
242                                 sizeof(struct commit_graft *)
243                                 * (commit_graft_nr - pos - 1));
244         commit_graft_nr--;
245         return 0;
246 }
247
248 define_commit_slab(buffer_slab, void *);
249 static struct buffer_slab buffer_slab = COMMIT_SLAB_INIT(1, buffer_slab);
250
251 void set_commit_buffer(struct commit *commit, void *buffer)
252 {
253         *buffer_slab_at(&buffer_slab, commit) = buffer;
254 }
255
256 const void *get_cached_commit_buffer(const struct commit *commit)
257 {
258         return *buffer_slab_at(&buffer_slab, commit);
259 }
260
261 const void *get_commit_buffer(const struct commit *commit)
262 {
263         const void *ret = get_cached_commit_buffer(commit);
264         if (!ret) {
265                 enum object_type type;
266                 unsigned long size;
267                 ret = read_sha1_file(commit->object.sha1, &type, &size);
268                 if (!ret)
269                         die("cannot read commit object %s",
270                             sha1_to_hex(commit->object.sha1));
271                 if (type != OBJ_COMMIT)
272                         die("expected commit for %s, got %s",
273                             sha1_to_hex(commit->object.sha1), typename(type));
274         }
275         return ret;
276 }
277
278 void unuse_commit_buffer(const struct commit *commit, const void *buffer)
279 {
280         void *cached = *buffer_slab_at(&buffer_slab, commit);
281         if (cached != buffer)
282                 free((void *)buffer);
283 }
284
285 void free_commit_buffer(struct commit *commit)
286 {
287         void **b = buffer_slab_at(&buffer_slab, commit);
288         free(*b);
289         *b = NULL;
290 }
291
292 const void *detach_commit_buffer(struct commit *commit)
293 {
294         void **b = buffer_slab_at(&buffer_slab, commit);
295         void *ret = *b;
296         *b = NULL;
297         return ret;
298 }
299
300 int parse_commit_buffer(struct commit *item, const void *buffer, unsigned long size)
301 {
302         const char *tail = buffer;
303         const char *bufptr = buffer;
304         unsigned char parent[20];
305         struct commit_list **pptr;
306         struct commit_graft *graft;
307
308         if (item->object.parsed)
309                 return 0;
310         item->object.parsed = 1;
311         tail += size;
312         if (tail <= bufptr + 46 || memcmp(bufptr, "tree ", 5) || bufptr[45] != '\n')
313                 return error("bogus commit object %s", sha1_to_hex(item->object.sha1));
314         if (get_sha1_hex(bufptr + 5, parent) < 0)
315                 return error("bad tree pointer in commit %s",
316                              sha1_to_hex(item->object.sha1));
317         item->tree = lookup_tree(parent);
318         bufptr += 46; /* "tree " + "hex sha1" + "\n" */
319         pptr = &item->parents;
320
321         graft = lookup_commit_graft(item->object.sha1);
322         while (bufptr + 48 < tail && !memcmp(bufptr, "parent ", 7)) {
323                 struct commit *new_parent;
324
325                 if (tail <= bufptr + 48 ||
326                     get_sha1_hex(bufptr + 7, parent) ||
327                     bufptr[47] != '\n')
328                         return error("bad parents in commit %s", sha1_to_hex(item->object.sha1));
329                 bufptr += 48;
330                 /*
331                  * The clone is shallow if nr_parent < 0, and we must
332                  * not traverse its real parents even when we unhide them.
333                  */
334                 if (graft && (graft->nr_parent < 0 || grafts_replace_parents))
335                         continue;
336                 new_parent = lookup_commit(parent);
337                 if (new_parent)
338                         pptr = &commit_list_insert(new_parent, pptr)->next;
339         }
340         if (graft) {
341                 int i;
342                 struct commit *new_parent;
343                 for (i = 0; i < graft->nr_parent; i++) {
344                         new_parent = lookup_commit(graft->parent[i]);
345                         if (!new_parent)
346                                 continue;
347                         pptr = &commit_list_insert(new_parent, pptr)->next;
348                 }
349         }
350         item->date = parse_commit_date(bufptr, tail);
351
352         return 0;
353 }
354
355 int parse_commit(struct commit *item)
356 {
357         enum object_type type;
358         void *buffer;
359         unsigned long size;
360         int ret;
361
362         if (!item)
363                 return -1;
364         if (item->object.parsed)
365                 return 0;
366         buffer = read_sha1_file(item->object.sha1, &type, &size);
367         if (!buffer)
368                 return error("Could not read %s",
369                              sha1_to_hex(item->object.sha1));
370         if (type != OBJ_COMMIT) {
371                 free(buffer);
372                 return error("Object %s not a commit",
373                              sha1_to_hex(item->object.sha1));
374         }
375         ret = parse_commit_buffer(item, buffer, size);
376         if (save_commit_buffer && !ret) {
377                 set_commit_buffer(item, buffer);
378                 return 0;
379         }
380         free(buffer);
381         return ret;
382 }
383
384 void parse_commit_or_die(struct commit *item)
385 {
386         if (parse_commit(item))
387                 die("unable to parse commit %s",
388                     item ? sha1_to_hex(item->object.sha1) : "(null)");
389 }
390
391 int find_commit_subject(const char *commit_buffer, const char **subject)
392 {
393         const char *eol;
394         const char *p = commit_buffer;
395
396         while (*p && (*p != '\n' || p[1] != '\n'))
397                 p++;
398         if (*p) {
399                 p += 2;
400                 for (eol = p; *eol && *eol != '\n'; eol++)
401                         ; /* do nothing */
402         } else
403                 eol = p;
404
405         *subject = p;
406
407         return eol - p;
408 }
409
410 struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
411 {
412         struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
413         new_list->item = item;
414         new_list->next = *list_p;
415         *list_p = new_list;
416         return new_list;
417 }
418
419 unsigned commit_list_count(const struct commit_list *l)
420 {
421         unsigned c = 0;
422         for (; l; l = l->next )
423                 c++;
424         return c;
425 }
426
427 struct commit_list *copy_commit_list(struct commit_list *list)
428 {
429         struct commit_list *head = NULL;
430         struct commit_list **pp = &head;
431         while (list) {
432                 struct commit_list *new;
433                 new = xmalloc(sizeof(struct commit_list));
434                 new->item = list->item;
435                 new->next = NULL;
436                 *pp = new;
437                 pp = &new->next;
438                 list = list->next;
439         }
440         return head;
441 }
442
443 void free_commit_list(struct commit_list *list)
444 {
445         while (list) {
446                 struct commit_list *temp = list;
447                 list = temp->next;
448                 free(temp);
449         }
450 }
451
452 struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
453 {
454         struct commit_list **pp = list;
455         struct commit_list *p;
456         while ((p = *pp) != NULL) {
457                 if (p->item->date < item->date) {
458                         break;
459                 }
460                 pp = &p->next;
461         }
462         return commit_list_insert(item, pp);
463 }
464
465 static int commit_list_compare_by_date(const void *a, const void *b)
466 {
467         unsigned long a_date = ((const struct commit_list *)a)->item->date;
468         unsigned long b_date = ((const struct commit_list *)b)->item->date;
469         if (a_date < b_date)
470                 return 1;
471         if (a_date > b_date)
472                 return -1;
473         return 0;
474 }
475
476 static void *commit_list_get_next(const void *a)
477 {
478         return ((const struct commit_list *)a)->next;
479 }
480
481 static void commit_list_set_next(void *a, void *next)
482 {
483         ((struct commit_list *)a)->next = next;
484 }
485
486 void commit_list_sort_by_date(struct commit_list **list)
487 {
488         *list = llist_mergesort(*list, commit_list_get_next, commit_list_set_next,
489                                 commit_list_compare_by_date);
490 }
491
492 struct commit *pop_most_recent_commit(struct commit_list **list,
493                                       unsigned int mark)
494 {
495         struct commit *ret = (*list)->item;
496         struct commit_list *parents = ret->parents;
497         struct commit_list *old = *list;
498
499         *list = (*list)->next;
500         free(old);
501
502         while (parents) {
503                 struct commit *commit = parents->item;
504                 if (!parse_commit(commit) && !(commit->object.flags & mark)) {
505                         commit->object.flags |= mark;
506                         commit_list_insert_by_date(commit, list);
507                 }
508                 parents = parents->next;
509         }
510         return ret;
511 }
512
513 static void clear_commit_marks_1(struct commit_list **plist,
514                                  struct commit *commit, unsigned int mark)
515 {
516         while (commit) {
517                 struct commit_list *parents;
518
519                 if (!(mark & commit->object.flags))
520                         return;
521
522                 commit->object.flags &= ~mark;
523
524                 parents = commit->parents;
525                 if (!parents)
526                         return;
527
528                 while ((parents = parents->next))
529                         commit_list_insert(parents->item, plist);
530
531                 commit = commit->parents->item;
532         }
533 }
534
535 void clear_commit_marks_many(int nr, struct commit **commit, unsigned int mark)
536 {
537         struct commit_list *list = NULL;
538
539         while (nr--) {
540                 commit_list_insert(*commit, &list);
541                 commit++;
542         }
543         while (list)
544                 clear_commit_marks_1(&list, pop_commit(&list), mark);
545 }
546
547 void clear_commit_marks(struct commit *commit, unsigned int mark)
548 {
549         clear_commit_marks_many(1, &commit, mark);
550 }
551
552 void clear_commit_marks_for_object_array(struct object_array *a, unsigned mark)
553 {
554         struct object *object;
555         struct commit *commit;
556         unsigned int i;
557
558         for (i = 0; i < a->nr; i++) {
559                 object = a->objects[i].item;
560                 commit = lookup_commit_reference_gently(object->sha1, 1);
561                 if (commit)
562                         clear_commit_marks(commit, mark);
563         }
564 }
565
566 struct commit *pop_commit(struct commit_list **stack)
567 {
568         struct commit_list *top = *stack;
569         struct commit *item = top ? top->item : NULL;
570
571         if (top) {
572                 *stack = top->next;
573                 free(top);
574         }
575         return item;
576 }
577
578 /*
579  * Topological sort support
580  */
581
582 /* count number of children that have not been emitted */
583 define_commit_slab(indegree_slab, int);
584
585 /* record author-date for each commit object */
586 define_commit_slab(author_date_slab, unsigned long);
587
588 static void record_author_date(struct author_date_slab *author_date,
589                                struct commit *commit)
590 {
591         const char *buf, *line_end, *ident_line;
592         const char *buffer = get_commit_buffer(commit);
593         struct ident_split ident;
594         char *date_end;
595         unsigned long date;
596
597         for (buf = buffer; buf; buf = line_end + 1) {
598                 line_end = strchrnul(buf, '\n');
599                 ident_line = skip_prefix(buf, "author ");
600                 if (!ident_line) {
601                         if (!line_end[0] || line_end[1] == '\n')
602                                 return; /* end of header */
603                         continue;
604                 }
605                 if (split_ident_line(&ident,
606                                      ident_line, line_end - ident_line) ||
607                     !ident.date_begin || !ident.date_end)
608                         goto fail_exit; /* malformed "author" line */
609                 break;
610         }
611
612         date = strtoul(ident.date_begin, &date_end, 10);
613         if (date_end != ident.date_end)
614                 goto fail_exit; /* malformed date */
615         *(author_date_slab_at(author_date, commit)) = date;
616
617 fail_exit:
618         unuse_commit_buffer(commit, buffer);
619 }
620
621 static int compare_commits_by_author_date(const void *a_, const void *b_,
622                                           void *cb_data)
623 {
624         const struct commit *a = a_, *b = b_;
625         struct author_date_slab *author_date = cb_data;
626         unsigned long a_date = *(author_date_slab_at(author_date, a));
627         unsigned long b_date = *(author_date_slab_at(author_date, b));
628
629         /* newer commits with larger date first */
630         if (a_date < b_date)
631                 return 1;
632         else if (a_date > b_date)
633                 return -1;
634         return 0;
635 }
636
637 int compare_commits_by_commit_date(const void *a_, const void *b_, void *unused)
638 {
639         const struct commit *a = a_, *b = b_;
640         /* newer commits with larger date first */
641         if (a->date < b->date)
642                 return 1;
643         else if (a->date > b->date)
644                 return -1;
645         return 0;
646 }
647
648 /*
649  * Performs an in-place topological sort on the list supplied.
650  */
651 void sort_in_topological_order(struct commit_list **list, enum rev_sort_order sort_order)
652 {
653         struct commit_list *next, *orig = *list;
654         struct commit_list **pptr;
655         struct indegree_slab indegree;
656         struct prio_queue queue;
657         struct commit *commit;
658         struct author_date_slab author_date;
659
660         if (!orig)
661                 return;
662         *list = NULL;
663
664         init_indegree_slab(&indegree);
665         memset(&queue, '\0', sizeof(queue));
666
667         switch (sort_order) {
668         default: /* REV_SORT_IN_GRAPH_ORDER */
669                 queue.compare = NULL;
670                 break;
671         case REV_SORT_BY_COMMIT_DATE:
672                 queue.compare = compare_commits_by_commit_date;
673                 break;
674         case REV_SORT_BY_AUTHOR_DATE:
675                 init_author_date_slab(&author_date);
676                 queue.compare = compare_commits_by_author_date;
677                 queue.cb_data = &author_date;
678                 break;
679         }
680
681         /* Mark them and clear the indegree */
682         for (next = orig; next; next = next->next) {
683                 struct commit *commit = next->item;
684                 *(indegree_slab_at(&indegree, commit)) = 1;
685                 /* also record the author dates, if needed */
686                 if (sort_order == REV_SORT_BY_AUTHOR_DATE)
687                         record_author_date(&author_date, commit);
688         }
689
690         /* update the indegree */
691         for (next = orig; next; next = next->next) {
692                 struct commit_list *parents = next->item->parents;
693                 while (parents) {
694                         struct commit *parent = parents->item;
695                         int *pi = indegree_slab_at(&indegree, parent);
696
697                         if (*pi)
698                                 (*pi)++;
699                         parents = parents->next;
700                 }
701         }
702
703         /*
704          * find the tips
705          *
706          * tips are nodes not reachable from any other node in the list
707          *
708          * the tips serve as a starting set for the work queue.
709          */
710         for (next = orig; next; next = next->next) {
711                 struct commit *commit = next->item;
712
713                 if (*(indegree_slab_at(&indegree, commit)) == 1)
714                         prio_queue_put(&queue, commit);
715         }
716
717         /*
718          * This is unfortunate; the initial tips need to be shown
719          * in the order given from the revision traversal machinery.
720          */
721         if (sort_order == REV_SORT_IN_GRAPH_ORDER)
722                 prio_queue_reverse(&queue);
723
724         /* We no longer need the commit list */
725         free_commit_list(orig);
726
727         pptr = list;
728         *list = NULL;
729         while ((commit = prio_queue_get(&queue)) != NULL) {
730                 struct commit_list *parents;
731
732                 for (parents = commit->parents; parents ; parents = parents->next) {
733                         struct commit *parent = parents->item;
734                         int *pi = indegree_slab_at(&indegree, parent);
735
736                         if (!*pi)
737                                 continue;
738
739                         /*
740                          * parents are only enqueued for emission
741                          * when all their children have been emitted thereby
742                          * guaranteeing topological order.
743                          */
744                         if (--(*pi) == 1)
745                                 prio_queue_put(&queue, parent);
746                 }
747                 /*
748                  * all children of commit have already been
749                  * emitted. we can emit it now.
750                  */
751                 *(indegree_slab_at(&indegree, commit)) = 0;
752
753                 pptr = &commit_list_insert(commit, pptr)->next;
754         }
755
756         clear_indegree_slab(&indegree);
757         clear_prio_queue(&queue);
758         if (sort_order == REV_SORT_BY_AUTHOR_DATE)
759                 clear_author_date_slab(&author_date);
760 }
761
762 /* merge-base stuff */
763
764 /* Remember to update object flag allocation in object.h */
765 #define PARENT1         (1u<<16)
766 #define PARENT2         (1u<<17)
767 #define STALE           (1u<<18)
768 #define RESULT          (1u<<19)
769
770 static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);
771
772 static struct commit *interesting(struct commit_list *list)
773 {
774         while (list) {
775                 struct commit *commit = list->item;
776                 list = list->next;
777                 if (commit->object.flags & STALE)
778                         continue;
779                 return commit;
780         }
781         return NULL;
782 }
783
784 /* all input commits in one and twos[] must have been parsed! */
785 static struct commit_list *paint_down_to_common(struct commit *one, int n, struct commit **twos)
786 {
787         struct commit_list *list = NULL;
788         struct commit_list *result = NULL;
789         int i;
790
791         one->object.flags |= PARENT1;
792         commit_list_insert_by_date(one, &list);
793         if (!n)
794                 return list;
795         for (i = 0; i < n; i++) {
796                 twos[i]->object.flags |= PARENT2;
797                 commit_list_insert_by_date(twos[i], &list);
798         }
799
800         while (interesting(list)) {
801                 struct commit *commit;
802                 struct commit_list *parents;
803                 struct commit_list *next;
804                 int flags;
805
806                 commit = list->item;
807                 next = list->next;
808                 free(list);
809                 list = next;
810
811                 flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
812                 if (flags == (PARENT1 | PARENT2)) {
813                         if (!(commit->object.flags & RESULT)) {
814                                 commit->object.flags |= RESULT;
815                                 commit_list_insert_by_date(commit, &result);
816                         }
817                         /* Mark parents of a found merge stale */
818                         flags |= STALE;
819                 }
820                 parents = commit->parents;
821                 while (parents) {
822                         struct commit *p = parents->item;
823                         parents = parents->next;
824                         if ((p->object.flags & flags) == flags)
825                                 continue;
826                         if (parse_commit(p))
827                                 return NULL;
828                         p->object.flags |= flags;
829                         commit_list_insert_by_date(p, &list);
830                 }
831         }
832
833         free_commit_list(list);
834         return result;
835 }
836
837 static struct commit_list *merge_bases_many(struct commit *one, int n, struct commit **twos)
838 {
839         struct commit_list *list = NULL;
840         struct commit_list *result = NULL;
841         int i;
842
843         for (i = 0; i < n; i++) {
844                 if (one == twos[i])
845                         /*
846                          * We do not mark this even with RESULT so we do not
847                          * have to clean it up.
848                          */
849                         return commit_list_insert(one, &result);
850         }
851
852         if (parse_commit(one))
853                 return NULL;
854         for (i = 0; i < n; i++) {
855                 if (parse_commit(twos[i]))
856                         return NULL;
857         }
858
859         list = paint_down_to_common(one, n, twos);
860
861         while (list) {
862                 struct commit_list *next = list->next;
863                 if (!(list->item->object.flags & STALE))
864                         commit_list_insert_by_date(list->item, &result);
865                 free(list);
866                 list = next;
867         }
868         return result;
869 }
870
871 struct commit_list *get_octopus_merge_bases(struct commit_list *in)
872 {
873         struct commit_list *i, *j, *k, *ret = NULL;
874
875         if (!in)
876                 return ret;
877
878         commit_list_insert(in->item, &ret);
879
880         for (i = in->next; i; i = i->next) {
881                 struct commit_list *new = NULL, *end = NULL;
882
883                 for (j = ret; j; j = j->next) {
884                         struct commit_list *bases;
885                         bases = get_merge_bases(i->item, j->item, 1);
886                         if (!new)
887                                 new = bases;
888                         else
889                                 end->next = bases;
890                         for (k = bases; k; k = k->next)
891                                 end = k;
892                 }
893                 ret = new;
894         }
895         return ret;
896 }
897
898 static int remove_redundant(struct commit **array, int cnt)
899 {
900         /*
901          * Some commit in the array may be an ancestor of
902          * another commit.  Move such commit to the end of
903          * the array, and return the number of commits that
904          * are independent from each other.
905          */
906         struct commit **work;
907         unsigned char *redundant;
908         int *filled_index;
909         int i, j, filled;
910
911         work = xcalloc(cnt, sizeof(*work));
912         redundant = xcalloc(cnt, 1);
913         filled_index = xmalloc(sizeof(*filled_index) * (cnt - 1));
914
915         for (i = 0; i < cnt; i++)
916                 parse_commit(array[i]);
917         for (i = 0; i < cnt; i++) {
918                 struct commit_list *common;
919
920                 if (redundant[i])
921                         continue;
922                 for (j = filled = 0; j < cnt; j++) {
923                         if (i == j || redundant[j])
924                                 continue;
925                         filled_index[filled] = j;
926                         work[filled++] = array[j];
927                 }
928                 common = paint_down_to_common(array[i], filled, work);
929                 if (array[i]->object.flags & PARENT2)
930                         redundant[i] = 1;
931                 for (j = 0; j < filled; j++)
932                         if (work[j]->object.flags & PARENT1)
933                                 redundant[filled_index[j]] = 1;
934                 clear_commit_marks(array[i], all_flags);
935                 for (j = 0; j < filled; j++)
936                         clear_commit_marks(work[j], all_flags);
937                 free_commit_list(common);
938         }
939
940         /* Now collect the result */
941         memcpy(work, array, sizeof(*array) * cnt);
942         for (i = filled = 0; i < cnt; i++)
943                 if (!redundant[i])
944                         array[filled++] = work[i];
945         for (j = filled, i = 0; i < cnt; i++)
946                 if (redundant[i])
947                         array[j++] = work[i];
948         free(work);
949         free(redundant);
950         free(filled_index);
951         return filled;
952 }
953
954 struct commit_list *get_merge_bases_many(struct commit *one,
955                                          int n,
956                                          struct commit **twos,
957                                          int cleanup)
958 {
959         struct commit_list *list;
960         struct commit **rslt;
961         struct commit_list *result;
962         int cnt, i;
963
964         result = merge_bases_many(one, n, twos);
965         for (i = 0; i < n; i++) {
966                 if (one == twos[i])
967                         return result;
968         }
969         if (!result || !result->next) {
970                 if (cleanup) {
971                         clear_commit_marks(one, all_flags);
972                         clear_commit_marks_many(n, twos, all_flags);
973                 }
974                 return result;
975         }
976
977         /* There are more than one */
978         cnt = 0;
979         list = result;
980         while (list) {
981                 list = list->next;
982                 cnt++;
983         }
984         rslt = xcalloc(cnt, sizeof(*rslt));
985         for (list = result, i = 0; list; list = list->next)
986                 rslt[i++] = list->item;
987         free_commit_list(result);
988
989         clear_commit_marks(one, all_flags);
990         clear_commit_marks_many(n, twos, all_flags);
991
992         cnt = remove_redundant(rslt, cnt);
993         result = NULL;
994         for (i = 0; i < cnt; i++)
995                 commit_list_insert_by_date(rslt[i], &result);
996         free(rslt);
997         return result;
998 }
999
1000 struct commit_list *get_merge_bases(struct commit *one, struct commit *two,
1001                                     int cleanup)
1002 {
1003         return get_merge_bases_many(one, 1, &two, cleanup);
1004 }
1005
1006 /*
1007  * Is "commit" a descendant of one of the elements on the "with_commit" list?
1008  */
1009 int is_descendant_of(struct commit *commit, struct commit_list *with_commit)
1010 {
1011         if (!with_commit)
1012                 return 1;
1013         while (with_commit) {
1014                 struct commit *other;
1015
1016                 other = with_commit->item;
1017                 with_commit = with_commit->next;
1018                 if (in_merge_bases(other, commit))
1019                         return 1;
1020         }
1021         return 0;
1022 }
1023
1024 /*
1025  * Is "commit" an ancestor of one of the "references"?
1026  */
1027 int in_merge_bases_many(struct commit *commit, int nr_reference, struct commit **reference)
1028 {
1029         struct commit_list *bases;
1030         int ret = 0, i;
1031
1032         if (parse_commit(commit))
1033                 return ret;
1034         for (i = 0; i < nr_reference; i++)
1035                 if (parse_commit(reference[i]))
1036                         return ret;
1037
1038         bases = paint_down_to_common(commit, nr_reference, reference);
1039         if (commit->object.flags & PARENT2)
1040                 ret = 1;
1041         clear_commit_marks(commit, all_flags);
1042         clear_commit_marks_many(nr_reference, reference, all_flags);
1043         free_commit_list(bases);
1044         return ret;
1045 }
1046
1047 /*
1048  * Is "commit" an ancestor of (i.e. reachable from) the "reference"?
1049  */
1050 int in_merge_bases(struct commit *commit, struct commit *reference)
1051 {
1052         return in_merge_bases_many(commit, 1, &reference);
1053 }
1054
1055 struct commit_list *reduce_heads(struct commit_list *heads)
1056 {
1057         struct commit_list *p;
1058         struct commit_list *result = NULL, **tail = &result;
1059         struct commit **array;
1060         int num_head, i;
1061
1062         if (!heads)
1063                 return NULL;
1064
1065         /* Uniquify */
1066         for (p = heads; p; p = p->next)
1067                 p->item->object.flags &= ~STALE;
1068         for (p = heads, num_head = 0; p; p = p->next) {
1069                 if (p->item->object.flags & STALE)
1070                         continue;
1071                 p->item->object.flags |= STALE;
1072                 num_head++;
1073         }
1074         array = xcalloc(sizeof(*array), num_head);
1075         for (p = heads, i = 0; p; p = p->next) {
1076                 if (p->item->object.flags & STALE) {
1077                         array[i++] = p->item;
1078                         p->item->object.flags &= ~STALE;
1079                 }
1080         }
1081         num_head = remove_redundant(array, num_head);
1082         for (i = 0; i < num_head; i++)
1083                 tail = &commit_list_insert(array[i], tail)->next;
1084         return result;
1085 }
1086
1087 static const char gpg_sig_header[] = "gpgsig";
1088 static const int gpg_sig_header_len = sizeof(gpg_sig_header) - 1;
1089
1090 static int do_sign_commit(struct strbuf *buf, const char *keyid)
1091 {
1092         struct strbuf sig = STRBUF_INIT;
1093         int inspos, copypos;
1094
1095         /* find the end of the header */
1096         inspos = strstr(buf->buf, "\n\n") - buf->buf + 1;
1097
1098         if (!keyid || !*keyid)
1099                 keyid = get_signing_key();
1100         if (sign_buffer(buf, &sig, keyid)) {
1101                 strbuf_release(&sig);
1102                 return -1;
1103         }
1104
1105         for (copypos = 0; sig.buf[copypos]; ) {
1106                 const char *bol = sig.buf + copypos;
1107                 const char *eol = strchrnul(bol, '\n');
1108                 int len = (eol - bol) + !!*eol;
1109
1110                 if (!copypos) {
1111                         strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
1112                         inspos += gpg_sig_header_len;
1113                 }
1114                 strbuf_insert(buf, inspos++, " ", 1);
1115                 strbuf_insert(buf, inspos, bol, len);
1116                 inspos += len;
1117                 copypos += len;
1118         }
1119         strbuf_release(&sig);
1120         return 0;
1121 }
1122
1123 int parse_signed_commit(const unsigned char *sha1,
1124                         struct strbuf *payload, struct strbuf *signature)
1125 {
1126         unsigned long size;
1127         enum object_type type;
1128         char *buffer = read_sha1_file(sha1, &type, &size);
1129         int in_signature, saw_signature = -1;
1130         char *line, *tail;
1131
1132         if (!buffer || type != OBJ_COMMIT)
1133                 goto cleanup;
1134
1135         line = buffer;
1136         tail = buffer + size;
1137         in_signature = 0;
1138         saw_signature = 0;
1139         while (line < tail) {
1140                 const char *sig = NULL;
1141                 char *next = memchr(line, '\n', tail - line);
1142
1143                 next = next ? next + 1 : tail;
1144                 if (in_signature && line[0] == ' ')
1145                         sig = line + 1;
1146                 else if (starts_with(line, gpg_sig_header) &&
1147                          line[gpg_sig_header_len] == ' ')
1148                         sig = line + gpg_sig_header_len + 1;
1149                 if (sig) {
1150                         strbuf_add(signature, sig, next - sig);
1151                         saw_signature = 1;
1152                         in_signature = 1;
1153                 } else {
1154                         if (*line == '\n')
1155                                 /* dump the whole remainder of the buffer */
1156                                 next = tail;
1157                         strbuf_add(payload, line, next - line);
1158                         in_signature = 0;
1159                 }
1160                 line = next;
1161         }
1162  cleanup:
1163         free(buffer);
1164         return saw_signature;
1165 }
1166
1167 static void handle_signed_tag(struct commit *parent, struct commit_extra_header ***tail)
1168 {
1169         struct merge_remote_desc *desc;
1170         struct commit_extra_header *mergetag;
1171         char *buf;
1172         unsigned long size, len;
1173         enum object_type type;
1174
1175         desc = merge_remote_util(parent);
1176         if (!desc || !desc->obj)
1177                 return;
1178         buf = read_sha1_file(desc->obj->sha1, &type, &size);
1179         if (!buf || type != OBJ_TAG)
1180                 goto free_return;
1181         len = parse_signature(buf, size);
1182         if (size == len)
1183                 goto free_return;
1184         /*
1185          * We could verify this signature and either omit the tag when
1186          * it does not validate, but the integrator may not have the
1187          * public key of the signer of the tag he is merging, while a
1188          * later auditor may have it while auditing, so let's not run
1189          * verify-signed-buffer here for now...
1190          *
1191          * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
1192          *      warn("warning: signed tag unverified.");
1193          */
1194         mergetag = xcalloc(1, sizeof(*mergetag));
1195         mergetag->key = xstrdup("mergetag");
1196         mergetag->value = buf;
1197         mergetag->len = size;
1198
1199         **tail = mergetag;
1200         *tail = &mergetag->next;
1201         return;
1202
1203 free_return:
1204         free(buf);
1205 }
1206
1207 static struct {
1208         char result;
1209         const char *check;
1210 } sigcheck_gpg_status[] = {
1211         { 'G', "\n[GNUPG:] GOODSIG " },
1212         { 'B', "\n[GNUPG:] BADSIG " },
1213         { 'U', "\n[GNUPG:] TRUST_NEVER" },
1214         { 'U', "\n[GNUPG:] TRUST_UNDEFINED" },
1215 };
1216
1217 static void parse_gpg_output(struct signature_check *sigc)
1218 {
1219         const char *buf = sigc->gpg_status;
1220         int i;
1221
1222         /* Iterate over all search strings */
1223         for (i = 0; i < ARRAY_SIZE(sigcheck_gpg_status); i++) {
1224                 const char *found, *next;
1225
1226                 found = skip_prefix(buf, sigcheck_gpg_status[i].check + 1);
1227                 if (!found) {
1228                         found = strstr(buf, sigcheck_gpg_status[i].check);
1229                         if (!found)
1230                                 continue;
1231                         found += strlen(sigcheck_gpg_status[i].check);
1232                 }
1233                 sigc->result = sigcheck_gpg_status[i].result;
1234                 /* The trust messages are not followed by key/signer information */
1235                 if (sigc->result != 'U') {
1236                         sigc->key = xmemdupz(found, 16);
1237                         found += 17;
1238                         next = strchrnul(found, '\n');
1239                         sigc->signer = xmemdupz(found, next - found);
1240                 }
1241         }
1242 }
1243
1244 void check_commit_signature(const struct commit* commit, struct signature_check *sigc)
1245 {
1246         struct strbuf payload = STRBUF_INIT;
1247         struct strbuf signature = STRBUF_INIT;
1248         struct strbuf gpg_output = STRBUF_INIT;
1249         struct strbuf gpg_status = STRBUF_INIT;
1250         int status;
1251
1252         sigc->result = 'N';
1253
1254         if (parse_signed_commit(commit->object.sha1,
1255                                 &payload, &signature) <= 0)
1256                 goto out;
1257         status = verify_signed_buffer(payload.buf, payload.len,
1258                                       signature.buf, signature.len,
1259                                       &gpg_output, &gpg_status);
1260         if (status && !gpg_output.len)
1261                 goto out;
1262         sigc->gpg_output = strbuf_detach(&gpg_output, NULL);
1263         sigc->gpg_status = strbuf_detach(&gpg_status, NULL);
1264         parse_gpg_output(sigc);
1265
1266  out:
1267         strbuf_release(&gpg_status);
1268         strbuf_release(&gpg_output);
1269         strbuf_release(&payload);
1270         strbuf_release(&signature);
1271 }
1272
1273
1274
1275 void append_merge_tag_headers(struct commit_list *parents,
1276                               struct commit_extra_header ***tail)
1277 {
1278         while (parents) {
1279                 struct commit *parent = parents->item;
1280                 handle_signed_tag(parent, tail);
1281                 parents = parents->next;
1282         }
1283 }
1284
1285 static void add_extra_header(struct strbuf *buffer,
1286                              struct commit_extra_header *extra)
1287 {
1288         strbuf_addstr(buffer, extra->key);
1289         if (extra->len)
1290                 strbuf_add_lines(buffer, " ", extra->value, extra->len);
1291         else
1292                 strbuf_addch(buffer, '\n');
1293 }
1294
1295 struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
1296                                                       const char **exclude)
1297 {
1298         struct commit_extra_header *extra = NULL;
1299         unsigned long size;
1300         enum object_type type;
1301         char *buffer = read_sha1_file(commit->object.sha1, &type, &size);
1302         if (buffer && type == OBJ_COMMIT)
1303                 extra = read_commit_extra_header_lines(buffer, size, exclude);
1304         free(buffer);
1305         return extra;
1306 }
1307
1308 static inline int standard_header_field(const char *field, size_t len)
1309 {
1310         return ((len == 4 && !memcmp(field, "tree ", 5)) ||
1311                 (len == 6 && !memcmp(field, "parent ", 7)) ||
1312                 (len == 6 && !memcmp(field, "author ", 7)) ||
1313                 (len == 9 && !memcmp(field, "committer ", 10)) ||
1314                 (len == 8 && !memcmp(field, "encoding ", 9)));
1315 }
1316
1317 static int excluded_header_field(const char *field, size_t len, const char **exclude)
1318 {
1319         if (!exclude)
1320                 return 0;
1321
1322         while (*exclude) {
1323                 size_t xlen = strlen(*exclude);
1324                 if (len == xlen &&
1325                     !memcmp(field, *exclude, xlen) && field[xlen] == ' ')
1326                         return 1;
1327                 exclude++;
1328         }
1329         return 0;
1330 }
1331
1332 static struct commit_extra_header *read_commit_extra_header_lines(
1333         const char *buffer, size_t size,
1334         const char **exclude)
1335 {
1336         struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
1337         const char *line, *next, *eof, *eob;
1338         struct strbuf buf = STRBUF_INIT;
1339
1340         for (line = buffer, eob = line + size;
1341              line < eob && *line != '\n';
1342              line = next) {
1343                 next = memchr(line, '\n', eob - line);
1344                 next = next ? next + 1 : eob;
1345                 if (*line == ' ') {
1346                         /* continuation */
1347                         if (it)
1348                                 strbuf_add(&buf, line + 1, next - (line + 1));
1349                         continue;
1350                 }
1351                 if (it)
1352                         it->value = strbuf_detach(&buf, &it->len);
1353                 strbuf_reset(&buf);
1354                 it = NULL;
1355
1356                 eof = strchr(line, ' ');
1357                 if (next <= eof)
1358                         eof = next;
1359
1360                 if (standard_header_field(line, eof - line) ||
1361                     excluded_header_field(line, eof - line, exclude))
1362                         continue;
1363
1364                 it = xcalloc(1, sizeof(*it));
1365                 it->key = xmemdupz(line, eof-line);
1366                 *tail = it;
1367                 tail = &it->next;
1368                 if (eof + 1 < next)
1369                         strbuf_add(&buf, eof + 1, next - (eof + 1));
1370         }
1371         if (it)
1372                 it->value = strbuf_detach(&buf, &it->len);
1373         return extra;
1374 }
1375
1376 void free_commit_extra_headers(struct commit_extra_header *extra)
1377 {
1378         while (extra) {
1379                 struct commit_extra_header *next = extra->next;
1380                 free(extra->key);
1381                 free(extra->value);
1382                 free(extra);
1383                 extra = next;
1384         }
1385 }
1386
1387 int commit_tree(const char *msg, size_t msg_len,
1388                 const unsigned char *tree,
1389                 struct commit_list *parents, unsigned char *ret,
1390                 const char *author, const char *sign_commit)
1391 {
1392         struct commit_extra_header *extra = NULL, **tail = &extra;
1393         int result;
1394
1395         append_merge_tag_headers(parents, &tail);
1396         result = commit_tree_extended(msg, msg_len, tree, parents, ret,
1397                                       author, sign_commit, extra);
1398         free_commit_extra_headers(extra);
1399         return result;
1400 }
1401
1402 static int find_invalid_utf8(const char *buf, int len)
1403 {
1404         int offset = 0;
1405         static const unsigned int max_codepoint[] = {
1406                 0x7f, 0x7ff, 0xffff, 0x10ffff
1407         };
1408
1409         while (len) {
1410                 unsigned char c = *buf++;
1411                 int bytes, bad_offset;
1412                 unsigned int codepoint;
1413                 unsigned int min_val, max_val;
1414
1415                 len--;
1416                 offset++;
1417
1418                 /* Simple US-ASCII? No worries. */
1419                 if (c < 0x80)
1420                         continue;
1421
1422                 bad_offset = offset-1;
1423
1424                 /*
1425                  * Count how many more high bits set: that's how
1426                  * many more bytes this sequence should have.
1427                  */
1428                 bytes = 0;
1429                 while (c & 0x40) {
1430                         c <<= 1;
1431                         bytes++;
1432                 }
1433
1434                 /*
1435                  * Must be between 1 and 3 more bytes.  Longer sequences result in
1436                  * codepoints beyond U+10FFFF, which are guaranteed never to exist.
1437                  */
1438                 if (bytes < 1 || 3 < bytes)
1439                         return bad_offset;
1440
1441                 /* Do we *have* that many bytes? */
1442                 if (len < bytes)
1443                         return bad_offset;
1444
1445                 /*
1446                  * Place the encoded bits at the bottom of the value and compute the
1447                  * valid range.
1448                  */
1449                 codepoint = (c & 0x7f) >> bytes;
1450                 min_val = max_codepoint[bytes-1] + 1;
1451                 max_val = max_codepoint[bytes];
1452
1453                 offset += bytes;
1454                 len -= bytes;
1455
1456                 /* And verify that they are good continuation bytes */
1457                 do {
1458                         codepoint <<= 6;
1459                         codepoint |= *buf & 0x3f;
1460                         if ((*buf++ & 0xc0) != 0x80)
1461                                 return bad_offset;
1462                 } while (--bytes);
1463
1464                 /* Reject codepoints that are out of range for the sequence length. */
1465                 if (codepoint < min_val || codepoint > max_val)
1466                         return bad_offset;
1467                 /* Surrogates are only for UTF-16 and cannot be encoded in UTF-8. */
1468                 if ((codepoint & 0x1ff800) == 0xd800)
1469                         return bad_offset;
1470                 /* U+xxFFFE and U+xxFFFF are guaranteed non-characters. */
1471                 if ((codepoint & 0xfffe) == 0xfffe)
1472                         return bad_offset;
1473                 /* So are anything in the range U+FDD0..U+FDEF. */
1474                 if (codepoint >= 0xfdd0 && codepoint <= 0xfdef)
1475                         return bad_offset;
1476         }
1477         return -1;
1478 }
1479
1480 /*
1481  * This verifies that the buffer is in proper utf8 format.
1482  *
1483  * If it isn't, it assumes any non-utf8 characters are Latin1,
1484  * and does the conversion.
1485  */
1486 static int verify_utf8(struct strbuf *buf)
1487 {
1488         int ok = 1;
1489         long pos = 0;
1490
1491         for (;;) {
1492                 int bad;
1493                 unsigned char c;
1494                 unsigned char replace[2];
1495
1496                 bad = find_invalid_utf8(buf->buf + pos, buf->len - pos);
1497                 if (bad < 0)
1498                         return ok;
1499                 pos += bad;
1500                 ok = 0;
1501                 c = buf->buf[pos];
1502                 strbuf_remove(buf, pos, 1);
1503
1504                 /* We know 'c' must be in the range 128-255 */
1505                 replace[0] = 0xc0 + (c >> 6);
1506                 replace[1] = 0x80 + (c & 0x3f);
1507                 strbuf_insert(buf, pos, replace, 2);
1508                 pos += 2;
1509         }
1510 }
1511
1512 static const char commit_utf8_warn[] =
1513 "Warning: commit message did not conform to UTF-8.\n"
1514 "You may want to amend it after fixing the message, or set the config\n"
1515 "variable i18n.commitencoding to the encoding your project uses.\n";
1516
1517 int commit_tree_extended(const char *msg, size_t msg_len,
1518                          const unsigned char *tree,
1519                          struct commit_list *parents, unsigned char *ret,
1520                          const char *author, const char *sign_commit,
1521                          struct commit_extra_header *extra)
1522 {
1523         int result;
1524         int encoding_is_utf8;
1525         struct strbuf buffer;
1526
1527         assert_sha1_type(tree, OBJ_TREE);
1528
1529         if (memchr(msg, '\0', msg_len))
1530                 return error("a NUL byte in commit log message not allowed.");
1531
1532         /* Not having i18n.commitencoding is the same as having utf-8 */
1533         encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1534
1535         strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */
1536         strbuf_addf(&buffer, "tree %s\n", sha1_to_hex(tree));
1537
1538         /*
1539          * NOTE! This ordering means that the same exact tree merged with a
1540          * different order of parents will be a _different_ changeset even
1541          * if everything else stays the same.
1542          */
1543         while (parents) {
1544                 struct commit_list *next = parents->next;
1545                 struct commit *parent = parents->item;
1546
1547                 strbuf_addf(&buffer, "parent %s\n",
1548                             sha1_to_hex(parent->object.sha1));
1549                 free(parents);
1550                 parents = next;
1551         }
1552
1553         /* Person/date information */
1554         if (!author)
1555                 author = git_author_info(IDENT_STRICT);
1556         strbuf_addf(&buffer, "author %s\n", author);
1557         strbuf_addf(&buffer, "committer %s\n", git_committer_info(IDENT_STRICT));
1558         if (!encoding_is_utf8)
1559                 strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding);
1560
1561         while (extra) {
1562                 add_extra_header(&buffer, extra);
1563                 extra = extra->next;
1564         }
1565         strbuf_addch(&buffer, '\n');
1566
1567         /* And add the comment */
1568         strbuf_add(&buffer, msg, msg_len);
1569
1570         /* And check the encoding */
1571         if (encoding_is_utf8 && !verify_utf8(&buffer))
1572                 fprintf(stderr, commit_utf8_warn);
1573
1574         if (sign_commit && do_sign_commit(&buffer, sign_commit))
1575                 return -1;
1576
1577         result = write_sha1_file(buffer.buf, buffer.len, commit_type, ret);
1578         strbuf_release(&buffer);
1579         return result;
1580 }
1581
1582 struct commit *get_merge_parent(const char *name)
1583 {
1584         struct object *obj;
1585         struct commit *commit;
1586         unsigned char sha1[20];
1587         if (get_sha1(name, sha1))
1588                 return NULL;
1589         obj = parse_object(sha1);
1590         commit = (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
1591         if (commit && !commit->util) {
1592                 struct merge_remote_desc *desc;
1593                 desc = xmalloc(sizeof(*desc));
1594                 desc->obj = obj;
1595                 desc->name = strdup(name);
1596                 commit->util = desc;
1597         }
1598         return commit;
1599 }
1600
1601 /*
1602  * Append a commit to the end of the commit_list.
1603  *
1604  * next starts by pointing to the variable that holds the head of an
1605  * empty commit_list, and is updated to point to the "next" field of
1606  * the last item on the list as new commits are appended.
1607  *
1608  * Usage example:
1609  *
1610  *     struct commit_list *list;
1611  *     struct commit_list **next = &list;
1612  *
1613  *     next = commit_list_append(c1, next);
1614  *     next = commit_list_append(c2, next);
1615  *     assert(commit_list_count(list) == 2);
1616  *     return list;
1617  */
1618 struct commit_list **commit_list_append(struct commit *commit,
1619                                         struct commit_list **next)
1620 {
1621         struct commit_list *new = xmalloc(sizeof(struct commit_list));
1622         new->item = commit;
1623         *next = new;
1624         new->next = NULL;
1625         return &new->next;
1626 }
1627
1628 void print_commit_list(struct commit_list *list,
1629                        const char *format_cur,
1630                        const char *format_last)
1631 {
1632         for ( ; list; list = list->next) {
1633                 const char *format = list->next ? format_cur : format_last;
1634                 printf(format, sha1_to_hex(list->item->object.sha1));
1635         }
1636 }