pack-objects.c 41.1 KB
Newer Older
Michael Schubert committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Michael Schubert committed
3 4 5 6 7 8 9
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */

#include "pack-objects.h"

10
#include "zstream.h"
Michael Schubert committed
11 12 13 14
#include "delta.h"
#include "iterator.h"
#include "netops.h"
#include "pack.h"
15
#include "thread.h"
Michael Schubert committed
16
#include "tree.h"
17
#include "util.h"
18 19
#include "revwalk.h"
#include "commit_list.h"
Michael Schubert committed
20 21 22 23 24 25 26 27 28 29 30

#include "git2/pack.h"
#include "git2/commit.h"
#include "git2/tag.h"
#include "git2/indexer.h"
#include "git2/config.h"

struct unpacked {
	git_pobject *object;
	void *data;
	struct git_delta_index *index;
31
	size_t depth;
Michael Schubert committed
32 33
};

34 35 36 37 38
struct tree_walk_context {
	git_packbuilder *pb;
	git_buf buf;
};

39
struct pack_write_context {
40
	git_indexer *indexer;
41
	git_indexer_progress *stats;
42 43
};

44 45 46 47 48 49
struct walk_object {
	git_oid id;
	unsigned int uninteresting:1,
		seen:1;
};

50
#ifdef GIT_THREADS
51
# define GIT_PACKBUILDER__MUTEX_OP(pb, mtx, op) git_mutex_##op(&(pb)->mtx)
52
#else
53
# define GIT_PACKBUILDER__MUTEX_OP(pb, mtx, op) git__noop()
54
#endif
55 56 57 58 59 60

#define git_packbuilder__cache_lock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, cache_mutex, lock)
#define git_packbuilder__cache_unlock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, cache_mutex, unlock)
#define git_packbuilder__progress_lock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, progress_mutex, lock)
#define git_packbuilder__progress_unlock(pb) GIT_PACKBUILDER__MUTEX_OP(pb, progress_mutex, unlock)

61 62 63
/* The minimal interval between progress updates (in seconds). */
#define MIN_PROGRESS_UPDATE_INTERVAL 0.5

64 65 66
/* Size of the buffer to feed to zlib */
#define COMPRESS_BUFLEN (1024 * 1024)

Michael Schubert committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
static unsigned name_hash(const char *name)
{
	unsigned c, hash = 0;

	if (!name)
		return 0;

	/*
	 * This effectively just creates a sortable number from the
	 * last sixteen non-whitespace characters. Last characters
	 * count "most", so things that end in ".c" sort together.
	 */
	while ((c = *name++) != 0) {
		if (git__isspace(c))
			continue;
		hash = (hash >> 2) + (c << 24);
	}
	return hash;
}

static int packbuilder_config(git_packbuilder *pb)
{
	git_config *config;
90
	int ret = 0;
91
	int64_t val;
Michael Schubert committed
92

93
	if ((ret = git_repository_config_snapshot(&config, pb->repo)) < 0)
94
		return ret;
Michael Schubert committed
95

96 97
#define config_get(KEY,DST,DFLT) do { \
	ret = git_config_get_int64(&val, config, KEY); \
98 99
	if (!ret) { \
		if (!git__is_sizet(val)) { \
100
			git_error_set(GIT_ERROR_CONFIG, \
101 102 103 104 105 106
				"configuration value '%s' is too large", KEY); \
			ret = -1; \
			goto out; \
		} \
		(DST) = (size_t)val; \
	} else if (ret == GIT_ENOTFOUND) { \
107 108 109
	    (DST) = (DFLT); \
	    ret = 0; \
	} else if (ret < 0) goto out; } while (0)
Michael Schubert committed
110 111 112 113 114 115 116 117 118 119 120

	config_get("pack.deltaCacheSize", pb->max_delta_cache_size,
		   GIT_PACK_DELTA_CACHE_SIZE);
	config_get("pack.deltaCacheLimit", pb->cache_max_small_delta_size,
		   GIT_PACK_DELTA_CACHE_LIMIT);
	config_get("pack.deltaCacheSize", pb->big_file_threshold,
		   GIT_PACK_BIG_FILE_THRESHOLD);
	config_get("pack.windowMemory", pb->window_memory_limit, 0);

#undef config_get

121
out:
122 123
	git_config_free(config);

124
	return ret;
Michael Schubert committed
125 126 127 128 129 130 131 132
}

int git_packbuilder_new(git_packbuilder **out, git_repository *repo)
{
	git_packbuilder *pb;

	*out = NULL;

133
	pb = git__calloc(1, sizeof(*pb));
134
	GIT_ERROR_CHECK_ALLOC(pb);
Michael Schubert committed
135

136 137 138
	if (git_oidmap_new(&pb->object_ix) < 0 ||
	    git_oidmap_new(&pb->walk_objects) < 0 ||
	    git_pool_init(&pb->object_pool, sizeof(struct walk_object)) < 0)
139
		goto on_error;
140

Michael Schubert committed
141 142 143
	pb->repo = repo;
	pb->nr_threads = 1; /* do not spawn any thread by default */

144
	if (git_hash_ctx_init(&pb->ctx) < 0 ||
145
		git_zstream_init(&pb->zstream, GIT_ZSTREAM_DEFLATE) < 0 ||
146 147
		git_repository_odb(&pb->odb, repo) < 0 ||
		packbuilder_config(pb) < 0)
Michael Schubert committed
148 149
		goto on_error;

150 151 152 153 154
#ifdef GIT_THREADS

	if (git_mutex_init(&pb->cache_mutex) ||
		git_mutex_init(&pb->progress_mutex) ||
		git_cond_init(&pb->progress_cond))
Russell Belfer committed
155
	{
156
		git_error_set(GIT_ERROR_OS, "failed to initialize packbuilder mutex");
Michael Schubert committed
157
		goto on_error;
Russell Belfer committed
158
	}
Michael Schubert committed
159

160 161
#endif

Michael Schubert committed
162 163 164 165
	*out = pb;
	return 0;

on_error:
166
	git_packbuilder_free(pb);
Michael Schubert committed
167 168 169
	return -1;
}

170
unsigned int git_packbuilder_set_threads(git_packbuilder *pb, unsigned int n)
Michael Schubert committed
171
{
172
	GIT_ASSERT_ARG(pb);
173 174

#ifdef GIT_THREADS
Michael Schubert committed
175
	pb->nr_threads = n;
176 177
#else
	GIT_UNUSED(n);
178
	GIT_ASSERT(pb->nr_threads == 1);
179 180
#endif

181
	return pb->nr_threads;
Michael Schubert committed
182 183
}

184
static int rehash(git_packbuilder *pb)
185 186
{
	git_pobject *po;
187
	size_t i;
188

189
	git_oidmap_clear(pb->object_ix);
190

191
	for (i = 0, po = pb->object_list; i < pb->nr_objects; i++, po++) {
192 193
		if (git_oidmap_set(pb->object_ix, &po->id, po) < 0)
			return -1;
194
	}
195 196

	return 0;
197 198
}

Michael Schubert committed
199 200 201 202
int git_packbuilder_insert(git_packbuilder *pb, const git_oid *oid,
			   const char *name)
{
	git_pobject *po;
203
	size_t newsize;
204
	int ret;
Michael Schubert committed
205

206 207
	GIT_ASSERT_ARG(pb);
	GIT_ASSERT_ARG(oid);
Michael Schubert committed
208

209 210
	/* If the object already exists in the hash table, then we don't
	 * have any work to do */
211
	if (git_oidmap_exists(pb->object_ix, oid))
Michael Schubert committed
212 213 214
		return 0;

	if (pb->nr_objects >= pb->nr_alloc) {
215
		GIT_ERROR_CHECK_ALLOC_ADD(&newsize, pb->nr_alloc, 1024);
216
		GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newsize, newsize / 2, 3);
217 218

		if (!git__is_uint32(newsize)) {
219
			git_error_set(GIT_ERROR_NOMEMORY, "packfile too large to fit in memory.");
220 221 222
			return -1;
		}

223
		pb->nr_alloc = newsize;
224

225 226
		pb->object_list = git__reallocarray(pb->object_list,
			pb->nr_alloc, sizeof(*po));
227
		GIT_ERROR_CHECK_ALLOC(pb->object_list);
228 229 230

		if (rehash(pb) < 0)
			return -1;
Michael Schubert committed
231 232
	}

233
	po = pb->object_list + pb->nr_objects;
Michael Schubert committed
234 235
	memset(po, 0x0, sizeof(*po));

236 237
	if ((ret = git_odb_read_header(&po->size, &po->type, pb->odb, oid)) < 0)
		return ret;
238 239

	pb->nr_objects++;
Michael Schubert committed
240
	git_oid_cpy(&po->id, oid);
241
	po->hash = name_hash(name);
Michael Schubert committed
242

243
	if (git_oidmap_set(pb->object_ix, &po->id, po) < 0) {
244
		git_error_set_oom();
245
		return -1;
246
	}
Michael Schubert committed
247

248 249
	pb->done = false;

250 251
	if (pb->progress_cb) {
		double current_time = git__timer();
252 253
		double elapsed = current_time - pb->last_progress_report_time;

254
		if (elapsed < 0 || elapsed >= MIN_PROGRESS_UPDATE_INTERVAL) {
255
			pb->last_progress_report_time = current_time;
256

257
			ret = pb->progress_cb(
258
				GIT_PACKBUILDER_ADDING_OBJECTS,
259 260 261
				pb->nr_objects, 0, pb->progress_cb_payload);

			if (ret)
262
				return git_error_set_after_callback(ret);
263 264 265
		}
	}

Michael Schubert committed
266 267 268 269 270 271
	return 0;
}

static int get_delta(void **out, git_odb *odb, git_pobject *po)
{
	git_odb_object *src = NULL, *trg = NULL;
272
	size_t delta_size;
Michael Schubert committed
273
	void *delta_buf;
274
	int error;
Michael Schubert committed
275 276 277 278 279 280 281

	*out = NULL;

	if (git_odb_read(&src, odb, &po->delta->id) < 0 ||
	    git_odb_read(&trg, odb, &po->id) < 0)
		goto on_error;

282 283 284 285 286 287 288
	error = git_delta(&delta_buf, &delta_size,
		git_odb_object_data(src), git_odb_object_size(src),
		git_odb_object_data(trg), git_odb_object_size(trg),
		0);

	if (error < 0 && error != GIT_EBUFS)
		goto on_error;
Michael Schubert committed
289

290
	if (error == GIT_EBUFS || delta_size != po->delta_size) {
291
		git_error_set(GIT_ERROR_INVALID, "delta size changed");
Michael Schubert committed
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
		goto on_error;
	}

	*out = delta_buf;

	git_odb_object_free(src);
	git_odb_object_free(trg);
	return 0;

on_error:
	git_odb_object_free(src);
	git_odb_object_free(trg);
	return -1;
}

307 308 309 310 311
static int write_object(
	git_packbuilder *pb,
	git_pobject *po,
	int (*write_cb)(void *buf, size_t size, void *cb_data),
	void *cb_data)
Michael Schubert committed
312 313
{
	git_odb_object *obj = NULL;
314
	git_object_t type;
315
	unsigned char hdr[10], *zbuf = NULL;
316
	void *data = NULL;
317 318
	size_t hdr_len, zbuf_len = COMPRESS_BUFLEN, data_len;
	int error;
Michael Schubert committed
319

320 321 322 323 324
	/*
	 * If we have a delta base, let's use the delta to save space.
	 * Otherwise load the whole object. 'data' ends up pointing to
	 * whatever data we want to put into the packfile.
	 */
Michael Schubert committed
325 326
	if (po->delta) {
		if (po->delta_data)
327 328
			data = po->delta_data;
		else if ((error = get_delta(&data, pb->odb, po)) < 0)
329 330 331
				goto done;

		data_len = po->delta_size;
332
		type = GIT_OBJECT_REF_DELTA;
Michael Schubert committed
333
	} else {
334 335
		if ((error = git_odb_read(&obj, pb->odb, &po->id)) < 0)
			goto done;
Michael Schubert committed
336 337

		data = (void *)git_odb_object_data(obj);
338
		data_len = git_odb_object_size(obj);
Michael Schubert committed
339 340 341 342
		type = git_odb_object_type(obj);
	}

	/* Write header */
Edward Thomson committed
343 344 345
	if ((error = git_packfile__object_header(&hdr_len, hdr, data_len, type)) < 0 ||
	    (error = write_cb(hdr, hdr_len, cb_data)) < 0 ||
	    (error = git_hash_update(&pb->ctx, hdr, hdr_len)) < 0)
346
		goto done;
Michael Schubert committed
347

348
	if (type == GIT_OBJECT_REF_DELTA) {
349 350 351
		if ((error = write_cb(po->delta->id.id, GIT_OID_RAWSZ, cb_data)) < 0 ||
			(error = git_hash_update(&pb->ctx, po->delta->id.id, GIT_OID_RAWSZ)) < 0)
			goto done;
Michael Schubert committed
352 353 354
	}

	/* Write data */
355 356 357 358 359 360 361 362
	if (po->z_delta_size) {
		data_len = po->z_delta_size;

		if ((error = write_cb(data, data_len, cb_data)) < 0 ||
			(error = git_hash_update(&pb->ctx, data, data_len)) < 0)
			goto done;
	} else {
		zbuf = git__malloc(zbuf_len);
363
		GIT_ERROR_CHECK_ALLOC(zbuf);
364

365
		git_zstream_reset(&pb->zstream);
366 367 368

		if ((error = git_zstream_set_input(&pb->zstream, data, data_len)) < 0)
			goto done;
369

370 371 372 373
		while (!git_zstream_done(&pb->zstream)) {
			if ((error = git_zstream_get_output(zbuf, &zbuf_len, &pb->zstream)) < 0 ||
				(error = write_cb(zbuf, zbuf_len, cb_data)) < 0 ||
				(error = git_hash_update(&pb->ctx, zbuf, zbuf_len)) < 0)
374 375
				goto done;

376
			zbuf_len = COMPRESS_BUFLEN; /* reuse buffer */
377
		}
Michael Schubert committed
378 379
	}

380 381 382 383 384 385 386 387 388
	/*
	 * If po->delta is true, data is a delta and it is our
	 * responsibility to free it (otherwise it's a git_object's
	 * data). We set po->delta_data to NULL in case we got the
	 * data from there instead of get_delta(). If we didn't,
	 * there's no harm.
	 */
	if (po->delta) {
		git__free(data);
389 390
		po->delta_data = NULL;
	}
Michael Schubert committed
391 392 393

	pb->nr_written++;

394 395
done:
	git__free(zbuf);
Michael Schubert committed
396
	git_odb_object_free(obj);
397
	return error;
Michael Schubert committed
398 399 400 401 402 403 404 405 406
}

enum write_one_status {
	WRITE_ONE_SKIP = -1, /* already written */
	WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
	WRITE_ONE_WRITTEN = 1, /* normal */
	WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
};

407 408 409 410 411 412
static int write_one(
	enum write_one_status *status,
	git_packbuilder *pb,
	git_pobject *po,
	int (*write_cb)(void *buf, size_t size, void *cb_data),
	void *cb_data)
Michael Schubert committed
413
{
414 415
	int error;

Michael Schubert committed
416 417 418 419 420 421 422 423 424 425
	if (po->recursing) {
		*status = WRITE_ONE_RECURSIVE;
		return 0;
	} else if (po->written) {
		*status = WRITE_ONE_SKIP;
		return 0;
	}

	if (po->delta) {
		po->recursing = 1;
426 427 428 429 430 431

		if ((error = write_one(status, pb, po->delta, write_cb, cb_data)) < 0)
			return error;

		/* we cannot depend on this one */
		if (*status == WRITE_ONE_RECURSIVE)
Michael Schubert committed
432 433 434
			po->delta = NULL;
	}

435
	*status = WRITE_ONE_WRITTEN;
Michael Schubert committed
436 437
	po->written = 1;
	po->recursing = 0;
438 439

	return write_object(pb, po, write_cb, cb_data);
Michael Schubert committed
440 441
}

442 443
GIT_INLINE(void) add_to_write_order(git_pobject **wo, size_t *endp,
	git_pobject *po)
Michael Schubert committed
444 445 446 447 448 449 450
{
	if (po->filled)
		return;
	wo[(*endp)++] = po;
	po->filled = 1;
}

451 452
static void add_descendants_to_write_order(git_pobject **wo, size_t *endp,
	git_pobject *po)
Michael Schubert committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
{
	int add_to_order = 1;
	while (po) {
		if (add_to_order) {
			git_pobject *s;
			/* add this node... */
			add_to_write_order(wo, endp, po);
			/* all its siblings... */
			for (s = po->delta_sibling; s; s = s->delta_sibling) {
				add_to_write_order(wo, endp, s);
			}
		}
		/* drop down a level to add left subtree nodes if possible */
		if (po->delta_child) {
			add_to_order = 1;
			po = po->delta_child;
		} else {
			add_to_order = 0;
			/* our sibling might have some children, it is next */
			if (po->delta_sibling) {
				po = po->delta_sibling;
				continue;
			}
			/* go back to our parent node */
			po = po->delta;
			while (po && !po->delta_sibling) {
				/* we're on the right side of a subtree, keep
				 * going up until we can go right again */
				po = po->delta;
			}
			if (!po) {
				/* done- we hit our original root node */
				return;
			}
			/* pass it off to sibling at this level */
			po = po->delta_sibling;
		}
	};
}

493 494
static void add_family_to_write_order(git_pobject **wo, size_t *endp,
	git_pobject *po)
Michael Schubert committed
495 496 497 498 499 500 501 502 503 504 505
{
	git_pobject *root;

	for (root = po; root->delta; root = root->delta)
		; /* nothing */
	add_descendants_to_write_order(wo, endp, root);
}

static int cb_tag_foreach(const char *name, git_oid *oid, void *data)
{
	git_packbuilder *pb = data;
506
	git_pobject *po;
Michael Schubert committed
507 508 509

	GIT_UNUSED(name);

510
	if ((po = git_oidmap_get(pb->object_ix, oid)) == NULL)
511 512 513 514
		return 0;

	po->tagged = 1;

Michael Schubert committed
515
	/* TODO: peel objects */
516

Michael Schubert committed
517 518 519
	return 0;
}

520
static int compute_write_order(git_pobject ***out, git_packbuilder *pb)
Michael Schubert committed
521
{
522
	size_t i, wo_end, last_untagged;
523
	git_pobject **wo;
Michael Schubert committed
524

525 526 527 528 529
	*out = NULL;

	if (!pb->nr_objects)
		return 0;

530
	if ((wo = git__mallocarray(pb->nr_objects, sizeof(*wo))) == NULL)
531
		return -1;
Michael Schubert committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557

	for (i = 0; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		po->tagged = 0;
		po->filled = 0;
		po->delta_child = NULL;
		po->delta_sibling = NULL;
	}

	/*
	 * Fully connect delta_child/delta_sibling network.
	 * Make sure delta_sibling is sorted in the original
	 * recency order.
	 */
	for (i = pb->nr_objects; i > 0;) {
		git_pobject *po = &pb->object_list[--i];
		if (!po->delta)
			continue;
		/* Mark me as the first child */
		po->delta_sibling = po->delta->delta_child;
		po->delta->delta_child = po;
	}

	/*
	 * Mark objects that are at the tip of tags.
	 */
558 559
	if (git_tag_foreach(pb->repo, &cb_tag_foreach, pb) < 0) {
		git__free(wo);
560
		return -1;
561
	}
Michael Schubert committed
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

	/*
	 * Give the objects in the original recency order until
	 * we see a tagged tip.
	 */
	for (i = wo_end = 0; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (po->tagged)
			break;
		add_to_write_order(wo, &wo_end, po);
	}
	last_untagged = i;

	/*
	 * Then fill all the tagged tips.
	 */
	for (; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (po->tagged)
			add_to_write_order(wo, &wo_end, po);
	}

	/*
	 * And then all remaining commits and tags.
	 */
	for (i = last_untagged; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
589 590
		if (po->type != GIT_OBJECT_COMMIT &&
		    po->type != GIT_OBJECT_TAG)
Michael Schubert committed
591 592 593 594 595 596 597 598 599
			continue;
		add_to_write_order(wo, &wo_end, po);
	}

	/*
	 * And then all the trees.
	 */
	for (i = last_untagged; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
600
		if (po->type != GIT_OBJECT_TREE)
Michael Schubert committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614
			continue;
		add_to_write_order(wo, &wo_end, po);
	}

	/*
	 * Finally all the rest in really tight order
	 */
	for (i = last_untagged; i < pb->nr_objects; i++) {
		git_pobject *po = pb->object_list + i;
		if (!po->filled)
			add_family_to_write_order(wo, &wo_end, po);
	}

	if (wo_end != pb->nr_objects) {
615
		git__free(wo);
616
		git_error_set(GIT_ERROR_INVALID, "invalid write order");
617
		return -1;
Michael Schubert committed
618 619
	}

620 621
	*out = wo;
	return 0;
Michael Schubert committed
622 623 624
}

static int write_pack(git_packbuilder *pb,
625 626
	int (*write_cb)(void *buf, size_t size, void *cb_data),
	void *cb_data)
Michael Schubert committed
627 628 629 630 631
{
	git_pobject **write_order;
	git_pobject *po;
	enum write_one_status status;
	struct git_pack_header ph;
632
	git_oid entry_oid;
633
	size_t i = 0;
634
	int error;
Michael Schubert committed
635

636 637
	if ((error = compute_write_order(&write_order, pb)) < 0)
		return error;
Michael Schubert committed
638

639
	if (!git__is_uint32(pb->nr_objects)) {
640
		git_error_set(GIT_ERROR_INVALID, "too many objects");
641 642
		error = -1;
		goto done;
643 644
	}

Michael Schubert committed
645 646 647 648 649
	/* Write pack header */
	ph.hdr_signature = htonl(PACK_SIGNATURE);
	ph.hdr_version = htonl(PACK_VERSION);
	ph.hdr_entries = htonl(pb->nr_objects);

650 651
	if ((error = write_cb(&ph, sizeof(ph), cb_data)) < 0 ||
		(error = git_hash_update(&pb->ctx, &ph, sizeof(ph))) < 0)
652
		goto done;
Michael Schubert committed
653 654 655 656 657 658

	pb->nr_remaining = pb->nr_objects;
	do {
		pb->nr_written = 0;
		for ( ; i < pb->nr_objects; ++i) {
			po = write_order[i];
659 660

			if ((error = write_one(&status, pb, po, write_cb, cb_data)) < 0)
661
				goto done;
Michael Schubert committed
662 663 664 665 666
		}

		pb->nr_remaining -= pb->nr_written;
	} while (pb->nr_remaining && i < pb->nr_objects);

667
	if ((error = git_hash_final(&entry_oid, &pb->ctx)) < 0)
668
		goto done;
Michael Schubert committed
669

670
	error = write_cb(entry_oid.id, GIT_OID_RAWSZ, cb_data);
Michael Schubert committed
671

672
done:
673 674 675 676 677 678 679 680 681
	/* if callback cancelled writing, we must still free delta_data */
	for ( ; i < pb->nr_objects; ++i) {
		po = write_order[i];
		if (po->delta_data) {
			git__free(po->delta_data);
			po->delta_data = NULL;
		}
	}

Michael Schubert committed
682
	git__free(write_order);
683
	return error;
Michael Schubert committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
}

static int write_pack_buf(void *buf, size_t size, void *data)
{
	git_buf *b = (git_buf *)data;
	return git_buf_put(b, buf, size);
}

static int type_size_sort(const void *_a, const void *_b)
{
	const git_pobject *a = (git_pobject *)_a;
	const git_pobject *b = (git_pobject *)_b;

	if (a->type > b->type)
		return -1;
	if (a->type < b->type)
		return 1;
	if (a->hash > b->hash)
		return -1;
	if (a->hash < b->hash)
		return 1;
	/*
	 * TODO
	 *
	if (a->preferred_base > b->preferred_base)
		return -1;
	if (a->preferred_base < b->preferred_base)
		return 1;
	*/
	if (a->size > b->size)
		return -1;
	if (a->size < b->size)
		return 1;
	return a < b ? -1 : (a > b); /* newest first */
}

720 721 722 723 724
static int delta_cacheable(
	git_packbuilder *pb,
	size_t src_size,
	size_t trg_size,
	size_t delta_size)
Michael Schubert committed
725
{
726 727 728 729 730 731
	size_t new_size;

	if (git__add_sizet_overflow(&new_size, pb->delta_cache_size, delta_size))
		return 0;

	if (pb->max_delta_cache_size && new_size > pb->max_delta_cache_size)
Michael Schubert committed
732 733 734 735 736 737 738 739 740 741 742 743 744
		return 0;

	if (delta_size < pb->cache_max_small_delta_size)
		return 1;

	/* cache delta, if objects are large enough compared to delta size */
	if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
		return 1;

	return 0;
}

static int try_delta(git_packbuilder *pb, struct unpacked *trg,
745 746
		     struct unpacked *src, size_t max_depth,
			 size_t *mem_usage, int *ret)
Michael Schubert committed
747 748 749 750
{
	git_pobject *trg_object = trg->object;
	git_pobject *src_object = src->object;
	git_odb_object *obj;
751 752
	size_t trg_size, src_size, delta_size, sizediff, max_size, sz;
	size_t ref_depth;
Michael Schubert committed
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
	void *delta_buf;

	/* Don't bother doing diffs between different types */
	if (trg_object->type != src_object->type) {
		*ret = -1;
		return 0;
	}

	*ret = 0;

	/* TODO: support reuse-delta */

	/* Let's not bust the allowed depth. */
	if (src->depth >= max_depth)
		return 0;

	/* Now some size filtering heuristics. */
770
	trg_size = trg_object->size;
Michael Schubert committed
771 772 773 774 775 776 777 778 779 780 781 782 783
	if (!trg_object->delta) {
		max_size = trg_size/2 - 20;
		ref_depth = 1;
	} else {
		max_size = trg_object->delta_size;
		ref_depth = trg->depth;
	}

	max_size = (uint64_t)max_size * (max_depth - src->depth) /
					(max_depth - ref_depth + 1);
	if (max_size == 0)
		return 0;

784
	src_size = src_object->size;
Michael Schubert committed
785 786 787 788 789 790 791 792 793 794 795
	sizediff = src_size < trg_size ? trg_size - src_size : 0;
	if (sizediff >= max_size)
		return 0;
	if (trg_size < src_size / 32)
		return 0;

	/* Load data if not already done */
	if (!trg->data) {
		if (git_odb_read(&obj, pb->odb, &trg_object->id) < 0)
			return -1;

796
		sz = git_odb_object_size(obj);
Michael Schubert committed
797
		trg->data = git__malloc(sz);
798
		GIT_ERROR_CHECK_ALLOC(trg->data);
Michael Schubert committed
799 800 801 802 803
		memcpy(trg->data, git_odb_object_data(obj), sz);

		git_odb_object_free(obj);

		if (sz != trg_size) {
804
			git_error_set(GIT_ERROR_INVALID,
805
				   "inconsistent target object length");
Michael Schubert committed
806 807 808 809 810 811
			return -1;
		}

		*mem_usage += sz;
	}
	if (!src->data) {
812 813 814 815
		size_t obj_sz;

		if (git_odb_read(&obj, pb->odb, &src_object->id) < 0 ||
			!git__is_ulong(obj_sz = git_odb_object_size(obj)))
Michael Schubert committed
816 817
			return -1;

818
		sz = obj_sz;
Michael Schubert committed
819
		src->data = git__malloc(sz);
820
		GIT_ERROR_CHECK_ALLOC(src->data);
Michael Schubert committed
821 822 823 824 825
		memcpy(src->data, git_odb_object_data(obj), sz);

		git_odb_object_free(obj);

		if (sz != src_size) {
826
			git_error_set(GIT_ERROR_INVALID,
827
				   "inconsistent source object length");
Michael Schubert committed
828 829 830 831 832 833
			return -1;
		}

		*mem_usage += sz;
	}
	if (!src->index) {
834
		if (git_delta_index_init(&src->index, src->data, src_size) < 0)
Michael Schubert committed
835 836
			return 0; /* suboptimal pack - out of memory */

837
		*mem_usage += git_delta_index_size(src->index);
Michael Schubert committed
838 839
	}

840 841
	if (git_delta_create_from_index(&delta_buf, &delta_size, src->index, trg->data, trg_size,
		max_size) < 0)
Michael Schubert committed
842 843 844 845 846 847 848 849 850 851 852
		return 0;

	if (trg_object->delta) {
		/* Prefer only shallower same-sized deltas. */
		if (delta_size == trg_object->delta_size &&
		    src->depth + 1 >= trg->depth) {
			git__free(delta_buf);
			return 0;
		}
	}

853 854
	GIT_ASSERT(git_packbuilder__cache_lock(pb) == 0);

Michael Schubert committed
855 856
	if (trg_object->delta_data) {
		git__free(trg_object->delta_data);
857
		GIT_ASSERT(pb->delta_cache_size >= trg_object->delta_size);
Michael Schubert committed
858 859 860 861
		pb->delta_cache_size -= trg_object->delta_size;
		trg_object->delta_data = NULL;
	}
	if (delta_cacheable(pb, src_size, trg_size, delta_size)) {
862
		bool overflow = git__add_sizet_overflow(
863
			&pb->delta_cache_size, pb->delta_cache_size, delta_size);
864

865
		GIT_ASSERT(git_packbuilder__cache_unlock(pb) == 0);
Michael Schubert committed
866

867 868
		if (overflow) {
			git__free(delta_buf);
869
			return -1;
870
		}
871 872

		trg_object->delta_data = git__realloc(delta_buf, delta_size);
873
		GIT_ERROR_CHECK_ALLOC(trg_object->delta_data);
Michael Schubert committed
874 875
	} else {
		/* create delta when writing the pack */
876
		GIT_ASSERT(git_packbuilder__cache_unlock(pb) == 0);
Michael Schubert committed
877 878 879 880 881 882 883 884 885 886 887
		git__free(delta_buf);
	}

	trg_object->delta = src_object;
	trg_object->delta_size = delta_size;
	trg->depth = src->depth + 1;

	*ret = 1;
	return 0;
}

888
static size_t check_delta_limit(git_pobject *me, size_t n)
Michael Schubert committed
889 890
{
	git_pobject *child = me->delta_child;
891
	size_t m = n;
Michael Schubert committed
892 893

	while (child) {
894
		size_t c = check_delta_limit(child, n + 1);
Michael Schubert committed
895 896 897 898 899 900 901
		if (m < c)
			m = c;
		child = child->delta_sibling;
	}
	return m;
}

902
static size_t free_unpacked(struct unpacked *n)
Michael Schubert committed
903
{
904
	size_t freed_mem = 0;
905

906 907 908 909
	if (n->index) {
		freed_mem += git_delta_index_size(n->index);
		git_delta_index_free(n->index);
	}
Michael Schubert committed
910
	n->index = NULL;
911

Michael Schubert committed
912
	if (n->data) {
913
		freed_mem += n->object->size;
Michael Schubert committed
914 915 916 917 918 919 920 921
		git__free(n->data);
		n->data = NULL;
	}
	n->object = NULL;
	n->depth = 0;
	return freed_mem;
}

922 923
static int report_delta_progress(
	git_packbuilder *pb, uint32_t count, bool force)
924 925 926 927 928 929 930
{
	int ret;

	if (pb->progress_cb) {
		double current_time = git__timer();
		double elapsed = current_time - pb->last_progress_report_time;

931
		if (force || elapsed < 0 || elapsed >= MIN_PROGRESS_UPDATE_INTERVAL) {
932 933 934 935 936 937 938
			pb->last_progress_report_time = current_time;

			ret = pb->progress_cb(
				GIT_PACKBUILDER_DELTAFICATION,
				count, pb->nr_objects, pb->progress_cb_payload);

			if (ret)
939
				return git_error_set_after_callback(ret);
940 941 942 943 944 945
		}
	}

	return 0;
}

Michael Schubert committed
946
static int find_deltas(git_packbuilder *pb, git_pobject **list,
947
	size_t *list_size, size_t window, size_t depth)
Michael Schubert committed
948 949 950 951
{
	git_pobject *po;
	git_buf zbuf = GIT_BUF_INIT;
	struct unpacked *array;
952 953 954
	size_t idx = 0, count = 0;
	size_t mem_usage = 0;
	size_t i;
Michael Schubert committed
955 956 957
	int error = -1;

	array = git__calloc(window, sizeof(struct unpacked));
958
	GIT_ERROR_CHECK_ALLOC(array);
Michael Schubert committed
959 960 961

	for (;;) {
		struct unpacked *n = array + idx;
962
		size_t max_depth, j, best_base = SIZE_MAX;
Michael Schubert committed
963

964
		GIT_ASSERT(git_packbuilder__progress_lock(pb) == 0);
Michael Schubert committed
965
		if (!*list_size) {
966
			GIT_ASSERT(git_packbuilder__progress_unlock(pb) == 0);
Michael Schubert committed
967 968 969
			break;
		}

970 971 972
		pb->nr_deltified += 1;
		report_delta_progress(pb, pb->nr_deltified, false);

Michael Schubert committed
973 974
		po = *list++;
		(*list_size)--;
975
		GIT_ASSERT(git_packbuilder__progress_unlock(pb) == 0);
Michael Schubert committed
976 977 978 979 980 981 982

		mem_usage -= free_unpacked(n);
		n->object = po;

		while (pb->window_memory_limit &&
		       mem_usage > pb->window_memory_limit &&
		       count > 1) {
983
			size_t tail = (idx + window - count) % window;
Michael Schubert committed
984 985 986 987 988 989 990 991 992 993 994
			mem_usage -= free_unpacked(array + tail);
			count--;
		}

		/*
		 * If the current object is at pack edge, take the depth the
		 * objects that depend on the current object into account
		 * otherwise they would become too deep.
		 */
		max_depth = depth;
		if (po->delta_child) {
995 996 997
			size_t delta_limit = check_delta_limit(po, 0);

			if (delta_limit > max_depth)
Michael Schubert committed
998
				goto next;
999 1000

			max_depth -= delta_limit;
Michael Schubert committed
1001 1002 1003 1004 1005
		}

		j = window;
		while (--j > 0) {
			int ret;
1006
			size_t other_idx = idx + j;
Michael Schubert committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
			struct unpacked *m;

			if (other_idx >= window)
				other_idx -= window;

			m = array + other_idx;
			if (!m->object)
				break;

			if (try_delta(pb, n, m, max_depth, &mem_usage, &ret) < 0)
				goto on_error;
			if (ret < 0)
				break;
			else if (ret > 0)
				best_base = other_idx;
		}

		/*
		 * If we decided to cache the delta data, then it is best
		 * to compress it right away.  First because we have to do
		 * it anyway, and doing it here while we're threaded will
		 * save a lot of time in the non threaded write phase,
		 * as well as allow for caching more deltas within
		 * the same cache size limit.
		 * ...
		 * But only if not writing to stdout, since in that case
		 * the network is most likely throttling writes anyway,
		 * and therefore it is best to go to the write phase ASAP
		 * instead, as we can afford spending more time compressing
		 * between writes at that moment.
		 */
		if (po->delta_data) {
1039
			if (git_zstream_deflatebuf(&zbuf, po->delta_data, po->delta_size) < 0)
Michael Schubert committed
1040 1041 1042 1043
				goto on_error;

			git__free(po->delta_data);
			po->delta_data = git__malloc(zbuf.size);
1044
			GIT_ERROR_CHECK_ALLOC(po->delta_data);
Michael Schubert committed
1045 1046

			memcpy(po->delta_data, zbuf.ptr, zbuf.size);
1047
			po->z_delta_size = zbuf.size;
Michael Schubert committed
1048 1049
			git_buf_clear(&zbuf);

1050
			GIT_ASSERT(git_packbuilder__cache_lock(pb) == 0);
Michael Schubert committed
1051 1052
			pb->delta_cache_size -= po->delta_size;
			pb->delta_cache_size += po->z_delta_size;
1053
			GIT_ASSERT(git_packbuilder__cache_unlock(pb) == 0);
Michael Schubert committed
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
		}

		/*
		 * If we made n a delta, and if n is already at max
		 * depth, leaving it in the window is pointless.  we
		 * should evict it first.
		 */
		if (po->delta && max_depth <= n->depth)
			continue;

		/*
		 * Move the best delta base up in the window, after the
		 * currently deltified object, to keep it longer.  It will
		 * be the first base object to be attempted next.
		 */
		if (po->delta) {
			struct unpacked swap = array[best_base];
1071 1072
			size_t dist = (window + idx - best_base) % window;
			size_t dst = best_base;
Michael Schubert committed
1073
			while (dist--) {
1074
				size_t src = (dst + 1) % window;
Michael Schubert committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
				array[dst] = array[src];
				dst = src;
			}
			array[dst] = swap;
		}

		next:
		idx++;
		if (count + 1 < window)
			count++;
		if (idx >= window)
			idx = 0;
	}
	error = 0;

on_error:
	for (i = 0; i < window; ++i) {
		git__free(array[i].index);
		git__free(array[i].data);
	}
	git__free(array);
1096
	git_buf_dispose(&zbuf);
Michael Schubert committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

	return error;
}

#ifdef GIT_THREADS

struct thread_params {
	git_thread thread;
	git_packbuilder *pb;

	git_pobject **list;

	git_cond cond;
	git_mutex mutex;

1112 1113
	size_t list_size;
	size_t remaining;
Michael Schubert committed
1114

1115 1116 1117 1118
	size_t window;
	size_t depth;
	size_t working;
	size_t data_ready;
Michael Schubert committed
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
};

static void *threaded_find_deltas(void *arg)
{
	struct thread_params *me = arg;

	while (me->remaining) {
		if (find_deltas(me->pb, me->list, &me->remaining,
				me->window, me->depth) < 0) {
			; /* TODO */
		}

1131
		GIT_ASSERT_WITH_RETVAL(git_packbuilder__progress_lock(me->pb) == 0, NULL);
Michael Schubert committed
1132
		me->working = 0;
1133
		git_cond_signal(&me->pb->progress_cond);
1134
		GIT_ASSERT_WITH_RETVAL(git_packbuilder__progress_unlock(me->pb) == 0, NULL);
Michael Schubert committed
1135

1136
		if (git_mutex_lock(&me->mutex)) {
1137
			git_error_set(GIT_ERROR_THREAD, "unable to lock packfile condition mutex");
1138 1139 1140 1141 1142 1143
			return NULL;
		}

		while (!me->data_ready)
			git_cond_wait(&me->cond, &me->mutex);

Michael Schubert committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
		/*
		 * We must not set ->data_ready before we wait on the
		 * condition because the main thread may have set it to 1
		 * before we get here. In order to be sure that new
		 * work is available if we see 1 in ->data_ready, it
		 * was initialized to 0 before this thread was spawned
		 * and we reset it to 0 right away.
		 */
		me->data_ready = 0;
		git_mutex_unlock(&me->mutex);
	}
	/* leave ->working 1 so that this doesn't get more work assigned */
	return NULL;
}

static int ll_find_deltas(git_packbuilder *pb, git_pobject **list,
1160
			  size_t list_size, size_t window, size_t depth)
Michael Schubert committed
1161 1162
{
	struct thread_params *p;
1163 1164
	size_t i;
	int ret, active_threads = 0;
Michael Schubert committed
1165 1166

	if (!pb->nr_threads)
1167
		pb->nr_threads = git__online_cpus();
1168

Michael Schubert committed
1169 1170 1171 1172 1173
	if (pb->nr_threads <= 1) {
		find_deltas(pb, list, &list_size, window, depth);
		return 0;
	}

1174
	p = git__mallocarray(pb->nr_threads, sizeof(*p));
1175
	GIT_ERROR_CHECK_ALLOC(p);
Michael Schubert committed
1176 1177 1178

	/* Partition the work among the threads */
	for (i = 0; i < pb->nr_threads; ++i) {
1179
		size_t sub_size = list_size / (pb->nr_threads - i);
Michael Schubert committed
1180 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

		/* don't use too small segments or no deltas will be found */
		if (sub_size < 2*window && i+1 < pb->nr_threads)
			sub_size = 0;

		p[i].pb = pb;
		p[i].window = window;
		p[i].depth = depth;
		p[i].working = 1;
		p[i].data_ready = 0;

		/* try to split chunks on "path" boundaries */
		while (sub_size && sub_size < list_size &&
		       list[sub_size]->hash &&
		       list[sub_size]->hash == list[sub_size-1]->hash)
			sub_size++;

		p[i].list = list;
		p[i].list_size = sub_size;
		p[i].remaining = sub_size;

		list += sub_size;
		list_size -= sub_size;
	}

	/* Start work threads */
	for (i = 0; i < pb->nr_threads; ++i) {
		if (!p[i].list_size)
			continue;

		git_mutex_init(&p[i].mutex);
		git_cond_init(&p[i].cond);

1213
		ret = git_thread_create(&p[i].thread,
Michael Schubert committed
1214 1215
					threaded_find_deltas, &p[i]);
		if (ret) {
1216
			git_error_set(GIT_ERROR_THREAD, "unable to create thread");
Michael Schubert committed
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
			return -1;
		}
		active_threads++;
	}

	/*
	 * Now let's wait for work completion.  Each time a thread is done
	 * with its work, we steal half of the remaining work from the
	 * thread with the largest number of unprocessed objects and give
	 * it to that newly idle thread.  This ensure good load balancing
	 * until the remaining object list segments are simply too short
	 * to be worth splitting anymore.
	 */
	while (active_threads) {
		struct thread_params *target = NULL;
		struct thread_params *victim = NULL;
1233
		size_t sub_size = 0;
Michael Schubert committed
1234

1235 1236 1237 1238
		/* Start by locating a thread that has transitioned its
		 * 'working' flag from 1 -> 0. This indicates that it is
		 * ready to receive more work using our work-stealing
		 * algorithm. */
1239
		GIT_ASSERT(git_packbuilder__progress_lock(pb) == 0);
Michael Schubert committed
1240 1241 1242 1243 1244 1245
		for (;;) {
			for (i = 0; !target && i < pb->nr_threads; i++)
				if (!p[i].working)
					target = &p[i];
			if (target)
				break;
1246
			git_cond_wait(&pb->progress_cond, &pb->progress_mutex);
Michael Schubert committed
1247 1248
		}

1249 1250 1251
		/* At this point we hold the progress lock and have located
		 * a thread to receive more work. We still need to locate a
		 * thread from which to steal work (the victim). */
Michael Schubert committed
1252 1253 1254 1255
		for (i = 0; i < pb->nr_threads; i++)
			if (p[i].remaining > 2*window &&
			    (!victim || victim->remaining < p[i].remaining))
				victim = &p[i];
1256

Michael Schubert committed
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
		if (victim) {
			sub_size = victim->remaining / 2;
			list = victim->list + victim->list_size - sub_size;
			while (sub_size && list[0]->hash &&
			       list[0]->hash == list[-1]->hash) {
				list++;
				sub_size--;
			}
			if (!sub_size) {
				/*
				 * It is possible for some "paths" to have
				 * so many objects that no hash boundary
				 * might be found.  Let's just steal the
				 * exact half in that case.
				 */
				sub_size = victim->remaining / 2;
				list -= sub_size;
			}
			target->list = list;
			victim->list_size -= sub_size;
			victim->remaining -= sub_size;
		}
		target->list_size = sub_size;
		target->remaining = sub_size;
		target->working = 1;
1282
		GIT_ASSERT(git_packbuilder__progress_unlock(pb) == 0);
Michael Schubert committed
1283

1284
		if (git_mutex_lock(&target->mutex)) {
1285
			git_error_set(GIT_ERROR_THREAD, "unable to lock packfile condition mutex");
1286 1287 1288 1289
			git__free(p);
			return -1;
		}

Michael Schubert committed
1290 1291 1292 1293 1294
		target->data_ready = 1;
		git_cond_signal(&target->cond);
		git_mutex_unlock(&target->mutex);

		if (!sub_size) {
1295
			git_thread_join(&target->thread, NULL);
Michael Schubert committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
			git_cond_free(&target->cond);
			git_mutex_free(&target->mutex);
			active_threads--;
		}
	}

	git__free(p);
	return 0;
}

#else
#define ll_find_deltas(pb, l, ls, w, d) find_deltas(pb, l, &ls, w, d)
#endif

static int prepare_pack(git_packbuilder *pb)
{
	git_pobject **delta_list;
1313
	size_t i, n = 0;
Michael Schubert committed
1314 1315 1316 1317

	if (pb->nr_objects == 0 || pb->done)
		return 0; /* nothing to do */

1318 1319 1320 1321 1322 1323 1324
	/*
	 * Although we do not report progress during deltafication, we
	 * at least report that we are in the deltafication stage
	 */
	if (pb->progress_cb)
			pb->progress_cb(GIT_PACKBUILDER_DELTAFICATION, 0, pb->nr_objects, pb->progress_cb_payload);

1325
	delta_list = git__mallocarray(pb->nr_objects, sizeof(*delta_list));
1326
	GIT_ERROR_CHECK_ALLOC(delta_list);
Michael Schubert committed
1327 1328 1329 1330

	for (i = 0; i < pb->nr_objects; ++i) {
		git_pobject *po = pb->object_list + i;

1331 1332
		/* Make sure the item is within our size limits */
		if (po->size < 50 || po->size > pb->big_file_threshold)
Michael Schubert committed
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
			continue;

		delta_list[n++] = po;
	}

	if (n > 1) {
		git__tsort((void **)delta_list, n, type_size_sort);
		if (ll_find_deltas(pb, delta_list, n,
				   GIT_PACK_WINDOW + 1,
				   GIT_PACK_DEPTH) < 0) {
			git__free(delta_list);
			return -1;
		}
	}

1348 1349
	report_delta_progress(pb, pb->nr_objects, true);

Michael Schubert committed
1350 1351 1352 1353 1354 1355 1356
	pb->done = true;
	git__free(delta_list);
	return 0;
}

#define PREPARE_PACK if (prepare_pack(pb) < 0) { return -1; }

1357 1358 1359 1360 1361 1362
int git_packbuilder_foreach(git_packbuilder *pb, int (*cb)(void *buf, size_t size, void *payload), void *payload)
{
	PREPARE_PACK;
	return write_pack(pb, cb, payload);
}

Michael Schubert committed
1363 1364
int git_packbuilder_write_buf(git_buf *buf, git_packbuilder *pb)
{
1365 1366 1367 1368 1369
	int error;

	if ((error = git_buf_sanitize(buf)) < 0)
		return error;

Michael Schubert committed
1370
	PREPARE_PACK;
1371

Michael Schubert committed
1372 1373 1374
	return write_pack(pb, &write_pack_buf, buf);
}

1375
static int write_cb(void *buf, size_t len, void *payload)
Michael Schubert committed
1376
{
1377
	struct pack_write_context *ctx = payload;
1378
	return git_indexer_append(ctx->indexer, buf, len, ctx->stats);
1379 1380 1381 1382 1383
}

int git_packbuilder_write(
	git_packbuilder *pb,
	const char *path,
1384
	unsigned int mode,
1385
	git_indexer_progress_cb progress_cb,
1386 1387
	void *progress_cb_payload)
{
1388
	int error = -1;
1389
	git_buf object_path = GIT_BUF_INIT;
1390
	git_indexer_options opts = GIT_INDEXER_OPTIONS_INIT;
1391
	git_indexer *indexer = NULL;
1392
	git_indexer_progress stats;
1393
	struct pack_write_context ctx;
1394
	int t;
1395

Michael Schubert committed
1396
	PREPARE_PACK;
1397

1398 1399 1400 1401 1402 1403 1404 1405
	if (path == NULL) {
		if ((error = git_repository_item_path(&object_path, pb->repo, GIT_REPOSITORY_ITEM_OBJECTS)) < 0)
			goto cleanup;
		if ((error = git_buf_joinpath(&object_path, git_buf_cstr(&object_path), "pack")) < 0)
			goto cleanup;
		path = git_buf_cstr(&object_path);
	}

1406 1407 1408
	opts.progress_cb = progress_cb;
	opts.progress_cb_payload = progress_cb_payload;

1409 1410
	if ((error = git_indexer_new(&indexer, path, mode, pb->odb, &opts)) < 0)
		goto cleanup;
1411

1412
	if (!git_repository__configmap_lookup(&t, pb->repo, GIT_CONFIGMAP_FSYNCOBJECTFILES) && t)
1413 1414
		git_indexer__set_fsync(indexer, 1);

1415 1416 1417
	ctx.indexer = indexer;
	ctx.stats = &stats;

1418 1419 1420 1421 1422
	if ((error = git_packbuilder_foreach(pb, write_cb, &ctx)) < 0)
		goto cleanup;

	if ((error = git_indexer_commit(indexer, &stats)) < 0)
		goto cleanup;
1423

1424 1425
	git_oid_cpy(&pb->pack_oid, git_indexer_hash(indexer));

1426
cleanup:
1427
	git_indexer_free(indexer);
1428
	git_buf_dispose(&object_path);
1429
	return error;
Michael Schubert committed
1430 1431 1432 1433
}

#undef PREPARE_PACK

1434 1435 1436 1437 1438
const git_oid *git_packbuilder_hash(git_packbuilder *pb)
{
	return &pb->pack_oid;
}

1439

1440 1441
static int cb_tree_walk(
	const char *root, const git_tree_entry *entry, void *payload)
Michael Schubert committed
1442
{
1443
	int error;
1444
	struct tree_walk_context *ctx = payload;
Michael Schubert committed
1445

1446
	/* A commit inside a tree represents a submodule commit and should be skipped. */
1447
	if (git_tree_entry_type(entry) == GIT_OBJECT_COMMIT)
1448 1449
		return 0;

1450 1451 1452 1453
	if (!(error = git_buf_sets(&ctx->buf, root)) &&
		!(error = git_buf_puts(&ctx->buf, git_tree_entry_name(entry))))
		error = git_packbuilder_insert(
			ctx->pb, git_tree_entry_id(entry), git_buf_cstr(&ctx->buf));
Michael Schubert committed
1454

1455
	return error;
Michael Schubert committed
1456 1457
}

1458 1459
int git_packbuilder_insert_commit(git_packbuilder *pb, const git_oid *oid)
{
Xavier L committed
1460
	git_commit *commit;
1461

Xavier L committed
1462 1463 1464
	if (git_commit_lookup(&commit, pb->repo, oid) < 0 ||
		git_packbuilder_insert(pb, oid, NULL) < 0)
		return -1;
1465

Xavier L committed
1466 1467
	if (git_packbuilder_insert_tree(pb, git_commit_tree_id(commit)) < 0)
		return -1;
1468

Xavier L committed
1469 1470
	git_commit_free(commit);
	return 0;
1471 1472
}

Michael Schubert committed
1473 1474
int git_packbuilder_insert_tree(git_packbuilder *pb, const git_oid *oid)
{
1475 1476
	int error;
	git_tree *tree = NULL;
1477
	struct tree_walk_context context = { pb, GIT_BUF_INIT };
Michael Schubert committed
1478

1479 1480 1481
	if (!(error = git_tree_lookup(&tree, pb->repo, oid)) &&
	    !(error = git_packbuilder_insert(pb, oid, NULL)))
		error = git_tree_walk(tree, GIT_TREEWALK_PRE, cb_tree_walk, &context);
Michael Schubert committed
1482 1483

	git_tree_free(tree);
1484
	git_buf_dispose(&context.buf);
1485
	return error;
Michael Schubert committed
1486 1487
}

1488 1489 1490 1491 1492
int git_packbuilder_insert_recur(git_packbuilder *pb, const git_oid *id, const char *name)
{
	git_object *obj;
	int error;

1493 1494
	GIT_ASSERT_ARG(pb);
	GIT_ASSERT_ARG(id);
1495

1496
	if ((error = git_object_lookup(&obj, pb->repo, id, GIT_OBJECT_ANY)) < 0)
1497 1498 1499
		return error;

	switch (git_object_type(obj)) {
1500
	case GIT_OBJECT_BLOB:
1501 1502
		error = git_packbuilder_insert(pb, id, name);
		break;
1503
	case GIT_OBJECT_TREE:
1504 1505
		error = git_packbuilder_insert_tree(pb, id);
		break;
1506
	case GIT_OBJECT_COMMIT:
1507 1508
		error = git_packbuilder_insert_commit(pb, id);
		break;
1509
	case GIT_OBJECT_TAG:
1510 1511 1512 1513 1514 1515
		if ((error = git_packbuilder_insert(pb, id, name)) < 0)
			goto cleanup;
		error = git_packbuilder_insert_recur(pb, git_tag_target_id((git_tag *) obj), NULL);
		break;

	default:
1516
		git_error_set(GIT_ERROR_INVALID, "unknown object type");
1517 1518 1519 1520 1521 1522 1523 1524
		error = -1;
	}

cleanup:
	git_object_free(obj);
	return error;
}

1525
size_t git_packbuilder_object_count(git_packbuilder *pb)
1526 1527 1528 1529
{
	return pb->nr_objects;
}

1530
size_t git_packbuilder_written(git_packbuilder *pb)
1531 1532 1533 1534
{
	return pb->nr_written;
}

1535
static int lookup_walk_object(struct walk_object **out, git_packbuilder *pb, const git_oid *id)
1536
{
1537
	struct walk_object *obj;
1538 1539 1540

	obj = git_pool_mallocz(&pb->object_pool, 1);
	if (!obj) {
1541
		git_error_set_oom();
1542 1543 1544 1545 1546 1547 1548 1549 1550
		return -1;
	}

	git_oid_cpy(&obj->id, id);

	*out = obj;
	return 0;
}

1551
static int retrieve_object(struct walk_object **out, git_packbuilder *pb, const git_oid *id)
1552
{
1553
	struct walk_object *obj;
1554
	int error;
1555

1556
	if ((obj = git_oidmap_get(pb->walk_objects, id)) == NULL) {
1557 1558 1559
		if ((error = lookup_walk_object(&obj, pb, id)) < 0)
			return error;

1560 1561
		if ((error = git_oidmap_set(pb->walk_objects, &obj->id, obj)) < 0)
			return error;
1562 1563 1564 1565 1566 1567 1568 1569 1570
	}

	*out = obj;
	return 0;
}

static int mark_blob_uninteresting(git_packbuilder *pb, const git_oid *id)
{
	int error;
1571
	struct walk_object *obj;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582

	if ((error = retrieve_object(&obj, pb, id)) < 0)
		return error;

	obj->uninteresting = 1;

	return 0;
}

static int mark_tree_uninteresting(git_packbuilder *pb, const git_oid *id)
{
1583
	struct walk_object *obj;
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
	git_tree *tree;
	int error;
	size_t i;

	if ((error = retrieve_object(&obj, pb, id)) < 0)
		return error;

	if (obj->uninteresting)
		return 0;

	obj->uninteresting = 1;

	if ((error = git_tree_lookup(&tree, pb->repo, id)) < 0)
		return error;

	for (i = 0; i < git_tree_entrycount(tree); i++) {
		const git_tree_entry *entry = git_tree_entry_byindex(tree, i);
		const git_oid *entry_id = git_tree_entry_id(entry);
		switch (git_tree_entry_type(entry)) {
1603
		case GIT_OBJECT_TREE:
1604 1605 1606
			if ((error = mark_tree_uninteresting(pb, entry_id)) < 0)
				goto cleanup;
			break;
1607
		case GIT_OBJECT_BLOB:
1608 1609 1610 1611 1612 1613 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 1641 1642 1643 1644 1645 1646 1647 1648 1649
			if ((error = mark_blob_uninteresting(pb, entry_id)) < 0)
				goto cleanup;
			break;
		default:
			/* it's a submodule or something unknown, we don't want it */
			;
		}
	}

cleanup:
	git_tree_free(tree);
	return error;
}

/*
 * Mark the edges of the graph uninteresting. Since we start from a
 * git_revwalk, the commits are already uninteresting, but we need to
 * mark the trees and blobs.
 */
static int mark_edges_uninteresting(git_packbuilder *pb, git_commit_list *commits)
{
	int error;
	git_commit_list *list;
	git_commit *commit;

	for (list = commits; list; list = list->next) {
		if (!list->item->uninteresting)
			continue;

		if ((error = git_commit_lookup(&commit, pb->repo, &list->item->oid)) < 0)
			return error;

		error = mark_tree_uninteresting(pb, git_commit_tree_id(commit));
		git_commit_free(commit);

		if (error < 0)
			return error;
	}

	return 0;
}

1650
static int pack_objects_insert_tree(git_packbuilder *pb, git_tree *tree)
1651 1652 1653 1654
{
	size_t i;
	int error;
	git_tree *subtree;
1655
	struct walk_object *obj;
1656 1657 1658 1659 1660
	const char *name;

	if ((error = retrieve_object(&obj, pb, git_tree_id(tree))) < 0)
		return error;

1661
	if (obj->seen || obj->uninteresting)
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
		return 0;

	obj->seen = 1;

	if ((error = git_packbuilder_insert(pb, &obj->id, NULL)))
		return error;

	for (i = 0; i < git_tree_entrycount(tree); i++) {
		const git_tree_entry *entry = git_tree_entry_byindex(tree, i);
		const git_oid *entry_id = git_tree_entry_id(entry);
		switch (git_tree_entry_type(entry)) {
1673
		case GIT_OBJECT_TREE:
1674 1675 1676
			if ((error = git_tree_lookup(&subtree, pb->repo, entry_id)) < 0)
				return error;

1677
			error = pack_objects_insert_tree(pb, subtree);
1678 1679 1680 1681 1682 1683
			git_tree_free(subtree);

			if (error < 0)
				return error;

			break;
1684
		case GIT_OBJECT_BLOB:
1685
			if ((error = retrieve_object(&obj, pb, entry_id)) < 0)
1686 1687 1688
				return error;
			if (obj->uninteresting)
				continue;
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
			name = git_tree_entry_name(entry);
			if ((error = git_packbuilder_insert(pb, entry_id, name)) < 0)
				return error;
			break;
		default:
			/* it's a submodule or something unknown, we don't want it */
			;
		}
	}


	return error;
}

1703
static int pack_objects_insert_commit(git_packbuilder *pb, struct walk_object *obj)
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
{
	int error;
	git_commit *commit = NULL;
	git_tree *tree = NULL;

	obj->seen = 1;

	if ((error = git_packbuilder_insert(pb, &obj->id, NULL)) < 0)
		return error;

	if ((error = git_commit_lookup(&commit, pb->repo, &obj->id)) < 0)
		return error;

	if ((error = git_tree_lookup(&tree, pb->repo, git_commit_tree_id(commit))) < 0)
		goto cleanup;

1720
	if ((error = pack_objects_insert_tree(pb, tree)) < 0)
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
		goto cleanup;

cleanup:
	git_commit_free(commit);
	git_tree_free(tree);
	return error;
}

int git_packbuilder_insert_walk(git_packbuilder *pb, git_revwalk *walk)
{
	int error;
	git_oid id;
1733
	struct walk_object *obj;
1734

1735 1736
	GIT_ASSERT_ARG(pb);
	GIT_ASSERT_ARG(walk);
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755

	if ((error = mark_edges_uninteresting(pb, walk->user_input)) < 0)
		return error;

	/*
	 * TODO: git marks the parents of the edges
	 * uninteresting. This may provide a speed advantage, but does
	 * seem to assume the remote does not have a single-commit
	 * history on the other end.
	 */

	/* walk down each tree up to the blobs and insert them, stopping when uninteresting */
	while ((error = git_revwalk_next(&id, walk)) == 0) {
		if ((error = retrieve_object(&obj, pb, &id)) < 0)
			return error;

		if (obj->seen || obj->uninteresting)
			continue;

1756
		if ((error = pack_objects_insert_commit(pb, obj)) < 0)
1757 1758 1759 1760 1761 1762
			return error;
	}

	if (error == GIT_ITEROVER)
		error = 0;

1763
	return error;
1764 1765
}

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
int git_packbuilder_set_callbacks(git_packbuilder *pb, git_packbuilder_progress progress_cb, void *progress_cb_payload)
{
	if (!pb)
		return -1;

	pb->progress_cb = progress_cb;
	pb->progress_cb_payload = progress_cb_payload;

	return 0;
}

Michael Schubert committed
1777 1778 1779 1780 1781
void git_packbuilder_free(git_packbuilder *pb)
{
	if (pb == NULL)
		return;

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
#ifdef GIT_THREADS

	git_mutex_free(&pb->cache_mutex);
	git_mutex_free(&pb->progress_mutex);
	git_cond_free(&pb->progress_cond);

#endif

	if (pb->odb)
		git_odb_free(pb->odb);

	if (pb->object_ix)
		git_oidmap_free(pb->object_ix);

	if (pb->object_list)
		git__free(pb->object_list);

1799 1800 1801
	git_oidmap_free(pb->walk_objects);
	git_pool_clear(&pb->object_pool);

1802
	git_hash_ctx_cleanup(&pb->ctx);
1803
	git_zstream_free(&pb->zstream);
1804

Michael Schubert committed
1805 1806
	git__free(pb);
}