refs/files: skip creation of "refs/{heads,tags}" for worktrees
[git.git] / commit.c
blob37956b836cd8e8d006b849ad3168175b85efd17c
1 #include "git-compat-util.h"
2 #include "tag.h"
3 #include "commit.h"
4 #include "commit-graph.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "repository.h"
9 #include "object-name.h"
10 #include "object-store-ll.h"
11 #include "pkt-line.h"
12 #include "utf8.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "notes.h"
16 #include "alloc.h"
17 #include "gpg-interface.h"
18 #include "mergesort.h"
19 #include "commit-slab.h"
20 #include "prio-queue.h"
21 #include "hash-lookup.h"
22 #include "wt-status.h"
23 #include "advice.h"
24 #include "refs.h"
25 #include "commit-reach.h"
26 #include "run-command.h"
27 #include "setup.h"
28 #include "shallow.h"
29 #include "tree.h"
30 #include "hook.h"
31 #include "parse.h"
33 static struct commit_extra_header *read_commit_extra_header_lines(const char *buf, size_t len, const char **);
35 int save_commit_buffer = 1;
36 int no_graft_file_deprecated_advice;
38 const char *commit_type = "commit";
40 struct commit *lookup_commit_reference_gently(struct repository *r,
41 const struct object_id *oid, int quiet)
43 struct object *obj = deref_tag(r,
44 parse_object(r, oid),
45 NULL, 0);
47 if (!obj)
48 return NULL;
49 return object_as_type(obj, OBJ_COMMIT, quiet);
52 struct commit *lookup_commit_reference(struct repository *r, const struct object_id *oid)
54 return lookup_commit_reference_gently(r, oid, 0);
57 struct commit *lookup_commit_or_die(const struct object_id *oid, const char *ref_name)
59 struct commit *c = lookup_commit_reference(the_repository, oid);
60 if (!c)
61 die(_("could not parse %s"), ref_name);
62 if (!oideq(oid, &c->object.oid)) {
63 warning(_("%s %s is not a commit!"),
64 ref_name, oid_to_hex(oid));
66 return c;
69 struct commit *lookup_commit_object(struct repository *r,
70 const struct object_id *oid)
72 struct object *obj = parse_object(r, oid);
73 return obj ? object_as_type(obj, OBJ_COMMIT, 0) : NULL;
77 struct commit *lookup_commit(struct repository *r, const struct object_id *oid)
79 struct object *obj = lookup_object(r, oid);
80 if (!obj)
81 return create_object(r, oid, alloc_commit_node(r));
82 return object_as_type(obj, OBJ_COMMIT, 0);
85 struct commit *lookup_commit_reference_by_name(const char *name)
87 struct object_id oid;
88 struct commit *commit;
90 if (repo_get_oid_committish(the_repository, name, &oid))
91 return NULL;
92 commit = lookup_commit_reference(the_repository, &oid);
93 if (repo_parse_commit(the_repository, commit))
94 return NULL;
95 return commit;
98 static timestamp_t parse_commit_date(const char *buf, const char *tail)
100 const char *dateptr;
101 const char *eol;
103 if (buf + 6 >= tail)
104 return 0;
105 if (memcmp(buf, "author", 6))
106 return 0;
107 while (buf < tail && *buf++ != '\n')
108 /* nada */;
109 if (buf + 9 >= tail)
110 return 0;
111 if (memcmp(buf, "committer", 9))
112 return 0;
115 * Jump to end-of-line so that we can walk backwards to find the
116 * end-of-email ">". This is more forgiving of malformed cases
117 * because unexpected characters tend to be in the name and email
118 * fields.
120 eol = memchr(buf, '\n', tail - buf);
121 if (!eol)
122 return 0;
123 dateptr = eol;
124 while (dateptr > buf && dateptr[-1] != '>')
125 dateptr--;
126 if (dateptr == buf)
127 return 0;
130 * Trim leading whitespace, but make sure we have at least one
131 * non-whitespace character, as parse_timestamp() will otherwise walk
132 * right past the newline we found in "eol" when skipping whitespace
133 * itself.
135 * In theory it would be sufficient to allow any character not matched
136 * by isspace(), but there's a catch: our isspace() does not
137 * necessarily match the behavior of parse_timestamp(), as the latter
138 * is implemented by system routines which match more exotic control
139 * codes, or even locale-dependent sequences.
141 * Since we expect the timestamp to be a number, we can check for that.
142 * Anything else (e.g., a non-numeric token like "foo") would just
143 * cause parse_timestamp() to return 0 anyway.
145 while (dateptr < eol && isspace(*dateptr))
146 dateptr++;
147 if (!isdigit(*dateptr) && *dateptr != '-')
148 return 0;
151 * We know there is at least one digit (or dash), so we'll begin
152 * parsing there and stop at worst case at eol.
154 * Note that we may feed parse_timestamp() extra characters here if the
155 * commit is malformed, and it will parse as far as it can. For
156 * example, "123foo456" would return "123". That might be questionable
157 * (versus returning "0"), but it would help in a hypothetical case
158 * like "123456+0100", where the whitespace from the timezone is
159 * missing. Since such syntactic errors may be baked into history and
160 * hard to correct now, let's err on trying to make our best guess
161 * here, rather than insist on perfect syntax.
163 return parse_timestamp(dateptr, NULL, 10);
166 static const struct object_id *commit_graft_oid_access(size_t index, const void *table)
168 const struct commit_graft * const *commit_graft_table = table;
169 return &commit_graft_table[index]->oid;
172 int commit_graft_pos(struct repository *r, const struct object_id *oid)
174 return oid_pos(oid, r->parsed_objects->grafts,
175 r->parsed_objects->grafts_nr,
176 commit_graft_oid_access);
179 static void unparse_commit(struct repository *r, const struct object_id *oid)
181 struct commit *c = lookup_commit(r, oid);
183 if (!c->object.parsed)
184 return;
185 free_commit_list(c->parents);
186 c->parents = NULL;
187 c->object.parsed = 0;
190 int register_commit_graft(struct repository *r, struct commit_graft *graft,
191 int ignore_dups)
193 int pos = commit_graft_pos(r, &graft->oid);
195 if (0 <= pos) {
196 if (ignore_dups)
197 free(graft);
198 else {
199 free(r->parsed_objects->grafts[pos]);
200 r->parsed_objects->grafts[pos] = graft;
202 return 1;
204 pos = -pos - 1;
205 ALLOC_GROW(r->parsed_objects->grafts,
206 r->parsed_objects->grafts_nr + 1,
207 r->parsed_objects->grafts_alloc);
208 r->parsed_objects->grafts_nr++;
209 if (pos < r->parsed_objects->grafts_nr)
210 memmove(r->parsed_objects->grafts + pos + 1,
211 r->parsed_objects->grafts + pos,
212 (r->parsed_objects->grafts_nr - pos - 1) *
213 sizeof(*r->parsed_objects->grafts));
214 r->parsed_objects->grafts[pos] = graft;
215 unparse_commit(r, &graft->oid);
216 return 0;
219 struct commit_graft *read_graft_line(struct strbuf *line)
221 /* The format is just "Commit Parent1 Parent2 ...\n" */
222 int i, phase;
223 const char *tail = NULL;
224 struct commit_graft *graft = NULL;
225 struct object_id dummy_oid, *oid;
227 strbuf_rtrim(line);
228 if (!line->len || line->buf[0] == '#')
229 return NULL;
231 * phase 0 verifies line, counts hashes in line and allocates graft
232 * phase 1 fills graft
234 for (phase = 0; phase < 2; phase++) {
235 oid = graft ? &graft->oid : &dummy_oid;
236 if (parse_oid_hex(line->buf, oid, &tail))
237 goto bad_graft_data;
238 for (i = 0; *tail != '\0'; i++) {
239 oid = graft ? &graft->parent[i] : &dummy_oid;
240 if (!isspace(*tail++) || parse_oid_hex(tail, oid, &tail))
241 goto bad_graft_data;
243 if (!graft) {
244 graft = xmalloc(st_add(sizeof(*graft),
245 st_mult(sizeof(struct object_id), i)));
246 graft->nr_parent = i;
249 return graft;
251 bad_graft_data:
252 error("bad graft data: %s", line->buf);
253 assert(!graft);
254 return NULL;
257 static int read_graft_file(struct repository *r, const char *graft_file)
259 FILE *fp = fopen_or_warn(graft_file, "r");
260 struct strbuf buf = STRBUF_INIT;
261 if (!fp)
262 return -1;
263 if (!no_graft_file_deprecated_advice &&
264 advice_enabled(ADVICE_GRAFT_FILE_DEPRECATED))
265 advise(_("Support for <GIT_DIR>/info/grafts is deprecated\n"
266 "and will be removed in a future Git version.\n"
267 "\n"
268 "Please use \"git replace --convert-graft-file\"\n"
269 "to convert the grafts into replace refs.\n"
270 "\n"
271 "Turn this message off by running\n"
272 "\"git config advice.graftFileDeprecated false\""));
273 while (!strbuf_getwholeline(&buf, fp, '\n')) {
274 /* The format is just "Commit Parent1 Parent2 ...\n" */
275 struct commit_graft *graft = read_graft_line(&buf);
276 if (!graft)
277 continue;
278 if (register_commit_graft(r, graft, 1))
279 error("duplicate graft data: %s", buf.buf);
281 fclose(fp);
282 strbuf_release(&buf);
283 return 0;
286 void prepare_commit_graft(struct repository *r)
288 char *graft_file;
290 if (r->parsed_objects->commit_graft_prepared)
291 return;
292 if (!startup_info->have_repository)
293 return;
295 graft_file = get_graft_file(r);
296 read_graft_file(r, graft_file);
297 /* make sure shallows are read */
298 is_repository_shallow(r);
299 r->parsed_objects->commit_graft_prepared = 1;
302 struct commit_graft *lookup_commit_graft(struct repository *r, const struct object_id *oid)
304 int pos;
305 prepare_commit_graft(r);
306 pos = commit_graft_pos(r, oid);
307 if (pos < 0)
308 return NULL;
309 return r->parsed_objects->grafts[pos];
312 int for_each_commit_graft(each_commit_graft_fn fn, void *cb_data)
314 int i, ret;
315 for (i = ret = 0; i < the_repository->parsed_objects->grafts_nr && !ret; i++)
316 ret = fn(the_repository->parsed_objects->grafts[i], cb_data);
317 return ret;
320 void reset_commit_grafts(struct repository *r)
322 int i;
324 for (i = 0; i < r->parsed_objects->grafts_nr; i++) {
325 unparse_commit(r, &r->parsed_objects->grafts[i]->oid);
326 free(r->parsed_objects->grafts[i]);
328 r->parsed_objects->grafts_nr = 0;
329 r->parsed_objects->commit_graft_prepared = 0;
332 struct commit_buffer {
333 void *buffer;
334 unsigned long size;
336 define_commit_slab(buffer_slab, struct commit_buffer);
338 struct buffer_slab *allocate_commit_buffer_slab(void)
340 struct buffer_slab *bs = xmalloc(sizeof(*bs));
341 init_buffer_slab(bs);
342 return bs;
345 void free_commit_buffer_slab(struct buffer_slab *bs)
347 clear_buffer_slab(bs);
348 free(bs);
351 void set_commit_buffer(struct repository *r, struct commit *commit, void *buffer, unsigned long size)
353 struct commit_buffer *v = buffer_slab_at(
354 r->parsed_objects->buffer_slab, commit);
355 v->buffer = buffer;
356 v->size = size;
359 const void *get_cached_commit_buffer(struct repository *r, const struct commit *commit, unsigned long *sizep)
361 struct commit_buffer *v = buffer_slab_peek(
362 r->parsed_objects->buffer_slab, commit);
363 if (!v) {
364 if (sizep)
365 *sizep = 0;
366 return NULL;
368 if (sizep)
369 *sizep = v->size;
370 return v->buffer;
373 const void *repo_get_commit_buffer(struct repository *r,
374 const struct commit *commit,
375 unsigned long *sizep)
377 const void *ret = get_cached_commit_buffer(r, commit, sizep);
378 if (!ret) {
379 enum object_type type;
380 unsigned long size;
381 ret = repo_read_object_file(r, &commit->object.oid, &type, &size);
382 if (!ret)
383 die("cannot read commit object %s",
384 oid_to_hex(&commit->object.oid));
385 if (type != OBJ_COMMIT)
386 die("expected commit for %s, got %s",
387 oid_to_hex(&commit->object.oid), type_name(type));
388 if (sizep)
389 *sizep = size;
391 return ret;
394 void repo_unuse_commit_buffer(struct repository *r,
395 const struct commit *commit,
396 const void *buffer)
398 struct commit_buffer *v = buffer_slab_peek(
399 r->parsed_objects->buffer_slab, commit);
400 if (!(v && v->buffer == buffer))
401 free((void *)buffer);
404 void free_commit_buffer(struct parsed_object_pool *pool, struct commit *commit)
406 struct commit_buffer *v = buffer_slab_peek(
407 pool->buffer_slab, commit);
408 if (v) {
409 FREE_AND_NULL(v->buffer);
410 v->size = 0;
414 static inline void set_commit_tree(struct commit *c, struct tree *t)
416 c->maybe_tree = t;
419 struct tree *repo_get_commit_tree(struct repository *r,
420 const struct commit *commit)
422 if (commit->maybe_tree || !commit->object.parsed)
423 return commit->maybe_tree;
425 if (commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
426 return get_commit_tree_in_graph(r, commit);
428 return NULL;
431 struct object_id *get_commit_tree_oid(const struct commit *commit)
433 struct tree *tree = repo_get_commit_tree(the_repository, commit);
434 return tree ? &tree->object.oid : NULL;
437 void release_commit_memory(struct parsed_object_pool *pool, struct commit *c)
439 set_commit_tree(c, NULL);
440 free_commit_buffer(pool, c);
441 c->index = 0;
442 free_commit_list(c->parents);
444 c->object.parsed = 0;
447 const void *detach_commit_buffer(struct commit *commit, unsigned long *sizep)
449 struct commit_buffer *v = buffer_slab_peek(
450 the_repository->parsed_objects->buffer_slab, commit);
451 void *ret;
453 if (!v) {
454 if (sizep)
455 *sizep = 0;
456 return NULL;
458 ret = v->buffer;
459 if (sizep)
460 *sizep = v->size;
462 v->buffer = NULL;
463 v->size = 0;
464 return ret;
467 int parse_commit_buffer(struct repository *r, struct commit *item, const void *buffer, unsigned long size, int check_graph)
469 const char *tail = buffer;
470 const char *bufptr = buffer;
471 struct object_id parent;
472 struct commit_list **pptr;
473 struct commit_graft *graft;
474 const int tree_entry_len = the_hash_algo->hexsz + 5;
475 const int parent_entry_len = the_hash_algo->hexsz + 7;
476 struct tree *tree;
478 if (item->object.parsed)
479 return 0;
481 * Presumably this is leftover from an earlier failed parse;
482 * clear it out in preparation for us re-parsing (we'll hit the
483 * same error, but that's good, since it lets our caller know
484 * the result cannot be trusted.
486 free_commit_list(item->parents);
487 item->parents = NULL;
489 tail += size;
490 if (tail <= bufptr + tree_entry_len + 1 || memcmp(bufptr, "tree ", 5) ||
491 bufptr[tree_entry_len] != '\n')
492 return error("bogus commit object %s", oid_to_hex(&item->object.oid));
493 if (get_oid_hex(bufptr + 5, &parent) < 0)
494 return error("bad tree pointer in commit %s",
495 oid_to_hex(&item->object.oid));
496 tree = lookup_tree(r, &parent);
497 if (!tree)
498 return error("bad tree pointer %s in commit %s",
499 oid_to_hex(&parent),
500 oid_to_hex(&item->object.oid));
501 set_commit_tree(item, tree);
502 bufptr += tree_entry_len + 1; /* "tree " + "hex sha1" + "\n" */
503 pptr = &item->parents;
505 graft = lookup_commit_graft(r, &item->object.oid);
506 if (graft)
507 r->parsed_objects->substituted_parent = 1;
508 while (bufptr + parent_entry_len < tail && !memcmp(bufptr, "parent ", 7)) {
509 struct commit *new_parent;
511 if (tail <= bufptr + parent_entry_len + 1 ||
512 get_oid_hex(bufptr + 7, &parent) ||
513 bufptr[parent_entry_len] != '\n')
514 return error("bad parents in commit %s", oid_to_hex(&item->object.oid));
515 bufptr += parent_entry_len + 1;
517 * The clone is shallow if nr_parent < 0, and we must
518 * not traverse its real parents even when we unhide them.
520 if (graft && (graft->nr_parent < 0 || !grafts_keep_true_parents))
521 continue;
522 new_parent = lookup_commit(r, &parent);
523 if (!new_parent)
524 return error("bad parent %s in commit %s",
525 oid_to_hex(&parent),
526 oid_to_hex(&item->object.oid));
527 pptr = &commit_list_insert(new_parent, pptr)->next;
529 if (graft) {
530 int i;
531 struct commit *new_parent;
532 for (i = 0; i < graft->nr_parent; i++) {
533 new_parent = lookup_commit(r,
534 &graft->parent[i]);
535 if (!new_parent)
536 return error("bad graft parent %s in commit %s",
537 oid_to_hex(&graft->parent[i]),
538 oid_to_hex(&item->object.oid));
539 pptr = &commit_list_insert(new_parent, pptr)->next;
542 item->date = parse_commit_date(bufptr, tail);
544 if (check_graph)
545 load_commit_graph_info(r, item);
547 item->object.parsed = 1;
548 return 0;
551 int repo_parse_commit_internal(struct repository *r,
552 struct commit *item,
553 int quiet_on_missing,
554 int use_commit_graph)
556 enum object_type type;
557 void *buffer;
558 unsigned long size;
559 struct object_info oi = {
560 .typep = &type,
561 .sizep = &size,
562 .contentp = &buffer,
565 * Git does not support partial clones that exclude commits, so set
566 * OBJECT_INFO_SKIP_FETCH_OBJECT to fail fast when an object is missing.
568 int flags = OBJECT_INFO_LOOKUP_REPLACE | OBJECT_INFO_SKIP_FETCH_OBJECT |
569 OBJECT_INFO_DIE_IF_CORRUPT;
570 int ret;
572 if (!item)
573 return -1;
574 if (item->object.parsed)
575 return 0;
576 if (use_commit_graph && parse_commit_in_graph(r, item)) {
577 static int commit_graph_paranoia = -1;
579 if (commit_graph_paranoia == -1)
580 commit_graph_paranoia = git_env_bool(GIT_COMMIT_GRAPH_PARANOIA, 0);
582 if (commit_graph_paranoia && !has_object(r, &item->object.oid, 0)) {
583 unparse_commit(r, &item->object.oid);
584 return quiet_on_missing ? -1 :
585 error(_("commit %s exists in commit-graph but not in the object database"),
586 oid_to_hex(&item->object.oid));
589 return 0;
592 if (oid_object_info_extended(r, &item->object.oid, &oi, flags) < 0)
593 return quiet_on_missing ? -1 :
594 error("Could not read %s",
595 oid_to_hex(&item->object.oid));
596 if (type != OBJ_COMMIT) {
597 free(buffer);
598 return error("Object %s not a commit",
599 oid_to_hex(&item->object.oid));
602 ret = parse_commit_buffer(r, item, buffer, size, 0);
603 if (save_commit_buffer && !ret) {
604 set_commit_buffer(r, item, buffer, size);
605 return 0;
607 free(buffer);
608 return ret;
611 int repo_parse_commit_gently(struct repository *r,
612 struct commit *item, int quiet_on_missing)
614 return repo_parse_commit_internal(r, item, quiet_on_missing, 1);
617 void parse_commit_or_die(struct commit *item)
619 if (repo_parse_commit(the_repository, item))
620 die("unable to parse commit %s",
621 item ? oid_to_hex(&item->object.oid) : "(null)");
624 int find_commit_subject(const char *commit_buffer, const char **subject)
626 const char *eol;
627 const char *p = commit_buffer;
629 while (*p && (*p != '\n' || p[1] != '\n'))
630 p++;
631 if (*p) {
632 p = skip_blank_lines(p + 2);
633 eol = strchrnul(p, '\n');
634 } else
635 eol = p;
637 *subject = p;
639 return eol - p;
642 size_t commit_subject_length(const char *body)
644 const char *p = body;
645 while (*p) {
646 const char *next = skip_blank_lines(p);
647 if (next != p)
648 break;
649 p = strchrnul(p, '\n');
650 if (*p)
651 p++;
653 return p - body;
656 struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
658 struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
659 new_list->item = item;
660 new_list->next = *list_p;
661 *list_p = new_list;
662 return new_list;
665 int commit_list_contains(struct commit *item, struct commit_list *list)
667 while (list) {
668 if (list->item == item)
669 return 1;
670 list = list->next;
673 return 0;
676 unsigned commit_list_count(const struct commit_list *l)
678 unsigned c = 0;
679 for (; l; l = l->next )
680 c++;
681 return c;
684 struct commit_list *copy_commit_list(struct commit_list *list)
686 struct commit_list *head = NULL;
687 struct commit_list **pp = &head;
688 while (list) {
689 pp = commit_list_append(list->item, pp);
690 list = list->next;
692 return head;
695 struct commit_list *reverse_commit_list(struct commit_list *list)
697 struct commit_list *next = NULL, *current, *backup;
698 for (current = list; current; current = backup) {
699 backup = current->next;
700 current->next = next;
701 next = current;
703 return next;
706 void free_commit_list(struct commit_list *list)
708 while (list)
709 pop_commit(&list);
712 struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
714 struct commit_list **pp = list;
715 struct commit_list *p;
716 while ((p = *pp) != NULL) {
717 if (p->item->date < item->date) {
718 break;
720 pp = &p->next;
722 return commit_list_insert(item, pp);
725 static int commit_list_compare_by_date(const struct commit_list *a,
726 const struct commit_list *b)
728 timestamp_t a_date = a->item->date;
729 timestamp_t b_date = b->item->date;
730 if (a_date < b_date)
731 return 1;
732 if (a_date > b_date)
733 return -1;
734 return 0;
737 DEFINE_LIST_SORT(static, commit_list_sort, struct commit_list, next);
739 void commit_list_sort_by_date(struct commit_list **list)
741 commit_list_sort(list, commit_list_compare_by_date);
744 struct commit *pop_most_recent_commit(struct commit_list **list,
745 unsigned int mark)
747 struct commit *ret = pop_commit(list);
748 struct commit_list *parents = ret->parents;
750 while (parents) {
751 struct commit *commit = parents->item;
752 if (!repo_parse_commit(the_repository, commit) && !(commit->object.flags & mark)) {
753 commit->object.flags |= mark;
754 commit_list_insert_by_date(commit, list);
756 parents = parents->next;
758 return ret;
761 static void clear_commit_marks_1(struct commit_list **plist,
762 struct commit *commit, unsigned int mark)
764 while (commit) {
765 struct commit_list *parents;
767 if (!(mark & commit->object.flags))
768 return;
770 commit->object.flags &= ~mark;
772 parents = commit->parents;
773 if (!parents)
774 return;
776 while ((parents = parents->next)) {
777 if (parents->item->object.flags & mark)
778 commit_list_insert(parents->item, plist);
781 commit = commit->parents->item;
785 void clear_commit_marks_many(int nr, struct commit **commit, unsigned int mark)
787 struct commit_list *list = NULL;
789 while (nr--) {
790 clear_commit_marks_1(&list, *commit, mark);
791 commit++;
793 while (list)
794 clear_commit_marks_1(&list, pop_commit(&list), mark);
797 void clear_commit_marks(struct commit *commit, unsigned int mark)
799 clear_commit_marks_many(1, &commit, mark);
802 struct commit *pop_commit(struct commit_list **stack)
804 struct commit_list *top = *stack;
805 struct commit *item = top ? top->item : NULL;
807 if (top) {
808 *stack = top->next;
809 free(top);
811 return item;
815 * Topological sort support
818 /* count number of children that have not been emitted */
819 define_commit_slab(indegree_slab, int);
821 define_commit_slab(author_date_slab, timestamp_t);
823 void record_author_date(struct author_date_slab *author_date,
824 struct commit *commit)
826 const char *buffer = repo_get_commit_buffer(the_repository, commit,
827 NULL);
828 struct ident_split ident;
829 const char *ident_line;
830 size_t ident_len;
831 char *date_end;
832 timestamp_t date;
834 ident_line = find_commit_header(buffer, "author", &ident_len);
835 if (!ident_line)
836 goto fail_exit; /* no author line */
837 if (split_ident_line(&ident, ident_line, ident_len) ||
838 !ident.date_begin || !ident.date_end)
839 goto fail_exit; /* malformed "author" line */
841 date = parse_timestamp(ident.date_begin, &date_end, 10);
842 if (date_end != ident.date_end)
843 goto fail_exit; /* malformed date */
844 *(author_date_slab_at(author_date, commit)) = date;
846 fail_exit:
847 repo_unuse_commit_buffer(the_repository, commit, buffer);
850 int compare_commits_by_author_date(const void *a_, const void *b_,
851 void *cb_data)
853 const struct commit *a = a_, *b = b_;
854 struct author_date_slab *author_date = cb_data;
855 timestamp_t a_date = *(author_date_slab_at(author_date, a));
856 timestamp_t b_date = *(author_date_slab_at(author_date, b));
858 /* newer commits with larger date first */
859 if (a_date < b_date)
860 return 1;
861 else if (a_date > b_date)
862 return -1;
863 return 0;
866 int compare_commits_by_gen_then_commit_date(const void *a_, const void *b_,
867 void *unused UNUSED)
869 const struct commit *a = a_, *b = b_;
870 const timestamp_t generation_a = commit_graph_generation(a),
871 generation_b = commit_graph_generation(b);
873 /* newer commits first */
874 if (generation_a < generation_b)
875 return 1;
876 else if (generation_a > generation_b)
877 return -1;
879 /* use date as a heuristic when generations are equal */
880 if (a->date < b->date)
881 return 1;
882 else if (a->date > b->date)
883 return -1;
884 return 0;
887 int compare_commits_by_commit_date(const void *a_, const void *b_,
888 void *unused UNUSED)
890 const struct commit *a = a_, *b = b_;
891 /* newer commits with larger date first */
892 if (a->date < b->date)
893 return 1;
894 else if (a->date > b->date)
895 return -1;
896 return 0;
900 * Performs an in-place topological sort on the list supplied.
902 void sort_in_topological_order(struct commit_list **list, enum rev_sort_order sort_order)
904 struct commit_list *next, *orig = *list;
905 struct commit_list **pptr;
906 struct indegree_slab indegree;
907 struct prio_queue queue;
908 struct commit *commit;
909 struct author_date_slab author_date;
911 if (!orig)
912 return;
913 *list = NULL;
915 init_indegree_slab(&indegree);
916 memset(&queue, '\0', sizeof(queue));
918 switch (sort_order) {
919 default: /* REV_SORT_IN_GRAPH_ORDER */
920 queue.compare = NULL;
921 break;
922 case REV_SORT_BY_COMMIT_DATE:
923 queue.compare = compare_commits_by_commit_date;
924 break;
925 case REV_SORT_BY_AUTHOR_DATE:
926 init_author_date_slab(&author_date);
927 queue.compare = compare_commits_by_author_date;
928 queue.cb_data = &author_date;
929 break;
932 /* Mark them and clear the indegree */
933 for (next = orig; next; next = next->next) {
934 struct commit *commit = next->item;
935 *(indegree_slab_at(&indegree, commit)) = 1;
936 /* also record the author dates, if needed */
937 if (sort_order == REV_SORT_BY_AUTHOR_DATE)
938 record_author_date(&author_date, commit);
941 /* update the indegree */
942 for (next = orig; next; next = next->next) {
943 struct commit_list *parents = next->item->parents;
944 while (parents) {
945 struct commit *parent = parents->item;
946 int *pi = indegree_slab_at(&indegree, parent);
948 if (*pi)
949 (*pi)++;
950 parents = parents->next;
955 * find the tips
957 * tips are nodes not reachable from any other node in the list
959 * the tips serve as a starting set for the work queue.
961 for (next = orig; next; next = next->next) {
962 struct commit *commit = next->item;
964 if (*(indegree_slab_at(&indegree, commit)) == 1)
965 prio_queue_put(&queue, commit);
969 * This is unfortunate; the initial tips need to be shown
970 * in the order given from the revision traversal machinery.
972 if (sort_order == REV_SORT_IN_GRAPH_ORDER)
973 prio_queue_reverse(&queue);
975 /* We no longer need the commit list */
976 free_commit_list(orig);
978 pptr = list;
979 *list = NULL;
980 while ((commit = prio_queue_get(&queue)) != NULL) {
981 struct commit_list *parents;
983 for (parents = commit->parents; parents ; parents = parents->next) {
984 struct commit *parent = parents->item;
985 int *pi = indegree_slab_at(&indegree, parent);
987 if (!*pi)
988 continue;
991 * parents are only enqueued for emission
992 * when all their children have been emitted thereby
993 * guaranteeing topological order.
995 if (--(*pi) == 1)
996 prio_queue_put(&queue, parent);
999 * all children of commit have already been
1000 * emitted. we can emit it now.
1002 *(indegree_slab_at(&indegree, commit)) = 0;
1004 pptr = &commit_list_insert(commit, pptr)->next;
1007 clear_indegree_slab(&indegree);
1008 clear_prio_queue(&queue);
1009 if (sort_order == REV_SORT_BY_AUTHOR_DATE)
1010 clear_author_date_slab(&author_date);
1013 struct rev_collect {
1014 struct commit **commit;
1015 int nr;
1016 int alloc;
1017 unsigned int initial : 1;
1020 static void add_one_commit(struct object_id *oid, struct rev_collect *revs)
1022 struct commit *commit;
1024 if (is_null_oid(oid))
1025 return;
1027 commit = lookup_commit(the_repository, oid);
1028 if (!commit ||
1029 (commit->object.flags & TMP_MARK) ||
1030 repo_parse_commit(the_repository, commit))
1031 return;
1033 ALLOC_GROW(revs->commit, revs->nr + 1, revs->alloc);
1034 revs->commit[revs->nr++] = commit;
1035 commit->object.flags |= TMP_MARK;
1038 static int collect_one_reflog_ent(struct object_id *ooid, struct object_id *noid,
1039 const char *ident UNUSED,
1040 timestamp_t timestamp UNUSED, int tz UNUSED,
1041 const char *message UNUSED, void *cbdata)
1043 struct rev_collect *revs = cbdata;
1045 if (revs->initial) {
1046 revs->initial = 0;
1047 add_one_commit(ooid, revs);
1049 add_one_commit(noid, revs);
1050 return 0;
1053 struct commit *get_fork_point(const char *refname, struct commit *commit)
1055 struct object_id oid;
1056 struct rev_collect revs;
1057 struct commit_list *bases;
1058 int i;
1059 struct commit *ret = NULL;
1060 char *full_refname;
1062 switch (repo_dwim_ref(the_repository, refname, strlen(refname), &oid,
1063 &full_refname, 0)) {
1064 case 0:
1065 die("No such ref: '%s'", refname);
1066 case 1:
1067 break; /* good */
1068 default:
1069 die("Ambiguous refname: '%s'", refname);
1072 memset(&revs, 0, sizeof(revs));
1073 revs.initial = 1;
1074 for_each_reflog_ent(full_refname, collect_one_reflog_ent, &revs);
1076 if (!revs.nr)
1077 add_one_commit(&oid, &revs);
1079 for (i = 0; i < revs.nr; i++)
1080 revs.commit[i]->object.flags &= ~TMP_MARK;
1082 bases = repo_get_merge_bases_many(the_repository, commit, revs.nr,
1083 revs.commit);
1086 * There should be one and only one merge base, when we found
1087 * a common ancestor among reflog entries.
1089 if (!bases || bases->next)
1090 goto cleanup_return;
1092 /* And the found one must be one of the reflog entries */
1093 for (i = 0; i < revs.nr; i++)
1094 if (&bases->item->object == &revs.commit[i]->object)
1095 break; /* found */
1096 if (revs.nr <= i)
1097 goto cleanup_return;
1099 ret = bases->item;
1101 cleanup_return:
1102 free(revs.commit);
1103 free_commit_list(bases);
1104 free(full_refname);
1105 return ret;
1109 * Indexed by hash algorithm identifier.
1111 static const char *gpg_sig_headers[] = {
1112 NULL,
1113 "gpgsig",
1114 "gpgsig-sha256",
1117 int sign_with_header(struct strbuf *buf, const char *keyid)
1119 struct strbuf sig = STRBUF_INIT;
1120 int inspos, copypos;
1121 const char *eoh;
1122 const char *gpg_sig_header = gpg_sig_headers[hash_algo_by_ptr(the_hash_algo)];
1123 int gpg_sig_header_len = strlen(gpg_sig_header);
1125 /* find the end of the header */
1126 eoh = strstr(buf->buf, "\n\n");
1127 if (!eoh)
1128 inspos = buf->len;
1129 else
1130 inspos = eoh - buf->buf + 1;
1132 if (!keyid || !*keyid)
1133 keyid = get_signing_key();
1134 if (sign_buffer(buf, &sig, keyid)) {
1135 strbuf_release(&sig);
1136 return -1;
1139 for (copypos = 0; sig.buf[copypos]; ) {
1140 const char *bol = sig.buf + copypos;
1141 const char *eol = strchrnul(bol, '\n');
1142 int len = (eol - bol) + !!*eol;
1144 if (!copypos) {
1145 strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
1146 inspos += gpg_sig_header_len;
1148 strbuf_insertstr(buf, inspos++, " ");
1149 strbuf_insert(buf, inspos, bol, len);
1150 inspos += len;
1151 copypos += len;
1153 strbuf_release(&sig);
1154 return 0;
1159 int parse_signed_commit(const struct commit *commit,
1160 struct strbuf *payload, struct strbuf *signature,
1161 const struct git_hash_algo *algop)
1163 unsigned long size;
1164 const char *buffer = repo_get_commit_buffer(the_repository, commit,
1165 &size);
1166 int ret = parse_buffer_signed_by_header(buffer, size, payload, signature, algop);
1168 repo_unuse_commit_buffer(the_repository, commit, buffer);
1169 return ret;
1172 int parse_buffer_signed_by_header(const char *buffer,
1173 unsigned long size,
1174 struct strbuf *payload,
1175 struct strbuf *signature,
1176 const struct git_hash_algo *algop)
1178 int in_signature = 0, saw_signature = 0, other_signature = 0;
1179 const char *line, *tail, *p;
1180 const char *gpg_sig_header = gpg_sig_headers[hash_algo_by_ptr(algop)];
1182 line = buffer;
1183 tail = buffer + size;
1184 while (line < tail) {
1185 const char *sig = NULL;
1186 const char *next = memchr(line, '\n', tail - line);
1188 next = next ? next + 1 : tail;
1189 if (in_signature && line[0] == ' ')
1190 sig = line + 1;
1191 else if (skip_prefix(line, gpg_sig_header, &p) &&
1192 *p == ' ') {
1193 sig = line + strlen(gpg_sig_header) + 1;
1194 other_signature = 0;
1196 else if (starts_with(line, "gpgsig"))
1197 other_signature = 1;
1198 else if (other_signature && line[0] != ' ')
1199 other_signature = 0;
1200 if (sig) {
1201 strbuf_add(signature, sig, next - sig);
1202 saw_signature = 1;
1203 in_signature = 1;
1204 } else {
1205 if (*line == '\n')
1206 /* dump the whole remainder of the buffer */
1207 next = tail;
1208 if (!other_signature)
1209 strbuf_add(payload, line, next - line);
1210 in_signature = 0;
1212 line = next;
1214 return saw_signature;
1217 int remove_signature(struct strbuf *buf)
1219 const char *line = buf->buf;
1220 const char *tail = buf->buf + buf->len;
1221 int in_signature = 0;
1222 struct sigbuf {
1223 const char *start;
1224 const char *end;
1225 } sigs[2], *sigp = &sigs[0];
1226 int i;
1227 const char *orig_buf = buf->buf;
1229 memset(sigs, 0, sizeof(sigs));
1231 while (line < tail) {
1232 const char *next = memchr(line, '\n', tail - line);
1233 next = next ? next + 1 : tail;
1235 if (in_signature && line[0] == ' ')
1236 sigp->end = next;
1237 else if (starts_with(line, "gpgsig")) {
1238 int i;
1239 for (i = 1; i < GIT_HASH_NALGOS; i++) {
1240 const char *p;
1241 if (skip_prefix(line, gpg_sig_headers[i], &p) &&
1242 *p == ' ') {
1243 sigp->start = line;
1244 sigp->end = next;
1245 in_signature = 1;
1248 } else {
1249 if (*line == '\n')
1250 /* dump the whole remainder of the buffer */
1251 next = tail;
1252 if (in_signature && sigp - sigs != ARRAY_SIZE(sigs))
1253 sigp++;
1254 in_signature = 0;
1256 line = next;
1259 for (i = ARRAY_SIZE(sigs) - 1; i >= 0; i--)
1260 if (sigs[i].start)
1261 strbuf_remove(buf, sigs[i].start - orig_buf, sigs[i].end - sigs[i].start);
1263 return sigs[0].start != NULL;
1266 static void handle_signed_tag(struct commit *parent, struct commit_extra_header ***tail)
1268 struct merge_remote_desc *desc;
1269 struct commit_extra_header *mergetag;
1270 char *buf;
1271 unsigned long size;
1272 enum object_type type;
1273 struct strbuf payload = STRBUF_INIT;
1274 struct strbuf signature = STRBUF_INIT;
1276 desc = merge_remote_util(parent);
1277 if (!desc || !desc->obj)
1278 return;
1279 buf = repo_read_object_file(the_repository, &desc->obj->oid, &type,
1280 &size);
1281 if (!buf || type != OBJ_TAG)
1282 goto free_return;
1283 if (!parse_signature(buf, size, &payload, &signature))
1284 goto free_return;
1286 * We could verify this signature and either omit the tag when
1287 * it does not validate, but the integrator may not have the
1288 * public key of the signer of the tag being merged, while a
1289 * later auditor may have it while auditing, so let's not run
1290 * verify-signed-buffer here for now...
1292 * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
1293 * warn("warning: signed tag unverified.");
1295 CALLOC_ARRAY(mergetag, 1);
1296 mergetag->key = xstrdup("mergetag");
1297 mergetag->value = buf;
1298 mergetag->len = size;
1300 **tail = mergetag;
1301 *tail = &mergetag->next;
1302 strbuf_release(&payload);
1303 strbuf_release(&signature);
1304 return;
1306 free_return:
1307 free(buf);
1310 int check_commit_signature(const struct commit *commit, struct signature_check *sigc)
1312 struct strbuf payload = STRBUF_INIT;
1313 struct strbuf signature = STRBUF_INIT;
1314 int ret = 1;
1316 sigc->result = 'N';
1318 if (parse_signed_commit(commit, &payload, &signature, the_hash_algo) <= 0)
1319 goto out;
1321 sigc->payload_type = SIGNATURE_PAYLOAD_COMMIT;
1322 sigc->payload = strbuf_detach(&payload, &sigc->payload_len);
1323 ret = check_signature(sigc, signature.buf, signature.len);
1325 out:
1326 strbuf_release(&payload);
1327 strbuf_release(&signature);
1329 return ret;
1332 void verify_merge_signature(struct commit *commit, int verbosity,
1333 int check_trust)
1335 char hex[GIT_MAX_HEXSZ + 1];
1336 struct signature_check signature_check;
1337 int ret;
1338 memset(&signature_check, 0, sizeof(signature_check));
1340 ret = check_commit_signature(commit, &signature_check);
1342 repo_find_unique_abbrev_r(the_repository, hex, &commit->object.oid,
1343 DEFAULT_ABBREV);
1344 switch (signature_check.result) {
1345 case 'G':
1346 if (ret || (check_trust && signature_check.trust_level < TRUST_MARGINAL))
1347 die(_("Commit %s has an untrusted GPG signature, "
1348 "allegedly by %s."), hex, signature_check.signer);
1349 break;
1350 case 'B':
1351 die(_("Commit %s has a bad GPG signature "
1352 "allegedly by %s."), hex, signature_check.signer);
1353 default: /* 'N' */
1354 die(_("Commit %s does not have a GPG signature."), hex);
1356 if (verbosity >= 0 && signature_check.result == 'G')
1357 printf(_("Commit %s has a good GPG signature by %s\n"),
1358 hex, signature_check.signer);
1360 signature_check_clear(&signature_check);
1363 void append_merge_tag_headers(struct commit_list *parents,
1364 struct commit_extra_header ***tail)
1366 while (parents) {
1367 struct commit *parent = parents->item;
1368 handle_signed_tag(parent, tail);
1369 parents = parents->next;
1373 static void add_extra_header(struct strbuf *buffer,
1374 struct commit_extra_header *extra)
1376 strbuf_addstr(buffer, extra->key);
1377 if (extra->len)
1378 strbuf_add_lines(buffer, " ", extra->value, extra->len);
1379 else
1380 strbuf_addch(buffer, '\n');
1383 struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
1384 const char **exclude)
1386 struct commit_extra_header *extra = NULL;
1387 unsigned long size;
1388 const char *buffer = repo_get_commit_buffer(the_repository, commit,
1389 &size);
1390 extra = read_commit_extra_header_lines(buffer, size, exclude);
1391 repo_unuse_commit_buffer(the_repository, commit, buffer);
1392 return extra;
1395 int for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
1397 struct commit_extra_header *extra, *to_free;
1398 int res = 0;
1400 to_free = read_commit_extra_headers(commit, NULL);
1401 for (extra = to_free; !res && extra; extra = extra->next) {
1402 if (strcmp(extra->key, "mergetag"))
1403 continue; /* not a merge tag */
1404 res = fn(commit, extra, data);
1406 free_commit_extra_headers(to_free);
1407 return res;
1410 static inline int standard_header_field(const char *field, size_t len)
1412 return ((len == 4 && !memcmp(field, "tree", 4)) ||
1413 (len == 6 && !memcmp(field, "parent", 6)) ||
1414 (len == 6 && !memcmp(field, "author", 6)) ||
1415 (len == 9 && !memcmp(field, "committer", 9)) ||
1416 (len == 8 && !memcmp(field, "encoding", 8)));
1419 static int excluded_header_field(const char *field, size_t len, const char **exclude)
1421 if (!exclude)
1422 return 0;
1424 while (*exclude) {
1425 size_t xlen = strlen(*exclude);
1426 if (len == xlen && !memcmp(field, *exclude, xlen))
1427 return 1;
1428 exclude++;
1430 return 0;
1433 static struct commit_extra_header *read_commit_extra_header_lines(
1434 const char *buffer, size_t size,
1435 const char **exclude)
1437 struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
1438 const char *line, *next, *eof, *eob;
1439 struct strbuf buf = STRBUF_INIT;
1441 for (line = buffer, eob = line + size;
1442 line < eob && *line != '\n';
1443 line = next) {
1444 next = memchr(line, '\n', eob - line);
1445 next = next ? next + 1 : eob;
1446 if (*line == ' ') {
1447 /* continuation */
1448 if (it)
1449 strbuf_add(&buf, line + 1, next - (line + 1));
1450 continue;
1452 if (it)
1453 it->value = strbuf_detach(&buf, &it->len);
1454 strbuf_reset(&buf);
1455 it = NULL;
1457 eof = memchr(line, ' ', next - line);
1458 if (!eof)
1459 eof = next;
1460 else if (standard_header_field(line, eof - line) ||
1461 excluded_header_field(line, eof - line, exclude))
1462 continue;
1464 CALLOC_ARRAY(it, 1);
1465 it->key = xmemdupz(line, eof-line);
1466 *tail = it;
1467 tail = &it->next;
1468 if (eof + 1 < next)
1469 strbuf_add(&buf, eof + 1, next - (eof + 1));
1471 if (it)
1472 it->value = strbuf_detach(&buf, &it->len);
1473 return extra;
1476 void free_commit_extra_headers(struct commit_extra_header *extra)
1478 while (extra) {
1479 struct commit_extra_header *next = extra->next;
1480 free(extra->key);
1481 free(extra->value);
1482 free(extra);
1483 extra = next;
1487 int commit_tree(const char *msg, size_t msg_len, const struct object_id *tree,
1488 struct commit_list *parents, struct object_id *ret,
1489 const char *author, const char *sign_commit)
1491 struct commit_extra_header *extra = NULL, **tail = &extra;
1492 int result;
1494 append_merge_tag_headers(parents, &tail);
1495 result = commit_tree_extended(msg, msg_len, tree, parents, ret, author,
1496 NULL, sign_commit, extra);
1497 free_commit_extra_headers(extra);
1498 return result;
1501 static int find_invalid_utf8(const char *buf, int len)
1503 int offset = 0;
1504 static const unsigned int max_codepoint[] = {
1505 0x7f, 0x7ff, 0xffff, 0x10ffff
1508 while (len) {
1509 unsigned char c = *buf++;
1510 int bytes, bad_offset;
1511 unsigned int codepoint;
1512 unsigned int min_val, max_val;
1514 len--;
1515 offset++;
1517 /* Simple US-ASCII? No worries. */
1518 if (c < 0x80)
1519 continue;
1521 bad_offset = offset-1;
1524 * Count how many more high bits set: that's how
1525 * many more bytes this sequence should have.
1527 bytes = 0;
1528 while (c & 0x40) {
1529 c <<= 1;
1530 bytes++;
1534 * Must be between 1 and 3 more bytes. Longer sequences result in
1535 * codepoints beyond U+10FFFF, which are guaranteed never to exist.
1537 if (bytes < 1 || 3 < bytes)
1538 return bad_offset;
1540 /* Do we *have* that many bytes? */
1541 if (len < bytes)
1542 return bad_offset;
1545 * Place the encoded bits at the bottom of the value and compute the
1546 * valid range.
1548 codepoint = (c & 0x7f) >> bytes;
1549 min_val = max_codepoint[bytes-1] + 1;
1550 max_val = max_codepoint[bytes];
1552 offset += bytes;
1553 len -= bytes;
1555 /* And verify that they are good continuation bytes */
1556 do {
1557 codepoint <<= 6;
1558 codepoint |= *buf & 0x3f;
1559 if ((*buf++ & 0xc0) != 0x80)
1560 return bad_offset;
1561 } while (--bytes);
1563 /* Reject codepoints that are out of range for the sequence length. */
1564 if (codepoint < min_val || codepoint > max_val)
1565 return bad_offset;
1566 /* Surrogates are only for UTF-16 and cannot be encoded in UTF-8. */
1567 if ((codepoint & 0x1ff800) == 0xd800)
1568 return bad_offset;
1569 /* U+xxFFFE and U+xxFFFF are guaranteed non-characters. */
1570 if ((codepoint & 0xfffe) == 0xfffe)
1571 return bad_offset;
1572 /* So are anything in the range U+FDD0..U+FDEF. */
1573 if (codepoint >= 0xfdd0 && codepoint <= 0xfdef)
1574 return bad_offset;
1576 return -1;
1580 * This verifies that the buffer is in proper utf8 format.
1582 * If it isn't, it assumes any non-utf8 characters are Latin1,
1583 * and does the conversion.
1585 static int verify_utf8(struct strbuf *buf)
1587 int ok = 1;
1588 long pos = 0;
1590 for (;;) {
1591 int bad;
1592 unsigned char c;
1593 unsigned char replace[2];
1595 bad = find_invalid_utf8(buf->buf + pos, buf->len - pos);
1596 if (bad < 0)
1597 return ok;
1598 pos += bad;
1599 ok = 0;
1600 c = buf->buf[pos];
1601 strbuf_remove(buf, pos, 1);
1603 /* We know 'c' must be in the range 128-255 */
1604 replace[0] = 0xc0 + (c >> 6);
1605 replace[1] = 0x80 + (c & 0x3f);
1606 strbuf_insert(buf, pos, replace, 2);
1607 pos += 2;
1611 static const char commit_utf8_warn[] =
1612 N_("Warning: commit message did not conform to UTF-8.\n"
1613 "You may want to amend it after fixing the message, or set the config\n"
1614 "variable i18n.commitEncoding to the encoding your project uses.\n");
1616 int commit_tree_extended(const char *msg, size_t msg_len,
1617 const struct object_id *tree,
1618 struct commit_list *parents, struct object_id *ret,
1619 const char *author, const char *committer,
1620 const char *sign_commit,
1621 struct commit_extra_header *extra)
1623 int result;
1624 int encoding_is_utf8;
1625 struct strbuf buffer;
1627 assert_oid_type(tree, OBJ_TREE);
1629 if (memchr(msg, '\0', msg_len))
1630 return error("a NUL byte in commit log message not allowed.");
1632 /* Not having i18n.commitencoding is the same as having utf-8 */
1633 encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);
1635 strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */
1636 strbuf_addf(&buffer, "tree %s\n", oid_to_hex(tree));
1639 * NOTE! This ordering means that the same exact tree merged with a
1640 * different order of parents will be a _different_ changeset even
1641 * if everything else stays the same.
1643 while (parents) {
1644 struct commit *parent = pop_commit(&parents);
1645 strbuf_addf(&buffer, "parent %s\n",
1646 oid_to_hex(&parent->object.oid));
1649 /* Person/date information */
1650 if (!author)
1651 author = git_author_info(IDENT_STRICT);
1652 strbuf_addf(&buffer, "author %s\n", author);
1653 if (!committer)
1654 committer = git_committer_info(IDENT_STRICT);
1655 strbuf_addf(&buffer, "committer %s\n", committer);
1656 if (!encoding_is_utf8)
1657 strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding);
1659 while (extra) {
1660 add_extra_header(&buffer, extra);
1661 extra = extra->next;
1663 strbuf_addch(&buffer, '\n');
1665 /* And add the comment */
1666 strbuf_add(&buffer, msg, msg_len);
1668 /* And check the encoding */
1669 if (encoding_is_utf8 && !verify_utf8(&buffer))
1670 fprintf(stderr, _(commit_utf8_warn));
1672 if (sign_commit && sign_with_header(&buffer, sign_commit)) {
1673 result = -1;
1674 goto out;
1677 result = write_object_file(buffer.buf, buffer.len, OBJ_COMMIT, ret);
1678 out:
1679 strbuf_release(&buffer);
1680 return result;
1683 define_commit_slab(merge_desc_slab, struct merge_remote_desc *);
1684 static struct merge_desc_slab merge_desc_slab = COMMIT_SLAB_INIT(1, merge_desc_slab);
1686 struct merge_remote_desc *merge_remote_util(struct commit *commit)
1688 return *merge_desc_slab_at(&merge_desc_slab, commit);
1691 void set_merge_remote_desc(struct commit *commit,
1692 const char *name, struct object *obj)
1694 struct merge_remote_desc *desc;
1695 FLEX_ALLOC_STR(desc, name, name);
1696 desc->obj = obj;
1697 *merge_desc_slab_at(&merge_desc_slab, commit) = desc;
1700 struct commit *get_merge_parent(const char *name)
1702 struct object *obj;
1703 struct commit *commit;
1704 struct object_id oid;
1705 if (repo_get_oid(the_repository, name, &oid))
1706 return NULL;
1707 obj = parse_object(the_repository, &oid);
1708 commit = (struct commit *)repo_peel_to_type(the_repository, name, 0,
1709 obj, OBJ_COMMIT);
1710 if (commit && !merge_remote_util(commit))
1711 set_merge_remote_desc(commit, name, obj);
1712 return commit;
1716 * Append a commit to the end of the commit_list.
1718 * next starts by pointing to the variable that holds the head of an
1719 * empty commit_list, and is updated to point to the "next" field of
1720 * the last item on the list as new commits are appended.
1722 * Usage example:
1724 * struct commit_list *list;
1725 * struct commit_list **next = &list;
1727 * next = commit_list_append(c1, next);
1728 * next = commit_list_append(c2, next);
1729 * assert(commit_list_count(list) == 2);
1730 * return list;
1732 struct commit_list **commit_list_append(struct commit *commit,
1733 struct commit_list **next)
1735 struct commit_list *new_commit = xmalloc(sizeof(struct commit_list));
1736 new_commit->item = commit;
1737 *next = new_commit;
1738 new_commit->next = NULL;
1739 return &new_commit->next;
1742 const char *find_header_mem(const char *msg, size_t len,
1743 const char *key, size_t *out_len)
1745 int key_len = strlen(key);
1746 const char *line = msg;
1749 * NEEDSWORK: It's possible for strchrnul() to scan beyond the range
1750 * given by len. However, current callers are safe because they compute
1751 * len by scanning a NUL-terminated block of memory starting at msg.
1752 * Nonetheless, it would be better to ensure the function does not look
1753 * at msg beyond the len provided by the caller.
1755 while (line && line < msg + len) {
1756 const char *eol = strchrnul(line, '\n');
1758 if (line == eol)
1759 return NULL;
1761 if (eol - line > key_len &&
1762 !strncmp(line, key, key_len) &&
1763 line[key_len] == ' ') {
1764 *out_len = eol - line - key_len - 1;
1765 return line + key_len + 1;
1767 line = *eol ? eol + 1 : NULL;
1769 return NULL;
1772 const char *find_commit_header(const char *msg, const char *key, size_t *out_len)
1774 return find_header_mem(msg, strlen(msg), key, out_len);
1777 * Inspect the given string and determine the true "end" of the log message, in
1778 * order to find where to put a new Signed-off-by trailer. Ignored are
1779 * trailing comment lines and blank lines. To support "git commit -s
1780 * --amend" on an existing commit, we also ignore "Conflicts:". To
1781 * support "git commit -v", we truncate at cut lines.
1783 * Returns the number of bytes from the tail to ignore, to be fed as
1784 * the second parameter to append_signoff().
1786 size_t ignore_non_trailer(const char *buf, size_t len)
1788 size_t boc = 0;
1789 size_t bol = 0;
1790 int in_old_conflicts_block = 0;
1791 size_t cutoff = wt_status_locate_end(buf, len);
1793 while (bol < cutoff) {
1794 const char *next_line = memchr(buf + bol, '\n', len - bol);
1796 if (!next_line)
1797 next_line = buf + len;
1798 else
1799 next_line++;
1801 if (buf[bol] == comment_line_char || buf[bol] == '\n') {
1802 /* is this the first of the run of comments? */
1803 if (!boc)
1804 boc = bol;
1805 /* otherwise, it is just continuing */
1806 } else if (starts_with(buf + bol, "Conflicts:\n")) {
1807 in_old_conflicts_block = 1;
1808 if (!boc)
1809 boc = bol;
1810 } else if (in_old_conflicts_block && buf[bol] == '\t') {
1811 ; /* a pathname in the conflicts block */
1812 } else if (boc) {
1813 /* the previous was not trailing comment */
1814 boc = 0;
1815 in_old_conflicts_block = 0;
1817 bol = next_line - buf;
1819 return boc ? len - boc : len - cutoff;
1822 int run_commit_hook(int editor_is_used, const char *index_file,
1823 int *invoked_hook, const char *name, ...)
1825 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1826 va_list args;
1827 const char *arg;
1829 strvec_pushf(&opt.env, "GIT_INDEX_FILE=%s", index_file);
1832 * Let the hook know that no editor will be launched.
1834 if (!editor_is_used)
1835 strvec_push(&opt.env, "GIT_EDITOR=:");
1837 va_start(args, name);
1838 while ((arg = va_arg(args, const char *)))
1839 strvec_push(&opt.args, arg);
1840 va_end(args);
1842 opt.invoked_hook = invoked_hook;
1843 return run_hooks_opt(name, &opt);