reftable/reader: inline `reader_close()`
[git/gitster.git] / commit.c
blob087cb19f4f84f353db26289f97d72f91578fd8c3
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "tag.h"
5 #include "commit.h"
6 #include "commit-graph.h"
7 #include "environment.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "repository.h"
11 #include "object-name.h"
12 #include "object-store-ll.h"
13 #include "utf8.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "notes.h"
17 #include "alloc.h"
18 #include "gpg-interface.h"
19 #include "mergesort.h"
20 #include "commit-slab.h"
21 #include "prio-queue.h"
22 #include "hash-lookup.h"
23 #include "wt-status.h"
24 #include "advice.h"
25 #include "refs.h"
26 #include "commit-reach.h"
27 #include "setup.h"
28 #include "shallow.h"
29 #include "tree.h"
30 #include "hook.h"
31 #include "parse.h"
32 #include "object-file-convert.h"
34 static struct commit_extra_header *read_commit_extra_header_lines(const char *buf, size_t len, const char **);
36 int save_commit_buffer = 1;
37 int no_graft_file_deprecated_advice;
39 const char *commit_type = "commit";
41 struct commit *lookup_commit_reference_gently(struct repository *r,
42 const struct object_id *oid, int quiet)
44 struct object *obj = deref_tag(r,
45 parse_object(r, oid),
46 NULL, 0);
48 if (!obj)
49 return NULL;
50 return object_as_type(obj, OBJ_COMMIT, quiet);
53 struct commit *lookup_commit_reference(struct repository *r, const struct object_id *oid)
55 return lookup_commit_reference_gently(r, oid, 0);
58 struct commit *lookup_commit_or_die(const struct object_id *oid, const char *ref_name)
60 struct commit *c = lookup_commit_reference(the_repository, oid);
61 if (!c)
62 die(_("could not parse %s"), ref_name);
63 if (!oideq(oid, &c->object.oid)) {
64 warning(_("%s %s is not a commit!"),
65 ref_name, oid_to_hex(oid));
67 return c;
70 struct commit *lookup_commit_object(struct repository *r,
71 const struct object_id *oid)
73 struct object *obj = parse_object(r, oid);
74 return obj ? object_as_type(obj, OBJ_COMMIT, 0) : NULL;
78 struct commit *lookup_commit(struct repository *r, const struct object_id *oid)
80 struct object *obj = lookup_object(r, oid);
81 if (!obj)
82 return create_object(r, oid, alloc_commit_node(r));
83 return object_as_type(obj, OBJ_COMMIT, 0);
86 struct commit *lookup_commit_reference_by_name(const char *name)
88 struct object_id oid;
89 struct commit *commit;
91 if (repo_get_oid_committish(the_repository, name, &oid))
92 return NULL;
93 commit = lookup_commit_reference(the_repository, &oid);
94 if (repo_parse_commit(the_repository, commit))
95 return NULL;
96 return commit;
99 static timestamp_t parse_commit_date(const char *buf, const char *tail)
101 const char *dateptr;
102 const char *eol;
104 if (buf + 6 >= tail)
105 return 0;
106 if (memcmp(buf, "author", 6))
107 return 0;
108 while (buf < tail && *buf++ != '\n')
109 /* nada */;
110 if (buf + 9 >= tail)
111 return 0;
112 if (memcmp(buf, "committer", 9))
113 return 0;
116 * Jump to end-of-line so that we can walk backwards to find the
117 * end-of-email ">". This is more forgiving of malformed cases
118 * because unexpected characters tend to be in the name and email
119 * fields.
121 eol = memchr(buf, '\n', tail - buf);
122 if (!eol)
123 return 0;
124 dateptr = eol;
125 while (dateptr > buf && dateptr[-1] != '>')
126 dateptr--;
127 if (dateptr == buf)
128 return 0;
131 * Trim leading whitespace, but make sure we have at least one
132 * non-whitespace character, as parse_timestamp() will otherwise walk
133 * right past the newline we found in "eol" when skipping whitespace
134 * itself.
136 * In theory it would be sufficient to allow any character not matched
137 * by isspace(), but there's a catch: our isspace() does not
138 * necessarily match the behavior of parse_timestamp(), as the latter
139 * is implemented by system routines which match more exotic control
140 * codes, or even locale-dependent sequences.
142 * Since we expect the timestamp to be a number, we can check for that.
143 * Anything else (e.g., a non-numeric token like "foo") would just
144 * cause parse_timestamp() to return 0 anyway.
146 while (dateptr < eol && isspace(*dateptr))
147 dateptr++;
148 if (!isdigit(*dateptr) && *dateptr != '-')
149 return 0;
152 * We know there is at least one digit (or dash), so we'll begin
153 * parsing there and stop at worst case at eol.
155 * Note that we may feed parse_timestamp() extra characters here if the
156 * commit is malformed, and it will parse as far as it can. For
157 * example, "123foo456" would return "123". That might be questionable
158 * (versus returning "0"), but it would help in a hypothetical case
159 * like "123456+0100", where the whitespace from the timezone is
160 * missing. Since such syntactic errors may be baked into history and
161 * hard to correct now, let's err on trying to make our best guess
162 * here, rather than insist on perfect syntax.
164 return parse_timestamp(dateptr, NULL, 10);
167 static const struct object_id *commit_graft_oid_access(size_t index, const void *table)
169 const struct commit_graft * const *commit_graft_table = table;
170 return &commit_graft_table[index]->oid;
173 int commit_graft_pos(struct repository *r, const struct object_id *oid)
175 return oid_pos(oid, r->parsed_objects->grafts,
176 r->parsed_objects->grafts_nr,
177 commit_graft_oid_access);
180 static void unparse_commit(struct repository *r, const struct object_id *oid)
182 struct commit *c = lookup_commit(r, oid);
184 if (!c->object.parsed)
185 return;
186 free_commit_list(c->parents);
187 c->parents = NULL;
188 c->object.parsed = 0;
191 int register_commit_graft(struct repository *r, struct commit_graft *graft,
192 int ignore_dups)
194 int pos = commit_graft_pos(r, &graft->oid);
196 if (0 <= pos) {
197 if (ignore_dups)
198 free(graft);
199 else {
200 free(r->parsed_objects->grafts[pos]);
201 r->parsed_objects->grafts[pos] = graft;
203 return 1;
205 pos = -pos - 1;
206 ALLOC_GROW(r->parsed_objects->grafts,
207 r->parsed_objects->grafts_nr + 1,
208 r->parsed_objects->grafts_alloc);
209 r->parsed_objects->grafts_nr++;
210 if (pos < r->parsed_objects->grafts_nr)
211 memmove(r->parsed_objects->grafts + pos + 1,
212 r->parsed_objects->grafts + pos,
213 (r->parsed_objects->grafts_nr - pos - 1) *
214 sizeof(*r->parsed_objects->grafts));
215 r->parsed_objects->grafts[pos] = graft;
216 unparse_commit(r, &graft->oid);
217 return 0;
220 struct commit_graft *read_graft_line(struct strbuf *line)
222 /* The format is just "Commit Parent1 Parent2 ...\n" */
223 int i, phase;
224 const char *tail = NULL;
225 struct commit_graft *graft = NULL;
226 struct object_id dummy_oid, *oid;
228 strbuf_rtrim(line);
229 if (!line->len || line->buf[0] == '#')
230 return NULL;
232 * phase 0 verifies line, counts hashes in line and allocates graft
233 * phase 1 fills graft
235 for (phase = 0; phase < 2; phase++) {
236 oid = graft ? &graft->oid : &dummy_oid;
237 if (parse_oid_hex(line->buf, oid, &tail))
238 goto bad_graft_data;
239 for (i = 0; *tail != '\0'; i++) {
240 oid = graft ? &graft->parent[i] : &dummy_oid;
241 if (!isspace(*tail++) || parse_oid_hex(tail, oid, &tail))
242 goto bad_graft_data;
244 if (!graft) {
245 graft = xmalloc(st_add(sizeof(*graft),
246 st_mult(sizeof(struct object_id), i)));
247 graft->nr_parent = i;
250 return graft;
252 bad_graft_data:
253 error("bad graft data: %s", line->buf);
254 assert(!graft);
255 return NULL;
258 static int read_graft_file(struct repository *r, const char *graft_file)
260 FILE *fp = fopen_or_warn(graft_file, "r");
261 struct strbuf buf = STRBUF_INIT;
262 if (!fp)
263 return -1;
264 if (!no_graft_file_deprecated_advice &&
265 advice_enabled(ADVICE_GRAFT_FILE_DEPRECATED))
266 advise(_("Support for <GIT_DIR>/info/grafts is deprecated\n"
267 "and will be removed in a future Git version.\n"
268 "\n"
269 "Please use \"git replace --convert-graft-file\"\n"
270 "to convert the grafts into replace refs.\n"
271 "\n"
272 "Turn this message off by running\n"
273 "\"git config advice.graftFileDeprecated false\""));
274 while (!strbuf_getwholeline(&buf, fp, '\n')) {
275 /* The format is just "Commit Parent1 Parent2 ...\n" */
276 struct commit_graft *graft = read_graft_line(&buf);
277 if (!graft)
278 continue;
279 if (register_commit_graft(r, graft, 1))
280 error("duplicate graft data: %s", buf.buf);
282 fclose(fp);
283 strbuf_release(&buf);
284 return 0;
287 void prepare_commit_graft(struct repository *r)
289 char *graft_file;
291 if (r->parsed_objects->commit_graft_prepared)
292 return;
293 if (!startup_info->have_repository)
294 return;
296 graft_file = get_graft_file(r);
297 read_graft_file(r, graft_file);
298 /* make sure shallows are read */
299 is_repository_shallow(r);
300 r->parsed_objects->commit_graft_prepared = 1;
303 struct commit_graft *lookup_commit_graft(struct repository *r, const struct object_id *oid)
305 int pos;
306 prepare_commit_graft(r);
307 pos = commit_graft_pos(r, oid);
308 if (pos < 0)
309 return NULL;
310 return r->parsed_objects->grafts[pos];
313 int for_each_commit_graft(each_commit_graft_fn fn, void *cb_data)
315 int i, ret;
316 for (i = ret = 0; i < the_repository->parsed_objects->grafts_nr && !ret; i++)
317 ret = fn(the_repository->parsed_objects->grafts[i], cb_data);
318 return ret;
321 void reset_commit_grafts(struct repository *r)
323 int i;
325 for (i = 0; i < r->parsed_objects->grafts_nr; i++) {
326 unparse_commit(r, &r->parsed_objects->grafts[i]->oid);
327 free(r->parsed_objects->grafts[i]);
329 r->parsed_objects->grafts_nr = 0;
330 r->parsed_objects->commit_graft_prepared = 0;
333 struct commit_buffer {
334 void *buffer;
335 unsigned long size;
337 define_commit_slab(buffer_slab, struct commit_buffer);
339 struct buffer_slab *allocate_commit_buffer_slab(void)
341 struct buffer_slab *bs = xmalloc(sizeof(*bs));
342 init_buffer_slab(bs);
343 return bs;
346 void free_commit_buffer_slab(struct buffer_slab *bs)
348 clear_buffer_slab(bs);
349 free(bs);
352 void set_commit_buffer(struct repository *r, struct commit *commit, void *buffer, unsigned long size)
354 struct commit_buffer *v = buffer_slab_at(
355 r->parsed_objects->buffer_slab, commit);
356 v->buffer = buffer;
357 v->size = size;
360 const void *get_cached_commit_buffer(struct repository *r, const struct commit *commit, unsigned long *sizep)
362 struct commit_buffer *v = buffer_slab_peek(
363 r->parsed_objects->buffer_slab, commit);
364 if (!v) {
365 if (sizep)
366 *sizep = 0;
367 return NULL;
369 if (sizep)
370 *sizep = v->size;
371 return v->buffer;
374 const void *repo_get_commit_buffer(struct repository *r,
375 const struct commit *commit,
376 unsigned long *sizep)
378 const void *ret = get_cached_commit_buffer(r, commit, sizep);
379 if (!ret) {
380 enum object_type type;
381 unsigned long size;
382 ret = repo_read_object_file(r, &commit->object.oid, &type, &size);
383 if (!ret)
384 die("cannot read commit object %s",
385 oid_to_hex(&commit->object.oid));
386 if (type != OBJ_COMMIT)
387 die("expected commit for %s, got %s",
388 oid_to_hex(&commit->object.oid), type_name(type));
389 if (sizep)
390 *sizep = size;
392 return ret;
395 void repo_unuse_commit_buffer(struct repository *r,
396 const struct commit *commit,
397 const void *buffer)
399 struct commit_buffer *v = buffer_slab_peek(
400 r->parsed_objects->buffer_slab, commit);
401 if (!(v && v->buffer == buffer))
402 free((void *)buffer);
405 void free_commit_buffer(struct parsed_object_pool *pool, struct commit *commit)
407 struct commit_buffer *v = buffer_slab_peek(
408 pool->buffer_slab, commit);
409 if (v) {
410 FREE_AND_NULL(v->buffer);
411 v->size = 0;
415 static inline void set_commit_tree(struct commit *c, struct tree *t)
417 c->maybe_tree = t;
420 struct tree *repo_get_commit_tree(struct repository *r,
421 const struct commit *commit)
423 if (commit->maybe_tree || !commit->object.parsed)
424 return commit->maybe_tree;
426 if (commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
427 return get_commit_tree_in_graph(r, commit);
429 return NULL;
432 struct object_id *get_commit_tree_oid(const struct commit *commit)
434 struct tree *tree = repo_get_commit_tree(the_repository, commit);
435 return tree ? &tree->object.oid : NULL;
438 void release_commit_memory(struct parsed_object_pool *pool, struct commit *c)
440 set_commit_tree(c, NULL);
441 free_commit_buffer(pool, c);
442 c->index = 0;
443 free_commit_list(c->parents);
445 c->object.parsed = 0;
448 const void *detach_commit_buffer(struct commit *commit, unsigned long *sizep)
450 struct commit_buffer *v = buffer_slab_peek(
451 the_repository->parsed_objects->buffer_slab, commit);
452 void *ret;
454 if (!v) {
455 if (sizep)
456 *sizep = 0;
457 return NULL;
459 ret = v->buffer;
460 if (sizep)
461 *sizep = v->size;
463 v->buffer = NULL;
464 v->size = 0;
465 return ret;
468 int parse_commit_buffer(struct repository *r, struct commit *item, const void *buffer, unsigned long size, int check_graph)
470 const char *tail = buffer;
471 const char *bufptr = buffer;
472 struct object_id parent;
473 struct commit_list **pptr;
474 struct commit_graft *graft;
475 const int tree_entry_len = the_hash_algo->hexsz + 5;
476 const int parent_entry_len = the_hash_algo->hexsz + 7;
477 struct tree *tree;
479 if (item->object.parsed)
480 return 0;
482 * Presumably this is leftover from an earlier failed parse;
483 * clear it out in preparation for us re-parsing (we'll hit the
484 * same error, but that's good, since it lets our caller know
485 * the result cannot be trusted.
487 free_commit_list(item->parents);
488 item->parents = NULL;
490 tail += size;
491 if (tail <= bufptr + tree_entry_len + 1 || memcmp(bufptr, "tree ", 5) ||
492 bufptr[tree_entry_len] != '\n')
493 return error("bogus commit object %s", oid_to_hex(&item->object.oid));
494 if (get_oid_hex(bufptr + 5, &parent) < 0)
495 return error("bad tree pointer in commit %s",
496 oid_to_hex(&item->object.oid));
497 tree = lookup_tree(r, &parent);
498 if (!tree)
499 return error("bad tree pointer %s in commit %s",
500 oid_to_hex(&parent),
501 oid_to_hex(&item->object.oid));
502 set_commit_tree(item, tree);
503 bufptr += tree_entry_len + 1; /* "tree " + "hex sha1" + "\n" */
504 pptr = &item->parents;
506 graft = lookup_commit_graft(r, &item->object.oid);
507 if (graft)
508 r->parsed_objects->substituted_parent = 1;
509 while (bufptr + parent_entry_len < tail && !memcmp(bufptr, "parent ", 7)) {
510 struct commit *new_parent;
512 if (tail <= bufptr + parent_entry_len + 1 ||
513 get_oid_hex(bufptr + 7, &parent) ||
514 bufptr[parent_entry_len] != '\n')
515 return error("bad parents in commit %s", oid_to_hex(&item->object.oid));
516 bufptr += parent_entry_len + 1;
518 * The clone is shallow if nr_parent < 0, and we must
519 * not traverse its real parents even when we unhide them.
521 if (graft && (graft->nr_parent < 0 || !grafts_keep_true_parents))
522 continue;
523 new_parent = lookup_commit(r, &parent);
524 if (!new_parent)
525 return error("bad parent %s in commit %s",
526 oid_to_hex(&parent),
527 oid_to_hex(&item->object.oid));
528 pptr = &commit_list_insert(new_parent, pptr)->next;
530 if (graft) {
531 int i;
532 struct commit *new_parent;
533 for (i = 0; i < graft->nr_parent; i++) {
534 new_parent = lookup_commit(r,
535 &graft->parent[i]);
536 if (!new_parent)
537 return error("bad graft parent %s in commit %s",
538 oid_to_hex(&graft->parent[i]),
539 oid_to_hex(&item->object.oid));
540 pptr = &commit_list_insert(new_parent, pptr)->next;
543 item->date = parse_commit_date(bufptr, tail);
545 if (check_graph)
546 load_commit_graph_info(r, item);
548 item->object.parsed = 1;
549 return 0;
552 int repo_parse_commit_internal(struct repository *r,
553 struct commit *item,
554 int quiet_on_missing,
555 int use_commit_graph)
557 enum object_type type;
558 void *buffer;
559 unsigned long size;
560 struct object_info oi = {
561 .typep = &type,
562 .sizep = &size,
563 .contentp = &buffer,
566 * Git does not support partial clones that exclude commits, so set
567 * OBJECT_INFO_SKIP_FETCH_OBJECT to fail fast when an object is missing.
569 int flags = OBJECT_INFO_LOOKUP_REPLACE | OBJECT_INFO_SKIP_FETCH_OBJECT |
570 OBJECT_INFO_DIE_IF_CORRUPT;
571 int ret;
573 if (!item)
574 return -1;
575 if (item->object.parsed)
576 return 0;
577 if (use_commit_graph && parse_commit_in_graph(r, item)) {
578 static int commit_graph_paranoia = -1;
580 if (commit_graph_paranoia == -1)
581 commit_graph_paranoia = git_env_bool(GIT_COMMIT_GRAPH_PARANOIA, 0);
583 if (commit_graph_paranoia && !has_object(r, &item->object.oid, 0)) {
584 unparse_commit(r, &item->object.oid);
585 return quiet_on_missing ? -1 :
586 error(_("commit %s exists in commit-graph but not in the object database"),
587 oid_to_hex(&item->object.oid));
590 return 0;
593 if (oid_object_info_extended(r, &item->object.oid, &oi, flags) < 0)
594 return quiet_on_missing ? -1 :
595 error("Could not read %s",
596 oid_to_hex(&item->object.oid));
597 if (type != OBJ_COMMIT) {
598 free(buffer);
599 return error("Object %s not a commit",
600 oid_to_hex(&item->object.oid));
603 ret = parse_commit_buffer(r, item, buffer, size, 0);
604 if (save_commit_buffer && !ret) {
605 set_commit_buffer(r, item, buffer, size);
606 return 0;
608 free(buffer);
609 return ret;
612 int repo_parse_commit_gently(struct repository *r,
613 struct commit *item, int quiet_on_missing)
615 return repo_parse_commit_internal(r, item, quiet_on_missing, 1);
618 void parse_commit_or_die(struct commit *item)
620 if (repo_parse_commit(the_repository, item))
621 die("unable to parse commit %s",
622 item ? oid_to_hex(&item->object.oid) : "(null)");
625 int find_commit_subject(const char *commit_buffer, const char **subject)
627 const char *eol;
628 const char *p = commit_buffer;
630 while (*p && (*p != '\n' || p[1] != '\n'))
631 p++;
632 if (*p) {
633 p = skip_blank_lines(p + 2);
634 eol = strchrnul(p, '\n');
635 } else
636 eol = p;
638 *subject = p;
640 return eol - p;
643 size_t commit_subject_length(const char *body)
645 const char *p = body;
646 while (*p) {
647 const char *next = skip_blank_lines(p);
648 if (next != p)
649 break;
650 p = strchrnul(p, '\n');
651 if (*p)
652 p++;
654 return p - body;
657 struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
659 struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
660 new_list->item = item;
661 new_list->next = *list_p;
662 *list_p = new_list;
663 return new_list;
666 int commit_list_contains(struct commit *item, struct commit_list *list)
668 while (list) {
669 if (list->item == item)
670 return 1;
671 list = list->next;
674 return 0;
677 unsigned commit_list_count(const struct commit_list *l)
679 unsigned c = 0;
680 for (; l; l = l->next )
681 c++;
682 return c;
685 struct commit_list *copy_commit_list(const struct commit_list *list)
687 struct commit_list *head = NULL;
688 struct commit_list **pp = &head;
689 while (list) {
690 pp = commit_list_append(list->item, pp);
691 list = list->next;
693 return head;
696 struct commit_list *reverse_commit_list(struct commit_list *list)
698 struct commit_list *next = NULL, *current, *backup;
699 for (current = list; current; current = backup) {
700 backup = current->next;
701 current->next = next;
702 next = current;
704 return next;
707 void free_commit_list(struct commit_list *list)
709 while (list)
710 pop_commit(&list);
713 struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
715 struct commit_list **pp = list;
716 struct commit_list *p;
717 while ((p = *pp) != NULL) {
718 if (p->item->date < item->date) {
719 break;
721 pp = &p->next;
723 return commit_list_insert(item, pp);
726 static int commit_list_compare_by_date(const struct commit_list *a,
727 const struct commit_list *b)
729 timestamp_t a_date = a->item->date;
730 timestamp_t b_date = b->item->date;
731 if (a_date < b_date)
732 return 1;
733 if (a_date > b_date)
734 return -1;
735 return 0;
738 DEFINE_LIST_SORT(static, commit_list_sort, struct commit_list, next);
740 void commit_list_sort_by_date(struct commit_list **list)
742 commit_list_sort(list, commit_list_compare_by_date);
745 struct commit *pop_most_recent_commit(struct commit_list **list,
746 unsigned int mark)
748 struct commit *ret = pop_commit(list);
749 struct commit_list *parents = ret->parents;
751 while (parents) {
752 struct commit *commit = parents->item;
753 if (!repo_parse_commit(the_repository, commit) && !(commit->object.flags & mark)) {
754 commit->object.flags |= mark;
755 commit_list_insert_by_date(commit, list);
757 parents = parents->next;
759 return ret;
762 static void clear_commit_marks_1(struct commit_list **plist,
763 struct commit *commit, unsigned int mark)
765 while (commit) {
766 struct commit_list *parents;
768 if (!(mark & commit->object.flags))
769 return;
771 commit->object.flags &= ~mark;
773 parents = commit->parents;
774 if (!parents)
775 return;
777 while ((parents = parents->next)) {
778 if (parents->item->object.flags & mark)
779 commit_list_insert(parents->item, plist);
782 commit = commit->parents->item;
786 void clear_commit_marks_many(int nr, struct commit **commit, unsigned int mark)
788 struct commit_list *list = NULL;
790 while (nr--) {
791 clear_commit_marks_1(&list, *commit, mark);
792 commit++;
794 while (list)
795 clear_commit_marks_1(&list, pop_commit(&list), mark);
798 void clear_commit_marks(struct commit *commit, unsigned int mark)
800 clear_commit_marks_many(1, &commit, mark);
803 struct commit *pop_commit(struct commit_list **stack)
805 struct commit_list *top = *stack;
806 struct commit *item = top ? top->item : NULL;
808 if (top) {
809 *stack = top->next;
810 free(top);
812 return item;
816 * Topological sort support
819 /* count number of children that have not been emitted */
820 define_commit_slab(indegree_slab, int);
822 define_commit_slab(author_date_slab, timestamp_t);
824 void record_author_date(struct author_date_slab *author_date,
825 struct commit *commit)
827 const char *buffer = repo_get_commit_buffer(the_repository, commit,
828 NULL);
829 struct ident_split ident;
830 const char *ident_line;
831 size_t ident_len;
832 char *date_end;
833 timestamp_t date;
835 ident_line = find_commit_header(buffer, "author", &ident_len);
836 if (!ident_line)
837 goto fail_exit; /* no author line */
838 if (split_ident_line(&ident, ident_line, ident_len) ||
839 !ident.date_begin || !ident.date_end)
840 goto fail_exit; /* malformed "author" line */
842 date = parse_timestamp(ident.date_begin, &date_end, 10);
843 if (date_end != ident.date_end)
844 goto fail_exit; /* malformed date */
845 *(author_date_slab_at(author_date, commit)) = date;
847 fail_exit:
848 repo_unuse_commit_buffer(the_repository, commit, buffer);
851 int compare_commits_by_author_date(const void *a_, const void *b_,
852 void *cb_data)
854 const struct commit *a = a_, *b = b_;
855 struct author_date_slab *author_date = cb_data;
856 timestamp_t a_date = *(author_date_slab_at(author_date, a));
857 timestamp_t b_date = *(author_date_slab_at(author_date, b));
859 /* newer commits with larger date first */
860 if (a_date < b_date)
861 return 1;
862 else if (a_date > b_date)
863 return -1;
864 return 0;
867 int compare_commits_by_gen_then_commit_date(const void *a_, const void *b_,
868 void *unused UNUSED)
870 const struct commit *a = a_, *b = b_;
871 const timestamp_t generation_a = commit_graph_generation(a),
872 generation_b = commit_graph_generation(b);
874 /* newer commits first */
875 if (generation_a < generation_b)
876 return 1;
877 else if (generation_a > generation_b)
878 return -1;
880 /* use date as a heuristic when generations are equal */
881 if (a->date < b->date)
882 return 1;
883 else if (a->date > b->date)
884 return -1;
885 return 0;
888 int compare_commits_by_commit_date(const void *a_, const void *b_,
889 void *unused UNUSED)
891 const struct commit *a = a_, *b = b_;
892 /* newer commits with larger date first */
893 if (a->date < b->date)
894 return 1;
895 else if (a->date > b->date)
896 return -1;
897 return 0;
901 * Performs an in-place topological sort on the list supplied.
903 void sort_in_topological_order(struct commit_list **list, enum rev_sort_order sort_order)
905 struct commit_list *next, *orig = *list;
906 struct commit_list **pptr;
907 struct indegree_slab indegree;
908 struct prio_queue queue;
909 struct commit *commit;
910 struct author_date_slab author_date;
912 if (!orig)
913 return;
914 *list = NULL;
916 init_indegree_slab(&indegree);
917 memset(&queue, '\0', sizeof(queue));
919 switch (sort_order) {
920 default: /* REV_SORT_IN_GRAPH_ORDER */
921 queue.compare = NULL;
922 break;
923 case REV_SORT_BY_COMMIT_DATE:
924 queue.compare = compare_commits_by_commit_date;
925 break;
926 case REV_SORT_BY_AUTHOR_DATE:
927 init_author_date_slab(&author_date);
928 queue.compare = compare_commits_by_author_date;
929 queue.cb_data = &author_date;
930 break;
933 /* Mark them and clear the indegree */
934 for (next = orig; next; next = next->next) {
935 struct commit *commit = next->item;
936 *(indegree_slab_at(&indegree, commit)) = 1;
937 /* also record the author dates, if needed */
938 if (sort_order == REV_SORT_BY_AUTHOR_DATE)
939 record_author_date(&author_date, commit);
942 /* update the indegree */
943 for (next = orig; next; next = next->next) {
944 struct commit_list *parents = next->item->parents;
945 while (parents) {
946 struct commit *parent = parents->item;
947 int *pi = indegree_slab_at(&indegree, parent);
949 if (*pi)
950 (*pi)++;
951 parents = parents->next;
956 * find the tips
958 * tips are nodes not reachable from any other node in the list
960 * the tips serve as a starting set for the work queue.
962 for (next = orig; next; next = next->next) {
963 struct commit *commit = next->item;
965 if (*(indegree_slab_at(&indegree, commit)) == 1)
966 prio_queue_put(&queue, commit);
970 * This is unfortunate; the initial tips need to be shown
971 * in the order given from the revision traversal machinery.
973 if (sort_order == REV_SORT_IN_GRAPH_ORDER)
974 prio_queue_reverse(&queue);
976 /* We no longer need the commit list */
977 free_commit_list(orig);
979 pptr = list;
980 *list = NULL;
981 while ((commit = prio_queue_get(&queue)) != NULL) {
982 struct commit_list *parents;
984 for (parents = commit->parents; parents ; parents = parents->next) {
985 struct commit *parent = parents->item;
986 int *pi = indegree_slab_at(&indegree, parent);
988 if (!*pi)
989 continue;
992 * parents are only enqueued for emission
993 * when all their children have been emitted thereby
994 * guaranteeing topological order.
996 if (--(*pi) == 1)
997 prio_queue_put(&queue, parent);
1000 * all children of commit have already been
1001 * emitted. we can emit it now.
1003 *(indegree_slab_at(&indegree, commit)) = 0;
1005 pptr = &commit_list_insert(commit, pptr)->next;
1008 clear_indegree_slab(&indegree);
1009 clear_prio_queue(&queue);
1010 if (sort_order == REV_SORT_BY_AUTHOR_DATE)
1011 clear_author_date_slab(&author_date);
1014 struct rev_collect {
1015 struct commit **commit;
1016 int nr;
1017 int alloc;
1018 unsigned int initial : 1;
1021 static void add_one_commit(struct object_id *oid, struct rev_collect *revs)
1023 struct commit *commit;
1025 if (is_null_oid(oid))
1026 return;
1028 commit = lookup_commit(the_repository, oid);
1029 if (!commit ||
1030 (commit->object.flags & TMP_MARK) ||
1031 repo_parse_commit(the_repository, commit))
1032 return;
1034 ALLOC_GROW(revs->commit, revs->nr + 1, revs->alloc);
1035 revs->commit[revs->nr++] = commit;
1036 commit->object.flags |= TMP_MARK;
1039 static int collect_one_reflog_ent(struct object_id *ooid, struct object_id *noid,
1040 const char *ident UNUSED,
1041 timestamp_t timestamp UNUSED, int tz UNUSED,
1042 const char *message UNUSED, void *cbdata)
1044 struct rev_collect *revs = cbdata;
1046 if (revs->initial) {
1047 revs->initial = 0;
1048 add_one_commit(ooid, revs);
1050 add_one_commit(noid, revs);
1051 return 0;
1054 struct commit *get_fork_point(const char *refname, struct commit *commit)
1056 struct object_id oid;
1057 struct rev_collect revs;
1058 struct commit_list *bases = NULL;
1059 int i;
1060 struct commit *ret = NULL;
1061 char *full_refname;
1063 switch (repo_dwim_ref(the_repository, refname, strlen(refname), &oid,
1064 &full_refname, 0)) {
1065 case 0:
1066 die("No such ref: '%s'", refname);
1067 case 1:
1068 break; /* good */
1069 default:
1070 die("Ambiguous refname: '%s'", refname);
1073 memset(&revs, 0, sizeof(revs));
1074 revs.initial = 1;
1075 refs_for_each_reflog_ent(get_main_ref_store(the_repository),
1076 full_refname, collect_one_reflog_ent, &revs);
1078 if (!revs.nr)
1079 add_one_commit(&oid, &revs);
1081 for (i = 0; i < revs.nr; i++)
1082 revs.commit[i]->object.flags &= ~TMP_MARK;
1084 if (repo_get_merge_bases_many(the_repository, commit, revs.nr,
1085 revs.commit, &bases) < 0)
1086 exit(128);
1089 * There should be one and only one merge base, when we found
1090 * a common ancestor among reflog entries.
1092 if (!bases || bases->next)
1093 goto cleanup_return;
1095 /* And the found one must be one of the reflog entries */
1096 for (i = 0; i < revs.nr; i++)
1097 if (&bases->item->object == &revs.commit[i]->object)
1098 break; /* found */
1099 if (revs.nr <= i)
1100 goto cleanup_return;
1102 ret = bases->item;
1104 cleanup_return:
1105 free(revs.commit);
1106 free_commit_list(bases);
1107 free(full_refname);
1108 return ret;
1112 * Indexed by hash algorithm identifier.
1114 static const char *gpg_sig_headers[] = {
1115 NULL,
1116 "gpgsig",
1117 "gpgsig-sha256",
1120 int add_header_signature(struct strbuf *buf, struct strbuf *sig, const struct git_hash_algo *algo)
1122 int inspos, copypos;
1123 const char *eoh;
1124 const char *gpg_sig_header = gpg_sig_headers[hash_algo_by_ptr(algo)];
1125 int gpg_sig_header_len = strlen(gpg_sig_header);
1127 /* find the end of the header */
1128 eoh = strstr(buf->buf, "\n\n");
1129 if (!eoh)
1130 inspos = buf->len;
1131 else
1132 inspos = eoh - buf->buf + 1;
1134 for (copypos = 0; sig->buf[copypos]; ) {
1135 const char *bol = sig->buf + copypos;
1136 const char *eol = strchrnul(bol, '\n');
1137 int len = (eol - bol) + !!*eol;
1139 if (!copypos) {
1140 strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
1141 inspos += gpg_sig_header_len;
1143 strbuf_insertstr(buf, inspos++, " ");
1144 strbuf_insert(buf, inspos, bol, len);
1145 inspos += len;
1146 copypos += len;
1148 return 0;
1151 static int sign_commit_to_strbuf(struct strbuf *sig, struct strbuf *buf, const char *keyid)
1153 if (!keyid || !*keyid)
1154 keyid = get_signing_key();
1155 if (sign_buffer(buf, sig, keyid))
1156 return -1;
1157 return 0;
1160 int parse_signed_commit(const struct commit *commit,
1161 struct strbuf *payload, struct strbuf *signature,
1162 const struct git_hash_algo *algop)
1164 unsigned long size;
1165 const char *buffer = repo_get_commit_buffer(the_repository, commit,
1166 &size);
1167 int ret = parse_buffer_signed_by_header(buffer, size, payload, signature, algop);
1169 repo_unuse_commit_buffer(the_repository, commit, buffer);
1170 return ret;
1173 int parse_buffer_signed_by_header(const char *buffer,
1174 unsigned long size,
1175 struct strbuf *payload,
1176 struct strbuf *signature,
1177 const struct git_hash_algo *algop)
1179 int in_signature = 0, saw_signature = 0, other_signature = 0;
1180 const char *line, *tail, *p;
1181 const char *gpg_sig_header = gpg_sig_headers[hash_algo_by_ptr(algop)];
1183 line = buffer;
1184 tail = buffer + size;
1185 while (line < tail) {
1186 const char *sig = NULL;
1187 const char *next = memchr(line, '\n', tail - line);
1189 next = next ? next + 1 : tail;
1190 if (in_signature && line[0] == ' ')
1191 sig = line + 1;
1192 else if (skip_prefix(line, gpg_sig_header, &p) &&
1193 *p == ' ') {
1194 sig = line + strlen(gpg_sig_header) + 1;
1195 other_signature = 0;
1197 else if (starts_with(line, "gpgsig"))
1198 other_signature = 1;
1199 else if (other_signature && line[0] != ' ')
1200 other_signature = 0;
1201 if (sig) {
1202 strbuf_add(signature, sig, next - sig);
1203 saw_signature = 1;
1204 in_signature = 1;
1205 } else {
1206 if (*line == '\n')
1207 /* dump the whole remainder of the buffer */
1208 next = tail;
1209 if (!other_signature)
1210 strbuf_add(payload, line, next - line);
1211 in_signature = 0;
1213 line = next;
1215 return saw_signature;
1218 int remove_signature(struct strbuf *buf)
1220 const char *line = buf->buf;
1221 const char *tail = buf->buf + buf->len;
1222 int in_signature = 0;
1223 struct sigbuf {
1224 const char *start;
1225 const char *end;
1226 } sigs[2], *sigp = &sigs[0];
1227 int i;
1228 const char *orig_buf = buf->buf;
1230 memset(sigs, 0, sizeof(sigs));
1232 while (line < tail) {
1233 const char *next = memchr(line, '\n', tail - line);
1234 next = next ? next + 1 : tail;
1236 if (in_signature && line[0] == ' ')
1237 sigp->end = next;
1238 else if (starts_with(line, "gpgsig")) {
1239 int i;
1240 for (i = 1; i < GIT_HASH_NALGOS; i++) {
1241 const char *p;
1242 if (skip_prefix(line, gpg_sig_headers[i], &p) &&
1243 *p == ' ') {
1244 sigp->start = line;
1245 sigp->end = next;
1246 in_signature = 1;
1249 } else {
1250 if (*line == '\n')
1251 /* dump the whole remainder of the buffer */
1252 next = tail;
1253 if (in_signature && sigp - sigs != ARRAY_SIZE(sigs))
1254 sigp++;
1255 in_signature = 0;
1257 line = next;
1260 for (i = ARRAY_SIZE(sigs) - 1; i >= 0; i--)
1261 if (sigs[i].start)
1262 strbuf_remove(buf, sigs[i].start - orig_buf, sigs[i].end - sigs[i].start);
1264 return sigs[0].start != NULL;
1267 static void handle_signed_tag(const struct commit *parent, struct commit_extra_header ***tail)
1269 struct merge_remote_desc *desc;
1270 struct commit_extra_header *mergetag;
1271 char *buf;
1272 unsigned long size;
1273 enum object_type type;
1274 struct strbuf payload = STRBUF_INIT;
1275 struct strbuf signature = STRBUF_INIT;
1277 desc = merge_remote_util(parent);
1278 if (!desc || !desc->obj)
1279 return;
1280 buf = repo_read_object_file(the_repository, &desc->obj->oid, &type,
1281 &size);
1282 if (!buf || type != OBJ_TAG)
1283 goto free_return;
1284 if (!parse_signature(buf, size, &payload, &signature))
1285 goto free_return;
1287 * We could verify this signature and either omit the tag when
1288 * it does not validate, but the integrator may not have the
1289 * public key of the signer of the tag being merged, while a
1290 * later auditor may have it while auditing, so let's not run
1291 * verify-signed-buffer here for now...
1293 * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
1294 * warn("warning: signed tag unverified.");
1296 CALLOC_ARRAY(mergetag, 1);
1297 mergetag->key = xstrdup("mergetag");
1298 mergetag->value = buf;
1299 mergetag->len = size;
1301 **tail = mergetag;
1302 *tail = &mergetag->next;
1303 strbuf_release(&payload);
1304 strbuf_release(&signature);
1305 return;
1307 free_return:
1308 free(buf);
1311 int check_commit_signature(const struct commit *commit, struct signature_check *sigc)
1313 struct strbuf payload = STRBUF_INIT;
1314 struct strbuf signature = STRBUF_INIT;
1315 int ret = 1;
1317 sigc->result = 'N';
1319 if (parse_signed_commit(commit, &payload, &signature, the_hash_algo) <= 0)
1320 goto out;
1322 sigc->payload_type = SIGNATURE_PAYLOAD_COMMIT;
1323 sigc->payload = strbuf_detach(&payload, &sigc->payload_len);
1324 ret = check_signature(sigc, signature.buf, signature.len);
1326 out:
1327 strbuf_release(&payload);
1328 strbuf_release(&signature);
1330 return ret;
1333 void verify_merge_signature(struct commit *commit, int verbosity,
1334 int check_trust)
1336 char hex[GIT_MAX_HEXSZ + 1];
1337 struct signature_check signature_check;
1338 int ret;
1339 memset(&signature_check, 0, sizeof(signature_check));
1341 ret = check_commit_signature(commit, &signature_check);
1343 repo_find_unique_abbrev_r(the_repository, hex, &commit->object.oid,
1344 DEFAULT_ABBREV);
1345 switch (signature_check.result) {
1346 case 'G':
1347 if (ret || (check_trust && signature_check.trust_level < TRUST_MARGINAL))
1348 die(_("Commit %s has an untrusted GPG signature, "
1349 "allegedly by %s."), hex, signature_check.signer);
1350 break;
1351 case 'B':
1352 die(_("Commit %s has a bad GPG signature "
1353 "allegedly by %s."), hex, signature_check.signer);
1354 default: /* 'N' */
1355 die(_("Commit %s does not have a GPG signature."), hex);
1357 if (verbosity >= 0 && signature_check.result == 'G')
1358 printf(_("Commit %s has a good GPG signature by %s\n"),
1359 hex, signature_check.signer);
1361 signature_check_clear(&signature_check);
1364 void append_merge_tag_headers(const struct commit_list *parents,
1365 struct commit_extra_header ***tail)
1367 while (parents) {
1368 const struct commit *parent = parents->item;
1369 handle_signed_tag(parent, tail);
1370 parents = parents->next;
1374 static int convert_commit_extra_headers(const struct commit_extra_header *orig,
1375 struct commit_extra_header **result)
1377 const struct git_hash_algo *compat = the_repository->compat_hash_algo;
1378 const struct git_hash_algo *algo = the_repository->hash_algo;
1379 struct commit_extra_header *extra = NULL, **tail = &extra;
1380 struct strbuf out = STRBUF_INIT;
1381 while (orig) {
1382 struct commit_extra_header *new;
1383 CALLOC_ARRAY(new, 1);
1384 if (!strcmp(orig->key, "mergetag")) {
1385 if (convert_object_file(&out, algo, compat,
1386 orig->value, orig->len,
1387 OBJ_TAG, 1)) {
1388 free(new);
1389 free_commit_extra_headers(extra);
1390 return -1;
1392 new->key = xstrdup("mergetag");
1393 new->value = strbuf_detach(&out, &new->len);
1394 } else {
1395 new->key = xstrdup(orig->key);
1396 new->len = orig->len;
1397 new->value = xmemdupz(orig->value, orig->len);
1399 *tail = new;
1400 tail = &new->next;
1401 orig = orig->next;
1403 *result = extra;
1404 return 0;
1407 static void add_extra_header(struct strbuf *buffer,
1408 const struct commit_extra_header *extra)
1410 strbuf_addstr(buffer, extra->key);
1411 if (extra->len)
1412 strbuf_add_lines(buffer, " ", extra->value, extra->len);
1413 else
1414 strbuf_addch(buffer, '\n');
1417 struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
1418 const char **exclude)
1420 struct commit_extra_header *extra = NULL;
1421 unsigned long size;
1422 const char *buffer = repo_get_commit_buffer(the_repository, commit,
1423 &size);
1424 extra = read_commit_extra_header_lines(buffer, size, exclude);
1425 repo_unuse_commit_buffer(the_repository, commit, buffer);
1426 return extra;
1429 int for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
1431 struct commit_extra_header *extra, *to_free;
1432 int res = 0;
1434 to_free = read_commit_extra_headers(commit, NULL);
1435 for (extra = to_free; !res && extra; extra = extra->next) {
1436 if (strcmp(extra->key, "mergetag"))
1437 continue; /* not a merge tag */
1438 res = fn(commit, extra, data);
1440 free_commit_extra_headers(to_free);
1441 return res;
1444 static inline int standard_header_field(const char *field, size_t len)
1446 return ((len == 4 && !memcmp(field, "tree", 4)) ||
1447 (len == 6 && !memcmp(field, "parent", 6)) ||
1448 (len == 6 && !memcmp(field, "author", 6)) ||
1449 (len == 9 && !memcmp(field, "committer", 9)) ||
1450 (len == 8 && !memcmp(field, "encoding", 8)));
1453 static int excluded_header_field(const char *field, size_t len, const char **exclude)
1455 if (!exclude)
1456 return 0;
1458 while (*exclude) {
1459 size_t xlen = strlen(*exclude);
1460 if (len == xlen && !memcmp(field, *exclude, xlen))
1461 return 1;
1462 exclude++;
1464 return 0;
1467 static struct commit_extra_header *read_commit_extra_header_lines(
1468 const char *buffer, size_t size,
1469 const char **exclude)
1471 struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
1472 const char *line, *next, *eof, *eob;
1473 struct strbuf buf = STRBUF_INIT;
1475 for (line = buffer, eob = line + size;
1476 line < eob && *line != '\n';
1477 line = next) {
1478 next = memchr(line, '\n', eob - line);
1479 next = next ? next + 1 : eob;
1480 if (*line == ' ') {
1481 /* continuation */
1482 if (it)
1483 strbuf_add(&buf, line + 1, next - (line + 1));
1484 continue;
1486 if (it)
1487 it->value = strbuf_detach(&buf, &it->len);
1488 strbuf_reset(&buf);
1489 it = NULL;
1491 eof = memchr(line, ' ', next - line);
1492 if (!eof)
1493 eof = next;
1494 else if (standard_header_field(line, eof - line) ||
1495 excluded_header_field(line, eof - line, exclude))
1496 continue;
1498 CALLOC_ARRAY(it, 1);
1499 it->key = xmemdupz(line, eof-line);
1500 *tail = it;
1501 tail = &it->next;
1502 if (eof + 1 < next)
1503 strbuf_add(&buf, eof + 1, next - (eof + 1));
1505 if (it)
1506 it->value = strbuf_detach(&buf, &it->len);
1507 return extra;
1510 void free_commit_extra_headers(struct commit_extra_header *extra)
1512 while (extra) {
1513 struct commit_extra_header *next = extra->next;
1514 free(extra->key);
1515 free(extra->value);
1516 free(extra);
1517 extra = next;
1521 int commit_tree(const char *msg, size_t msg_len, const struct object_id *tree,
1522 const struct commit_list *parents, struct object_id *ret,
1523 const char *author, const char *sign_commit)
1525 struct commit_extra_header *extra = NULL, **tail = &extra;
1526 int result;
1528 append_merge_tag_headers(parents, &tail);
1529 result = commit_tree_extended(msg, msg_len, tree, parents, ret, author,
1530 NULL, sign_commit, extra);
1531 free_commit_extra_headers(extra);
1532 return result;
1535 static int find_invalid_utf8(const char *buf, int len)
1537 int offset = 0;
1538 static const unsigned int max_codepoint[] = {
1539 0x7f, 0x7ff, 0xffff, 0x10ffff
1542 while (len) {
1543 unsigned char c = *buf++;
1544 int bytes, bad_offset;
1545 unsigned int codepoint;
1546 unsigned int min_val, max_val;
1548 len--;
1549 offset++;
1551 /* Simple US-ASCII? No worries. */
1552 if (c < 0x80)
1553 continue;
1555 bad_offset = offset-1;
1558 * Count how many more high bits set: that's how
1559 * many more bytes this sequence should have.
1561 bytes = 0;
1562 while (c & 0x40) {
1563 c <<= 1;
1564 bytes++;
1568 * Must be between 1 and 3 more bytes. Longer sequences result in
1569 * codepoints beyond U+10FFFF, which are guaranteed never to exist.
1571 if (bytes < 1 || 3 < bytes)
1572 return bad_offset;
1574 /* Do we *have* that many bytes? */
1575 if (len < bytes)
1576 return bad_offset;
1579 * Place the encoded bits at the bottom of the value and compute the
1580 * valid range.
1582 codepoint = (c & 0x7f) >> bytes;
1583 min_val = max_codepoint[bytes-1] + 1;
1584 max_val = max_codepoint[bytes];
1586 offset += bytes;
1587 len -= bytes;
1589 /* And verify that they are good continuation bytes */
1590 do {
1591 codepoint <<= 6;
1592 codepoint |= *buf & 0x3f;
1593 if ((*buf++ & 0xc0) != 0x80)
1594 return bad_offset;
1595 } while (--bytes);
1597 /* Reject codepoints that are out of range for the sequence length. */
1598 if (codepoint < min_val || codepoint > max_val)
1599 return bad_offset;
1600 /* Surrogates are only for UTF-16 and cannot be encoded in UTF-8. */
1601 if ((codepoint & 0x1ff800) == 0xd800)
1602 return bad_offset;
1603 /* U+xxFFFE and U+xxFFFF are guaranteed non-characters. */
1604 if ((codepoint & 0xfffe) == 0xfffe)
1605 return bad_offset;
1606 /* So are anything in the range U+FDD0..U+FDEF. */
1607 if (codepoint >= 0xfdd0 && codepoint <= 0xfdef)
1608 return bad_offset;
1610 return -1;
1614 * This verifies that the buffer is in proper utf8 format.
1616 * If it isn't, it assumes any non-utf8 characters are Latin1,
1617 * and does the conversion.
1619 static int verify_utf8(struct strbuf *buf)
1621 int ok = 1;
1622 long pos = 0;
1624 for (;;) {
1625 int bad;
1626 unsigned char c;
1627 unsigned char replace[2];
1629 bad = find_invalid_utf8(buf->buf + pos, buf->len - pos);
1630 if (bad < 0)
1631 return ok;
1632 pos += bad;
1633 ok = 0;
1634 c = buf->buf[pos];
1635 strbuf_remove(buf, pos, 1);
1637 /* We know 'c' must be in the range 128-255 */
1638 replace[0] = 0xc0 + (c >> 6);
1639 replace[1] = 0x80 + (c & 0x3f);
1640 strbuf_insert(buf, pos, replace, 2);
1641 pos += 2;
1645 static const char commit_utf8_warn[] =
1646 N_("Warning: commit message did not conform to UTF-8.\n"
1647 "You may want to amend it after fixing the message, or set the config\n"
1648 "variable i18n.commitEncoding to the encoding your project uses.\n");
1650 static void write_commit_tree(struct strbuf *buffer, const char *msg, size_t msg_len,
1651 const struct object_id *tree,
1652 const struct object_id *parents, size_t parents_len,
1653 const char *author, const char *committer,
1654 const struct commit_extra_header *extra)
1656 int encoding_is_utf8;
1657 size_t i;
1659 /* Not having i18n.commitencoding is the same as having utf-8 */
1660 encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1662 strbuf_grow(buffer, 8192); /* should avoid reallocs for the headers */
1663 strbuf_addf(buffer, "tree %s\n", oid_to_hex(tree));
1666 * NOTE! This ordering means that the same exact tree merged with a
1667 * different order of parents will be a _different_ changeset even
1668 * if everything else stays the same.
1670 for (i = 0; i < parents_len; i++)
1671 strbuf_addf(buffer, "parent %s\n", oid_to_hex(&parents[i]));
1673 /* Person/date information */
1674 if (!author)
1675 author = git_author_info(IDENT_STRICT);
1676 strbuf_addf(buffer, "author %s\n", author);
1677 if (!committer)
1678 committer = git_committer_info(IDENT_STRICT);
1679 strbuf_addf(buffer, "committer %s\n", committer);
1680 if (!encoding_is_utf8)
1681 strbuf_addf(buffer, "encoding %s\n", git_commit_encoding);
1683 while (extra) {
1684 add_extra_header(buffer, extra);
1685 extra = extra->next;
1687 strbuf_addch(buffer, '\n');
1689 /* And add the comment */
1690 strbuf_add(buffer, msg, msg_len);
1693 int commit_tree_extended(const char *msg, size_t msg_len,
1694 const struct object_id *tree,
1695 const struct commit_list *parents, struct object_id *ret,
1696 const char *author, const char *committer,
1697 const char *sign_commit,
1698 const struct commit_extra_header *extra)
1700 struct repository *r = the_repository;
1701 int result = 0;
1702 int encoding_is_utf8;
1703 struct strbuf buffer = STRBUF_INIT, compat_buffer = STRBUF_INIT;
1704 struct strbuf sig = STRBUF_INIT, compat_sig = STRBUF_INIT;
1705 struct object_id *parent_buf = NULL, *compat_oid = NULL;
1706 struct object_id compat_oid_buf;
1707 size_t i, nparents;
1709 /* Not having i18n.commitencoding is the same as having utf-8 */
1710 encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1712 assert_oid_type(tree, OBJ_TREE);
1714 if (memchr(msg, '\0', msg_len))
1715 return error("a NUL byte in commit log message not allowed.");
1717 nparents = commit_list_count(parents);
1718 CALLOC_ARRAY(parent_buf, nparents);
1719 i = 0;
1720 for (const struct commit_list *p = parents; p; p = p->next)
1721 oidcpy(&parent_buf[i++], &p->item->object.oid);
1723 write_commit_tree(&buffer, msg, msg_len, tree, parent_buf, nparents, author, committer, extra);
1724 if (sign_commit && sign_commit_to_strbuf(&sig, &buffer, sign_commit)) {
1725 result = -1;
1726 goto out;
1728 if (r->compat_hash_algo) {
1729 struct commit_extra_header *compat_extra = NULL;
1730 struct object_id mapped_tree;
1731 struct object_id *mapped_parents;
1733 CALLOC_ARRAY(mapped_parents, nparents);
1735 if (repo_oid_to_algop(r, tree, r->compat_hash_algo, &mapped_tree)) {
1736 result = -1;
1737 free(mapped_parents);
1738 goto out;
1740 for (i = 0; i < nparents; i++)
1741 if (repo_oid_to_algop(r, &parent_buf[i], r->compat_hash_algo, &mapped_parents[i])) {
1742 result = -1;
1743 free(mapped_parents);
1744 goto out;
1746 if (convert_commit_extra_headers(extra, &compat_extra)) {
1747 result = -1;
1748 free(mapped_parents);
1749 goto out;
1751 write_commit_tree(&compat_buffer, msg, msg_len, &mapped_tree,
1752 mapped_parents, nparents, author, committer, compat_extra);
1753 free_commit_extra_headers(compat_extra);
1754 free(mapped_parents);
1756 if (sign_commit && sign_commit_to_strbuf(&compat_sig, &compat_buffer, sign_commit)) {
1757 result = -1;
1758 goto out;
1762 if (sign_commit) {
1763 struct sig_pairs {
1764 struct strbuf *sig;
1765 const struct git_hash_algo *algo;
1766 } bufs [2] = {
1767 { &compat_sig, r->compat_hash_algo },
1768 { &sig, r->hash_algo },
1770 int i;
1773 * We write algorithms in the order they were implemented in
1774 * Git to produce a stable hash when multiple algorithms are
1775 * used.
1777 if (r->compat_hash_algo && hash_algo_by_ptr(bufs[0].algo) > hash_algo_by_ptr(bufs[1].algo))
1778 SWAP(bufs[0], bufs[1]);
1781 * We traverse each algorithm in order, and apply the signature
1782 * to each buffer.
1784 for (i = 0; i < ARRAY_SIZE(bufs); i++) {
1785 if (!bufs[i].algo)
1786 continue;
1787 add_header_signature(&buffer, bufs[i].sig, bufs[i].algo);
1788 if (r->compat_hash_algo)
1789 add_header_signature(&compat_buffer, bufs[i].sig, bufs[i].algo);
1793 /* And check the encoding. */
1794 if (encoding_is_utf8 && (!verify_utf8(&buffer) || !verify_utf8(&compat_buffer)))
1795 fprintf(stderr, _(commit_utf8_warn));
1797 if (r->compat_hash_algo) {
1798 hash_object_file(r->compat_hash_algo, compat_buffer.buf, compat_buffer.len,
1799 OBJ_COMMIT, &compat_oid_buf);
1800 compat_oid = &compat_oid_buf;
1803 result = write_object_file_flags(buffer.buf, buffer.len, OBJ_COMMIT,
1804 ret, compat_oid, 0);
1805 out:
1806 free(parent_buf);
1807 strbuf_release(&buffer);
1808 strbuf_release(&compat_buffer);
1809 strbuf_release(&sig);
1810 strbuf_release(&compat_sig);
1811 return result;
1814 define_commit_slab(merge_desc_slab, struct merge_remote_desc *);
1815 static struct merge_desc_slab merge_desc_slab = COMMIT_SLAB_INIT(1, merge_desc_slab);
1817 struct merge_remote_desc *merge_remote_util(const struct commit *commit)
1819 return *merge_desc_slab_at(&merge_desc_slab, commit);
1822 void set_merge_remote_desc(struct commit *commit,
1823 const char *name, struct object *obj)
1825 struct merge_remote_desc *desc;
1826 FLEX_ALLOC_STR(desc, name, name);
1827 desc->obj = obj;
1828 *merge_desc_slab_at(&merge_desc_slab, commit) = desc;
1831 struct commit *get_merge_parent(const char *name)
1833 struct object *obj;
1834 struct commit *commit;
1835 struct object_id oid;
1836 if (repo_get_oid(the_repository, name, &oid))
1837 return NULL;
1838 obj = parse_object(the_repository, &oid);
1839 commit = (struct commit *)repo_peel_to_type(the_repository, name, 0,
1840 obj, OBJ_COMMIT);
1841 if (commit && !merge_remote_util(commit))
1842 set_merge_remote_desc(commit, name, obj);
1843 return commit;
1847 * Append a commit to the end of the commit_list.
1849 * next starts by pointing to the variable that holds the head of an
1850 * empty commit_list, and is updated to point to the "next" field of
1851 * the last item on the list as new commits are appended.
1853 * Usage example:
1855 * struct commit_list *list;
1856 * struct commit_list **next = &list;
1858 * next = commit_list_append(c1, next);
1859 * next = commit_list_append(c2, next);
1860 * assert(commit_list_count(list) == 2);
1861 * return list;
1863 struct commit_list **commit_list_append(struct commit *commit,
1864 struct commit_list **next)
1866 struct commit_list *new_commit = xmalloc(sizeof(struct commit_list));
1867 new_commit->item = commit;
1868 *next = new_commit;
1869 new_commit->next = NULL;
1870 return &new_commit->next;
1873 const char *find_commit_header(const char *msg, const char *key, size_t *out_len)
1875 int key_len = strlen(key);
1876 const char *line = msg;
1878 while (line) {
1879 const char *eol = strchrnul(line, '\n');
1881 if (line == eol)
1882 return NULL;
1884 if (eol - line > key_len &&
1885 !strncmp(line, key, key_len) &&
1886 line[key_len] == ' ') {
1887 *out_len = eol - line - key_len - 1;
1888 return line + key_len + 1;
1890 line = *eol ? eol + 1 : NULL;
1892 return NULL;
1896 * Inspect the given string and determine the true "end" of the log message, in
1897 * order to find where to put a new Signed-off-by trailer. Ignored are
1898 * trailing comment lines and blank lines. To support "git commit -s
1899 * --amend" on an existing commit, we also ignore "Conflicts:". To
1900 * support "git commit -v", we truncate at cut lines.
1902 * Returns the number of bytes from the tail to ignore, to be fed as
1903 * the second parameter to append_signoff().
1905 size_t ignored_log_message_bytes(const char *buf, size_t len)
1907 size_t boc = 0;
1908 size_t bol = 0;
1909 int in_old_conflicts_block = 0;
1910 size_t cutoff = wt_status_locate_end(buf, len);
1912 while (bol < cutoff) {
1913 const char *next_line = memchr(buf + bol, '\n', len - bol);
1915 if (!next_line)
1916 next_line = buf + len;
1917 else
1918 next_line++;
1920 if (starts_with_mem(buf + bol, cutoff - bol, comment_line_str) ||
1921 buf[bol] == '\n') {
1922 /* is this the first of the run of comments? */
1923 if (!boc)
1924 boc = bol;
1925 /* otherwise, it is just continuing */
1926 } else if (starts_with(buf + bol, "Conflicts:\n")) {
1927 in_old_conflicts_block = 1;
1928 if (!boc)
1929 boc = bol;
1930 } else if (in_old_conflicts_block && buf[bol] == '\t') {
1931 ; /* a pathname in the conflicts block */
1932 } else if (boc) {
1933 /* the previous was not trailing comment */
1934 boc = 0;
1935 in_old_conflicts_block = 0;
1937 bol = next_line - buf;
1939 return boc ? len - boc : len - cutoff;
1942 int run_commit_hook(int editor_is_used, const char *index_file,
1943 int *invoked_hook, const char *name, ...)
1945 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1946 va_list args;
1947 const char *arg;
1949 strvec_pushf(&opt.env, "GIT_INDEX_FILE=%s", index_file);
1952 * Let the hook know that no editor will be launched.
1954 if (!editor_is_used)
1955 strvec_push(&opt.env, "GIT_EDITOR=:");
1957 va_start(args, name);
1958 while ((arg = va_arg(args, const char *)))
1959 strvec_push(&opt.args, arg);
1960 va_end(args);
1962 opt.invoked_hook = invoked_hook;
1963 return run_hooks_opt(name, &opt);