commit.c 41.0 KB
Newer Older
1
#include "cache.h"
2
#include "tag.h"
3
#include "commit.h"
4
#include "pkt-line.h"
J
Junio C Hamano 已提交
5
#include "utf8.h"
J
Junio C Hamano 已提交
6 7
#include "diff.h"
#include "revision.h"
J
Johannes Schindelin 已提交
8
#include "notes.h"
J
Junio C Hamano 已提交
9
#include "gpg-interface.h"
10
#include "mergesort.h"
11
#include "commit-slab.h"
12
#include "prio-queue.h"
13
#include "sha1-lookup.h"
14
#include "wt-status.h"
15

16 17
static struct commit_extra_header *read_commit_extra_header_lines(const char *buf, size_t len, const char **);

18 19
int save_commit_buffer = 1;

20 21
const char *commit_type = "commit";

22
struct commit *lookup_commit_reference_gently(const struct object_id *oid,
J
Junio C Hamano 已提交
23
					      int quiet)
24
{
25
	struct object *obj = deref_tag(parse_object(oid), NULL, 0);
26 27 28

	if (!obj)
		return NULL;
29
	return object_as_type(obj, OBJ_COMMIT, quiet);
J
Junio C Hamano 已提交
30 31
}

32
struct commit *lookup_commit_reference(const struct object_id *oid)
J
Junio C Hamano 已提交
33
{
34
	return lookup_commit_reference_gently(oid, 0);
35 36
}

37
struct commit *lookup_commit_or_die(const struct object_id *oid, const char *ref_name)
38
{
39
	struct commit *c = lookup_commit_reference(oid);
40 41
	if (!c)
		die(_("could not parse %s"), ref_name);
42
	if (oidcmp(oid, &c->object.oid)) {
43
		warning(_("%s %s is not a commit!"),
44
			ref_name, oid_to_hex(oid));
45 46 47 48
	}
	return c;
}

49
struct commit *lookup_commit(const struct object_id *oid)
50
{
51
	struct object *obj = lookup_object(oid->hash);
52
	if (!obj)
53
		return create_object(oid->hash, alloc_commit_node());
54
	return object_as_type(obj, OBJ_COMMIT, 0);
55 56
}

57 58
struct commit *lookup_commit_reference_by_name(const char *name)
{
59
	struct object_id oid;
60 61
	struct commit *commit;

62
	if (get_oid_committish(name, &oid))
63
		return NULL;
64
	commit = lookup_commit_reference(&oid);
65
	if (parse_commit(commit))
66 67 68 69
		return NULL;
	return commit;
}

70
static timestamp_t parse_commit_date(const char *buf, const char *tail)
71
{
72
	const char *dateptr;
73

74 75
	if (buf + 6 >= tail)
		return 0;
76 77
	if (memcmp(buf, "author", 6))
		return 0;
78
	while (buf < tail && *buf++ != '\n')
79
		/* nada */;
80 81
	if (buf + 9 >= tail)
		return 0;
82 83
	if (memcmp(buf, "committer", 9))
		return 0;
84
	while (buf < tail && *buf++ != '>')
85
		/* nada */;
86 87 88 89 90 91 92
	if (buf >= tail)
		return 0;
	dateptr = buf;
	while (buf < tail && *buf++ != '\n')
		/* nada */;
	if (buf >= tail)
		return 0;
93 94
	/* dateptr < buf && buf[-1] == '\n', so parsing will stop at buf-1 */
	return parse_timestamp(dateptr, NULL, 10);
95 96
}

J
Junio C Hamano 已提交
97
static struct commit_graft **commit_graft;
98 99
static int commit_graft_alloc, commit_graft_nr;

100 101 102
static const unsigned char *commit_graft_sha1_access(size_t index, void *table)
{
	struct commit_graft **commit_graft_table = table;
103
	return commit_graft_table[index]->oid.hash;
104 105
}

106 107
static int commit_graft_pos(const unsigned char *sha1)
{
108 109
	return sha1_pos(sha1, commit_graft, commit_graft_nr,
			commit_graft_sha1_access);
110 111
}

J
Junio C Hamano 已提交
112 113
int register_commit_graft(struct commit_graft *graft, int ignore_dups)
{
114
	int pos = commit_graft_pos(graft->oid.hash);
J
Junio C Hamano 已提交
115

J
Junio C Hamano 已提交
116 117 118 119 120 121 122 123 124 125
	if (0 <= pos) {
		if (ignore_dups)
			free(graft);
		else {
			free(commit_graft[pos]);
			commit_graft[pos] = graft;
		}
		return 1;
	}
	pos = -pos - 1;
126 127
	ALLOC_GROW(commit_graft, commit_graft_nr + 1, commit_graft_alloc);
	commit_graft_nr++;
J
Junio C Hamano 已提交
128 129 130 131 132 133 134 135 136
	if (pos < commit_graft_nr)
		memmove(commit_graft + pos + 1,
			commit_graft + pos,
			(commit_graft_nr - pos - 1) *
			sizeof(*commit_graft));
	commit_graft[pos] = graft;
	return 0;
}

137
struct commit_graft *read_graft_line(struct strbuf *line)
J
Junio C Hamano 已提交
138 139
{
	/* The format is just "Commit Parent1 Parent2 ...\n" */
P
Patryk Obara 已提交
140 141
	int i, phase;
	const char *tail = NULL;
J
Junio C Hamano 已提交
142
	struct commit_graft *graft = NULL;
P
Patryk Obara 已提交
143
	struct object_id dummy_oid, *oid;
J
Junio C Hamano 已提交
144

145 146
	strbuf_rtrim(line);
	if (!line->len || line->buf[0] == '#')
147
		return NULL;
P
Patryk Obara 已提交
148 149 150 151 152 153 154
	/*
	 * phase 0 verifies line, counts hashes in line and allocates graft
	 * phase 1 fills graft
	 */
	for (phase = 0; phase < 2; phase++) {
		oid = graft ? &graft->oid : &dummy_oid;
		if (parse_oid_hex(line->buf, oid, &tail))
J
Junio C Hamano 已提交
155
			goto bad_graft_data;
P
Patryk Obara 已提交
156 157 158 159 160 161 162 163 164 165
		for (i = 0; *tail != '\0'; i++) {
			oid = graft ? &graft->parent[i] : &dummy_oid;
			if (!isspace(*tail++) || parse_oid_hex(tail, oid, &tail))
				goto bad_graft_data;
		}
		if (!graft) {
			graft = xmalloc(st_add(sizeof(*graft),
					       st_mult(sizeof(struct object_id), i)));
			graft->nr_parent = i;
		}
J
Junio C Hamano 已提交
166 167
	}
	return graft;
168 169

bad_graft_data:
170
	error("bad graft data: %s", line->buf);
P
Patryk Obara 已提交
171
	assert(!graft);
172
	return NULL;
J
Junio C Hamano 已提交
173 174
}

175
static int read_graft_file(const char *graft_file)
176
{
177
	FILE *fp = fopen_or_warn(graft_file, "r");
178
	struct strbuf buf = STRBUF_INIT;
J
Junio C Hamano 已提交
179 180
	if (!fp)
		return -1;
181
	while (!strbuf_getwholeline(&buf, fp, '\n')) {
182
		/* The format is just "Commit Parent1 Parent2 ...\n" */
183
		struct commit_graft *graft = read_graft_line(&buf);
184 185
		if (!graft)
			continue;
J
Junio C Hamano 已提交
186
		if (register_commit_graft(graft, 1))
187
			error("duplicate graft data: %s", buf.buf);
188 189
	}
	fclose(fp);
190
	strbuf_release(&buf);
J
Junio C Hamano 已提交
191 192 193 194 195 196 197 198 199 200 201 202
	return 0;
}

static void prepare_commit_graft(void)
{
	static int commit_graft_prepared;
	char *graft_file;

	if (commit_graft_prepared)
		return;
	graft_file = get_graft_file();
	read_graft_file(graft_file);
203 204
	/* make sure shallows are read */
	is_repository_shallow();
J
Junio C Hamano 已提交
205
	commit_graft_prepared = 1;
206 207
}

208
struct commit_graft *lookup_commit_graft(const struct object_id *oid)
209 210
{
	int pos;
J
Junio C Hamano 已提交
211
	prepare_commit_graft();
212
	pos = commit_graft_pos(oid->hash);
213 214 215 216 217
	if (pos < 0)
		return NULL;
	return commit_graft[pos];
}

218
int for_each_commit_graft(each_commit_graft_fn fn, void *cb_data)
219
{
220 221 222 223
	int i, ret;
	for (i = ret = 0; i < commit_graft_nr && !ret; i++)
		ret = fn(commit_graft[i], cb_data);
	return ret;
224 225
}

226
int unregister_shallow(const struct object_id *oid)
227
{
228
	int pos = commit_graft_pos(oid->hash);
229 230 231
	if (pos < 0)
		return -1;
	if (pos + 1 < commit_graft_nr)
R
René Scharfe 已提交
232 233
		MOVE_ARRAY(commit_graft + pos, commit_graft + pos + 1,
			   commit_graft_nr - pos - 1);
234 235 236 237
	commit_graft_nr--;
	return 0;
}

238 239 240 241 242
struct commit_buffer {
	void *buffer;
	unsigned long size;
};
define_commit_slab(buffer_slab, struct commit_buffer);
243 244
static struct buffer_slab buffer_slab = COMMIT_SLAB_INIT(1, buffer_slab);

245
void set_commit_buffer(struct commit *commit, void *buffer, unsigned long size)
246
{
247 248 249
	struct commit_buffer *v = buffer_slab_at(&buffer_slab, commit);
	v->buffer = buffer;
	v->size = size;
250 251
}

252
const void *get_cached_commit_buffer(const struct commit *commit, unsigned long *sizep)
253
{
254 255 256 257 258 259
	struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
	if (!v) {
		if (sizep)
			*sizep = 0;
		return NULL;
	}
260 261 262
	if (sizep)
		*sizep = v->size;
	return v->buffer;
263 264
}

265
const void *get_commit_buffer(const struct commit *commit, unsigned long *sizep)
266
{
267
	const void *ret = get_cached_commit_buffer(commit, sizep);
268 269 270
	if (!ret) {
		enum object_type type;
		unsigned long size;
B
brian m. carlson 已提交
271
		ret = read_sha1_file(commit->object.oid.hash, &type, &size);
272 273
		if (!ret)
			die("cannot read commit object %s",
274
			    oid_to_hex(&commit->object.oid));
275 276
		if (type != OBJ_COMMIT)
			die("expected commit for %s, got %s",
277
			    oid_to_hex(&commit->object.oid), typename(type));
278 279
		if (sizep)
			*sizep = size;
280 281 282 283 284 285
	}
	return ret;
}

void unuse_commit_buffer(const struct commit *commit, const void *buffer)
{
286 287
	struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
	if (!(v && v->buffer == buffer))
288 289 290
		free((void *)buffer);
}

291 292
void free_commit_buffer(struct commit *commit)
{
293 294
	struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
	if (v) {
295
		FREE_AND_NULL(v->buffer);
296 297
		v->size = 0;
	}
298 299
}

300
const void *detach_commit_buffer(struct commit *commit, unsigned long *sizep)
301
{
302
	struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
303 304
	void *ret;

305 306 307 308 309
	if (!v) {
		if (sizep)
			*sizep = 0;
		return NULL;
	}
310 311 312 313 314 315
	ret = v->buffer;
	if (sizep)
		*sizep = v->size;

	v->buffer = NULL;
	v->size = 0;
316 317 318
	return ret;
}

319
int parse_commit_buffer(struct commit *item, const void *buffer, unsigned long size)
320
{
321 322
	const char *tail = buffer;
	const char *bufptr = buffer;
323
	struct object_id parent;
324
	struct commit_list **pptr;
325
	struct commit_graft *graft;
326 327
	const int tree_entry_len = GIT_SHA1_HEXSZ + 5;
	const int parent_entry_len = GIT_SHA1_HEXSZ + 7;
328

329 330 331
	if (item->object.parsed)
		return 0;
	item->object.parsed = 1;
332
	tail += size;
333 334
	if (tail <= bufptr + tree_entry_len + 1 || memcmp(bufptr, "tree ", 5) ||
			bufptr[tree_entry_len] != '\n')
335
		return error("bogus commit object %s", oid_to_hex(&item->object.oid));
336
	if (get_sha1_hex(bufptr + 5, parent.hash) < 0)
337
		return error("bad tree pointer in commit %s",
338
			     oid_to_hex(&item->object.oid));
339
	item->tree = lookup_tree(&parent);
340
	bufptr += tree_entry_len + 1; /* "tree " + "hex sha1" + "\n" */
341
	pptr = &item->parents;
342

343
	graft = lookup_commit_graft(&item->object.oid);
344
	while (bufptr + parent_entry_len < tail && !memcmp(bufptr, "parent ", 7)) {
345 346
		struct commit *new_parent;

347 348 349
		if (tail <= bufptr + parent_entry_len + 1 ||
		    get_sha1_hex(bufptr + 7, parent.hash) ||
		    bufptr[parent_entry_len] != '\n')
350
			return error("bad parents in commit %s", oid_to_hex(&item->object.oid));
351
		bufptr += parent_entry_len + 1;
352 353 354 355 356
		/*
		 * The clone is shallow if nr_parent < 0, and we must
		 * not traverse its real parents even when we unhide them.
		 */
		if (graft && (graft->nr_parent < 0 || grafts_replace_parents))
357
			continue;
358
		new_parent = lookup_commit(&parent);
359
		if (new_parent)
360
			pptr = &commit_list_insert(new_parent, pptr)->next;
361 362 363 364 365
	}
	if (graft) {
		int i;
		struct commit *new_parent;
		for (i = 0; i < graft->nr_parent; i++) {
366
			new_parent = lookup_commit(&graft->parent[i]);
367 368 369 370
			if (!new_parent)
				continue;
			pptr = &commit_list_insert(new_parent, pptr)->next;
		}
371
	}
372
	item->date = parse_commit_date(bufptr, tail);
J
Junio C Hamano 已提交
373

374 375 376
	return 0;
}

377
int parse_commit_gently(struct commit *item, int quiet_on_missing)
378
{
379
	enum object_type type;
380 381 382 383
	void *buffer;
	unsigned long size;
	int ret;

384 385
	if (!item)
		return -1;
386 387
	if (item->object.parsed)
		return 0;
B
brian m. carlson 已提交
388
	buffer = read_sha1_file(item->object.oid.hash, &type, &size);
389
	if (!buffer)
390 391
		return quiet_on_missing ? -1 :
			error("Could not read %s",
392
			     oid_to_hex(&item->object.oid));
393
	if (type != OBJ_COMMIT) {
394 395
		free(buffer);
		return error("Object %s not a commit",
396
			     oid_to_hex(&item->object.oid));
397 398
	}
	ret = parse_commit_buffer(item, buffer, size);
399
	if (save_commit_buffer && !ret) {
400
		set_commit_buffer(item, buffer, size);
401 402
		return 0;
	}
403 404 405 406
	free(buffer);
	return ret;
}

407 408 409 410
void parse_commit_or_die(struct commit *item)
{
	if (parse_commit(item))
		die("unable to parse commit %s",
411
		    item ? oid_to_hex(&item->object.oid) : "(null)");
412 413
}

414 415 416 417 418 419 420 421
int find_commit_subject(const char *commit_buffer, const char **subject)
{
	const char *eol;
	const char *p = commit_buffer;

	while (*p && (*p != '\n' || p[1] != '\n'))
		p++;
	if (*p) {
422
		p = skip_blank_lines(p + 2);
423
		eol = strchrnul(p, '\n');
424 425 426 427 428 429 430 431
	} else
		eol = p;

	*subject = p;

	return eol - p;
}

432
struct commit_list *commit_list_insert(struct commit *item, struct commit_list **list_p)
433
{
434
	struct commit_list *new_list = xmalloc(sizeof(struct commit_list));
435 436 437
	new_list->item = item;
	new_list->next = *list_p;
	*list_p = new_list;
438
	return new_list;
439 440
}

441 442 443 444 445 446 447 448
unsigned commit_list_count(const struct commit_list *l)
{
	unsigned c = 0;
	for (; l; l = l->next )
		c++;
	return c;
}

449 450 451 452 453
struct commit_list *copy_commit_list(struct commit_list *list)
{
	struct commit_list *head = NULL;
	struct commit_list **pp = &head;
	while (list) {
454
		pp = commit_list_append(list->item, pp);
455 456 457 458 459
		list = list->next;
	}
	return head;
}

460 461
void free_commit_list(struct commit_list *list)
{
462 463
	while (list)
		pop_commit(&list);
464
}
465

466
struct commit_list * commit_list_insert_by_date(struct commit *item, struct commit_list **list)
467 468 469 470 471 472 473 474 475
{
	struct commit_list **pp = list;
	struct commit_list *p;
	while ((p = *pp) != NULL) {
		if (p->item->date < item->date) {
			break;
		}
		pp = &p->next;
	}
476
	return commit_list_insert(item, pp);
477 478
}

479 480
static int commit_list_compare_by_date(const void *a, const void *b)
{
481 482
	timestamp_t a_date = ((const struct commit_list *)a)->item->date;
	timestamp_t b_date = ((const struct commit_list *)b)->item->date;
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
	if (a_date < b_date)
		return 1;
	if (a_date > b_date)
		return -1;
	return 0;
}

static void *commit_list_get_next(const void *a)
{
	return ((const struct commit_list *)a)->next;
}

static void commit_list_set_next(void *a, void *next)
{
	((struct commit_list *)a)->next = next;
}
J
Junio C Hamano 已提交
499

500
void commit_list_sort_by_date(struct commit_list **list)
501
{
502 503
	*list = llist_mergesort(*list, commit_list_get_next, commit_list_set_next,
				commit_list_compare_by_date);
504 505
}

506 507
struct commit *pop_most_recent_commit(struct commit_list **list,
				      unsigned int mark)
508
{
509
	struct commit *ret = pop_commit(list);
510 511 512
	struct commit_list *parents = ret->parents;

	while (parents) {
513
		struct commit *commit = parents->item;
514
		if (!parse_commit(commit) && !(commit->object.flags & mark)) {
515
			commit->object.flags |= mark;
516
			commit_list_insert_by_date(commit, list);
517
		}
518 519 520 521
		parents = parents->next;
	}
	return ret;
}
522

523 524
static void clear_commit_marks_1(struct commit_list **plist,
				 struct commit *commit, unsigned int mark)
525
{
526 527
	while (commit) {
		struct commit_list *parents;
528

529 530
		if (!(mark & commit->object.flags))
			return;
J
Junio C Hamano 已提交
531

532 533 534 535 536 537 538
		commit->object.flags &= ~mark;

		parents = commit->parents;
		if (!parents)
			return;

		while ((parents = parents->next))
539
			commit_list_insert(parents->item, plist);
540 541

		commit = commit->parents->item;
542 543 544
	}
}

545
void clear_commit_marks_many(int nr, struct commit **commit, unsigned int mark)
546 547
{
	struct commit_list *list = NULL;
548 549 550 551 552

	while (nr--) {
		commit_list_insert(*commit, &list);
		commit++;
	}
553 554 555 556
	while (list)
		clear_commit_marks_1(&list, pop_commit(&list), mark);
}

557 558 559 560 561
void clear_commit_marks(struct commit *commit, unsigned int mark)
{
	clear_commit_marks_many(1, &commit, mark);
}

562 563 564 565 566 567 568 569
void clear_commit_marks_for_object_array(struct object_array *a, unsigned mark)
{
	struct object *object;
	struct commit *commit;
	unsigned int i;

	for (i = 0; i < a->nr; i++) {
		object = a->objects[i].item;
570
		commit = lookup_commit_reference_gently(&object->oid, 1);
571 572 573 574 575
		if (commit)
			clear_commit_marks(commit, mark);
	}
}

576 577 578 579 580 581 582 583 584 585 586 587
struct commit *pop_commit(struct commit_list **stack)
{
	struct commit_list *top = *stack;
	struct commit *item = top ? top->item : NULL;

	if (top) {
		*stack = top->next;
		free(top);
	}
	return item;
}

588 589 590
/*
 * Topological sort support
 */
591

592 593
/* count number of children that have not been emitted */
define_commit_slab(indegree_slab, int);
594

J
Junio C Hamano 已提交
595 596 597 598 599 600
/* record author-date for each commit object */
define_commit_slab(author_date_slab, unsigned long);

static void record_author_date(struct author_date_slab *author_date,
			       struct commit *commit)
{
601
	const char *buffer = get_commit_buffer(commit, NULL);
J
Junio C Hamano 已提交
602
	struct ident_split ident;
603 604
	const char *ident_line;
	size_t ident_len;
J
Junio C Hamano 已提交
605
	char *date_end;
606
	timestamp_t date;
J
Junio C Hamano 已提交
607

608 609 610 611 612 613
	ident_line = find_commit_header(buffer, "author", &ident_len);
	if (!ident_line)
		goto fail_exit; /* no author line */
	if (split_ident_line(&ident, ident_line, ident_len) ||
	    !ident.date_begin || !ident.date_end)
		goto fail_exit; /* malformed "author" line */
J
Junio C Hamano 已提交
614

615
	date = parse_timestamp(ident.date_begin, &date_end, 10);
J
Junio C Hamano 已提交
616 617 618 619 620
	if (date_end != ident.date_end)
		goto fail_exit; /* malformed date */
	*(author_date_slab_at(author_date, commit)) = date;

fail_exit:
621
	unuse_commit_buffer(commit, buffer);
J
Junio C Hamano 已提交
622 623 624 625 626 627 628
}

static int compare_commits_by_author_date(const void *a_, const void *b_,
					  void *cb_data)
{
	const struct commit *a = a_, *b = b_;
	struct author_date_slab *author_date = cb_data;
629 630
	timestamp_t a_date = *(author_date_slab_at(author_date, a));
	timestamp_t b_date = *(author_date_slab_at(author_date, b));
J
Junio C Hamano 已提交
631 632 633 634 635 636 637 638 639

	/* newer commits with larger date first */
	if (a_date < b_date)
		return 1;
	else if (a_date > b_date)
		return -1;
	return 0;
}

640
int compare_commits_by_commit_date(const void *a_, const void *b_, void *unused)
641 642 643 644 645 646 647 648 649 650
{
	const struct commit *a = a_, *b = b_;
	/* newer commits with larger date first */
	if (a->date < b->date)
		return 1;
	else if (a->date > b->date)
		return -1;
	return 0;
}

651 652 653
/*
 * Performs an in-place topological sort on the list supplied.
 */
654
void sort_in_topological_order(struct commit_list **list, enum rev_sort_order sort_order)
655
{
L
Linus Torvalds 已提交
656 657
	struct commit_list *next, *orig = *list;
	struct commit_list **pptr;
658
	struct indegree_slab indegree;
659 660
	struct prio_queue queue;
	struct commit *commit;
J
Junio C Hamano 已提交
661
	struct author_date_slab author_date;
J
Junio C Hamano 已提交
662

L
Linus Torvalds 已提交
663
	if (!orig)
664
		return;
L
Linus Torvalds 已提交
665 666
	*list = NULL;

667
	init_indegree_slab(&indegree);
668
	memset(&queue, '\0', sizeof(queue));
J
Junio C Hamano 已提交
669

670 671 672 673 674 675 676
	switch (sort_order) {
	default: /* REV_SORT_IN_GRAPH_ORDER */
		queue.compare = NULL;
		break;
	case REV_SORT_BY_COMMIT_DATE:
		queue.compare = compare_commits_by_commit_date;
		break;
J
Junio C Hamano 已提交
677 678 679 680 681
	case REV_SORT_BY_AUTHOR_DATE:
		init_author_date_slab(&author_date);
		queue.compare = compare_commits_by_author_date;
		queue.cb_data = &author_date;
		break;
682
	}
683

L
Linus Torvalds 已提交
684 685 686
	/* Mark them and clear the indegree */
	for (next = orig; next; next = next->next) {
		struct commit *commit = next->item;
687
		*(indegree_slab_at(&indegree, commit)) = 1;
J
Junio C Hamano 已提交
688 689 690
		/* also record the author dates, if needed */
		if (sort_order == REV_SORT_BY_AUTHOR_DATE)
			record_author_date(&author_date, commit);
691
	}
L
Linus Torvalds 已提交
692

693
	/* update the indegree */
L
Linus Torvalds 已提交
694
	for (next = orig; next; next = next->next) {
695
		struct commit_list *parents = next->item->parents;
696
		while (parents) {
L
Linus Torvalds 已提交
697
			struct commit *parent = parents->item;
698
			int *pi = indegree_slab_at(&indegree, parent);
699

700 701
			if (*pi)
				(*pi)++;
L
Linus Torvalds 已提交
702
			parents = parents->next;
703 704
		}
	}
L
Linus Torvalds 已提交
705

J
Junio C Hamano 已提交
706
	/*
707 708 709 710 711 712
	 * find the tips
	 *
	 * tips are nodes not reachable from any other node in the list
	 *
	 * the tips serve as a starting set for the work queue.
	 */
L
Linus Torvalds 已提交
713 714
	for (next = orig; next; next = next->next) {
		struct commit *commit = next->item;
715

716
		if (*(indegree_slab_at(&indegree, commit)) == 1)
717
			prio_queue_put(&queue, commit);
718
	}
719

720 721 722 723 724 725 726 727 728
	/*
	 * This is unfortunate; the initial tips need to be shown
	 * in the order given from the revision traversal machinery.
	 */
	if (sort_order == REV_SORT_IN_GRAPH_ORDER)
		prio_queue_reverse(&queue);

	/* We no longer need the commit list */
	free_commit_list(orig);
L
Linus Torvalds 已提交
729 730 731

	pptr = list;
	*list = NULL;
732 733
	while ((commit = prio_queue_get(&queue)) != NULL) {
		struct commit_list *parents;
L
Linus Torvalds 已提交
734 735

		for (parents = commit->parents; parents ; parents = parents->next) {
736
			struct commit *parent = parents->item;
737
			int *pi = indegree_slab_at(&indegree, parent);
L
Linus Torvalds 已提交
738

739
			if (!*pi)
L
Linus Torvalds 已提交
740 741 742 743 744 745 746
				continue;

			/*
			 * parents are only enqueued for emission
			 * when all their children have been emitted thereby
			 * guaranteeing topological order.
			 */
747 748
			if (--(*pi) == 1)
				prio_queue_put(&queue, parent);
749 750
		}
		/*
751 752
		 * all children of commit have already been
		 * emitted. we can emit it now.
753
		 */
754
		*(indegree_slab_at(&indegree, commit)) = 0;
755 756

		pptr = &commit_list_insert(commit, pptr)->next;
757
	}
758

759
	clear_indegree_slab(&indegree);
760
	clear_prio_queue(&queue);
J
Junio C Hamano 已提交
761 762
	if (sort_order == REV_SORT_BY_AUTHOR_DATE)
		clear_author_date_slab(&author_date);
763
}
764

765
/* merge-base stuff */
766

767
/* Remember to update object flag allocation in object.h */
J
Junio C Hamano 已提交
768 769 770 771
#define PARENT1		(1u<<16)
#define PARENT2		(1u<<17)
#define STALE		(1u<<18)
#define RESULT		(1u<<19)
772

773 774
static const unsigned all_flags = (PARENT1 | PARENT2 | STALE | RESULT);

J
Jeff King 已提交
775
static int queue_has_nonstale(struct prio_queue *queue)
776
{
J
Jeff King 已提交
777 778 779 780 781
	int i;
	for (i = 0; i < queue->nr; i++) {
		struct commit *commit = queue->array[i].data;
		if (!(commit->object.flags & STALE))
			return 1;
782
	}
J
Jeff King 已提交
783
	return 0;
784 785
}

786
/* all input commits in one and twos[] must have been parsed! */
787
static struct commit_list *paint_down_to_common(struct commit *one, int n, struct commit **twos)
788
{
J
Jeff King 已提交
789
	struct prio_queue queue = { compare_commits_by_commit_date };
790
	struct commit_list *result = NULL;
791
	int i;
792

793
	one->object.flags |= PARENT1;
J
Jeff King 已提交
794 795 796 797 798 799
	if (!n) {
		commit_list_append(one, &result);
		return result;
	}
	prio_queue_put(&queue, one);

800 801
	for (i = 0; i < n; i++) {
		twos[i]->object.flags |= PARENT2;
J
Jeff King 已提交
802
		prio_queue_put(&queue, twos[i]);
803
	}
804

J
Jeff King 已提交
805 806
	while (queue_has_nonstale(&queue)) {
		struct commit *commit = prio_queue_get(&queue);
807
		struct commit_list *parents;
808
		int flags;
809

810 811 812 813
		flags = commit->object.flags & (PARENT1 | PARENT2 | STALE);
		if (flags == (PARENT1 | PARENT2)) {
			if (!(commit->object.flags & RESULT)) {
				commit->object.flags |= RESULT;
814
				commit_list_insert_by_date(commit, &result);
815
			}
816 817
			/* Mark parents of a found merge stale */
			flags |= STALE;
818 819 820 821 822 823 824
		}
		parents = commit->parents;
		while (parents) {
			struct commit *p = parents->item;
			parents = parents->next;
			if ((p->object.flags & flags) == flags)
				continue;
825 826
			if (parse_commit(p))
				return NULL;
827
			p->object.flags |= flags;
J
Jeff King 已提交
828
			prio_queue_put(&queue, p);
829 830 831
		}
	}

J
Jeff King 已提交
832
	clear_prio_queue(&queue);
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	return result;
}

static struct commit_list *merge_bases_many(struct commit *one, int n, struct commit **twos)
{
	struct commit_list *list = NULL;
	struct commit_list *result = NULL;
	int i;

	for (i = 0; i < n; i++) {
		if (one == twos[i])
			/*
			 * We do not mark this even with RESULT so we do not
			 * have to clean it up.
			 */
			return commit_list_insert(one, &result);
	}

	if (parse_commit(one))
		return NULL;
	for (i = 0; i < n; i++) {
		if (parse_commit(twos[i]))
			return NULL;
	}

	list = paint_down_to_common(one, n, twos);

860
	while (list) {
861 862 863
		struct commit *commit = pop_commit(&list);
		if (!(commit->object.flags & STALE))
			commit_list_insert_by_date(commit, &result);
864 865 866
	}
	return result;
}
867

868 869 870 871
struct commit_list *get_octopus_merge_bases(struct commit_list *in)
{
	struct commit_list *i, *j, *k, *ret = NULL;

872 873 874 875 876 877 878 879 880 881
	if (!in)
		return ret;

	commit_list_insert(in->item, &ret);

	for (i = in->next; i; i = i->next) {
		struct commit_list *new = NULL, *end = NULL;

		for (j = ret; j; j = j->next) {
			struct commit_list *bases;
882
			bases = get_merge_bases(i->item, j->item);
883 884 885 886 887 888
			if (!new)
				new = bases;
			else
				end->next = bases;
			for (k = bases; k; k = k->next)
				end = k;
889
		}
890
		ret = new;
891 892 893 894
	}
	return ret;
}

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
static int remove_redundant(struct commit **array, int cnt)
{
	/*
	 * Some commit in the array may be an ancestor of
	 * another commit.  Move such commit to the end of
	 * the array, and return the number of commits that
	 * are independent from each other.
	 */
	struct commit **work;
	unsigned char *redundant;
	int *filled_index;
	int i, j, filled;

	work = xcalloc(cnt, sizeof(*work));
	redundant = xcalloc(cnt, 1);
J
Jeff King 已提交
910
	ALLOC_ARRAY(filled_index, cnt - 1);
911

912 913
	for (i = 0; i < cnt; i++)
		parse_commit(array[i]);
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
	for (i = 0; i < cnt; i++) {
		struct commit_list *common;

		if (redundant[i])
			continue;
		for (j = filled = 0; j < cnt; j++) {
			if (i == j || redundant[j])
				continue;
			filled_index[filled] = j;
			work[filled++] = array[j];
		}
		common = paint_down_to_common(array[i], filled, work);
		if (array[i]->object.flags & PARENT2)
			redundant[i] = 1;
		for (j = 0; j < filled; j++)
			if (work[j]->object.flags & PARENT1)
				redundant[filled_index[j]] = 1;
		clear_commit_marks(array[i], all_flags);
		for (j = 0; j < filled; j++)
			clear_commit_marks(work[j], all_flags);
		free_commit_list(common);
	}

	/* Now collect the result */
R
René Scharfe 已提交
938
	COPY_ARRAY(work, array, cnt);
939 940 941 942 943 944 945 946 947 948 949 950
	for (i = filled = 0; i < cnt; i++)
		if (!redundant[i])
			array[filled++] = work[i];
	for (j = filled, i = 0; i < cnt; i++)
		if (redundant[i])
			array[j++] = work[i];
	free(work);
	free(redundant);
	free(filled_index);
	return filled;
}

951 952 953 954
static struct commit_list *get_merge_bases_many_0(struct commit *one,
						  int n,
						  struct commit **twos,
						  int cleanup)
955 956 957 958
{
	struct commit_list *list;
	struct commit **rslt;
	struct commit_list *result;
959
	int cnt, i;
960

961 962 963 964 965
	result = merge_bases_many(one, n, twos);
	for (i = 0; i < n; i++) {
		if (one == twos[i])
			return result;
	}
966 967 968
	if (!result || !result->next) {
		if (cleanup) {
			clear_commit_marks(one, all_flags);
969
			clear_commit_marks_many(n, twos, all_flags);
970
		}
971
		return result;
972 973
	}

974
	/* There are more than one */
975
	cnt = commit_list_count(result);
976 977 978 979 980 981
	rslt = xcalloc(cnt, sizeof(*rslt));
	for (list = result, i = 0; list; list = list->next)
		rslt[i++] = list->item;
	free_commit_list(result);

	clear_commit_marks(one, all_flags);
982
	clear_commit_marks_many(n, twos, all_flags);
983

984
	cnt = remove_redundant(rslt, cnt);
985
	result = NULL;
986 987
	for (i = 0; i < cnt; i++)
		commit_list_insert_by_date(rslt[i], &result);
988
	free(rslt);
989 990
	return result;
}
J
Junio C Hamano 已提交
991

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
struct commit_list *get_merge_bases_many(struct commit *one,
					 int n,
					 struct commit **twos)
{
	return get_merge_bases_many_0(one, n, twos, 1);
}

struct commit_list *get_merge_bases_many_dirty(struct commit *one,
					       int n,
					       struct commit **twos)
{
	return get_merge_bases_many_0(one, n, twos, 0);
}

struct commit_list *get_merge_bases(struct commit *one, struct commit *two)
1007
{
1008
	return get_merge_bases_many_0(one, 1, &two, 1);
1009 1010
}

1011
/*
1012
 * Is "commit" a descendant of one of the elements on the "with_commit" list?
1013
 */
J
Jake Goulding 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022
int is_descendant_of(struct commit *commit, struct commit_list *with_commit)
{
	if (!with_commit)
		return 1;
	while (with_commit) {
		struct commit *other;

		other = with_commit->item;
		with_commit = with_commit->next;
1023
		if (in_merge_bases(other, commit))
J
Jake Goulding 已提交
1024 1025 1026 1027 1028
			return 1;
	}
	return 0;
}

1029
/*
1030
 * Is "commit" an ancestor of one of the "references"?
1031
 */
1032
int in_merge_bases_many(struct commit *commit, int nr_reference, struct commit **reference)
J
Junio C Hamano 已提交
1033
{
1034
	struct commit_list *bases;
1035
	int ret = 0, i;
J
Junio C Hamano 已提交
1036

1037
	if (parse_commit(commit))
1038
		return ret;
1039 1040 1041
	for (i = 0; i < nr_reference; i++)
		if (parse_commit(reference[i]))
			return ret;
J
Junio C Hamano 已提交
1042

1043
	bases = paint_down_to_common(commit, nr_reference, reference);
1044 1045
	if (commit->object.flags & PARENT2)
		ret = 1;
1046
	clear_commit_marks(commit, all_flags);
1047
	clear_commit_marks_many(nr_reference, reference, all_flags);
J
Junio C Hamano 已提交
1048 1049 1050
	free_commit_list(bases);
	return ret;
}
J
Junio C Hamano 已提交
1051

1052 1053 1054 1055 1056 1057 1058 1059
/*
 * Is "commit" an ancestor of (i.e. reachable from) the "reference"?
 */
int in_merge_bases(struct commit *commit, struct commit *reference)
{
	return in_merge_bases_many(commit, 1, &reference);
}

J
Junio C Hamano 已提交
1060 1061 1062 1063
struct commit_list *reduce_heads(struct commit_list *heads)
{
	struct commit_list *p;
	struct commit_list *result = NULL, **tail = &result;
1064 1065
	struct commit **array;
	int num_head, i;
J
Junio C Hamano 已提交
1066 1067 1068 1069

	if (!heads)
		return NULL;

1070 1071 1072 1073 1074
	/* Uniquify */
	for (p = heads; p; p = p->next)
		p->item->object.flags &= ~STALE;
	for (p = heads, num_head = 0; p; p = p->next) {
		if (p->item->object.flags & STALE)
1075
			continue;
1076 1077 1078
		p->item->object.flags |= STALE;
		num_head++;
	}
1079
	array = xcalloc(num_head, sizeof(*array));
1080 1081 1082 1083
	for (p = heads, i = 0; p; p = p->next) {
		if (p->item->object.flags & STALE) {
			array[i++] = p->item;
			p->item->object.flags &= ~STALE;
J
Junio C Hamano 已提交
1084 1085
		}
	}
1086 1087 1088
	num_head = remove_redundant(array, num_head);
	for (i = 0; i < num_head; i++)
		tail = &commit_list_insert(array[i], tail)->next;
1089
	free(array);
J
Junio C Hamano 已提交
1090 1091
	return result;
}
J
Jeff King 已提交
1092

M
Martin Ågren 已提交
1093 1094 1095 1096 1097 1098 1099
void reduce_heads_replace(struct commit_list **heads)
{
	struct commit_list *result = reduce_heads(*heads);
	free_commit_list(*heads);
	*heads = result;
}

J
Junio C Hamano 已提交
1100 1101 1102 1103 1104 1105 1106
static const char gpg_sig_header[] = "gpgsig";
static const int gpg_sig_header_len = sizeof(gpg_sig_header) - 1;

static int do_sign_commit(struct strbuf *buf, const char *keyid)
{
	struct strbuf sig = STRBUF_INIT;
	int inspos, copypos;
1107
	const char *eoh;
J
Junio C Hamano 已提交
1108 1109

	/* find the end of the header */
1110 1111 1112 1113 1114
	eoh = strstr(buf->buf, "\n\n");
	if (!eoh)
		inspos = buf->len;
	else
		inspos = eoh - buf->buf + 1;
J
Junio C Hamano 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

	if (!keyid || !*keyid)
		keyid = get_signing_key();
	if (sign_buffer(buf, &sig, keyid)) {
		strbuf_release(&sig);
		return -1;
	}

	for (copypos = 0; sig.buf[copypos]; ) {
		const char *bol = sig.buf + copypos;
		const char *eol = strchrnul(bol, '\n');
		int len = (eol - bol) + !!*eol;

		if (!copypos) {
			strbuf_insert(buf, inspos, gpg_sig_header, gpg_sig_header_len);
			inspos += gpg_sig_header_len;
		}
		strbuf_insert(buf, inspos++, " ", 1);
		strbuf_insert(buf, inspos, bol, len);
		inspos += len;
		copypos += len;
	}
	strbuf_release(&sig);
	return 0;
}

1141
int parse_signed_commit(const struct commit *commit,
J
Junio C Hamano 已提交
1142 1143
			struct strbuf *payload, struct strbuf *signature)
{
1144

J
Junio C Hamano 已提交
1145
	unsigned long size;
1146
	const char *buffer = get_commit_buffer(commit, &size);
J
Junio C Hamano 已提交
1147
	int in_signature, saw_signature = -1;
1148
	const char *line, *tail;
J
Junio C Hamano 已提交
1149 1150 1151 1152 1153 1154 1155

	line = buffer;
	tail = buffer + size;
	in_signature = 0;
	saw_signature = 0;
	while (line < tail) {
		const char *sig = NULL;
1156
		const char *next = memchr(line, '\n', tail - line);
J
Junio C Hamano 已提交
1157 1158 1159 1160

		next = next ? next + 1 : tail;
		if (in_signature && line[0] == ' ')
			sig = line + 1;
1161
		else if (starts_with(line, gpg_sig_header) &&
J
Junio C Hamano 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
			 line[gpg_sig_header_len] == ' ')
			sig = line + gpg_sig_header_len + 1;
		if (sig) {
			strbuf_add(signature, sig, next - sig);
			saw_signature = 1;
			in_signature = 1;
		} else {
			if (*line == '\n')
				/* dump the whole remainder of the buffer */
				next = tail;
			strbuf_add(payload, line, next - line);
			in_signature = 0;
		}
		line = next;
	}
1177
	unuse_commit_buffer(commit, buffer);
J
Junio C Hamano 已提交
1178 1179 1180
	return saw_signature;
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
int remove_signature(struct strbuf *buf)
{
	const char *line = buf->buf;
	const char *tail = buf->buf + buf->len;
	int in_signature = 0;
	const char *sig_start = NULL;
	const char *sig_end = NULL;

	while (line < tail) {
		const char *next = memchr(line, '\n', tail - line);
		next = next ? next + 1 : tail;

		if (in_signature && line[0] == ' ')
			sig_end = next;
		else if (starts_with(line, gpg_sig_header) &&
			 line[gpg_sig_header_len] == ' ') {
			sig_start = line;
			sig_end = next;
			in_signature = 1;
		} else {
			if (*line == '\n')
				/* dump the whole remainder of the buffer */
				next = tail;
			in_signature = 0;
		}
		line = next;
	}

	if (sig_start)
		strbuf_remove(buf, sig_start - buf->buf, sig_end - sig_start);

	return sig_start != NULL;
}

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
static void handle_signed_tag(struct commit *parent, struct commit_extra_header ***tail)
{
	struct merge_remote_desc *desc;
	struct commit_extra_header *mergetag;
	char *buf;
	unsigned long size, len;
	enum object_type type;

	desc = merge_remote_util(parent);
	if (!desc || !desc->obj)
		return;
B
brian m. carlson 已提交
1226
	buf = read_sha1_file(desc->obj->oid.hash, &type, &size);
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
	if (!buf || type != OBJ_TAG)
		goto free_return;
	len = parse_signature(buf, size);
	if (size == len)
		goto free_return;
	/*
	 * We could verify this signature and either omit the tag when
	 * it does not validate, but the integrator may not have the
	 * public key of the signer of the tag he is merging, while a
	 * later auditor may have it while auditing, so let's not run
	 * verify-signed-buffer here for now...
	 *
	 * if (verify_signed_buffer(buf, len, buf + len, size - len, ...))
	 *	warn("warning: signed tag unverified.");
	 */
	mergetag = xcalloc(1, sizeof(*mergetag));
	mergetag->key = xstrdup("mergetag");
	mergetag->value = buf;
	mergetag->len = size;

	**tail = mergetag;
	*tail = &mergetag->next;
	return;

free_return:
	free(buf);
}

1255
int check_commit_signature(const struct commit *commit, struct signature_check *sigc)
1256 1257 1258
{
	struct strbuf payload = STRBUF_INIT;
	struct strbuf signature = STRBUF_INIT;
1259
	int ret = 1;
1260 1261 1262

	sigc->result = 'N';

1263
	if (parse_signed_commit(commit, &payload, &signature) <= 0)
1264
		goto out;
1265 1266
	ret = check_signature(payload.buf, payload.len, signature.buf,
		signature.len, sigc);
1267 1268 1269 1270

 out:
	strbuf_release(&payload);
	strbuf_release(&signature);
1271 1272

	return ret;
1273 1274 1275 1276
}



1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
void append_merge_tag_headers(struct commit_list *parents,
			      struct commit_extra_header ***tail)
{
	while (parents) {
		struct commit *parent = parents->item;
		handle_signed_tag(parent, tail);
		parents = parents->next;
	}
}

static void add_extra_header(struct strbuf *buffer,
			     struct commit_extra_header *extra)
{
	strbuf_addstr(buffer, extra->key);
1291 1292 1293 1294 1295 1296
	if (extra->len)
		strbuf_add_lines(buffer, " ", extra->value, extra->len);
	else
		strbuf_addch(buffer, '\n');
}

1297 1298
struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
						      const char **exclude)
1299 1300 1301
{
	struct commit_extra_header *extra = NULL;
	unsigned long size;
1302 1303 1304
	const char *buffer = get_commit_buffer(commit, &size);
	extra = read_commit_extra_header_lines(buffer, size, exclude);
	unuse_commit_buffer(commit, buffer);
1305 1306 1307
	return extra;
}

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
void for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
{
	struct commit_extra_header *extra, *to_free;

	to_free = read_commit_extra_headers(commit, NULL);
	for (extra = to_free; extra; extra = extra->next) {
		if (strcmp(extra->key, "mergetag"))
			continue; /* not a merge tag */
		fn(commit, extra, data);
	}
	free_commit_extra_headers(to_free);
}

1321 1322
static inline int standard_header_field(const char *field, size_t len)
{
1323 1324 1325 1326 1327
	return ((len == 4 && !memcmp(field, "tree", 4)) ||
		(len == 6 && !memcmp(field, "parent", 6)) ||
		(len == 6 && !memcmp(field, "author", 6)) ||
		(len == 9 && !memcmp(field, "committer", 9)) ||
		(len == 8 && !memcmp(field, "encoding", 8)));
1328 1329
}

1330 1331 1332 1333 1334 1335 1336
static int excluded_header_field(const char *field, size_t len, const char **exclude)
{
	if (!exclude)
		return 0;

	while (*exclude) {
		size_t xlen = strlen(*exclude);
1337
		if (len == xlen && !memcmp(field, *exclude, xlen))
1338 1339 1340 1341 1342 1343
			return 1;
		exclude++;
	}
	return 0;
}

1344 1345 1346
static struct commit_extra_header *read_commit_extra_header_lines(
	const char *buffer, size_t size,
	const char **exclude)
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
{
	struct commit_extra_header *extra = NULL, **tail = &extra, *it = NULL;
	const char *line, *next, *eof, *eob;
	struct strbuf buf = STRBUF_INIT;

	for (line = buffer, eob = line + size;
	     line < eob && *line != '\n';
	     line = next) {
		next = memchr(line, '\n', eob - line);
		next = next ? next + 1 : eob;
		if (*line == ' ') {
			/* continuation */
			if (it)
				strbuf_add(&buf, line + 1, next - (line + 1));
			continue;
		}
		if (it)
			it->value = strbuf_detach(&buf, &it->len);
		strbuf_reset(&buf);
		it = NULL;

1368 1369
		eof = memchr(line, ' ', next - line);
		if (!eof)
1370
			eof = next;
1371 1372
		else if (standard_header_field(line, eof - line) ||
			 excluded_header_field(line, eof - line, exclude))
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
			continue;

		it = xcalloc(1, sizeof(*it));
		it->key = xmemdupz(line, eof-line);
		*tail = it;
		tail = &it->next;
		if (eof + 1 < next)
			strbuf_add(&buf, eof + 1, next - (eof + 1));
	}
	if (it)
		it->value = strbuf_detach(&buf, &it->len);
	return extra;
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
}

void free_commit_extra_headers(struct commit_extra_header *extra)
{
	while (extra) {
		struct commit_extra_header *next = extra->next;
		free(extra->key);
		free(extra->value);
		free(extra);
		extra = next;
	}
}

1398 1399
int commit_tree(const char *msg, size_t msg_len,
		const unsigned char *tree,
1400
		struct commit_list *parents, unsigned char *ret,
J
Junio C Hamano 已提交
1401
		const char *author, const char *sign_commit)
1402 1403 1404 1405 1406
{
	struct commit_extra_header *extra = NULL, **tail = &extra;
	int result;

	append_merge_tag_headers(parents, &tail);
1407
	result = commit_tree_extended(msg, msg_len, tree, parents, ret,
J
Junio C Hamano 已提交
1408
				      author, sign_commit, extra);
1409 1410 1411 1412
	free_commit_extra_headers(extra);
	return result;
}

1413 1414 1415
static int find_invalid_utf8(const char *buf, int len)
{
	int offset = 0;
1416 1417 1418
	static const unsigned int max_codepoint[] = {
		0x7f, 0x7ff, 0xffff, 0x10ffff
	};
1419 1420 1421 1422

	while (len) {
		unsigned char c = *buf++;
		int bytes, bad_offset;
1423
		unsigned int codepoint;
1424
		unsigned int min_val, max_val;
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444

		len--;
		offset++;

		/* Simple US-ASCII? No worries. */
		if (c < 0x80)
			continue;

		bad_offset = offset-1;

		/*
		 * Count how many more high bits set: that's how
		 * many more bytes this sequence should have.
		 */
		bytes = 0;
		while (c & 0x40) {
			c <<= 1;
			bytes++;
		}

1445 1446 1447 1448 1449
		/*
		 * Must be between 1 and 3 more bytes.  Longer sequences result in
		 * codepoints beyond U+10FFFF, which are guaranteed never to exist.
		 */
		if (bytes < 1 || 3 < bytes)
1450 1451 1452 1453 1454 1455
			return bad_offset;

		/* Do we *have* that many bytes? */
		if (len < bytes)
			return bad_offset;

1456 1457 1458 1459
		/*
		 * Place the encoded bits at the bottom of the value and compute the
		 * valid range.
		 */
1460
		codepoint = (c & 0x7f) >> bytes;
1461 1462
		min_val = max_codepoint[bytes-1] + 1;
		max_val = max_codepoint[bytes];
1463

1464 1465 1466 1467 1468
		offset += bytes;
		len -= bytes;

		/* And verify that they are good continuation bytes */
		do {
1469 1470
			codepoint <<= 6;
			codepoint |= *buf & 0x3f;
1471 1472 1473 1474
			if ((*buf++ & 0xc0) != 0x80)
				return bad_offset;
		} while (--bytes);

1475 1476
		/* Reject codepoints that are out of range for the sequence length. */
		if (codepoint < min_val || codepoint > max_val)
1477 1478 1479 1480
			return bad_offset;
		/* Surrogates are only for UTF-16 and cannot be encoded in UTF-8. */
		if ((codepoint & 0x1ff800) == 0xd800)
			return bad_offset;
P
Peter Krefting 已提交
1481
		/* U+xxFFFE and U+xxFFFF are guaranteed non-characters. */
1482
		if ((codepoint & 0xfffe) == 0xfffe)
P
Peter Krefting 已提交
1483 1484 1485
			return bad_offset;
		/* So are anything in the range U+FDD0..U+FDEF. */
		if (codepoint >= 0xfdd0 && codepoint <= 0xfdef)
1486
			return bad_offset;
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
	}
	return -1;
}

/*
 * This verifies that the buffer is in proper utf8 format.
 *
 * If it isn't, it assumes any non-utf8 characters are Latin1,
 * and does the conversion.
 */
static int verify_utf8(struct strbuf *buf)
{
	int ok = 1;
	long pos = 0;

	for (;;) {
		int bad;
		unsigned char c;
		unsigned char replace[2];

		bad = find_invalid_utf8(buf->buf + pos, buf->len - pos);
		if (bad < 0)
			return ok;
		pos += bad;
		ok = 0;
		c = buf->buf[pos];
		strbuf_remove(buf, pos, 1);

		/* We know 'c' must be in the range 128-255 */
		replace[0] = 0xc0 + (c >> 6);
		replace[1] = 0x80 + (c & 0x3f);
		strbuf_insert(buf, pos, replace, 2);
		pos += 2;
	}
}

J
Jeff King 已提交
1523
static const char commit_utf8_warn[] =
1524 1525 1526
N_("Warning: commit message did not conform to UTF-8.\n"
   "You may want to amend it after fixing the message, or set the config\n"
   "variable i18n.commitencoding to the encoding your project uses.\n");
J
Jeff King 已提交
1527

1528 1529
int commit_tree_extended(const char *msg, size_t msg_len,
			 const unsigned char *tree,
1530
			 struct commit_list *parents, unsigned char *ret,
J
Junio C Hamano 已提交
1531 1532
			 const char *author, const char *sign_commit,
			 struct commit_extra_header *extra)
J
Jeff King 已提交
1533 1534 1535 1536 1537 1538 1539
{
	int result;
	int encoding_is_utf8;
	struct strbuf buffer;

	assert_sha1_type(tree, OBJ_TREE);

1540
	if (memchr(msg, '\0', msg_len))
1541 1542
		return error("a NUL byte in commit log message not allowed.");

J
Jeff King 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
	/* Not having i18n.commitencoding is the same as having utf-8 */
	encoding_is_utf8 = is_encoding_utf8(git_commit_encoding);

	strbuf_init(&buffer, 8192); /* should avoid reallocs for the headers */
	strbuf_addf(&buffer, "tree %s\n", sha1_to_hex(tree));

	/*
	 * NOTE! This ordering means that the same exact tree merged with a
	 * different order of parents will be a _different_ changeset even
	 * if everything else stays the same.
	 */
	while (parents) {
1555
		struct commit *parent = pop_commit(&parents);
J
Jeff King 已提交
1556
		strbuf_addf(&buffer, "parent %s\n",
1557
			    oid_to_hex(&parent->object.oid));
J
Jeff King 已提交
1558 1559 1560 1561
	}

	/* Person/date information */
	if (!author)
1562
		author = git_author_info(IDENT_STRICT);
J
Jeff King 已提交
1563
	strbuf_addf(&buffer, "author %s\n", author);
1564
	strbuf_addf(&buffer, "committer %s\n", git_committer_info(IDENT_STRICT));
J
Jeff King 已提交
1565 1566
	if (!encoding_is_utf8)
		strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding);
1567 1568 1569 1570 1571

	while (extra) {
		add_extra_header(&buffer, extra);
		extra = extra->next;
	}
J
Jeff King 已提交
1572 1573 1574
	strbuf_addch(&buffer, '\n');

	/* And add the comment */
1575
	strbuf_add(&buffer, msg, msg_len);
J
Jeff King 已提交
1576 1577

	/* And check the encoding */
1578
	if (encoding_is_utf8 && !verify_utf8(&buffer))
1579
		fprintf(stderr, _(commit_utf8_warn));
J
Jeff King 已提交
1580

1581 1582 1583 1584
	if (sign_commit && do_sign_commit(&buffer, sign_commit)) {
		result = -1;
		goto out;
	}
J
Junio C Hamano 已提交
1585

J
Jeff King 已提交
1586
	result = write_sha1_file(buffer.buf, buffer.len, commit_type, ret);
1587
out:
J
Jeff King 已提交
1588 1589 1590
	strbuf_release(&buffer);
	return result;
}
1591

1592 1593 1594 1595
void set_merge_remote_desc(struct commit *commit,
			   const char *name, struct object *obj)
{
	struct merge_remote_desc *desc;
1596
	FLEX_ALLOC_STR(desc, name, name);
1597 1598 1599 1600
	desc->obj = obj;
	commit->util = desc;
}

1601 1602 1603 1604
struct commit *get_merge_parent(const char *name)
{
	struct object *obj;
	struct commit *commit;
1605
	struct object_id oid;
1606
	if (get_oid(name, &oid))
1607
		return NULL;
1608
	obj = parse_object(&oid);
1609
	commit = (struct commit *)peel_to_type(name, 0, obj, OBJ_COMMIT);
1610 1611
	if (commit && !commit->util)
		set_merge_remote_desc(commit, name, obj);
1612 1613
	return commit;
}
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640

/*
 * Append a commit to the end of the commit_list.
 *
 * next starts by pointing to the variable that holds the head of an
 * empty commit_list, and is updated to point to the "next" field of
 * the last item on the list as new commits are appended.
 *
 * Usage example:
 *
 *     struct commit_list *list;
 *     struct commit_list **next = &list;
 *
 *     next = commit_list_append(c1, next);
 *     next = commit_list_append(c2, next);
 *     assert(commit_list_count(list) == 2);
 *     return list;
 */
struct commit_list **commit_list_append(struct commit *commit,
					struct commit_list **next)
{
	struct commit_list *new = xmalloc(sizeof(struct commit_list));
	new->item = commit;
	*next = new;
	new->next = NULL;
	return &new->next;
}
1641

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
const char *find_commit_header(const char *msg, const char *key, size_t *out_len)
{
	int key_len = strlen(key);
	const char *line = msg;

	while (line) {
		const char *eol = strchrnul(line, '\n');

		if (line == eol)
			return NULL;

		if (eol - line > key_len &&
		    !strncmp(line, key, key_len) &&
		    line[key_len] == ' ') {
			*out_len = eol - line - key_len - 1;
			return line + key_len + 1;
		}
		line = *eol ? eol + 1 : NULL;
	}
	return NULL;
}
1663

1664
/*
1665
 * Inspect the given string and determine the true "end" of the log message, in
1666
 * order to find where to put a new Signed-off-by: line.  Ignored are
1667 1668 1669
 * trailing comment lines and blank lines.  To support "git commit -s
 * --amend" on an existing commit, we also ignore "Conflicts:".  To
 * support "git commit -v", we truncate at cut lines.
1670 1671 1672 1673
 *
 * Returns the number of bytes from the tail to ignore, to be fed as
 * the second parameter to append_signoff().
 */
1674
int ignore_non_trailer(const char *buf, size_t len)
1675 1676 1677 1678
{
	int boc = 0;
	int bol = 0;
	int in_old_conflicts_block = 0;
1679
	size_t cutoff = wt_status_locate_end(buf, len);
1680

1681
	while (bol < cutoff) {
1682
		const char *next_line = memchr(buf + bol, '\n', len - bol);
1683

1684 1685
		if (!next_line)
			next_line = buf + len;
1686 1687 1688
		else
			next_line++;

1689
		if (buf[bol] == comment_line_char || buf[bol] == '\n') {
1690 1691 1692 1693
			/* is this the first of the run of comments? */
			if (!boc)
				boc = bol;
			/* otherwise, it is just continuing */
1694
		} else if (starts_with(buf + bol, "Conflicts:\n")) {
1695 1696 1697
			in_old_conflicts_block = 1;
			if (!boc)
				boc = bol;
1698
		} else if (in_old_conflicts_block && buf[bol] == '\t') {
1699 1700 1701 1702 1703 1704
			; /* a pathname in the conflicts block */
		} else if (boc) {
			/* the previous was not trailing comment */
			boc = 0;
			in_old_conflicts_block = 0;
		}
1705
		bol = next_line - buf;
1706
	}
1707
	return boc ? len - boc : len - cutoff;
1708
}