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