commit: add short-circuit to 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, int check_graph)
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         if (check_graph)
390                 load_commit_graph_info(item);
391
392         return 0;
393 }
394
395 int parse_commit_gently(struct commit *item, int quiet_on_missing)
396 {
397         enum object_type type;
398         void *buffer;
399         unsigned long size;
400         int ret;
401
402         if (!item)
403                 return -1;
404         if (item->object.parsed)
405                 return 0;
406         if (parse_commit_in_graph(item))
407                 return 0;
408         buffer = read_sha1_file(item->object.oid.hash, &type, &size);
409         if (!buffer)
410                 return quiet_on_missing ? -1 :
411                         error("Could not read %s",
412                              oid_to_hex(&item->object.oid));
413         if (type != OBJ_COMMIT) {
414                 free(buffer);
415                 return error("Object %s not a commit",
416                              oid_to_hex(&item->object.oid));
417         }
418         ret = parse_commit_buffer(item, buffer, size, 0);
419         if (save_commit_buffer && !ret) {
420                 set_commit_buffer(item, buffer, size);
421                 return 0;
422         }
423         free(buffer);
424         return ret;
425 }
426
427 void parse_commit_or_die(struct commit *item)
428 {
429         if (parse_commit(item))
430                 die("unable to parse commit %s",
431                     item ? oid_to_hex(&item->object.oid) : "(null)");
432 }
433
434 int find_commit_subject(const char *commit_buffer, const char **subject)
435 {
436         const char *eol;
437         const char *p = commit_buffer;
438
439         while (*p && (*p != '\n' || p[1] != '\n'))
440                 p++;
441         if (*p) {
442                 p = skip_blank_lines(p + 2);
443                 eol = strchrnul(p, '\n');
444         } else
445                 eol = p;
446
447         *subject = p;
448
449         return eol - p;
450 }
451
452 struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
453 {
454         struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
455         new_list->item = item;
456         new_list->next = *list_p;
457         *list_p = new_list;
458         return new_list;
459 }
460
461 unsigned commit_list_count(const struct commit_list *l)
462 {
463         unsigned c = 0;
464         for (; l; l = l->next )
465                 c++;
466         return c;
467 }
468
469 struct commit_list *copy_commit_list(struct commit_list *list)
470 {
471         struct commit_list *head = NULL;
472         struct commit_list **pp = &head;
473         while (list) {
474                 pp = commit_list_append(list->item, pp);
475                 list = list->next;
476         }
477         return head;
478 }
479
480 void free_commit_list(struct commit_list *list)
481 {
482         while (list)
483                 pop_commit(&list);
484 }
485
486 struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
487 {
488         struct commit_list **pp = list;
489         struct commit_list *p;
490         while ((p = *pp) != NULL) {
491                 if (p->item->date < item->date) {
492                         break;
493                 }
494                 pp = &p->next;
495         }
496         return commit_list_insert(item, pp);
497 }
498
499 static int commit_list_compare_by_date(const void *a, const void *b)
500 {
501         timestamp_t a_date = ((const struct commit_list *)a)->item->date;
502         timestamp_t b_date = ((const struct commit_list *)b)->item->date;
503         if (a_date < b_date)
504                 return 1;
505         if (a_date > b_date)
506                 return -1;
507         return 0;
508 }
509
510 static void *commit_list_get_next(const void *a)
511 {
512         return ((const struct commit_list *)a)->next;
513 }
514
515 static void commit_list_set_next(void *a, void *next)
516 {
517         ((struct commit_list *)a)->next = next;
518 }
519
520 void commit_list_sort_by_date(struct commit_list **list)
521 {
522         *list = llist_mergesort(*list, commit_list_get_next, commit_list_set_next,
523                                 commit_list_compare_by_date);
524 }
525
526 struct commit *pop_most_recent_commit(struct commit_list **list,
527                                       unsigned int mark)
528 {
529         struct commit *ret = pop_commit(list);
530         struct commit_list *parents = ret->parents;
531
532         while (parents) {
533                 struct commit *commit = parents->item;
534                 if (!parse_commit(commit) && !(commit->object.flags & mark)) {
535                         commit->object.flags |= mark;
536                         commit_list_insert_by_date(commit, list);
537                 }
538                 parents = parents->next;
539         }
540         return ret;
541 }
542
543 static void clear_commit_marks_1(struct commit_list **plist,
544                                  struct commit *commit, unsigned int mark)
545 {
546         while (commit) {
547                 struct commit_list *parents;
548
549                 if (!(mark & commit->object.flags))
550                         return;
551
552                 commit->object.flags &= ~mark;
553
554                 parents = commit->parents;
555                 if (!parents)
556                         return;
557
558                 while ((parents = parents->next))
559                         commit_list_insert(parents->item, plist);
560
561                 commit = commit->parents->item;
562         }
563 }
564
565 void clear_commit_marks_many(int nr, struct commit **commit, unsigned int mark)
566 {
567         struct commit_list *list = NULL;
568
569         while (nr--) {
570                 clear_commit_marks_1(&list, *commit, mark);
571                 commit++;
572         }
573         while (list)
574                 clear_commit_marks_1(&list, pop_commit(&list), mark);
575 }
576
577 void clear_commit_marks(struct commit *commit, unsigned int mark)
578 {
579         clear_commit_marks_many(1, &commit, mark);
580 }
581
582 struct commit *pop_commit(struct commit_list **stack)
583 {
584         struct commit_list *top = *stack;
585         struct commit *item = top ? top->item : NULL;
586
587         if (top) {
588                 *stack = top->next;
589                 free(top);
590         }
591         return item;
592 }
593
594 /*
595  * Topological sort support
596  */
597
598 /* count number of children that have not been emitted */
599 define_commit_slab(indegree_slab, int);
600
601 /* record author-date for each commit object */
602 define_commit_slab(author_date_slab, unsigned long);
603
604 static void record_author_date(struct author_date_slab *author_date,
605                                struct commit *commit)
606 {
607         const char *buffer = get_commit_buffer(commit, NULL);
608         struct ident_split ident;
609         const char *ident_line;
610         size_t ident_len;
611         char *date_end;
612         timestamp_t date;
613
614         ident_line = find_commit_header(buffer, "author", &ident_len);
615         if (!ident_line)
616                 goto fail_exit; /* no author line */
617         if (split_ident_line(&ident, ident_line, ident_len) ||
618             !ident.date_begin || !ident.date_end)
619                 goto fail_exit; /* malformed "author" line */
620
621         date = parse_timestamp(ident.date_begin, &date_end, 10);
622         if (date_end != ident.date_end)
623                 goto fail_exit; /* malformed date */
624         *(author_date_slab_at(author_date, commit)) = date;
625
626 fail_exit:
627         unuse_commit_buffer(commit, buffer);
628 }
629
630 static int compare_commits_by_author_date(const void *a_, const void *b_,
631                                           void *cb_data)
632 {
633         const struct commit *a = a_, *b = b_;
634         struct author_date_slab *author_date = cb_data;
635         timestamp_t a_date = *(author_date_slab_at(author_date, a));
636         timestamp_t b_date = *(author_date_slab_at(author_date, b));
637
638         /* newer commits with larger date first */
639         if (a_date < b_date)
640                 return 1;
641         else if (a_date > b_date)
642                 return -1;
643         return 0;
644 }
645
646 int compare_commits_by_gen_then_commit_date(const void *a_, const void *b_, void *unused)
647 {
648         const struct commit *a = a_, *b = b_;
649
650         /* newer commits first */
651         if (a->generation < b->generation)
652                 return 1;
653         else if (a->generation > b->generation)
654                 return -1;
655
656         /* use date as a heuristic when generations are equal */
657         if (a->date < b->date)
658                 return 1;
659         else if (a->date > b->date)
660                 return -1;
661         return 0;
662 }
663
664 int compare_commits_by_commit_date(const void *a_, const void *b_, void *unused)
665 {
666         const struct commit *a = a_, *b = b_;
667         /* newer commits with larger date first */
668         if (a->date < b->date)
669                 return 1;
670         else if (a->date > b->date)
671                 return -1;
672         return 0;
673 }
674
675 /*
676  * Performs an in-place topological sort on the list supplied.
677  */
678 void sort_in_topological_order(struct commit_list **list, enum rev_sort_order sort_order)
679 {
680         struct commit_list *next, *orig = *list;
681         struct commit_list **pptr;
682         struct indegree_slab indegree;
683         struct prio_queue queue;
684         struct commit *commit;
685         struct author_date_slab author_date;
686
687         if (!orig)
688                 return;
689         *list = NULL;
690
691         init_indegree_slab(&indegree);
692         memset(&queue, '\0', sizeof(queue));
693
694         switch (sort_order) {
695         default: /* REV_SORT_IN_GRAPH_ORDER */
696                 queue.compare = NULL;
697                 break;
698         case REV_SORT_BY_COMMIT_DATE:
699                 queue.compare = compare_commits_by_commit_date;
700                 break;
701         case REV_SORT_BY_AUTHOR_DATE:
702                 init_author_date_slab(&author_date);
703                 queue.compare = compare_commits_by_author_date;
704                 queue.cb_data = &author_date;
705                 break;
706         }
707
708         /* Mark them and clear the indegree */
709         for (next = orig; next; next = next->next) {
710                 struct commit *commit = next->item;
711                 *(indegree_slab_at(&indegree, commit)) = 1;
712                 /* also record the author dates, if needed */
713                 if (sort_order == REV_SORT_BY_AUTHOR_DATE)
714                         record_author_date(&author_date, commit);
715         }
716
717         /* update the indegree */
718         for (next = orig; next; next = next->next) {
719                 struct commit_list *parents = next->item->parents;
720                 while (parents) {
721                         struct commit *parent = parents->item;
722                         int *pi = indegree_slab_at(&indegree, parent);
723
724                         if (*pi)
725                                 (*pi)++;
726                         parents = parents->next;
727                 }
728         }
729
730         /*
731          * find the tips
732          *
733          * tips are nodes not reachable from any other node in the list
734          *
735          * the tips serve as a starting set for the work queue.
736          */
737         for (next = orig; next; next = next->next) {
738                 struct commit *commit = next->item;
739
740                 if (*(indegree_slab_at(&indegree, commit)) == 1)
741                         prio_queue_put(&queue, commit);
742         }
743
744         /*
745          * This is unfortunate; the initial tips need to be shown
746          * in the order given from the revision traversal machinery.
747          */
748         if (sort_order == REV_SORT_IN_GRAPH_ORDER)
749                 prio_queue_reverse(&queue);
750
751         /* We no longer need the commit list */
752         free_commit_list(orig);
753
754         pptr = list;
755         *list = NULL;
756         while ((commit = prio_queue_get(&queue)) != NULL) {
757                 struct commit_list *parents;
758
759                 for (parents = commit->parents; parents ; parents = parents->next) {
760                         struct commit *parent = parents->item;
761                         int *pi = indegree_slab_at(&indegree, parent);
762
763                         if (!*pi)
764                                 continue;
765
766                         /*
767                          * parents are only enqueued for emission
768                          * when all their children have been emitted thereby
769                          * guaranteeing topological order.
770                          */
771                         if (--(*pi) == 1)
772                                 prio_queue_put(&queue, parent);
773                 }
774                 /*
775                  * all children of commit have already been
776                  * emitted. we can emit it now.
777                  */
778                 *(indegree_slab_at(&indegree, commit)) = 0;
779
780                 pptr = &commit_list_insert(commit, pptr)->next;
781         }
782
783         clear_indegree_slab(&indegree);
784         clear_prio_queue(&queue);
785         if (sort_order == REV_SORT_BY_AUTHOR_DATE)
786                 clear_author_date_slab(&author_date);
787 }
788
789 /* merge-base stuff */
790
791 /* Remember to update object flag allocation in object.h */
792 #define PARENT1         (1u<<16)
793 #define PARENT2         (1u<<17)
794 #define STALE           (1u<<18)
795 #define RESULT          (1u<<19)
796
797 static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);
798
799 static int queue_has_nonstale(struct prio_queue *queue)
800 {
801         int i;
802         for (i = 0; i < queue->nr; i++) {
803                 struct commit *commit = queue->array[i].data;
804                 if (!(commit->object.flags & STALE))
805                         return 1;
806         }
807         return 0;
808 }
809
810 /* all input commits in one and twos[] must have been parsed! */
811 static struct commit_list *paint_down_to_common(struct commit *one, int n,
812                                                 struct commit **twos,
813                                                 int min_generation)
814 {
815         struct prio_queue queue = { compare_commits_by_gen_then_commit_date };
816         struct commit_list *result = NULL;
817         int i;
818         uint32_t last_gen = GENERATION_NUMBER_INFINITY;
819
820         one->object.flags |= PARENT1;
821         if (!n) {
822                 commit_list_append(one, &result);
823                 return result;
824         }
825         prio_queue_put(&queue, one);
826
827         for (i = 0; i < n; i++) {
828                 twos[i]->object.flags |= PARENT2;
829                 prio_queue_put(&queue, twos[i]);
830         }
831
832         while (queue_has_nonstale(&queue)) {
833                 struct commit *commit = prio_queue_get(&queue);
834                 struct commit_list *parents;
835                 int flags;
836
837                 if (commit->generation > last_gen)
838                         BUG("bad generation skip %8x > %8x at %s",
839                             commit->generation, last_gen,
840                             oid_to_hex(&commit->object.oid));
841                 last_gen = commit->generation;
842
843                 if (commit->generation < min_generation)
844                         break;
845
846                 flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
847                 if (flags == (PARENT1 | PARENT2)) {
848                         if (!(commit->object.flags & RESULT)) {
849                                 commit->object.flags |= RESULT;
850                                 commit_list_insert_by_date(commit, &result);
851                         }
852                         /* Mark parents of a found merge stale */
853                         flags |= STALE;
854                 }
855                 parents = commit->parents;
856                 while (parents) {
857                         struct commit *p = parents->item;
858                         parents = parents->next;
859                         if ((p->object.flags & flags) == flags)
860                                 continue;
861                         if (parse_commit(p))
862                                 return NULL;
863                         p->object.flags |= flags;
864                         prio_queue_put(&queue, p);
865                 }
866         }
867
868         clear_prio_queue(&queue);
869         return result;
870 }
871
872 static struct commit_list *merge_bases_many(struct commit *one, int n, struct commit **twos)
873 {
874         struct commit_list *list = NULL;
875         struct commit_list *result = NULL;
876         int i;
877
878         for (i = 0; i < n; i++) {
879                 if (one == twos[i])
880                         /*
881                          * We do not mark this even with RESULT so we do not
882                          * have to clean it up.
883                          */
884                         return commit_list_insert(one, &result);
885         }
886
887         if (parse_commit(one))
888                 return NULL;
889         for (i = 0; i < n; i++) {
890                 if (parse_commit(twos[i]))
891                         return NULL;
892         }
893
894         list = paint_down_to_common(one, n, twos, 0);
895
896         while (list) {
897                 struct commit *commit = pop_commit(&list);
898                 if (!(commit->object.flags & STALE))
899                         commit_list_insert_by_date(commit, &result);
900         }
901         return result;
902 }
903
904 struct commit_list *get_octopus_merge_bases(struct commit_list *in)
905 {
906         struct commit_list *i, *j, *k, *ret = NULL;
907
908         if (!in)
909                 return ret;
910
911         commit_list_insert(in->item, &ret);
912
913         for (i = in->next; i; i = i->next) {
914                 struct commit_list *new_commits = NULL, *end = NULL;
915
916                 for (j = ret; j; j = j->next) {
917                         struct commit_list *bases;
918                         bases = get_merge_bases(i->item, j->item);
919                         if (!new_commits)
920                                 new_commits = bases;
921                         else
922                                 end->next = bases;
923                         for (k = bases; k; k = k->next)
924                                 end = k;
925                 }
926                 ret = new_commits;
927         }
928         return ret;
929 }
930
931 static int remove_redundant(struct commit **array, int cnt)
932 {
933         /*
934          * Some commit in the array may be an ancestor of
935          * another commit.  Move such commit to the end of
936          * the array, and return the number of commits that
937          * are independent from each other.
938          */
939         struct commit **work;
940         unsigned char *redundant;
941         int *filled_index;
942         int i, j, filled;
943
944         work = xcalloc(cnt, sizeof(*work));
945         redundant = xcalloc(cnt, 1);
946         ALLOC_ARRAY(filled_index, cnt - 1);
947
948         for (i = 0; i < cnt; i++)
949                 parse_commit(array[i]);
950         for (i = 0; i < cnt; i++) {
951                 struct commit_list *common;
952
953                 if (redundant[i])
954                         continue;
955                 for (j = filled = 0; j < cnt; j++) {
956                         if (i == j || redundant[j])
957                                 continue;
958                         filled_index[filled] = j;
959                         work[filled++] = array[j];
960                 }
961                 common = paint_down_to_common(array[i], filled, work, 0);
962                 if (array[i]->object.flags & PARENT2)
963                         redundant[i] = 1;
964                 for (j = 0; j < filled; j++)
965                         if (work[j]->object.flags & PARENT1)
966                                 redundant[filled_index[j]] = 1;
967                 clear_commit_marks(array[i], all_flags);
968                 clear_commit_marks_many(filled, work, all_flags);
969                 free_commit_list(common);
970         }
971
972         /* Now collect the result */
973         COPY_ARRAY(work, array, cnt);
974         for (i = filled = 0; i < cnt; i++)
975                 if (!redundant[i])
976                         array[filled++] = work[i];
977         for (j = filled, i = 0; i < cnt; i++)
978                 if (redundant[i])
979                         array[j++] = work[i];
980         free(work);
981         free(redundant);
982         free(filled_index);
983         return filled;
984 }
985
986 static struct commit_list *get_merge_bases_many_0(struct commit *one,
987                                                   int n,
988                                                   struct commit **twos,
989                                                   int cleanup)
990 {
991         struct commit_list *list;
992         struct commit **rslt;
993         struct commit_list *result;
994         int cnt, i;
995
996         result = merge_bases_many(one, n, twos);
997         for (i = 0; i < n; i++) {
998                 if (one == twos[i])
999                         return result;
1000         }
1001         if (!result || !result->next) {
1002                 if (cleanup) {
1003                         clear_commit_marks(one, all_flags);
1004                         clear_commit_marks_many(n, twos, all_flags);
1005                 }
1006                 return result;
1007         }
1008
1009         /* There are more than one */
1010         cnt = commit_list_count(result);
1011         rslt = xcalloc(cnt, sizeof(*rslt));
1012         for (list = result, i = 0; list; list = list->next)
1013                 rslt[i++] = list->item;
1014         free_commit_list(result);
1015
1016         clear_commit_marks(one, all_flags);
1017         clear_commit_marks_many(n, twos, all_flags);
1018
1019         cnt = remove_redundant(rslt, cnt);
1020         result = NULL;
1021         for (i = 0; i < cnt; i++)
1022                 commit_list_insert_by_date(rslt[i], &result);
1023         free(rslt);
1024         return result;
1025 }
1026
1027 struct commit_list *get_merge_bases_many(struct commit *one,
1028                                          int n,
1029                                          struct commit **twos)
1030 {
1031         return get_merge_bases_many_0(one, n, twos, 1);
1032 }
1033
1034 struct commit_list *get_merge_bases_many_dirty(struct commit *one,
1035                                                int n,
1036                                                struct commit **twos)
1037 {
1038         return get_merge_bases_many_0(one, n, twos, 0);
1039 }
1040
1041 struct commit_list *get_merge_bases(struct commit *one, struct commit *two)
1042 {
1043         return get_merge_bases_many_0(one, 1, &two, 1);
1044 }
1045
1046 /*
1047  * Is "commit" a descendant of one of the elements on the "with_commit" list?
1048  */
1049 int is_descendant_of(struct commit *commit, struct commit_list *with_commit)
1050 {
1051         if (!with_commit)
1052                 return 1;
1053         while (with_commit) {
1054                 struct commit *other;
1055
1056                 other = with_commit->item;
1057                 with_commit = with_commit->next;
1058                 if (in_merge_bases(other, commit))
1059                         return 1;
1060         }
1061         return 0;
1062 }
1063
1064 /*
1065  * Is "commit" an ancestor of one of the "references"?
1066  */
1067 int in_merge_bases_many(struct commit *commit, int nr_reference, struct commit **reference)
1068 {
1069         struct commit_list *bases;
1070         int ret = 0, i;
1071         uint32_t min_generation = GENERATION_NUMBER_INFINITY;
1072
1073         if (parse_commit(commit))
1074                 return ret;
1075         for (i = 0; i < nr_reference; i++) {
1076                 if (parse_commit(reference[i]))
1077                         return ret;
1078                 if (reference[i]->generation < min_generation)
1079                         min_generation = reference[i]->generation;
1080         }
1081
1082         if (commit->generation > min_generation)
1083                 return ret;
1084
1085         bases = paint_down_to_common(commit, nr_reference, reference, commit->generation);
1086         if (commit->object.flags & PARENT2)
1087                 ret = 1;
1088         clear_commit_marks(commit, all_flags);
1089         clear_commit_marks_many(nr_reference, reference, all_flags);
1090         free_commit_list(bases);
1091         return ret;
1092 }
1093
1094 /*
1095  * Is "commit" an ancestor of (i.e. reachable from) the "reference"?
1096  */
1097 int in_merge_bases(struct commit *commit, struct commit *reference)
1098 {
1099         return in_merge_bases_many(commit, 1, &reference);
1100 }
1101
1102 struct commit_list *reduce_heads(struct commit_list *heads)
1103 {
1104         struct commit_list *p;
1105         struct commit_list *result = NULL, **tail = &result;
1106         struct commit **array;
1107         int num_head, i;
1108
1109         if (!heads)
1110                 return NULL;
1111
1112         /* Uniquify */
1113         for (p = heads; p; p = p->next)
1114                 p->item->object.flags &= ~STALE;
1115         for (p = heads, num_head = 0; p; p = p->next) {
1116                 if (p->item->object.flags & STALE)
1117                         continue;
1118                 p->item->object.flags |= STALE;
1119                 num_head++;
1120         }
1121         array = xcalloc(num_head, sizeof(*array));
1122         for (p = heads, i = 0; p; p = p->next) {
1123                 if (p->item->object.flags & STALE) {
1124                         array[i++] = p->item;
1125                         p->item->object.flags &= ~STALE;
1126                 }
1127         }
1128         num_head = remove_redundant(array, num_head);
1129         for (i = 0; i < num_head; i++)
1130                 tail = &commit_list_insert(array[i], tail)->next;
1131         free(array);
1132         return result;
1133 }
1134
1135 void reduce_heads_replace(struct commit_list **heads)
1136 {
1137         struct commit_list *result = reduce_heads(*heads);
1138         free_commit_list(*heads);
1139         *heads = result;
1140 }
1141
1142 static const char gpg_sig_header[] = "gpgsig";
1143 static const int gpg_sig_header_len = sizeof(gpg_sig_header) - 1;
1144
1145 static int do_sign_commit(struct strbuf *buf, const char *keyid)
1146 {
1147         struct strbuf sig = STRBUF_INIT;
1148         int inspos, copypos;
1149         const char *eoh;
1150
1151         /* find the end of the header */
1152         eoh = strstr(buf->buf, "\n\n");
1153         if (!eoh)
1154                 inspos = buf->len;
1155         else
1156                 inspos = eoh - buf->buf + 1;
1157
1158         if (!keyid || !*keyid)
1159                 keyid = get_signing_key();
1160         if (sign_buffer(buf, &sig, keyid)) {
1161                 strbuf_release(&sig);
1162                 return -1;
1163         }
1164
1165         for (copypos = 0; sig.buf[copypos]; ) {
1166                 const char *bol = sig.buf + copypos;
1167                 const char *eol = strchrnul(bol, '\n');
1168                 int len = (eol - bol) + !!*eol;
1169
1170                 if (!copypos) {
1171                         strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
1172                         inspos += gpg_sig_header_len;
1173                 }
1174                 strbuf_insert(buf, inspos++, " ", 1);
1175                 strbuf_insert(buf, inspos, bol, len);
1176                 inspos += len;
1177                 copypos += len;
1178         }
1179         strbuf_release(&sig);
1180         return 0;
1181 }
1182
1183 int parse_signed_commit(const struct commit *commit,
1184                         struct strbuf *payload, struct strbuf *signature)
1185 {
1186
1187         unsigned long size;
1188         const char *buffer = get_commit_buffer(commit, &size);
1189         int in_signature, saw_signature = -1;
1190         const char *line, *tail;
1191
1192         line = buffer;
1193         tail = buffer + size;
1194         in_signature = 0;
1195         saw_signature = 0;
1196         while (line < tail) {
1197                 const char *sig = NULL;
1198                 const char *next = memchr(line, '\n', tail - line);
1199
1200                 next = next ? next + 1 : tail;
1201                 if (in_signature && line[0] == ' ')
1202                         sig = line + 1;
1203                 else if (starts_with(line, gpg_sig_header) &&
1204                          line[gpg_sig_header_len] == ' ')
1205                         sig = line + gpg_sig_header_len + 1;
1206                 if (sig) {
1207                         strbuf_add(signature, sig, next - sig);
1208                         saw_signature = 1;
1209                         in_signature = 1;
1210                 } else {
1211                         if (*line == '\n')
1212                                 /* dump the whole remainder of the buffer */
1213                                 next = tail;
1214                         strbuf_add(payload, line, next - line);
1215                         in_signature = 0;
1216                 }
1217                 line = next;
1218         }
1219         unuse_commit_buffer(commit, buffer);
1220         return saw_signature;
1221 }
1222
1223 int remove_signature(struct strbuf *buf)
1224 {
1225         const char *line = buf->buf;
1226         const char *tail = buf->buf + buf->len;
1227         int in_signature = 0;
1228         const char *sig_start = NULL;
1229         const char *sig_end = NULL;
1230
1231         while (line < tail) {
1232                 const char *next = memchr(line, '\n', tail - line);
1233                 next = next ? next + 1 : tail;
1234
1235                 if (in_signature && line[0] == ' ')
1236                         sig_end = next;
1237                 else if (starts_with(line, gpg_sig_header) &&
1238                          line[gpg_sig_header_len] == ' ') {
1239                         sig_start = line;
1240                         sig_end = next;
1241                         in_signature = 1;
1242                 } else {
1243                         if (*line == '\n')
1244                                 /* dump the whole remainder of the buffer */
1245                                 next = tail;
1246                         in_signature = 0;
1247                 }
1248                 line = next;
1249         }
1250
1251         if (sig_start)
1252                 strbuf_remove(buf, sig_start - buf->buf, sig_end - sig_start);
1253
1254         return sig_start != NULL;
1255 }
1256
1257 static void handle_signed_tag(struct commit *parent, struct commit_extra_header ***tail)
1258 {
1259         struct merge_remote_desc *desc;
1260         struct commit_extra_header *mergetag;
1261         char *buf;
1262         unsigned long size, len;
1263         enum object_type type;
1264
1265         desc = merge_remote_util(parent);
1266         if (!desc || !desc->obj)
1267                 return;
1268         buf = read_sha1_file(desc->obj->oid.hash, &type, &size);
1269         if (!buf || type != OBJ_TAG)
1270                 goto free_return;
1271         len = parse_signature(buf, size);
1272         if (size == len)
1273                 goto free_return;
1274         /*
1275          * We could verify this signature and either omit the tag when
1276          * it does not validate, but the integrator may not have the
1277          * public key of the signer of the tag he is merging, while a
1278          * later auditor may have it while auditing, so let's not run
1279          * verify-signed-buffer here for now...
1280          *
1281          * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
1282          *      warn("warning: signed tag unverified.");
1283          */
1284         mergetag = xcalloc(1, sizeof(*mergetag));
1285         mergetag->key = xstrdup("mergetag");
1286         mergetag->value = buf;
1287         mergetag->len = size;
1288
1289         **tail = mergetag;
1290         *tail = &mergetag->next;
1291         return;
1292
1293 free_return:
1294         free(buf);
1295 }
1296
1297 int check_commit_signature(const struct commit *commit, struct signature_check *sigc)
1298 {
1299         struct strbuf payload = STRBUF_INIT;
1300         struct strbuf signature = STRBUF_INIT;
1301         int ret = 1;
1302
1303         sigc->result = 'N';
1304
1305         if (parse_signed_commit(commit, &payload, &signature) <= 0)
1306                 goto out;
1307         ret = check_signature(payload.buf, payload.len, signature.buf,
1308                 signature.len, sigc);
1309
1310  out:
1311         strbuf_release(&payload);
1312         strbuf_release(&signature);
1313
1314         return ret;
1315 }
1316
1317
1318
1319 void append_merge_tag_headers(struct commit_list *parents,
1320                               struct commit_extra_header ***tail)
1321 {
1322         while (parents) {
1323                 struct commit *parent = parents->item;
1324                 handle_signed_tag(parent, tail);
1325                 parents = parents->next;
1326         }
1327 }
1328
1329 static void add_extra_header(struct strbuf *buffer,
1330                              struct commit_extra_header *extra)
1331 {
1332         strbuf_addstr(buffer, extra->key);
1333         if (extra->len)
1334                 strbuf_add_lines(buffer, " ", extra->value, extra->len);
1335         else
1336                 strbuf_addch(buffer, '\n');
1337 }
1338
1339 struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
1340                                                       const char **exclude)
1341 {
1342         struct commit_extra_header *extra = NULL;
1343         unsigned long size;
1344         const char *buffer = get_commit_buffer(commit, &size);
1345         extra = read_commit_extra_header_lines(buffer, size, exclude);
1346         unuse_commit_buffer(commit, buffer);
1347         return extra;
1348 }
1349
1350 void for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
1351 {
1352         struct commit_extra_header *extra, *to_free;
1353
1354         to_free = read_commit_extra_headers(commit, NULL);
1355         for (extra = to_free; extra; extra = extra->next) {
1356                 if (strcmp(extra->key, "mergetag"))
1357                         continue; /* not a merge tag */
1358                 fn(commit, extra, data);
1359         }
1360         free_commit_extra_headers(to_free);
1361 }
1362
1363 static inline int standard_header_field(const char *field, size_t len)
1364 {
1365         return ((len == 4 && !memcmp(field, "tree", 4)) ||
1366                 (len == 6 && !memcmp(field, "parent", 6)) ||
1367                 (len == 6 && !memcmp(field, "author", 6)) ||
1368                 (len == 9 && !memcmp(field, "committer", 9)) ||
1369                 (len == 8 && !memcmp(field, "encoding", 8)));
1370 }
1371
1372 static int excluded_header_field(const char *field, size_t len, const char **exclude)
1373 {
1374         if (!exclude)
1375                 return 0;
1376
1377         while (*exclude) {
1378                 size_t xlen = strlen(*exclude);
1379                 if (len == xlen && !memcmp(field, *exclude, xlen))
1380                         return 1;
1381                 exclude++;
1382         }
1383         return 0;
1384 }
1385
1386 static struct commit_extra_header *read_commit_extra_header_lines(
1387         const char *buffer, size_t size,
1388         const char **exclude)
1389 {
1390         struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
1391         const char *line, *next, *eof, *eob;
1392         struct strbuf buf = STRBUF_INIT;
1393
1394         for (line = buffer, eob = line + size;
1395              line < eob && *line != '\n';
1396              line = next) {
1397                 next = memchr(line, '\n', eob - line);
1398                 next = next ? next + 1 : eob;
1399                 if (*line == ' ') {
1400                         /* continuation */
1401                         if (it)
1402                                 strbuf_add(&buf, line + 1, next - (line + 1));
1403                         continue;
1404                 }
1405                 if (it)
1406                         it->value = strbuf_detach(&buf, &it->len);
1407                 strbuf_reset(&buf);
1408                 it = NULL;
1409
1410                 eof = memchr(line, ' ', next - line);
1411                 if (!eof)
1412                         eof = next;
1413                 else if (standard_header_field(line, eof - line) ||
1414                          excluded_header_field(line, eof - line, exclude))
1415                         continue;
1416
1417                 it = xcalloc(1, sizeof(*it));
1418                 it->key = xmemdupz(line, eof-line);
1419                 *tail = it;
1420                 tail = &it->next;
1421                 if (eof + 1 < next)
1422                         strbuf_add(&buf, eof + 1, next - (eof + 1));
1423         }
1424         if (it)
1425                 it->value = strbuf_detach(&buf, &it->len);
1426         return extra;
1427 }
1428
1429 void free_commit_extra_headers(struct commit_extra_header *extra)
1430 {
1431         while (extra) {
1432                 struct commit_extra_header *next = extra->next;
1433                 free(extra->key);
1434                 free(extra->value);
1435                 free(extra);
1436                 extra = next;
1437         }
1438 }
1439
1440 int commit_tree(const char *msg, size_t msg_len, const struct object_id *tree,
1441                 struct commit_list *parents, struct object_id *ret,
1442                 const char *author, const char *sign_commit)
1443 {
1444         struct commit_extra_header *extra = NULL, **tail = &extra;
1445         int result;
1446
1447         append_merge_tag_headers(parents, &tail);
1448         result = commit_tree_extended(msg, msg_len, tree, parents, ret,
1449                                       author, sign_commit, extra);
1450         free_commit_extra_headers(extra);
1451         return result;
1452 }
1453
1454 static int find_invalid_utf8(const char *buf, int len)
1455 {
1456         int offset = 0;
1457         static const unsigned int max_codepoint[] = {
1458                 0x7f, 0x7ff, 0xffff, 0x10ffff
1459         };
1460
1461         while (len) {
1462                 unsigned char c = *buf++;
1463                 int bytes, bad_offset;
1464                 unsigned int codepoint;
1465                 unsigned int min_val, max_val;
1466
1467                 len--;
1468                 offset++;
1469
1470                 /* Simple US-ASCII? No worries. */
1471                 if (c < 0x80)
1472                         continue;
1473
1474                 bad_offset = offset-1;
1475
1476                 /*
1477                  * Count how many more high bits set: that's how
1478                  * many more bytes this sequence should have.
1479                  */
1480                 bytes = 0;
1481                 while (c & 0x40) {
1482                         c <<= 1;
1483                         bytes++;
1484                 }
1485
1486                 /*
1487                  * Must be between 1 and 3 more bytes.  Longer sequences result in
1488                  * codepoints beyond U+10FFFF, which are guaranteed never to exist.
1489                  */
1490                 if (bytes < 1 || 3 < bytes)
1491                         return bad_offset;
1492
1493                 /* Do we *have* that many bytes? */
1494                 if (len < bytes)
1495                         return bad_offset;
1496
1497                 /*
1498                  * Place the encoded bits at the bottom of the value and compute the
1499                  * valid range.
1500                  */
1501                 codepoint = (c & 0x7f) >> bytes;
1502                 min_val = max_codepoint[bytes-1] + 1;
1503                 max_val = max_codepoint[bytes];
1504
1505                 offset += bytes;
1506                 len -= bytes;
1507
1508                 /* And verify that they are good continuation bytes */
1509                 do {
1510                         codepoint <<= 6;
1511                         codepoint |= *buf & 0x3f;
1512                         if ((*buf++ & 0xc0) != 0x80)
1513                                 return bad_offset;
1514                 } while (--bytes);
1515
1516                 /* Reject codepoints that are out of range for the sequence length. */
1517                 if (codepoint < min_val || codepoint > max_val)
1518                         return bad_offset;
1519                 /* Surrogates are only for UTF-16 and cannot be encoded in UTF-8. */
1520                 if ((codepoint & 0x1ff800) == 0xd800)
1521                         return bad_offset;
1522                 /* U+xxFFFE and U+xxFFFF are guaranteed non-characters. */
1523                 if ((codepoint & 0xfffe) == 0xfffe)
1524                         return bad_offset;
1525                 /* So are anything in the range U+FDD0..U+FDEF. */
1526                 if (codepoint >= 0xfdd0 && codepoint <= 0xfdef)
1527                         return bad_offset;
1528         }
1529         return -1;
1530 }
1531
1532 /*
1533  * This verifies that the buffer is in proper utf8 format.
1534  *
1535  * If it isn't, it assumes any non-utf8 characters are Latin1,
1536  * and does the conversion.
1537  */
1538 static int verify_utf8(struct strbuf *buf)
1539 {
1540         int ok = 1;
1541         long pos = 0;
1542
1543         for (;;) {
1544                 int bad;
1545                 unsigned char c;
1546                 unsigned char replace[2];
1547
1548                 bad = find_invalid_utf8(buf->buf + pos, buf->len - pos);
1549                 if (bad < 0)
1550                         return ok;
1551                 pos += bad;
1552                 ok = 0;
1553                 c = buf->buf[pos];
1554                 strbuf_remove(buf, pos, 1);
1555
1556                 /* We know 'c' must be in the range 128-255 */
1557                 replace[0] = 0xc0 + (c >> 6);
1558                 replace[1] = 0x80 + (c & 0x3f);
1559                 strbuf_insert(buf, pos, replace, 2);
1560                 pos += 2;
1561         }
1562 }
1563
1564 static const char commit_utf8_warn[] =
1565 N_("Warning: commit message did not conform to UTF-8.\n"
1566    "You may want to amend it after fixing the message, or set the config\n"
1567    "variable i18n.commitencoding to the encoding your project uses.\n");
1568
1569 int commit_tree_extended(const char *msg, size_t msg_len,
1570                          const struct object_id *tree,
1571                          struct commit_list *parents, struct object_id *ret,
1572                          const char *author, const char *sign_commit,
1573                          struct commit_extra_header *extra)
1574 {
1575         int result;
1576         int encoding_is_utf8;
1577         struct strbuf buffer;
1578
1579         assert_sha1_type(tree->hash, OBJ_TREE);
1580
1581         if (memchr(msg, '\0', msg_len))
1582                 return error("a NUL byte in commit log message not allowed.");
1583
1584         /* Not having i18n.commitencoding is the same as having utf-8 */
1585         encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1586
1587         strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */
1588         strbuf_addf(&buffer, "tree %s\n", oid_to_hex(tree));
1589
1590         /*
1591          * NOTE! This ordering means that the same exact tree merged with a
1592          * different order of parents will be a _different_ changeset even
1593          * if everything else stays the same.
1594          */
1595         while (parents) {
1596                 struct commit *parent = pop_commit(&parents);
1597                 strbuf_addf(&buffer, "parent %s\n",
1598                             oid_to_hex(&parent->object.oid));
1599         }
1600
1601         /* Person/date information */
1602         if (!author)
1603                 author = git_author_info(IDENT_STRICT);
1604         strbuf_addf(&buffer, "author %s\n", author);
1605         strbuf_addf(&buffer, "committer %s\n", git_committer_info(IDENT_STRICT));
1606         if (!encoding_is_utf8)
1607                 strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding);
1608
1609         while (extra) {
1610                 add_extra_header(&buffer, extra);
1611                 extra = extra->next;
1612         }
1613         strbuf_addch(&buffer, '\n');
1614
1615         /* And add the comment */
1616         strbuf_add(&buffer, msg, msg_len);
1617
1618         /* And check the encoding */
1619         if (encoding_is_utf8 && !verify_utf8(&buffer))
1620                 fprintf(stderr, _(commit_utf8_warn));
1621
1622         if (sign_commit && do_sign_commit(&buffer, sign_commit)) {
1623                 result = -1;
1624                 goto out;
1625         }
1626
1627         result = write_object_file(buffer.buf, buffer.len, commit_type, ret);
1628 out:
1629         strbuf_release(&buffer);
1630         return result;
1631 }
1632
1633 void set_merge_remote_desc(struct commit *commit,
1634                            const char *name, struct object *obj)
1635 {
1636         struct merge_remote_desc *desc;
1637         FLEX_ALLOC_STR(desc, name, name);
1638         desc->obj = obj;
1639         commit->util = desc;
1640 }
1641
1642 struct commit *get_merge_parent(const char *name)
1643 {
1644         struct object *obj;
1645         struct commit *commit;
1646         struct object_id oid;
1647         if (get_oid(name, &oid))
1648                 return NULL;
1649         obj = parse_object(&oid);
1650         commit = (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
1651         if (commit && !commit->util)
1652                 set_merge_remote_desc(commit, name, obj);
1653         return commit;
1654 }
1655
1656 /*
1657  * Append a commit to the end of the commit_list.
1658  *
1659  * next starts by pointing to the variable that holds the head of an
1660  * empty commit_list, and is updated to point to the "next" field of
1661  * the last item on the list as new commits are appended.
1662  *
1663  * Usage example:
1664  *
1665  *     struct commit_list *list;
1666  *     struct commit_list **next = &list;
1667  *
1668  *     next = commit_list_append(c1, next);
1669  *     next = commit_list_append(c2, next);
1670  *     assert(commit_list_count(list) == 2);
1671  *     return list;
1672  */
1673 struct commit_list **commit_list_append(struct commit *commit,
1674                                         struct commit_list **next)
1675 {
1676         struct commit_list *new_commit = xmalloc(sizeof(struct commit_list));
1677         new_commit->item = commit;
1678         *next = new_commit;
1679         new_commit->next = NULL;
1680         return &new_commit->next;
1681 }
1682
1683 const char *find_commit_header(const char *msg, const char *key, size_t *out_len)
1684 {
1685         int key_len = strlen(key);
1686         const char *line = msg;
1687
1688         while (line) {
1689                 const char *eol = strchrnul(line, '\n');
1690
1691                 if (line == eol)
1692                         return NULL;
1693
1694                 if (eol - line > key_len &&
1695                     !strncmp(line, key, key_len) &&
1696                     line[key_len] == ' ') {
1697                         *out_len = eol - line - key_len - 1;
1698                         return line + key_len + 1;
1699                 }
1700                 line = *eol ? eol + 1 : NULL;
1701         }
1702         return NULL;
1703 }
1704
1705 /*
1706  * Inspect the given string and determine the true "end" of the log message, in
1707  * order to find where to put a new Signed-off-by: line.  Ignored are
1708  * trailing comment lines and blank lines.  To support "git commit -s
1709  * --amend" on an existing commit, we also ignore "Conflicts:".  To
1710  * support "git commit -v", we truncate at cut lines.
1711  *
1712  * Returns the number of bytes from the tail to ignore, to be fed as
1713  * the second parameter to append_signoff().
1714  */
1715 int ignore_non_trailer(const char *buf, size_t len)
1716 {
1717         int boc = 0;
1718         int bol = 0;
1719         int in_old_conflicts_block = 0;
1720         size_t cutoff = wt_status_locate_end(buf, len);
1721
1722         while (bol < cutoff) {
1723                 const char *next_line = memchr(buf + bol, '\n', len - bol);
1724
1725                 if (!next_line)
1726                         next_line = buf + len;
1727                 else
1728                         next_line++;
1729
1730                 if (buf[bol] == comment_line_char || buf[bol] == '\n') {
1731                         /* is this the first of the run of comments? */
1732                         if (!boc)
1733                                 boc = bol;
1734                         /* otherwise, it is just continuing */
1735                 } else if (starts_with(buf + bol, "Conflicts:\n")) {
1736                         in_old_conflicts_block = 1;
1737                         if (!boc)
1738                                 boc = bol;
1739                 } else if (in_old_conflicts_block && buf[bol] == '\t') {
1740                         ; /* a pathname in the conflicts block */
1741                 } else if (boc) {
1742                         /* the previous was not trailing comment */
1743                         boc = 0;
1744                         in_old_conflicts_block = 0;
1745                 }
1746                 bol = next_line - buf;
1747         }
1748         return boc ? len - boc : len - cutoff;
1749 }