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