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