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