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