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