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