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